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

lightningnetwork / lnd / 19027031130

03 Nov 2025 07:27AM UTC coverage: 56.922% (-9.7%) from 66.639%
19027031130

Pull #9334

github

web-flow
Merge b9be11a16 into f938e40af
Pull Request #9334: Use all valid routes during blinded path construction

9 of 11 new or added lines in 3 files covered. (81.82%)

29175 existing lines in 461 files now uncovered.

99696 of 175144 relevant lines covered (56.92%)

1.77 hits per line

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

84.7
/routing/blindedpath/blinded_path.go
1
package blindedpath
2

3
import (
4
        "bytes"
5
        "errors"
6
        "fmt"
7
        "math"
8
        "sort"
9

10
        "github.com/btcsuite/btcd/btcec/v2"
11
        "github.com/btcsuite/btcd/btcutil"
12
        sphinx "github.com/lightningnetwork/lightning-onion"
13
        "github.com/lightningnetwork/lnd/channeldb"
14
        "github.com/lightningnetwork/lnd/graph/db/models"
15
        "github.com/lightningnetwork/lnd/lnwire"
16
        "github.com/lightningnetwork/lnd/record"
17
        "github.com/lightningnetwork/lnd/routing/route"
18
        "github.com/lightningnetwork/lnd/tlv"
19
        "github.com/lightningnetwork/lnd/zpay32"
20
)
21

22
const (
23
        // oneMillion is a constant used frequently in fee rate calculations.
24
        oneMillion = uint32(1_000_000)
25
)
26

27
// errInvalidBlindedPath indicates that the chosen real path is not usable as
28
// a blinded path.
29
var errInvalidBlindedPath = errors.New("the chosen path results in an " +
30
        "unusable blinded path")
31

32
// BuildBlindedPathCfg defines the various resources and configuration values
33
// required to build a blinded payment path to this node.
34
type BuildBlindedPathCfg struct {
35
        // FindRoutes returns a set of routes to us that can be used for the
36
        // construction of blinded paths. These routes will consist of real
37
        // nodes advertising the route blinding feature bit. They may be of
38
        // various lengths and may even contain only a single hop. Any route
39
        // shorter than MinNumHops will be padded with dummy hops during route
40
        // construction.
41
        FindRoutes func(value lnwire.MilliSatoshi) ([]*route.Route, error)
42

43
        // FetchChannelEdgesByID attempts to look up the two directed edges for
44
        // the channel identified by the channel ID.
45
        FetchChannelEdgesByID func(chanID uint64) (*models.ChannelEdgeInfo,
46
                *models.ChannelEdgePolicy, *models.ChannelEdgePolicy, error)
47

48
        // FetchOurOpenChannels fetches this node's set of open channels.
49
        FetchOurOpenChannels func() ([]*channeldb.OpenChannel, error)
50

51
        // BestHeight can be used to fetch the best block height that this node
52
        // is aware of.
53
        BestHeight func() (uint32, error)
54

55
        // AddPolicyBuffer is a function that can be used to alter the policy
56
        // values of the given channel edge. The main reason for doing this is
57
        // to add a safety buffer so that if the node makes small policy changes
58
        // during the lifetime of the blinded path, then the path remains valid
59
        // and so probing is more difficult. Note that this will only be called
60
        // for the policies of real nodes and won't be applied to
61
        // DefaultDummyHopPolicy.
62
        AddPolicyBuffer func(policy *BlindedHopPolicy) (*BlindedHopPolicy,
63
                error)
64

65
        // PathID is the secret data to embed in the blinded path data that we
66
        // will receive back as the recipient. This is the equivalent of the
67
        // payment address used in normal payments. It lets the recipient check
68
        // that the path is being used in the correct context.
69
        PathID []byte
70

71
        // ValueMsat is the payment amount in milli-satoshis that must be
72
        // routed. This will be used for selecting appropriate routes to use for
73
        // the blinded path.
74
        ValueMsat lnwire.MilliSatoshi
75

76
        // MinFinalCLTVExpiryDelta is the minimum CLTV delta that the recipient
77
        // requires for the final hop of the payment.
78
        //
79
        // NOTE that the caller is responsible for adding additional block
80
        // padding to this value to account for blocks being mined while the
81
        // payment is in-flight.
82
        MinFinalCLTVExpiryDelta uint32
83

84
        // BlocksUntilExpiry is the number of blocks that this blinded path
85
        // should remain valid for. This is a relative number of blocks. This
86
        // number in addition with a potential minimum cltv delta for the last
87
        // hop and some block padding will be the payment constraint which is
88
        // part of the blinded hop info. Every htlc using the provided blinded
89
        // hops cannot have a higher cltv delta otherwise it will get rejected
90
        // by the forwarding nodes or the final node.
91
        //
92
        // This number should at least be greater than the invoice expiry time
93
        // so that the blinded route is always valid as long as the invoice is
94
        // valid.
95
        BlocksUntilExpiry uint32
96

97
        // MinNumHops is the minimum number of hops that each blinded path
98
        // should be. If the number of hops in a path returned by FindRoutes is
99
        // less than this number, then dummy hops will be post-fixed to the
100
        // route.
101
        MinNumHops uint8
102

103
        // DefaultDummyHopPolicy holds the policy values that should be used for
104
        // dummy hops in the cases where it cannot be derived via other means
105
        // such as averaging the policy values of other hops on the path. This
106
        // would happen in the case where the introduction node is also the
107
        // introduction node. If these default policy values are used, then
108
        // the MaxHTLCMsat value must be carefully chosen.
109
        DefaultDummyHopPolicy *BlindedHopPolicy
110

111
        // MaxNumPaths is the maximum number of blinded paths to select.
112
        MaxNumPaths uint8
113
}
114

