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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

75.31
/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"
8
        "github.com/lightningnetwork/lnd/build"
9
        "github.com/lightningnetwork/lnd/channeldb"
10
        "github.com/lightningnetwork/lnd/channeldb/models"
11
        "github.com/lightningnetwork/lnd/lnutils"
12
        "github.com/lightningnetwork/lnd/lnwire"
13
        "github.com/lightningnetwork/lnd/netann"
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 {
2✔
25
        if includePad {
4✔
26
                delta += BlockPadding
2✔
27
        }
2✔
28

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

34
        return nil
2✔
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 {
2✔
79
        switch e {
2✔
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:
2✔
87
                return "unable to find a path to destination"
2✔
88

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

92
        case errInsufficientBalance:
2✔
93
                return "insufficient local balance"
2✔
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() channeldb.FailureReason {
2✔
108
        switch e {
2✔
109
        case
110
                errNoTlvPayload,
111
                errNoPaymentAddr,
112
                errNoPathFound,
113
                errEmptyPaySession,
114
                errUnknownRequiredFeature,
115
                errMissingDependentFeature:
2✔
116

2✔
117
                return channeldb.FailureReasonNoRoute
2✔
118

119
        case errInsufficientBalance:
2✔
120
                return channeldb.FailureReasonInsufficientBalance
2✔
121

122
        default:
×
123
                return channeldb.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) {
2✔
205

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

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

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

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

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

239
// RequestRoute returns a route which is likely to be capable for successfully
240
// routing the specified HTLC payment to the target node. Initially the first
241
// set of paths returned from this method may encounter routing failure along
242
// the way, however as more payments are sent, mission control will start to
243
// build an up to date view of the network itself. With each payment a new area
244
// will be explored, which feeds into the recommendations made for routing.
245
//
246
// NOTE: This function is safe for concurrent access.
247
// NOTE: Part of the PaymentSession interface.
248
func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
249
        activeShards, height uint32,
250
        firstHopCustomRecords lnwire.CustomRecords) (*route.Route, error) {
2✔
251

2✔
252
        if p.empty {
4✔
253
                return nil, errEmptyPaySession
2✔
254
        }
2✔
255

256
        // Add BlockPadding to the finalCltvDelta so that the receiving node
257
        // does not reject the HTLC if some blocks are mined while it's in-flight.
258
        finalCltvDelta := p.payment.FinalCLTVDelta
2✔
259
        finalCltvDelta += BlockPadding
2✔
260

2✔
261
        // We need to subtract the final delta before passing it into path
2✔
262
        // finding. The optimal path is independent of the final cltv delta and
2✔
263
        // the path finding algorithm is unaware of this value.
2✔
264
        cltvLimit := p.payment.CltvLimit - uint32(finalCltvDelta)
2✔
265

2✔
266
        // TODO(roasbeef): sync logic amongst dist sys
2✔
267

2✔
268
        // Taking into account this prune view, we'll attempt to locate a path
2✔
269
        // to our destination, respecting the recommendations from
2✔
270
        // MissionController.
2✔
271
        restrictions := &RestrictParams{
2✔
272
                ProbabilitySource:     p.missionControl.GetProbability,
2✔
273
                FeeLimit:              feeLimit,
2✔
274
                OutgoingChannelIDs:    p.payment.OutgoingChannelIDs,
2✔
275
                LastHop:               p.payment.LastHop,
2✔
276
                CltvLimit:             cltvLimit,
2✔
277
                DestCustomRecords:     p.payment.DestCustomRecords,
2✔
278
                DestFeatures:          p.payment.DestFeatures,
2✔
279
                PaymentAddr:           p.payment.PaymentAddr,
2✔
280
                Amp:                   p.payment.amp,
2✔
281
                Metadata:              p.payment.Metadata,
2✔
282
                FirstHopCustomRecords: firstHopCustomRecords,
2✔
283
        }
2✔
284

2✔
285
        finalHtlcExpiry := int32(height) + int32(finalCltvDelta)
2✔
286

2✔
287
        // Before we enter the loop below, we'll make sure to respect the max
2✔
288
        // payment shard size (if it's set), which is effectively our
2✔
289
        // client-side MTU that we'll attempt to respect at all times.
2✔
290
        maxShardActive := p.payment.MaxShardAmt != nil
2✔
291
        if maxShardActive && maxAmt > *p.payment.MaxShardAmt {
2✔
UNCOV
292
                p.log.Debugf("Clamping payment attempt from %v to %v due to "+
×
UNCOV
293
                        "max shard size of %v", maxAmt, *p.payment.MaxShardAmt,
×
UNCOV
294
                        maxAmt)
×
UNCOV
295

×
UNCOV
296
                maxAmt = *p.payment.MaxShardAmt
×
UNCOV
297
        }
×
298

299
        for {
4✔
300
                // Get a routing graph session.
2✔
301
                graph, closeGraph, err := p.graphSessFactory.NewGraphSession()
2✔
302
                if err != nil {
2✔
303
                        return nil, err
×
304
                }
×
305

306
                // We'll also obtain a set of bandwidthHints from the lower
307
                // layer for each of our outbound channels. This will allow the
308
                // path finding to skip any links that aren't active or just
309
                // don't have enough bandwidth to carry the payment. New
310
                // bandwidth hints are queried for every new path finding
311
                // attempt, because concurrent payments may change balances.
312
                bandwidthHints, err := p.getBandwidthHints(graph)
2✔
313
                if err != nil {
2✔
314
                        // Close routing graph session.
×
315
                        if graphErr := closeGraph(); graphErr != nil {
×
316
                                log.Errorf("could not close graph session: %v",
×
317
                                        graphErr)
×
318
                        }
×
319

320
                        return nil, err
×
321
                }
322

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

2✔
325
                // Find a route for the current amount.
2✔
326
                path, _, err := p.pathFinder(
2✔
327
                        &graphParams{
2✔
328
                                additionalEdges: p.additionalEdges,
2✔
329
                                bandwidthHints:  bandwidthHints,
2✔
330
                                graph:           graph,
2✔
331
                        },
2✔
332
                        restrictions, &p.pathFindingConfig,
2✔
333
                        p.selfNode, p.selfNode, p.payment.Target,
2✔
334
                        maxAmt, p.payment.TimePref, finalHtlcExpiry,
2✔
335
                )
2✔
336

2✔
337
                // Close routing graph session.
2✔
338
                if err := closeGraph(); err != nil {
2✔
339
                        log.Errorf("could not close graph session: %v", err)
×
340
                }
×
341

342
                switch {
2✔
343
                case err == errNoPathFound:
2✔
344
                        // Don't split if this is a legacy payment without mpp
2✔
345
                        // record. If it has a blinded path though, then we
2✔
346
                        // can split. Split payments to blinded paths won't have
2✔
347
                        // MPP records.
2✔
348
                        if p.payment.PaymentAddr.IsNone() &&
2✔
349
                                p.payment.BlindedPathSet == nil {
4✔
350

2✔
351
                                p.log.Debugf("not splitting because payment " +
2✔
352
                                        "address is unspecified")
2✔
353

2✔
354
                                return nil, errNoPathFound
2✔
355
                        }
2✔
356

357
                        if p.payment.DestFeatures == nil {
2✔
358
                                p.log.Debug("Not splitting because " +
×
359
                                        "destination DestFeatures is nil")
×
360
                                return nil, errNoPathFound
×
361
                        }
×
362

363
                        destFeatures := p.payment.DestFeatures
2✔
364
                        if !destFeatures.HasFeature(lnwire.MPPOptional) &&
2✔
365
                                !destFeatures.HasFeature(lnwire.AMPOptional) {
2✔
UNCOV
366

×
UNCOV
367
                                p.log.Debug("not splitting because " +
×
UNCOV
368
                                        "destination doesn't declare MPP or " +
×
UNCOV
369
                                        "AMP")
×
UNCOV
370

×
UNCOV
371
                                return nil, errNoPathFound
×
UNCOV
372
                        }
×
373

374
                        // No splitting if this is the last shard.
375
                        isLastShard := activeShards+1 >= p.payment.MaxParts
2✔
376
                        if isLastShard {
4✔
377
                                p.log.Debugf("not splitting because shard "+
2✔
378
                                        "limit %v has been reached",
2✔
379
                                        p.payment.MaxParts)
2✔
380

2✔
381
                                return nil, errNoPathFound
2✔
382
                        }
2✔
383

384
                        // This is where the magic happens. If we can't find a
385
                        // route, try it for half the amount.
386
                        maxAmt /= 2
2✔
387

2✔
388
                        // Put a lower bound on the minimum shard size.
2✔
389
                        if maxAmt < p.minShardAmt {
4✔
390
                                p.log.Debugf("not splitting because minimum "+
2✔
391
                                        "shard amount %v has been reached",
2✔
392
                                        p.minShardAmt)
2✔
393

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

397
                        // Go pathfinding.
398
                        continue
2✔
399

400
                // If there isn't enough local bandwidth, there is no point in
401
                // splitting. It won't be possible to create a complete set in
402
                // any case, but the sent out partial payments would be held by
403
                // the receiver until the mpp timeout.
404
                case err == errInsufficientBalance:
2✔
405
                        p.log.Debug("not splitting because local balance " +
2✔
406
                                "is insufficient")
2✔
407

2✔
408
                        return nil, err
2✔
409

410
                case err != nil:
×
411
                        return nil, err
×
412
                }
413

414
                // With the next candidate path found, we'll attempt to turn
415
                // this into a route by applying the time-lock and fee
416
                // requirements.
417
                route, err := newRoute(
2✔
418
                        p.selfNode, path, height,
2✔
419
                        finalHopParams{
2✔
420
                                amt:         maxAmt,
2✔
421
                                totalAmt:    p.payment.Amount,
2✔
422
                                cltvDelta:   finalCltvDelta,
2✔
423
                                records:     p.payment.DestCustomRecords,
2✔
424
                                paymentAddr: p.payment.PaymentAddr,
2✔
425
                                metadata:    p.payment.Metadata,
2✔
426
                        }, p.payment.BlindedPathSet,
2✔
427
                )
2✔
428
                if err != nil {
2✔
429
                        return nil, err
×
430
                }
×
431

432
                return route, err
2✔
433
        }
434
}
435

436
// UpdateAdditionalEdge updates the channel edge policy for a private edge. It
437
// validates the message signature and checks it's up to date, then applies the
438
// updates to the supplied policy. It returns a boolean to indicate whether
439
// there's an error when applying the updates.
440
func (p *paymentSession) UpdateAdditionalEdge(msg *lnwire.ChannelUpdate1,
441
        pubKey *btcec.PublicKey, policy *models.CachedEdgePolicy) bool {
2✔
442

2✔
443
        // Validate the message signature.
2✔
444
        if err := netann.VerifyChannelUpdateSignature(msg, pubKey); err != nil {
2✔
445
                log.Errorf(
×
446
                        "Unable to validate channel update signature: %v", err,
×
447
                )
×
448
                return false
×
449
        }
×
450

451
        // Update channel policy for the additional edge.
452
        policy.TimeLockDelta = msg.TimeLockDelta
2✔
453
        policy.FeeBaseMSat = lnwire.MilliSatoshi(msg.BaseFee)
2✔
454
        policy.FeeProportionalMillionths = lnwire.MilliSatoshi(msg.FeeRate)
2✔
455

2✔
456
        log.Debugf("New private channel update applied: %v",
2✔
457
                lnutils.SpewLogClosure(msg))
2✔
458

2✔
459
        return true
2✔
460
}
461

462
// GetAdditionalEdgePolicy uses the public key and channel ID to query the
463
// ephemeral channel edge policy for additional edges. Returns a nil if nothing
464
// found.
465
func (p *paymentSession) GetAdditionalEdgePolicy(pubKey *btcec.PublicKey,
466
        channelID uint64) *models.CachedEdgePolicy {
2✔
467

2✔
468
        target := route.NewVertex(pubKey)
2✔
469

2✔
470
        edges, ok := p.additionalEdges[target]
2✔
471
        if !ok {
4✔
472
                return nil
2✔
473
        }
2✔
474

475
        for _, edge := range edges {
4✔
476
                policy := edge.EdgePolicy()
2✔
477
                if policy.ChannelID != channelID {
2✔
478
                        continue
×
479
                }
480

481
                return policy
2✔
482
        }
483

484
        return nil
×
485
}
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