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

lightningnetwork / lnd / 16931860422

13 Aug 2025 08:28AM UTC coverage: 66.948%. First build
16931860422

Pull #10151

github

web-flow
Merge 461dfb1e2 into 4e0af2f49
Pull Request #10151: Refactor Payment PR 5

227 of 282 new or added lines in 20 files covered. (80.5%)

135783 of 202820 relevant lines covered (66.95%)

21589.43 hits per line

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

85.0
/routing/payment_session.go
1
package routing
2

3
import (
4
        "fmt"
5

6
        "github.com/btcsuite/btcd/btcec/v2"
7
        "github.com/btcsuite/btclog/v2"
8
        graphdb "github.com/lightningnetwork/lnd/graph/db"
9
        "github.com/lightningnetwork/lnd/graph/db/models"
10
        "github.com/lightningnetwork/lnd/lnutils"
11
        "github.com/lightningnetwork/lnd/lnwire"
12
        "github.com/lightningnetwork/lnd/netann"
13
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
14
        "github.com/lightningnetwork/lnd/routing/route"
15
)
16

17
// BlockPadding is used to increment the finalCltvDelta value for the last hop
18
// to prevent an HTLC being failed if some blocks are mined while it's in-flight.
19
const BlockPadding uint16 = 3
20

21
// ValidateCLTVLimit is a helper function that validates that the cltv limit is
22
// greater than the final cltv delta parameter, optionally including the
23
// BlockPadding in this calculation.
24
func ValidateCLTVLimit(limit uint32, delta uint16, includePad bool) error {
15✔
25
        if includePad {
22✔
26
                delta += BlockPadding
7✔
27
        }
7✔
28

29
        if limit <= uint32(delta) {
18✔
30
                return fmt.Errorf("cltv limit %v should be greater than %v",
3✔
31
                        limit, delta)
3✔
32
        }
3✔
33

34
        return nil
12✔
35
}
36

37
// noRouteError encodes a non-critical error encountered during path finding.
38
type noRouteError uint8
39

40
const (
41
        // errNoTlvPayload is returned when the destination hop does not support
42
        // a tlv payload.
43
        errNoTlvPayload noRouteError = iota
44

45
        // errNoPaymentAddr is returned when the destination hop does not
46
        // support payment addresses.
47
        errNoPaymentAddr
48

49
        // errNoPathFound is returned when a path to the target destination does
50
        // not exist in the graph.
51
        errNoPathFound
52

53
        // errInsufficientLocalBalance is returned when none of the local
54
        // channels have enough balance for the payment.
55
        errInsufficientBalance
56

57
        // errEmptyPaySession is returned when the empty payment session is
58
        // queried for a route.
59
        errEmptyPaySession
60

61
        // errUnknownRequiredFeature is returned when the destination node
62
        // requires an unknown feature.
63
        errUnknownRequiredFeature
64

65
        // errMissingDependentFeature is returned when the destination node
66
        // misses a feature that a feature that we require depends on.
67
        errMissingDependentFeature
68
)
69

70
var (
71
        // DefaultShardMinAmt is the default amount beyond which we won't try to
72
        // further split the payment if no route is found. It is the minimum
73
        // amount that we use as the shard size when splitting.
74
        DefaultShardMinAmt = lnwire.NewMSatFromSatoshis(10000)
75
)
76

77
// Error returns the string representation of the noRouteError.
78
func (e noRouteError) Error() string {
3✔
79
        switch e {
3✔
80
        case errNoTlvPayload:
×
81
                return "destination hop doesn't understand new TLV payloads"
×
82

83
        case errNoPaymentAddr:
×
84
                return "destination hop doesn't understand payment addresses"
×
85

86
        case errNoPathFound:
3✔
87
                return "unable to find a path to destination"
3✔
88

89
        case errEmptyPaySession:
3✔
90
                return "empty payment session"
3✔
91

92
        case errInsufficientBalance:
3✔
93
                return "insufficient local balance"
3✔
94

95
        case errUnknownRequiredFeature:
×
96
                return "unknown required feature"
×
97

98
        case errMissingDependentFeature:
×
99
                return "missing dependent feature"
×
100

101
        default:
×
102
                return "unknown no-route error"
×
103
        }
104
}
105