115
// BuildBlindedPaymentPaths uses the passed config to construct a set of blinded
116
// payment paths that can be added to the invoice.
117
func BuildBlindedPaymentPaths(cfg *BuildBlindedPathCfg) (
118
        []*zpay32.BlindedPaymentPath, error) {
3✔
119

3✔
120
        // Find some appropriate routes for the value to be routed. This will
3✔
121
        // return a set of routes made up of real nodes.
3✔
122
        routes, err := cfg.FindRoutes(cfg.ValueMsat)
3✔
123
        if err != nil {
6✔
124
                return nil, err
3✔
125
        }
3✔
126

127
        if len(routes) == 0 {
3✔
128
                return nil, fmt.Errorf("could not find any routes to self to " +
×
129
                        "use for blinded route construction")
×
130
        }
×
131

132
        // Not every route returned will necessarily result in a usable blinded
133
        // path and so the number of paths returned might be less than the
134
        // number of real routes returned by FindRoutes above.
135
        paths := make([]*zpay32.BlindedPaymentPath, 0, min(len(routes),
3✔
136
                int(cfg.MaxNumPaths)))
3✔
137

3✔
138
        // For each route returned, we will construct the associated blinded
3✔
139
        // payment path, until the maximum number of allowed paths is reached.
3✔
140
        for _, route := range routes {
6✔
141
                if len(paths) >= int(cfg.MaxNumPaths) {
3✔
NEW
142
                        break
×
143
                }
144

145
                // Extract the information we need from the route.
146
                candidatePath := extractCandidatePath(route)
3✔
147

3✔
148
                // Pad the given route with dummy hops until the minimum number
3✔
149
                // of hops is met.
3✔
150
                candidatePath.padWithDummyHops(cfg.MinNumHops)
3✔
151

3✔
152
                path, err := buildBlindedPaymentPath(cfg, candidatePath)
3✔
153
                if errors.Is(err, errInvalidBlindedPath) {
3✔
154
                        log.Debugf("Not using route (%s) as a blinded path "+
×
155
                                "since it resulted in an invalid blinded path",
×
156
                                route)
×
157

×
158
                        continue
×
159
                } else if err != nil {
3✔
UNCOV
160
                        log.Errorf("Not using route (%s) as a blinded path: %v",
×
UNCOV
161
                                route, err)
×
UNCOV
162

×
UNCOV
163
                        continue
×
164
                }
165

166
                log.Debugf("Route selected for blinded path: %s", candidatePath)
3✔
167

3✔
168
                paths = append(paths, path)
3✔
169
        }
170

171
        if len(paths) == 0 {
3✔
172
                return nil, fmt.Errorf("could not build any blinded paths")
×
173
        }
×
174

175
        return paths, nil
3✔
176
}
177

178
// buildBlindedPaymentPath takes a route from an introduction node to this node
179
// and uses the given config to convert it into a blinded payment path.
180
func buildBlindedPaymentPath(cfg *BuildBlindedPathCfg, path *candidatePath) (
181
        *zpay32.BlindedPaymentPath, error) {
3✔
182

3✔
183
        hops, minHTLC, maxHTLC, err := collectRelayInfo(cfg, path)
3✔
184
        if err != nil {
3✔
UNCOV
185
                return nil, fmt.Errorf("could not collect blinded path relay "+
×
UNCOV
186
                        "info: %w", err)
×
UNCOV
187
        }
×
188

189
        relayInfo := make([]*record.PaymentRelayInfo, len(hops))
3✔
190
        for i, hop := range hops {
6✔
191
                relayInfo[i] = hop.relayInfo
3✔
192
        }
3✔
193

194
        // Using the collected relay info, we can calculate the aggregated
195
        // policy values for the route.
196
        baseFee, feeRate, cltvDelta := calcBlindedPathPolicies(
3✔
197
                relayInfo, uint16(cfg.MinFinalCLTVExpiryDelta),
3✔
198
        )
3✔
199

3✔
200
        currentHeight, err := cfg.BestHeight()
3✔
201
        if err != nil {
3✔
202
                return nil, err
×
203
        }
×
204

205
        // The next step is to calculate the payment constraints to communicate
206
        // to each hop and to package up the hop info for each hop. We will
207
        // handle the final hop first since its payload looks a bit different,
208
        // and then we will iterate backwards through the remaining hops.
209
        //
210
        // Note that the +1 here is required because the route won't have the
211
        // introduction node included in the "Hops". But since we want to create
212
        // payloads for all the hops as well as the introduction node, we add 1
213
        // here to get the full hop length along with the introduction node.
214
        hopDataSet := make([]*hopData, 0, len(path.hops)+1)
3✔
215

3✔
216
        // Determine the maximum CLTV expiry for the destination node.
3✔
217
        cltvExpiry := currentHeight + cfg.BlocksUntilExpiry +
3✔
218
                cfg.MinFinalCLTVExpiryDelta
3✔
219

3✔
220
        constraints := &record.PaymentConstraints{
3✔
221
                MaxCltvExpiry:   cltvExpiry,
3✔
222
                HtlcMinimumMsat: minHTLC,
3✔
223
        }
3✔
224

3✔
225
        // If the blinded route has only a source node (introduction node) and
3✔
226
        // no hops, then the destination node is also the source node.
3✔
227
        finalHopPubKey := path.introNode
3✔
228
        if len(path.hops) > 0 {
6✔
229
                finalHopPubKey = path.hops[len(path.hops)-1].pubKey
3✔
230
        }
3✔
231

232
        // For the final hop, we only send it the path ID and payment
233
        // constraints.
234
        info, err := buildFinalHopRouteData(
3✔
235
                finalHopPubKey, cfg.PathID, constraints,
3✔
236
        )
3✔
237
        if err != nil {
3✔
238
                return nil, err
×
239
        }
×
240

241
        hopDataSet = append(hopDataSet, info)
3✔
242

3✔
243
        // Iterate through the remaining (non-final) hops, back to front.
3✔
244
        for i := len(hops) - 1; i >= 0; i-- {
6✔
245
                hop := hops[i]
3✔
246

3✔
247
                cltvExpiry += uint32(hop.relayInfo.CltvExpiryDelta)
3✔
248

3✔
249
                constraints = &record.PaymentConstraints{
3✔
250
                        MaxCltvExpiry:   cltvExpiry,
3✔
251
                        HtlcMinimumMsat: minHTLC,
3✔
252
                }
3✔
253

3✔
254
                var info *hopData
3✔
255
                if hop.nextHopIsDummy {
6✔
256
                        info, err = buildDummyRouteData(
3✔
257
                                hop.hopPubKey, hop.relayInfo, constraints,
3✔
258
                        )
3✔
259
                } else {
6✔
260
                        info, err = buildHopRouteData(
3✔
261
                                hop.hopPubKey, hop.nextSCID, hop.relayInfo,
3✔
262
                                constraints,
3✔
263
                        )
3✔
264
                }
3✔
265
                if err != nil {
3✔
266
                        return nil, err
×
267
                }
×
268

269
                hopDataSet = append(hopDataSet, info)
3✔
270
        }
271

272
        // Sort the hop info list in reverse order so that the data for the
273
        // introduction node is first.
274
        sort.Slice(hopDataSet, func(i, j int) bool {
6✔
275
                return j < i
3✔
276
        })
3✔
277

278
        // Add padding to each route data instance until the encrypted data
279
        // blobs are all the same size.
280
        paymentPath, _, err := padHopInfo(
3✔
281
                hopDataSet, true, record.AverageDummyHopPayloadSize,
3✔
282
        )
3✔
283
        if err != nil {
3✔
284
                return nil, err
×
285
        }
×
286

287
        // Derive an ephemeral session key.
288
        sessionKey, err := btcec.NewPrivateKey()
3✔
289
        if err != nil {
3✔
290
                return nil, err
×
291
        }
×
292

293
        // Encrypt the hop info.
294
        blindedPathInfo, err := sphinx.BuildBlindedPath(sessionKey, paymentPath)
3✔
295
        if err != nil {
3✔
296
                return nil, err
×
297
        }
×
298
        blindedPath := blindedPathInfo.Path
3✔
299

3✔
300
        if len(blindedPath.BlindedHops) < 1 {
3✔
301
                return nil, fmt.Errorf("blinded path must have at least one " +
×
302
                        "hop")
×
303
        }
×
304

305
        // Overwrite the introduction point's blinded pub key with the real
306
        // pub key since then we can use this more compact format in the
307
        // invoice without needing to encode the un-used blinded node pub key of
308
        // the intro node.
309
        blindedPath.BlindedHops[0].BlindedNodePub =
3✔
310
                blindedPath.IntroductionPoint
3✔
311

3✔
312
        // Now construct a z32 blinded path.
3✔
313
        return &zpay32.BlindedPaymentPath{
3✔
314
                FeeBaseMsat:                 uint32(baseFee),
3✔
315
                FeeRate:                     feeRate,
3✔
316
                CltvExpiryDelta:             cltvDelta,
3✔
317
                HTLCMinMsat:                 uint64(minHTLC),
3✔
318
                HTLCMaxMsat:                 uint64(maxHTLC),
3✔
319
                Features:                    lnwire.EmptyFeatureVector(),
3✔
320
                FirstEphemeralBlindingPoint: blindedPath.BlindingPoint,
3✔
321
                Hops:                        blindedPath.BlindedHops,
3✔
322
        }, nil
3✔
323
}
324

