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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

77.37
/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 {
4✔
25
        if includePad {
6✔
26
                delta += BlockPadding
2✔
27
        }
2✔
28

29
        if limit <= uint32(delta) {
6✔
30
                return fmt.Errorf("cltv limit %v should be greater than %v",
2✔
31
                        limit, delta)
2✔
32
        }
2✔
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

UNCOV
89
        case errEmptyPaySession:
×
UNCOV
90
                return "empty payment session"
×
91

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

5✔
117
                return channeldb.FailureReasonNoRoute
5✔
118

UNCOV
119
        case errInsufficientBalance:
×
UNCOV
120
                return channeldb.FailureReasonInsufficientBalance
×
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) {
23✔
205

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

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

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

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

23✔
225
        return &paymentSession{
23✔
226
                selfNode:          selfNode,
23✔
227
                additionalEdges:   edges,
23✔
228
                getBandwidthHints: getBandwidthHints,
23✔
229
                payment:           p,
23✔
230
                pathFinder:        findPath,
23✔
231
                graphSessFactory:  graphSessFactory,
23✔
232
                pathFindingConfig: pathFindingConfig,
23✔
233
                missionControl:    missionControl,
23✔
234
                minShardAmt:       DefaultShardMinAmt,
23✔
235
                log:               build.NewPrefixLog(logPrefix, log),
23✔
236
        }, nil
23✔
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) {
63✔
251

63✔
252
        if p.empty {
63✔
UNCOV
253
                return nil, errEmptyPaySession
×
UNCOV
254
        }
×
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
63✔
259
        finalCltvDelta += BlockPadding
63✔
260

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

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

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

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

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

2✔
296
                maxAmt = *p.payment.MaxShardAmt
2✔
297
        }
2✔
298

299
        for {
136✔
300
                // Get a routing graph session.
73✔
301
                graph, closeGraph, err := p.graphSessFactory.NewGraphSession()
73✔
302
                if err != nil {
73✔
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)
73✔
313
                if err != nil {
73✔
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)
73✔
324

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

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

342
                switch {
73✔
343
                case err == errNoPathFound:
15✔
344
                        // Don't split if this is a legacy payment without mpp
15✔
345
                        // record. If it has a blinded path though, then we
15✔
346
                        // can split. Split payments to blinded paths won't have
15✔
347
                        // MPP records.
15✔
348
                        if p.payment.PaymentAddr.IsNone() &&
15✔
349
                                p.payment.BlindedPathSet == nil {
17✔
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 {
13✔
358
                                p.log.Debug("Not splitting because " +
×
359
                                        "destination DestFeatures is nil")
×
360
                                return nil, errNoPathFound
×
361
                        }
×
362

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

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

1✔
371
                                return nil, errNoPathFound
1✔
372
                        }
1✔
373

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

1✔
381
                                return nil, errNoPathFound
1✔
382
                        }
1✔
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
11✔
387

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

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

397
                        // Go pathfinding.
398
                        continue
10✔
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:
1✔
405
                        p.log.Debug("not splitting because local balance " +
1✔
406
                                "is insufficient")
1✔
407

1✔
408
                        return nil, err
1✔
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(
57✔
418
                        p.selfNode, path, height,
57✔
419
                        finalHopParams{
57✔
420
                                amt:         maxAmt,
57✔
421
                                totalAmt:    p.payment.Amount,
57✔
422
                                cltvDelta:   finalCltvDelta,
57✔
423
                                records:     p.payment.DestCustomRecords,
57✔
424
                                paymentAddr: p.payment.PaymentAddr,
57✔
425
                                metadata:    p.payment.Metadata,
57✔
426
                        }, p.payment.BlindedPathSet,
57✔
427
                )
57✔
428
                if err != nil {
57✔
429
                        return nil, err
×
430
                }
×
431

432
                return route, err
57✔
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 {
3✔
442

3✔
443
        // Validate the message signature.
3✔
444
        if err := netann.VerifyChannelUpdateSignature(msg, pubKey); err != nil {
3✔
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
3✔
453
        policy.FeeBaseMSat = lnwire.MilliSatoshi(msg.BaseFee)
3✔
454
        policy.FeeProportionalMillionths = lnwire.MilliSatoshi(msg.FeeRate)
3✔
455

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

3✔
459
        return true
3✔
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 {
5✔
467

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

5✔
470
        edges, ok := p.additionalEdges[target]
5✔
471
        if !ok {
8✔
472
                return nil
3✔
473
        }
3✔
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