106
// FailureReason converts a path finding error into a payment-level failure.
107
func (e noRouteError) FailureReason() paymentsdb.FailureReason {
8✔
108
        switch e {
8✔
109
        case
110
                errNoTlvPayload,
111
                errNoPaymentAddr,
112
                errNoPathFound,
113
                errEmptyPaySession,
114
                errUnknownRequiredFeature,
115
                errMissingDependentFeature:
8✔
116

8✔
117
                return paymentsdb.FailureReasonNoRoute
8✔
118

119
        case errInsufficientBalance:
3✔
120
                return paymentsdb.FailureReasonInsufficientBalance
3✔
121

122
        default:
×
NEW
123
                return paymentsdb.FailureReasonError
×
124
        }
125
}
126

127
// PaymentSession is used during SendPayment attempts to provide routes to
128
// attempt. It also defines methods to give the PaymentSession additional
129
// information learned during the previous attempts.
130
type PaymentSession interface {
131
        // RequestRoute returns the next route to attempt for routing the
132
        // specified HTLC payment to the target node. The returned route should
133
        // carry at most maxAmt to the target node, and pay at most feeLimit in
134
        // fees. It can carry less if the payment is MPP. The activeShards
135
        // argument should be set to instruct the payment session about the
136
        // number of in flight HTLCS for the payment, such that it can choose
137
        // splitting strategy accordingly.
138
        //
139
        // A noRouteError is returned if a non-critical error is encountered
140
        // during path finding.
141
        RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
142
                activeShards, height uint32,
143
                firstHopCustomRecords lnwire.CustomRecords) (*route.Route,
144
                error)
145

146
        // UpdateAdditionalEdge takes an additional channel edge policy
147
        // (private channels) and applies the update from the message. Returns
148
        // a boolean to indicate whether the update has been applied without
149
        // error.
150
        UpdateAdditionalEdge(msg *lnwire.ChannelUpdate1,
151
                pubKey *btcec.PublicKey, policy *models.CachedEdgePolicy) bool
152

153
        // GetAdditionalEdgePolicy uses the public key and channel ID to query
154
        // the ephemeral channel edge policy for additional edges. Returns a nil
155
        // if nothing found.
156
        GetAdditionalEdgePolicy(pubKey *btcec.PublicKey,
157
                channelID uint64) *models.CachedEdgePolicy
158
}
159

160
// paymentSession is used during an HTLC routings session to prune the local
161
// chain view in response to failures, and also report those failures back to
162
// MissionController. The snapshot copied for this session will only ever grow,
163
// and will now be pruned after a decay like the main view within mission
164
// control. We do this as we want to avoid the case where we continually try a
165
// bad edge or route multiple times in a session. This can lead to an infinite
166
// loop if payment attempts take long enough. An additional set of edges can
167
// also be provided to assist in reaching the payment's destination.
168
type paymentSession struct {
169
        selfNode route.Vertex
170

171
        additionalEdges map[route.Vertex][]AdditionalEdge
172

173
        getBandwidthHints func(Graph) (bandwidthHints, error)
174

175
        payment *LightningPayment
176

177
        empty bool
178

179
        pathFinder pathFinder
180

181
        graphSessFactory GraphSessionFactory
182

183
        // pathFindingConfig defines global parameters that control the
184
        // trade-off in path finding between fees and probability.
185
        pathFindingConfig PathFindingConfig
186

187
        missionControl MissionControlQuerier
188

189
        // minShardAmt is the amount beyond which we won't try to further split
190
        // the payment if no route is found. If the maximum number of htlcs
191
        // specified in the payment is one, under no circumstances splitting
192
        // will happen and this value remains unused.
193
        minShardAmt lnwire.MilliSatoshi
194

195
        // log is a payment session-specific logger.
196
        log btclog.Logger
197
}
198