325
// hopRelayInfo packages together the relay info to send to hop on a blinded
326
// path along with the pub key of that hop and the SCID that the hop should
327
// forward the payment on to.
328
type hopRelayInfo struct {
329
        hopPubKey      route.Vertex
330
        nextSCID       lnwire.ShortChannelID
331
        relayInfo      *record.PaymentRelayInfo
332
        nextHopIsDummy bool
333
}
334

335
// collectRelayInfo collects the relay policy rules for each relay hop on the
336
// route and applies any policy buffers.
337
//
338
// For the blinded route:
339
//
340
//        C --chan(CB)--> B --chan(BA)--> A
341
//
342
// where C is the introduction node, the route.Route struct we are given will
343
// have SourcePubKey set to C's pub key, and then it will have the following
344
// route.Hops:
345
//
346
//   - PubKeyBytes: B, ChannelID: chan(CB)
347
//   - PubKeyBytes: A, ChannelID: chan(BA)
348
//
349
// We, however, want to collect the channel policies for the following PubKey
350
// and ChannelID pairs:
351
//
352
//   - PubKey: C, ChannelID: chan(CB)
353
//   - PubKey: B, ChannelID: chan(BA)
354
//
355
// Therefore, when we go through the route and its hops to collect policies, our
356
// index for collecting public keys will be trailing that of the channel IDs by
357
// 1.
358
//
359
// For any dummy hops on the route, this function also decides what to use as
360
// policy values for the dummy hops. If there are other real hops, then the
361
// dummy hop policy values are derived by taking the average of the real
362
// policy values. If there are no real hops (in other words we are the
363
// introduction node), then we use some default routing values and we use the
364
// average of our channel capacities for the MaxHTLC value.
365
func collectRelayInfo(cfg *BuildBlindedPathCfg, path *candidatePath) (
366
        []*hopRelayInfo, lnwire.MilliSatoshi, lnwire.MilliSatoshi, error) {
3✔
367

3✔
368
        var (
3✔
369
                // The first pub key is that of the introduction node.
3✔
370
                hopSource = path.introNode
3✔
371

3✔
372
                // A collection of the policy values of real hops on the path.
3✔
373
                policies = make(map[uint64]*BlindedHopPolicy)
3✔
374

3✔
375
                hasDummyHops bool
3✔
376
        )
3✔
377

3✔
378
        // On this first iteration, we just collect policy values of the real
3✔
379
        // hops on the path.
3✔
380
        for _, hop := range path.hops {
6✔
381
                // Once we have hit a dummy hop, all hops after will be dummy
3✔
382
                // hops too.
3✔
383
                if hop.isDummy {
6✔
384
                        hasDummyHops = true
3✔
385

3✔
386
                        break
3✔
387
                }
388

389
                // For real hops, retrieve the channel policy for this hop's
390
                // channel ID in the direction pointing away from the hopSource
391
                // node.
392
                policy, err := getNodeChannelPolicy(
3✔
393
                        cfg, hop.channelID, hopSource,
3✔
394
                )
3✔
395
                if err != nil {
3✔
UNCOV
396
                        return nil, 0, 0, err
×
UNCOV
397
                }
×
398

399
                policies[hop.channelID] = policy
3✔
400

3✔
401
                // This hop's pub key will be the policy creator for the next
3✔
402
                // hop.
3✔
403
                hopSource = hop.pubKey
3✔
404
        }
405

406
        var (
3✔
407
                dummyHopPolicy *BlindedHopPolicy
3✔
408
                err            error
3✔
409
        )
3✔
410

3✔
411
        // If the path does have dummy hops, we need to decide which policy
3✔
412
        // values to use for these hops.
3✔
413
        if hasDummyHops {
6✔
414
                dummyHopPolicy, err = computeDummyHopPolicy(
3✔
415
                        cfg.DefaultDummyHopPolicy, cfg.FetchOurOpenChannels,
3✔
416
                        policies,
3✔
417
                )
3✔
418
                if err != nil {
3✔
419
                        return nil, 0, 0, err
×
420
                }
×
421
        }
422

423
        // We iterate through the hops one more time. This time it is to
424
        // buffer the policy values, collect the payment relay info to send to
425
        // each hop, and to compute the min and max HTLC values for the path.
426
        var (
3✔
427
                hops    = make([]*hopRelayInfo, 0, len(path.hops))
3✔
428
                minHTLC lnwire.MilliSatoshi
3✔
429
                maxHTLC lnwire.MilliSatoshi
3✔
430
        )
3✔
431
        // The first pub key is that of the introduction node.
3✔
432
        hopSource = path.introNode
3✔
433
        for _, hop := range path.hops {
6✔
434
                var (
3✔
435
                        policy = dummyHopPolicy
3✔
436
                        ok     bool
3✔
437
                        err    error
3✔
438
                )
3✔
439

3✔
440
                if !hop.isDummy {
6✔
441
                        policy, ok = policies[hop.channelID]
3✔
442
                        if !ok {
3✔
443
                                return nil, 0, 0, fmt.Errorf("no cached "+
×
444
                                        "policy found for channel ID: %d",
×
445
                                        hop.channelID)
×
446
                        }
×
447
                }
448

449
                if policy.MinHTLCMsat > cfg.ValueMsat {
3✔
450
                        return nil, 0, 0, fmt.Errorf("%w: minHTLC of hop "+
×
451
                                "policy larger than payment amt: sentAmt(%v), "+
×
452
                                "minHTLC(%v)", errInvalidBlindedPath,
×
453
                                cfg.ValueMsat, policy.MinHTLCMsat)
×
454
                }
×
455

456
                bufferPolicy, err := cfg.AddPolicyBuffer(policy)
3✔
457
                if err != nil {
3✔
458
                        return nil, 0, 0, err
×
459
                }
×
460

461
                // We only use the new buffered policy if the new minHTLC value
462
                // does not violate the sender amount.
463
                //
464
                // NOTE: We don't check this for maxHTLC, because the payment
465
                // amount can always be splitted using MPP.
466
                if bufferPolicy.MinHTLCMsat <= cfg.ValueMsat {
6✔
467
                        policy = bufferPolicy
3✔
468
                }
3✔
469

470
                // If this is the first policy we are collecting, then use this
471
                // policy to set the base values for min/max htlc.
472
                if len(hops) == 0 {
6✔
473
                        minHTLC = policy.MinHTLCMsat
3✔
474
                        maxHTLC = policy.MaxHTLCMsat
3✔
475
                } else {
6✔
476
                        if policy.MinHTLCMsat > minHTLC {
3✔
477
                                minHTLC = policy.MinHTLCMsat
×
478
                        }
×
479

480
                        if policy.MaxHTLCMsat < maxHTLC {
3✔
481
                                maxHTLC = policy.MaxHTLCMsat
×
482
                        }
×
483
                }
484

485
                // From the policy values for this hop, we can collect the
486
                // payment relay info that we will send to this hop.
487
                hops = append(hops, &hopRelayInfo{
3✔
488
                        hopPubKey: hopSource,
3✔
489
                        nextSCID:  lnwire.NewShortChanIDFromInt(hop.channelID),
3✔
490
                        relayInfo: &record.PaymentRelayInfo{
3✔
491
                                FeeRate:         policy.FeeRate,
3✔
492
                                BaseFee:         policy.BaseFee,
3✔
493
                                CltvExpiryDelta: policy.CLTVExpiryDelta,
3✔
494
                        },
3✔
495
                        nextHopIsDummy: hop.isDummy,
3✔
496
                })
3✔
497

3✔
498
                // This hop's pub key will be the policy creator for the next
3✔
499
                // hop.
3✔
500
                hopSource = hop.pubKey
3✔
501
        }
502

503
        // It can happen that there is no HTLC-range overlap between the various
504
        // hops along the path. We return errInvalidBlindedPath to indicate that
505
        // this route was not usable
506
        if minHTLC > maxHTLC {
3✔
507
                return nil, 0, 0, fmt.Errorf("%w: resulting blinded path min "+
×
508
                        "HTLC value is larger than the resulting max HTLC "+
×
509
                        "value", errInvalidBlindedPath)
×
510
        }
×
511

512
        return hops, minHTLC, maxHTLC, nil
3✔
513
}
514

