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

lightningnetwork / lnd / 13423774416

19 Feb 2025 10:39PM UTC coverage: 49.338% (-9.5%) from 58.794%
13423774416

Pull #9484

github

Abdulkbk
lnutils: add createdir util function

This utility function replaces repetitive logic patterns
throughout LND.
Pull Request #9484: lnutils: add createDir util function

0 of 13 new or added lines in 1 file covered. (0.0%)

27149 existing lines in 431 files now uncovered.

100732 of 204168 relevant lines covered (49.34%)

1.54 hits per line

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

79.54
/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
        "github.com/lightningnetwork/lnd/channeldb"
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
        "github.com/lightningnetwork/lnd/routing/route"
14
)
15

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

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

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

×
33
        return nil
34
}
3✔
35

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
94
        case errUnknownRequiredFeature:
95
                return "unknown required feature"
×
96

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

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

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

3✔
116
                return channeldb.FailureReasonNoRoute
3✔
117

3✔
118
        case errInsufficientBalance:
119
                return channeldb.FailureReasonInsufficientBalance
3✔
120

3✔
121
        default:
122
                return channeldb.FailureReasonError
×
123
        }
×
124
}
125

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

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

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

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

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

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

174
        payment *LightningPayment
175

176
        empty bool
177

178
        pathFinder pathFinder
179

180
        graphSessFactory GraphSessionFactory
181

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

186
        missionControl MissionControlQuerier
187

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

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

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

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

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

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

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

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

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

251
        if p.empty {
252
                return nil, errEmptyPaySession
253
        }
254

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

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

3✔
265
        // TODO(roasbeef): sync logic amongst dist sys
3✔
266

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

3✔
284
        finalHtlcExpiry := int32(height) + int32(finalCltvDelta)
3✔
285

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

3✔
295
                maxAmt = *p.payment.MaxShardAmt
3✔
296
        }
3✔
297

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

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

3✔
319
                        return nil, err
3✔
320
                }
×
321

×
322
                p.log.Debugf("pathfinding for amt=%v", maxAmt)
323

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

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

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

3✔
350
                                p.log.Debugf("not splitting because payment " +
×
351
                                        "address is unspecified")
6✔
352

3✔
353
                                return nil, errNoPathFound
3✔
354
                        }
3✔
355

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

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

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

3✔
370
                                return nil, errNoPathFound
3✔
371
                        }
3✔
372

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

×
380
                                return nil, errNoPathFound
×
381
                        }
382

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

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

393
                                return nil, errNoPathFound
394
                        }
3✔
395

6✔
396
                        // Go pathfinding.
3✔
397
                        continue
3✔
398

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

3✔
407
                        return nil, err
3✔
408

6✔
409
                case err != nil:
3✔
410
                        return nil, err
3✔
411
                }
3✔
412

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

×
431
                return route, err
432
        }
433
}
434

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

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

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

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

458
        return true
459
}
460

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

×
467
        target := route.NewVertex(pubKey)
×
468

×
469
        edges, ok := p.additionalEdges[target]
470
        if !ok {
471
                return nil
3✔
472
        }
3✔
473

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

480
                return policy
481
        }
482

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