199
// newPaymentSession instantiates a new payment session.
200
func newPaymentSession(p *LightningPayment, selfNode route.Vertex,
201
        getBandwidthHints func(Graph) (bandwidthHints, error),
202
        graphSessFactory GraphSessionFactory,
203
        missionControl MissionControlQuerier,
204
        pathFindingConfig PathFindingConfig) (*paymentSession, error) {
26✔
205

26✔
206
        edges, err := RouteHintsToEdges(p.RouteHints, p.Target)
26✔
207
        if err != nil {
26✔
208
                return nil, err
×
209
        }
×
210

211
        if p.BlindedPathSet != nil {
29✔
212
                if len(edges) != 0 {
3✔
213
                        return nil, fmt.Errorf("cannot have both route hints " +
×
214
                                "and blinded path")
×
215
                }
×
216

217
                edges, err = p.BlindedPathSet.ToRouteHints()
3✔
218
                if err != nil {
3✔
219
                        return nil, err
×
220
                }
×
221
        }
222

223
        logPrefix := fmt.Sprintf("PaymentSession(%x):", p.Identifier())
26✔
224

26✔
225
        return &paymentSession{
26✔
226
                selfNode:          selfNode,
26✔
227
                additionalEdges:   edges,
26✔
228
                getBandwidthHints: getBandwidthHints,
26✔
229
                payment:           p,
26✔
230
                pathFinder:        findPath,
26✔
231
                graphSessFactory:  graphSessFactory,
26✔
232
                pathFindingConfig: pathFindingConfig,
26✔
233
                missionControl:    missionControl,
26✔
234
                minShardAmt:       DefaultShardMinAmt,
26✔
235
                log:               log.WithPrefix(logPrefix),
26✔
236
        }, nil
26✔
237
}
238

239
// pathFindingError is a wrapper error type that is used to distinguish path
240
// finding errors from other errors in path finding loop.
241
type pathFindingError struct {
242
        error
243
}
244

245
// Unwrap returns the underlying error.
246
func (e *pathFindingError) Unwrap() error {
19✔
247
        return e.error
19✔
248
}
19✔
249

250
// RequestRoute returns a route which is likely to be capable for successfully
251
// routing the specified HTLC payment to the target node. Initially the first
252
// set of paths returned from this method may encounter routing failure along
253
// the way, however as more payments are sent, mission control will start to
254
// build an up to date view of the network itself. With each payment a new area
255
// will be explored, which feeds into the recommendations made for routing.
256
//
257
// NOTE: This function is safe for concurrent access.
258
// NOTE: Part of the PaymentSession interface.
259
func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
260
        activeShards, height uint32,