515
// buildDummyRouteData constructs the record.BlindedRouteData struct for the
516
// given a hop in a blinded route where the following hop is a dummy hop.
517
func buildDummyRouteData(node route.Vertex, relayInfo *record.PaymentRelayInfo,
518
        constraints *record.PaymentConstraints) (*hopData, error) {
3✔
519

3✔
520
        nodeID, err := btcec.ParsePubKey(node[:])
3✔
521
        if err != nil {
3✔
522
                return nil, err
×
523
        }
×
524

525
        return &hopData{
3✔
526
                data: record.NewDummyHopRouteData(
3✔
527
                        nodeID, *relayInfo, *constraints,
3✔
528
                ),
3✔
529
                nodeID: nodeID,
3✔
530
        }, nil
3✔
531
}
532

533
// computeDummyHopPolicy determines policy values to use for a dummy hop on a
534
// blinded path. If other real policy values exist, then we use the average of
535
// those values for the dummy hop policy values. Otherwise, in the case were
536
// there are no real policy values due to this node being the introduction node,
537
// we use the provided default policy values, and we get the average capacity of
538
// this node's channels to compute a MaxHTLC value.
539
func computeDummyHopPolicy(defaultPolicy *BlindedHopPolicy,
540
        fetchOurChannels func() ([]*channeldb.OpenChannel, error),
541
        policies map[uint64]*BlindedHopPolicy) (*BlindedHopPolicy, error) {
3✔
542

3✔
543
        numPolicies := len(policies)
3✔
544

3✔
545
        // If there are no real policies to calculate an average policy from,
3✔
546
        // then we use the default. The only thing we need to calculate here
3✔
547
        // though is the MaxHTLC value.
3✔
548
        if numPolicies == 0 {
6✔
549
                chans, err := fetchOurChannels()
3✔
550
                if err != nil {
3✔
551
                        return nil, err
×
552
                }
×
553

554
                if len(chans) == 0 {
3✔
555
                        return nil, fmt.Errorf("node has no channels to " +
×
556
                                "receive on")
×
557
                }
×
558

559
                // Calculate the average channel capacity and use this as the
560
                // MaxHTLC value.
561
                var maxHTLC btcutil.Amount
3✔
562
                for _, c := range chans {
6✔
563
                        maxHTLC += c.Capacity
3✔
564
                }
3✔
565

566
                maxHTLC = btcutil.Amount(float64(maxHTLC) / float64(len(chans)))
3✔
567

3✔
568
                return &BlindedHopPolicy{
3✔
569
                        CLTVExpiryDelta: defaultPolicy.CLTVExpiryDelta,
3✔
570
                        FeeRate:         defaultPolicy.FeeRate,
3✔
571
                        BaseFee:         defaultPolicy.BaseFee,
3✔
572
                        MinHTLCMsat:     defaultPolicy.MinHTLCMsat,
3✔
573
                        MaxHTLCMsat:     lnwire.NewMSatFromSatoshis(maxHTLC),
3✔
574
                }, nil
3✔
575
        }
576

577
        var avgPolicy BlindedHopPolicy
3✔
578

3✔
579
        for _, policy := range policies {
6✔
580
                avgPolicy.MinHTLCMsat += policy.MinHTLCMsat
3✔
581
                avgPolicy.MaxHTLCMsat += policy.MaxHTLCMsat
3✔
582
                avgPolicy.BaseFee += policy.BaseFee
3✔
583
                avgPolicy.FeeRate += policy.FeeRate
3✔
584
                avgPolicy.CLTVExpiryDelta += policy.CLTVExpiryDelta
3✔
585
        }
3✔
586

587
        avgPolicy.MinHTLCMsat = lnwire.MilliSatoshi(
3✔
588
                float64(avgPolicy.MinHTLCMsat) / float64(numPolicies),
3✔
589
        )
3✔
590
        avgPolicy.MaxHTLCMsat = lnwire.MilliSatoshi(
3✔
591
                float64(avgPolicy.MaxHTLCMsat) / float64(numPolicies),
3✔
592
        )
3✔
593
        avgPolicy.BaseFee = lnwire.MilliSatoshi(
3✔
594
                float64(avgPolicy.BaseFee) / float64(numPolicies),
3✔
595
        )
3✔
596
        avgPolicy.FeeRate = uint32(
3✔
597
                float64(avgPolicy.FeeRate) / float64(numPolicies),
3✔
598
        )
3✔
599
        avgPolicy.CLTVExpiryDelta = uint16(
3✔
600
                float64(avgPolicy.CLTVExpiryDelta) / float64(numPolicies),
3✔
601
        )
3✔
602

3✔
603
        return &avgPolicy, nil
3✔
604
}
605

