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

lightningnetwork / lnd / 13907742068

17 Mar 2025 07:03PM UTC coverage: 58.307% (-0.008%) from 58.315%
13907742068

Pull #9334

github

web-flow
Merge 1b389e91e into 053d63e11
Pull Request #9334: Use all valid routes during blinded path construction

103 of 117 new or added lines in 4 files covered. (88.03%)

49 existing lines in 12 files now uncovered.

94796 of 162581 relevant lines covered (58.31%)

1.81 hits per line

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

84.48
/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
        // Routes to be used for the construction of blinded paths. These routes
36
        // will consist of real nodes advertising the route blinding feature
37
        // bit. They may be of various lengths and may even contain only a
38
        // single hop. Any route shorter than MinNumHops will be padded with
39
        //  dummy hops during route construction.
40
        Routes []*route.Route
41

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

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

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

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

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

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

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

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

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

102
        // MaxNumPaths is the maximum number of blinded paths to select.
103
        MaxNumPaths uint8
104

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

114
// BlindedHop holds the information about a hop we have selected for a blinded
115
// path.
116
type BlindedHop struct {
117
        Vertex       route.Vertex
118
        ChannelID    uint64
119
        EdgeCapacity btcutil.Amount
120
}
121

122
// BuildBlindedPaymentPaths uses the passed config to construct a set of blinded
123
// payment paths that can be added to the invoice.
124
func BuildBlindedPaymentPaths(cfg *BuildBlindedPathCfg) (
125
        []*zpay32.BlindedPaymentPath, error) {
3✔
126

3✔
127
        if len(cfg.Routes) == 0 {
3✔
UNCOV
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(cfg.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 cfg.Routes {
6✔
141
                if len(paths) >= int(cfg.MaxNumPaths) {
3✔
NEW
142
                        break
×
143
                }
144
                // Extract the information we need from the route.
145
                candidatePath := extractCandidatePath(route)
3✔
146

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

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

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

×
162
                        continue
×
163
                }
164

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

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

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

174
        return paths, nil
3✔
175
}
176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
373
                hasDummyHops bool
3✔
374
        )
3✔
375

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

3✔
384
                        break
3✔
385
                }
386

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

397
                policies[hop.channelID] = policy
3✔
398

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

404
        var (
3✔
405
                dummyHopPolicy *BlindedHopPolicy
3✔
406
                err            error
3✔
407
        )
3✔
408

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

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

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

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

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

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

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

478
                        if policy.MaxHTLCMsat < maxHTLC {
3✔
479
                                maxHTLC = policy.MaxHTLCMsat
×
480
                        }
×
481
                }
482

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

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

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

510
        return hops, minHTLC, maxHTLC, nil
3✔
511
}
512

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

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

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

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

3✔
541
        numPolicies := len(policies)
3✔
542

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

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

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

564
                maxHTLC = btcutil.Amount(float64(maxHTLC) / float64(len(chans)))
3✔
565

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

575
        var avgPolicy BlindedHopPolicy
3✔
576

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

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

3✔
601
        return &avgPolicy, nil
3✔
602
}
603

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

706
        return str
3✔
707
}
708

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

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

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

732
        // isDummy is true if this hop is an appended dummy hop.
733
        isDummy bool
734
}
735

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
853
                totalFeeBase = calcNextTotalBaseFee(
3✔
854
                        totalFeeBase, info.BaseFee, info.FeeRate,
3✔
855
                )
3✔
856

3✔
857
                totalFeeProp = calcNextTotalFeeRate(totalFeeProp, info.FeeRate)
3✔
858

3✔
859
                totalCLTV += info.CltvExpiryDelta
3✔
860
        }
3✔
861

862
        return totalFeeBase, totalFeeProp, totalCLTV
3✔
863
}
864

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

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

3✔
875
        return lnwire.MilliSatoshi(numerator / oneMillion)
3✔
876
}
3✔
877

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

3✔
885
        return numerator / oneMillion
3✔
886
}
3✔
887

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

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

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

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

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

935
                        info.data.PadBy(0)
3✔
936
                }
937
        }
938

939
        for {
6✔
940
                stats.numIterations++
3✔
941

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

957
                        if len(plainText) > maxLen {
6✔
958
                                maxLen = len(plainText)
3✔
959

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

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

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

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

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

3✔
995
                                continue
3✔
996
                        }
997

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

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

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

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

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