261
        firstHopCustomRecords lnwire.CustomRecords) (*route.Route, error) {
66✔
262

66✔
263
        if p.empty {
69✔
264
                return nil, errEmptyPaySession
3✔
265
        }
3✔
266

267
        // Add BlockPadding to the finalCltvDelta so that the receiving node
268
        // does not reject the HTLC if some blocks are mined while it's in-flight.
269
        finalCltvDelta := p.payment.FinalCLTVDelta
66✔
270
        finalCltvDelta += BlockPadding
66✔
271

66✔
272
        // We need to subtract the final delta before passing it into path
66✔
273
        // finding. The optimal path is independent of the final cltv delta and
66✔
274
        // the path finding algorithm is unaware of this value.
66✔
275
        cltvLimit := p.payment.CltvLimit - uint32(finalCltvDelta)
66✔
276

66✔
277
        // TODO(roasbeef): sync logic amongst dist sys
66✔
278

66✔
279
        // Taking into account this prune view, we'll attempt to locate a path
66✔
280
        // to our destination, respecting the recommendations from
66✔
281
        // MissionController.
66✔
282
        restrictions := &RestrictParams{
66✔
283
                ProbabilitySource:     p.missionControl.GetProbability,
66✔
284
                FeeLimit:              feeLimit,
66✔
285
                OutgoingChannelIDs:    p.payment.OutgoingChannelIDs,
66✔
286
                LastHop:               p.payment.LastHop,
66✔
287
                CltvLimit:             cltvLimit,
66✔
288
                DestCustomRecords:     p.payment.DestCustomRecords,
66✔
289
                DestFeatures:          p.payment.DestFeatures,
66✔
290
                PaymentAddr:           p.payment.PaymentAddr,
66✔
291
                Amp:                   p.payment.amp,
66✔
292
                Metadata:              p.payment.Metadata,
66✔
293
                FirstHopCustomRecords: firstHopCustomRecords,
66✔
294
        }
66✔
295

66✔
296
        finalHtlcExpiry := int32(height) + int32(finalCltvDelta)
66✔
297

66✔
298
        // Before we enter the loop below, we'll make sure to respect the max
66✔
299
        // payment shard size (if it's set), which is effectively our
66✔
300
        // client-side MTU that we'll attempt to respect at all times.
66✔
301
        maxShardActive := p.payment.MaxShardAmt != nil
66✔
302
        if maxShardActive && maxAmt > *p.payment.MaxShardAmt {
68✔
303
                p.log.Debugf("Clamping payment attempt from %v to %v due to "+
2✔
304
                        "max shard size of %v", maxAmt, *p.payment.MaxShardAmt,
2✔
305
                        maxAmt)
2✔
306

2✔
307
                maxAmt = *p.payment.MaxShardAmt
2✔
308
        }
2✔
309

310
        var path []*unifiedEdge
66✔
311
        findPath := func(graph graphdb.NodeTraverser) error {
142✔
312
                // We'll also obtain a set of bandwidthHints from the lower
76✔
313
                // layer for each of our outbound channels. This will allow the
76✔
314
                // path finding to skip any links that aren't active or just
76✔
315
                // don't have enough bandwidth to carry the payment. New
76✔
316
                // bandwidth hints are queried for every new path finding
76✔
317
                // attempt, because concurrent payments may change balances.
76✔
318
                bandwidthHints, err := p.getBandwidthHints(graph)
76✔
319
                if err != nil {
76✔
320
                        return err
×
321
                }
×
322

323
                p.log.Debugf("pathfinding for amt=%v", maxAmt)
76✔
324

76✔
325
                // Find a route for the current amount.
76✔
326
                path, _, err = p.pathFinder(
76✔
327
                        &graphParams{
76✔
328
                                additionalEdges: p.additionalEdges,
76✔
329
                                bandwidthHints:  bandwidthHints,
76✔
330
                                graph:           graph,
76✔
331
                        },
76✔
332
                        restrictions, &p.pathFindingConfig,
76✔
333
                        p.selfNode, p.selfNode, p.payment.Target,
76✔
334
                        maxAmt, p.payment.TimePref, finalHtlcExpiry,
76✔
335
                )
76✔
336
                if err != nil {
95✔
337
                        // Wrap the error to distinguish path finding errors
19✔
338
                        // from other errors in this closure.
19✔
339
                        return &pathFindingError{err}
19✔
340
                }
19✔
341

342
                return nil
60✔
343
        }
344

345
        for {
142✔
346
                err := p.graphSessFactory.GraphSession(
76✔
347
                        findPath, func() {
76✔
348
                                path = nil
×
349
                        },
×
350
                )
351
                // If there is an error, and it is not a path finding error, we
352
                // return it immediately.
353
                if err != nil && !lnutils.ErrorAs[*pathFindingError](err) {
76✔
354
                        return nil, err
×
355
                } else if err != nil {
95✔
356
                        // If the error is a path finding error, we'll unwrap it
19✔
357
                        // to check the underlying error.
19✔
358
                        //
19✔
359
                        //nolint:errorlint
19✔
360
                        pErr, _ := err.(*pathFindingError)
19✔
361
                        err = pErr.Unwrap()
19✔
362
                }
19✔
363

364
                // Otherwise, we'll switch on the path finding error.
365
                switch {
76✔
366
                case err == errNoPathFound:
18✔
367
                        // Don't split if this is a legacy payment without mpp
18✔
368
                        // record. If it has a blinded path though, then we
18✔
369
                        // can split. Split payments to blinded paths won't have
18✔
370
                        // MPP records.
18✔
371
                        if p.payment.PaymentAddr.IsNone() &&
18✔
372
                                p.payment.BlindedPathSet == nil {
23✔
373

5✔
374
                                p.log.Debugf("not splitting because payment " +
5✔
375
                                        "address is unspecified")
5✔
376

5✔
377
                                return nil, errNoPathFound
5✔
378
                        }
5✔
379

380
                        if p.payment.DestFeatures == nil {
16✔
381
                                p.log.Debug("Not splitting because " +
×
382
                                        "destination DestFeatures is nil")
×
383
                                return nil, errNoPathFound
×
384
                        }
×
385

386
                        destFeatures := p.payment.DestFeatures
16✔
387
                        if !destFeatures.HasFeature(lnwire.MPPOptional) &&
16✔
388
                                !destFeatures.HasFeature(lnwire.AMPOptional) {
17✔
389

1✔
390
                                p.log.Debug("not splitting because " +
1✔
391
                                        "destination doesn't declare MPP or " +
1✔
392
                                        "AMP")
1✔
393

1✔
394
                                return nil, errNoPathFound
1✔
395
                        }
1✔
396

397
                        // No splitting if this is the last shard.
398
                        isLastShard := activeShards+1 >= p.payment.MaxParts
15✔
399
                        if isLastShard {
19✔
400
                                p.log.Debugf("not splitting because shard "+
4✔
401
                                        "limit %v has been reached",
4✔
402
                                        p.payment.MaxParts)
4✔
403

4✔
404
                                return nil, errNoPathFound
4✔
405
                        }
4✔
406

407
                        // This is where the magic happens. If we can't find a
408
                        // route, try it for half the amount.
409
                        maxAmt /= 2
14✔
410

14✔
411
                        // Put a lower bound on the minimum shard size.
14✔
412
                        if maxAmt < p.minShardAmt {
18✔
413
                                p.log.Debugf("not splitting because minimum "+
4✔
414
                                        "shard amount %v has been reached",
4✔
415
                                        p.minShardAmt)
4✔
416

4✔
417
                                return nil, errNoPathFound
4✔
418
                        }
4✔
419

420
                        // Go pathfinding.
421
                        continue
13✔
422

423
                // If there isn't enough local bandwidth, there is no point in
424
                // splitting. It won't be possible to create a complete set in
425
                // any case, but the sent out partial payments would be held by
426
                // the receiver until the mpp timeout.
427
                case err == errInsufficientBalance:
4✔
428
                        p.log.Debug("not splitting because local balance " +
4✔
429
                                "is insufficient")
4✔
430

4✔
431
                        return nil, err
4✔
432

433
                case err != nil:
×
434
                        return nil, err
×
435
                }
436

437
                // With the next candidate path found, we'll attempt to turn
438
                // this into a route by applying the time-lock and fee
439
                // requirements.
440
                route, err := newRoute(
60✔
441
                        p.selfNode, path, height,
60✔
442
                        finalHopParams{
60✔
443
                                amt:         maxAmt,
60✔
444
                                totalAmt:    p.payment.Amount,
60✔
445
                                cltvDelta:   finalCltvDelta,
60✔
446
                                records:     p.payment.DestCustomRecords,
60✔
447
                                paymentAddr: p.payment.PaymentAddr,
60✔
448
                                metadata:    p.payment.Metadata,
60✔
449
                        }, p.payment.BlindedPathSet,
60✔
450
                )
60✔
451
                if err != nil {
60✔
452
                        return nil, err
×
453
                }
×
454

455
                return route, err
60✔
456
        }
457
}
458