606
// buildHopRouteData constructs the record.BlindedRouteData struct for the given
607
// non-final hop on a blinded path and packages it with the node's ID.
608
func buildHopRouteData(node route.Vertex, scid lnwire.ShortChannelID,
609
        relayInfo *record.PaymentRelayInfo,
610
        constraints *record.PaymentConstraints) (*hopData, error) {
3✔
611

3✔
612
        // Wrap up the data we want to send to this hop.
3✔
613
        blindedRouteHopData := record.NewNonFinalBlindedRouteData(
3✔
614
                scid, nil, *relayInfo, constraints, nil,
3✔
615
        )
3✔
616

3✔
617
        nodeID, err := btcec.ParsePubKey(node[:])
3✔
618
        if err != nil {
3✔
619
                return nil, err
×
620
        }
×
621

622
        return &hopData{
3✔
623
                data:   blindedRouteHopData,
3✔
624
                nodeID: nodeID,
3✔
625
        }, nil
3✔
626
}
627

628
// buildFinalHopRouteData constructs the record.BlindedRouteData struct for the
629
// final hop and packages it with the real node ID of the node it is intended
630
// for.
631
func buildFinalHopRouteData(node route.Vertex, pathID []byte,
632
        constraints *record.PaymentConstraints) (*hopData, error) {
3✔
633

3✔
634
        blindedRouteHopData := record.NewFinalHopBlindedRouteData(
3✔
635
                constraints, pathID,
3✔
636
        )
3✔
637
        nodeID, err := btcec.ParsePubKey(node[:])
3✔
638
        if err != nil {
3✔
639
                return nil, err
×
640
        }
×
641

642
        return &hopData{
3✔
643
                data:   blindedRouteHopData,
3✔
644
                nodeID: nodeID,
3✔
645
        }, nil
3✔
646
}
647

648
// getNodeChanPolicy fetches the routing policy info for the given channel and
649
// node pair.
650
func getNodeChannelPolicy(cfg *BuildBlindedPathCfg, chanID uint64,
651
        nodeID route.Vertex) (*BlindedHopPolicy, error) {
3✔
652

3✔
653
        // Attempt to fetch channel updates for the given channel. We will have
3✔
654
        // at most two updates for a given channel.
3✔
655
        _, update1, update2, err := cfg.FetchChannelEdgesByID(chanID)
3✔
656
        if err != nil {
3✔
UNCOV
657
                return nil, err
×
UNCOV
658
        }
×
659

660
        // Now we need to determine which of the updates was created by the
661
        // node in question. We know the update is the correct one if the
662
        // "ToNode" for the fetched policy is _not_ equal to the node ID in
663
        // question.
664
        var policy *models.ChannelEdgePolicy
3✔
665
        switch {
3✔
666
        case update1 != nil && !bytes.Equal(update1.ToNode[:], nodeID[:]):
3✔
667
                policy = update1
3✔
668

669
        case update2 != nil && !bytes.Equal(update2.ToNode[:], nodeID[:]):
3✔
670
                policy = update2
3✔
671

672
        default:
×
673
                return nil, fmt.Errorf("no channel updates found from node "+
×
674
                        "%s for channel %d", nodeID, chanID)
×
675
        }
676

677
        return &BlindedHopPolicy{
3✔
678
                CLTVExpiryDelta: policy.TimeLockDelta,
3✔
679
                FeeRate:         uint32(policy.FeeProportionalMillionths),
3✔
680
                BaseFee:         policy.FeeBaseMSat,
3✔
681
                MinHTLCMsat:     policy.MinHTLC,
3✔
682
                MaxHTLCMsat:     policy.MaxHTLC,
3✔
683
        }, nil
3✔
684
}
685

686
// candidatePath holds all the information about a route to this node that we
687
// need in order to build a blinded route.
688
type candidatePath struct {
689
        introNode   route.Vertex
690
        finalNodeID route.Vertex
691
        hops        []*blindedPathHop
692
}
693

694
// String returns a string representation of the candidatePath which can be
695
// useful for logging and debugging.
696
func (c *candidatePath) String() string {
3✔
697
        str := fmt.Sprintf("[%s (intro node)]", c.introNode)
3✔
698

3✔
699
        for _, hop := range c.hops {
6✔
700
                if hop.isDummy {
6✔
701
                        str += "--->[dummy hop]"
3✔
702
                        continue
3✔
703
                }
704

705
                str += fmt.Sprintf("--<%d>-->[%s]", hop.channelID, hop.pubKey)
3✔
706
        }
707

708
        return str
3✔
709
}
710

711
// padWithDummyHops will append n dummy hops to the candidatePath hop set. The
712
// pub key for the dummy hop will be the same as the pub key for the final hop
713
// of the path. That way, the final hop will be able to decrypt the data
714
// encrypted for each dummy hop.
715
func (c *candidatePath) padWithDummyHops(n uint8) {
3✔
716
        for len(c.hops) < int(n) {
6✔
717
                c.hops = append(c.hops, &blindedPathHop{
3✔
718
                        pubKey:  c.finalNodeID,
3✔
719
                        isDummy: true,
3✔
720
                })
3✔
721
        }
3✔
722
}
723

724
// blindedPathHop holds the information we need to know about a hop in a route
725
// in order to use it in the construction of a blinded path.
726
type blindedPathHop struct {
727
        // pubKey is the real pub key of a node on a blinded path.
728
        pubKey route.Vertex
729

730
        // channelID is the channel along which the previous hop should forward
731
        // their HTLC in order to reach this hop.
732
        channelID uint64
733

734
        // isDummy is true if this hop is an appended dummy hop.
735
        isDummy bool
736
}
737

738
// extractCandidatePath extracts the data it needs from the given route.Route in
739
// order to construct a candidatePath.
740
func extractCandidatePath(path *route.Route) *candidatePath {
3✔
741
        var (
3✔
742
                hops      = make([]*blindedPathHop, len(path.Hops))
3✔
743
                finalNode = path.SourcePubKey
3✔
744
        )
3✔
745
        for i, hop := range path.Hops {
6✔
746
                hops[i] = &blindedPathHop{
3✔
747
                        pubKey:    hop.PubKeyBytes,
3✔
748
                        channelID: hop.ChannelID,
3✔
749
                }
3✔
750

3✔
751
                if i == len(path.Hops)-1 {
6✔
752
                        finalNode = hop.PubKeyBytes
3✔
753
                }
3✔
754
        }
755

756
        return &candidatePath{
3✔
757
                introNode:   path.SourcePubKey,
3✔
758
                finalNodeID: finalNode,
3✔
759
                hops:        hops,
3✔
760
        }
3✔
761
}
762

763
// BlindedHopPolicy holds the set of relay policy values to use for a channel
764
// in a blinded path.
765
type BlindedHopPolicy struct {
766
        CLTVExpiryDelta uint16
767
        FeeRate         uint32
768
        BaseFee         lnwire.MilliSatoshi
769
        MinHTLCMsat     lnwire.MilliSatoshi
770
        MaxHTLCMsat     lnwire.MilliSatoshi
771
}
772