459
// UpdateAdditionalEdge updates the channel edge policy for a private edge. It
460
// validates the message signature and checks it's up to date, then applies the
461
// updates to the supplied policy. It returns a boolean to indicate whether
462
// there's an error when applying the updates.
463
func (p *paymentSession) UpdateAdditionalEdge(msg *lnwire.ChannelUpdate1,
464
        pubKey *btcec.PublicKey, policy *models.CachedEdgePolicy) bool {
6✔
465

6✔
466
        // Validate the message signature.
6✔
467
        if err := netann.VerifyChannelUpdateSignature(msg, pubKey); err != nil {
6✔
468
                log.Errorf(
×
469
                        "Unable to validate channel update signature: %v", err,
×
470
                )
×
471
                return false
×
472
        }
×
473

474
        // Update channel policy for the additional edge.
475
        policy.TimeLockDelta = msg.TimeLockDelta
6✔
476
        policy.FeeBaseMSat = lnwire.MilliSatoshi(msg.BaseFee)
6✔
477
        policy.FeeProportionalMillionths = lnwire.MilliSatoshi(msg.FeeRate)
6✔
478

6✔
479
        log.Debugf("New private channel update applied: %v",
6✔
480
                lnutils.SpewLogClosure(msg))
6✔
481

6✔
482
        return true
6✔
483
}
484

485
// GetAdditionalEdgePolicy uses the public key and channel ID to query the
486
// ephemeral channel edge policy for additional edges. Returns a nil if nothing
487
// found.
488
func (p *paymentSession) GetAdditionalEdgePolicy(pubKey *btcec.PublicKey,
489
        channelID uint64) *models.CachedEdgePolicy {
8✔
490

8✔
491
        target := route.NewVertex(pubKey)
8✔
492

8✔
493
        edges, ok := p.additionalEdges[target]
8✔
494
        if !ok {
14✔
495
                return nil
6✔
496
        }
6✔
497

498
        for _, edge := range edges {
10✔
499
                policy := edge.EdgePolicy()
5✔
500
                if policy.ChannelID != channelID {
5✔
501
                        continue
×
502
                }
503

504
                return policy
5✔
505
        }
506

507
        return nil
×
508
}
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