773
// AddPolicyBuffer constructs the bufferedChanPolicies for a path hop by taking
774
// its actual policy values and multiplying them by the given multipliers.
775
// The base fee, fee rate and minimum HTLC msat values are adjusted via the
776
// incMultiplier while the maximum HTLC msat value is adjusted via the
777
// decMultiplier. If adjustments of the HTLC values no longer make sense
778
// then the original HTLC value is used.
779
func AddPolicyBuffer(policy *BlindedHopPolicy, incMultiplier,
780
        decMultiplier float64) (*BlindedHopPolicy, error) {
3✔
781

3✔
782
        if incMultiplier < 1 {
3✔
UNCOV
783
                return nil, fmt.Errorf("blinded path policy increase " +
×
UNCOV
784
                        "multiplier must be greater than or equal to 1")
×
UNCOV
785
        }
×
786

787
        if decMultiplier < 0 || decMultiplier > 1 {
3✔
UNCOV
788
                return nil, fmt.Errorf("blinded path policy decrease " +
×
UNCOV
789
                        "multiplier must be in the range [0;1]")
×
UNCOV
790
        }
×
791

792
        var (
3✔
793
                minHTLCMsat = lnwire.MilliSatoshi(
3✔
794
                        float64(policy.MinHTLCMsat) * incMultiplier,
3✔
795
                )
3✔
796
                maxHTLCMsat = lnwire.MilliSatoshi(
3✔
797
                        float64(policy.MaxHTLCMsat) * decMultiplier,
3✔
798
                )
3✔
799
        )
3✔
800

3✔
801
        // Make sure the new minimum is not more than the original maximum.
3✔
802
        // If it is, then just stick to the original minimum.
3✔
803
        if minHTLCMsat > policy.MaxHTLCMsat {
3✔
UNCOV
804
                minHTLCMsat = policy.MinHTLCMsat
×
UNCOV
805
        }
×
806

807
        // Make sure the new maximum is not less than the original minimum.
808
        // If it is, then just stick to the original maximum.
809
        if maxHTLCMsat < policy.MinHTLCMsat {
3✔
UNCOV
810
                maxHTLCMsat = policy.MaxHTLCMsat
×
UNCOV
811
        }
×
812

813
        // Also ensure that the new htlc bounds make sense. If the new minimum
814
        // is greater than the new maximum, then just let both to their original
815
        // values.
816
        if minHTLCMsat > maxHTLCMsat {
3✔
UNCOV
817
                minHTLCMsat = policy.MinHTLCMsat
×
UNCOV
818
                maxHTLCMsat = policy.MaxHTLCMsat
×
UNCOV
819
        }
×
820

821
        return &BlindedHopPolicy{
3✔
822
                CLTVExpiryDelta: uint16(
3✔
823
                        float64(policy.CLTVExpiryDelta) * incMultiplier,
3✔
824
                ),
3✔
825
                FeeRate: uint32(
3✔
826
                        float64(policy.FeeRate) * incMultiplier,
3✔
827
                ),
3✔
828
                BaseFee: lnwire.MilliSatoshi(
3✔
829
                        float64(policy.BaseFee) * incMultiplier,
3✔
830
                ),
3✔
831
                MinHTLCMsat: minHTLCMsat,
3✔
832
                MaxHTLCMsat: maxHTLCMsat,
3✔
833
        }, nil
3✔
834
}
835

836
// calcBlindedPathPolicies computes the accumulated policy values for the path.
837
// These values include the total base fee, the total proportional fee and the
838
// total CLTV delta. This function assumes that all the passed relay infos have
839
// already been adjusted with a buffer to account for easy probing attacks.
840
func calcBlindedPathPolicies(relayInfo []*record.PaymentRelayInfo,
841
        ourMinFinalCLTVDelta uint16) (lnwire.MilliSatoshi, uint32, uint16) {
3✔
842

3✔
843
        var (
3✔
844
                totalFeeBase lnwire.MilliSatoshi
3✔
845
                totalFeeProp uint32
3✔
846
                totalCLTV    = ourMinFinalCLTVDelta
3✔
847
        )
3✔
848
        // Use the algorithms defined in BOLT 4 to calculate the accumulated
3✔
849
        // relay fees for the route:
3✔
850
        //nolint:ll
3✔
851
        // https://github.com/lightning/bolts/blob/db278ab9b2baa0b30cfe79fb3de39280595938d3/04-onion-routing.md?plain=1#L255
3✔
852
        for i := len(relayInfo) - 1; i >= 0; i-- {
6✔
853
                info := relayInfo[i]
3✔
854

3✔
855
                totalFeeBase = calcNextTotalBaseFee(
3✔
856
                        totalFeeBase, info.BaseFee, info.FeeRate,
3✔
857
                )
3✔
858

3✔
859
                totalFeeProp = calcNextTotalFeeRate(totalFeeProp, info.FeeRate)
3✔
860

3✔
861
                totalCLTV += info.CltvExpiryDelta
3✔
862
        }
3✔
863

864
        return totalFeeBase, totalFeeProp, totalCLTV
3✔
865
}
866

867
// calcNextTotalBaseFee takes the current total accumulated base fee of a
868
// blinded path at hop `n` along with the fee rate and base fee of the hop at
869
// `n+1` and uses these to calculate the accumulated base fee at hop `n+1`.
870
func calcNextTotalBaseFee(currentTotal, hopBaseFee lnwire.MilliSatoshi,
871
        hopFeeRate uint32) lnwire.MilliSatoshi {
3✔
872

3✔
873
        numerator := (uint32(hopBaseFee) * oneMillion) +
3✔
874
                (uint32(currentTotal) * (oneMillion + hopFeeRate)) +
3✔
875
                oneMillion - 1
3✔
876

3✔
877
        return lnwire.MilliSatoshi(numerator / oneMillion)
3✔
878
}
3✔
879

880
// calculateNextTotalFeeRate takes the current total accumulated fee rate of a
881
// blinded path at hop `n` along with the fee rate of the hop at `n+1` and uses
882
// these to calculate the accumulated fee rate at hop `n+1`.
883
func calcNextTotalFeeRate(currentTotal, hopFeeRate uint32) uint32 {
3✔
884
        numerator := (currentTotal+hopFeeRate)*oneMillion +
3✔
885
                currentTotal*hopFeeRate + oneMillion - 1
3✔
886

3✔
887
        return numerator / oneMillion
3✔
888
}
3✔
889

890
// hopData packages the record.BlindedRouteData for a hop on a blinded path with
891
// the real node ID of that hop.
892
type hopData struct {
893
        data   *record.BlindedRouteData
894
        nodeID *btcec.PublicKey
895
}
896

897
// padStats can be used to keep track of various pieces of data that we collect
898
// during a call to padHopInfo. This is useful for logging and for test
899
// assertions.
900
type padStats struct {
901
        minPayloadSize  int
902
        maxPayloadSize  int
903
        finalPaddedSize int
904
        numIterations   int
905
}
906

907
// padHopInfo iterates over a set of record.BlindedRouteData and adds padding
908
// where needed until the resulting encrypted data blobs are all the same size.
909
// This may take a few iterations due to the fact that a TLV field is used to
910
// add this padding. For example, if we want to add a 1 byte padding to a
911
// record.BlindedRouteData when it does not yet have any padding, then adding
912
// a 1 byte padding will actually add 3 bytes due to the bytes required when
913
// adding the initial type and length bytes. However, on the next iteration if
914
// we again add just 1 byte, then only a single byte will be added. The same
915
// iteration is required for padding values on the BigSize encoding bucket
916
// edges. The number of iterations that this function takes is also returned for
917
// testing purposes. If prePad is true, then zero byte padding is added to each
918
// payload that does not yet have padding. This will save some iterations for
919
// the majority of cases. minSize can be used to specify a minimum size that all
920
// payloads should be.
921
func padHopInfo(hopInfo []*hopData, prePad bool, minSize int) (
922
        []*sphinx.HopInfo, *padStats, error) {
3✔
923

3✔
924
        var (
3✔
925
                paymentPath = make([]*sphinx.HopInfo, len(hopInfo))
3✔
926
                stats       = padStats{finalPaddedSize: minSize}
3✔
927
        )
3✔
928

3✔
929
        // Pre-pad each payload with zero byte padding (if it does not yet have
3✔
930
        // padding) to save a couple of iterations in the majority of cases.
3✔
931
        if prePad {
6✔
932
                for _, info := range hopInfo {
6✔
933
                        if info.data.Padding.IsSome() {
3✔
934
                                continue
×
935
                        }
936

937
                        info.data.PadBy(0)
3✔
938
                }
939
        }
940

941
        for {
6✔
942
                stats.numIterations++
3✔
943

3✔
944
                // On each iteration of the loop, we first determine the
3✔
945
                // current largest encoded data blob size. This will be the
3✔
946
                // size we aim to get the others to match.
3✔
947
                var (
3✔
948
                        maxLen = minSize
3✔
949
                        minLen = math.MaxInt8
3✔
950
                )
3✔
951
                for i, hop := range hopInfo {
6✔
952
                        plainText, err := record.EncodeBlindedRouteData(
3✔
953
                                hop.data,
3✔
954
                        )
3✔
955
                        if err != nil {
3✔
956
                                return nil, nil, err
×
957
                        }
×
958

959
                        if len(plainText) > maxLen {
6✔
960
                                maxLen = len(plainText)
3✔
961

3✔
962
                                // Update the stats to take note of this new
3✔
963
                                // max since this may be the final max that all
3✔
964
                                // payloads will be padded to.
3✔
965
                                stats.finalPaddedSize = maxLen
3✔
966
                        }
3✔
967
                        if len(plainText) < minLen {
6✔
968
                                minLen = len(plainText)
3✔
969
                        }
3✔
970

971
                        paymentPath[i] = &sphinx.HopInfo{
3✔
972
                                NodePub:   hop.nodeID,
3✔
973
                                PlainText: plainText,
3✔
974
                        }
3✔
975
                }
976

977
                // If this is our first iteration, then we take note of the min
978
                // and max lengths of the payloads pre-padding for logging
979
                // later.
980
                if stats.numIterations == 1 {
6✔
981
                        stats.minPayloadSize = minLen
3✔
982
                        stats.maxPayloadSize = maxLen
3✔
983
                }
3✔
984

985
                // Now we iterate over them again and determine which ones we
986
                // need to add padding to.
987
                var numEqual int
3✔
988
                for i, hop := range hopInfo {
6✔
989
                        plainText := paymentPath[i].PlainText
3✔
990

3✔
991
                        // If the plaintext length is equal to the desired
3✔
992
                        // length, then we can continue. We use numEqual to
3✔
993
                        // keep track of how many have the same length.
3✔
994
                        if len(plainText) == maxLen {
6✔
995
                                numEqual++
3✔
996

3✔
997
                                continue
3✔
998
                        }
999

1000
                        // If we previously added padding to this hop, we keep
1001
                        // the length of that initial padding too.
1002
                        var existingPadding int
3✔
1003
                        hop.data.Padding.WhenSome(
3✔
1004
                                func(p tlv.RecordT[tlv.TlvType1, []byte]) {
6✔
1005
                                        existingPadding = len(p.Val)
3✔
1006
                                },
3✔
1007
                        )
1008

1009
                        // Add some padding bytes to the hop.
1010
                        hop.data.PadBy(
3✔
1011
                                existingPadding + maxLen - len(plainText),
3✔
1012
                        )
3✔
1013
                }
1014

1015
                // If all the payloads have the same length, we can exit the
1016
                // loop.
1017
                if numEqual == len(hopInfo) {
6✔
1018
                        break
3✔
1019
                }
1020
        }
1021

1022
        log.Debugf("Finished padding %d blinded path payloads to %d bytes "+
3✔
1023
                "each where the pre-padded min and max sizes were %d and %d "+
3✔
1024
                "bytes respectively", len(hopInfo), stats.finalPaddedSize,
3✔
1025
                stats.minPayloadSize, stats.maxPayloadSize)
3✔
1026

3✔
1027
        return paymentPath, &stats, nil
3✔
1028
}
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