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

lightningnetwork / lnd / 15838907453

24 Jun 2025 01:26AM UTC coverage: 57.079% (-11.1%) from 68.172%
15838907453

Pull #9982

github

web-flow
Merge e42780be2 into 45c15646c
Pull Request #9982: lnwire+lnwallet: add LocalNonces field for splice nonce coordination w/ taproot channels

103 of 167 new or added lines in 5 files covered. (61.68%)

30191 existing lines in 463 files now uncovered.

96331 of 168768 relevant lines covered (57.08%)

0.6 hits per line

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

84.82
/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

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

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

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

129
        // Not every route returned will necessarily result in a usable blinded
130
        // path and so the number of paths returned might be less than the
131
        // number of real routes returned by FindRoutes above.
132
        paths := make([]*zpay32.BlindedPaymentPath, 0, len(routes))
1✔
133

1✔
134
        // For each route returned, we will construct the associated blinded
1✔
135
        // payment path.
1✔
136
        for _, route := range routes {
2✔
137
                // Extract the information we need from the route.
1✔
138
                candidatePath := extractCandidatePath(route)
1✔
139

1✔
140
                // Pad the given route with dummy hops until the minimum number
1✔
141
                // of hops is met.
1✔
142
                candidatePath.padWithDummyHops(cfg.MinNumHops)
1✔
143

1✔
144
                path, err := buildBlindedPaymentPath(cfg, candidatePath)
1✔
145
                if errors.Is(err, errInvalidBlindedPath) {
1✔
146
                        log.Debugf("Not using route (%s) as a blinded path "+
×
147
                                "since it resulted in an invalid blinded path",
×
148
                                route)
×
149

×
150
                        continue
×
151
                } else if err != nil {
1✔
UNCOV
152
                        log.Errorf("Not using route (%s) as a blinded path: %v",
×
UNCOV
153
                                route, err)
×
UNCOV
154

×
UNCOV
155
                        continue
×
156
                }
157

158
                log.Debugf("Route selected for blinded path: %s", candidatePath)
1✔
159

1✔
160
                paths = append(paths, path)
1✔
161
        }
162

163
        if len(paths) == 0 {
1✔
164
                return nil, fmt.Errorf("could not build any blinded paths")
×
165
        }
×
166

167
        return paths, nil
1✔
168
}
169

170
// buildBlindedPaymentPath takes a route from an introduction node to this node
171
// and uses the given config to convert it into a blinded payment path.
172
func buildBlindedPaymentPath(cfg *BuildBlindedPathCfg, path *candidatePath) (
173
        *zpay32.BlindedPaymentPath, error) {
1✔
174

1✔
175
        hops, minHTLC, maxHTLC, err := collectRelayInfo(cfg, path)
1✔
176
        if err != nil {
1✔
UNCOV
177
                return nil, fmt.Errorf("could not collect blinded path relay "+
×
UNCOV
178
                        "info: %w", err)
×
UNCOV
179
        }
×
180

181
        relayInfo := make([]*record.PaymentRelayInfo, len(hops))
1✔
182
        for i, hop := range hops {
2✔
183
                relayInfo[i] = hop.relayInfo
1✔
184
        }
1✔
185

186
        // Using the collected relay info, we can calculate the aggregated
187
        // policy values for the route.
188
        baseFee, feeRate, cltvDelta := calcBlindedPathPolicies(
1✔
189
                relayInfo, uint16(cfg.MinFinalCLTVExpiryDelta),
1✔
190
        )
1✔
191

1✔
192
        currentHeight, err := cfg.BestHeight()
1✔
193
        if err != nil {
1✔
194
                return nil, err
×
195
        }
×
196

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

1✔
208
        // Determine the maximum CLTV expiry for the destination node.
1✔
209
        cltvExpiry := currentHeight + cfg.BlocksUntilExpiry +
1✔
210
                cfg.MinFinalCLTVExpiryDelta
1✔
211

1✔
212
        constraints := &record.PaymentConstraints{
1✔
213
                MaxCltvExpiry:   cltvExpiry,
1✔
214
                HtlcMinimumMsat: minHTLC,
1✔
215
        }
1✔
216

1✔
217
        // If the blinded route has only a source node (introduction node) and
1✔
218
        // no hops, then the destination node is also the source node.
1✔
219
        finalHopPubKey := path.introNode
1✔
220
        if len(path.hops) > 0 {
2✔
221
                finalHopPubKey = path.hops[len(path.hops)-1].pubKey
1✔
222
        }
1✔
223

224
        // For the final hop, we only send it the path ID and payment
225
        // constraints.
226
        info, err := buildFinalHopRouteData(
1✔
227
                finalHopPubKey, cfg.PathID, constraints,
1✔
228
        )
1✔
229
        if err != nil {
1✔
230
                return nil, err
×
231
        }
×
232

233
        hopDataSet = append(hopDataSet, info)
1✔
234

1✔
235
        // Iterate through the remaining (non-final) hops, back to front.
1✔
236
        for i := len(hops) - 1; i >= 0; i-- {
2✔
237
                hop := hops[i]
1✔
238

1✔
239
                cltvExpiry += uint32(hop.relayInfo.CltvExpiryDelta)
1✔
240

1✔
241
                constraints = &record.PaymentConstraints{
1✔
242
                        MaxCltvExpiry:   cltvExpiry,
1✔
243
                        HtlcMinimumMsat: minHTLC,
1✔
244
                }
1✔
245

1✔
246
                var info *hopData
1✔
247
                if hop.nextHopIsDummy {
2✔
248
                        info, err = buildDummyRouteData(
1✔
249
                                hop.hopPubKey, hop.relayInfo, constraints,
1✔
250
                        )
1✔
251
                } else {
2✔
252
                        info, err = buildHopRouteData(
1✔
253
                                hop.hopPubKey, hop.nextSCID, hop.relayInfo,
1✔
254
                                constraints,
1✔
255
                        )
1✔
256
                }
1✔
257
                if err != nil {
1✔
258
                        return nil, err
×
259
                }
×
260

261
                hopDataSet = append(hopDataSet, info)
1✔
262
        }
263

264
        // Sort the hop info list in reverse order so that the data for the
265
        // introduction node is first.
266
        sort.Slice(hopDataSet, func(i, j int) bool {
2✔
267
                return j < i
1✔
268
        })
1✔
269

270
        // Add padding to each route data instance until the encrypted data
271
        // blobs are all the same size.
272
        paymentPath, _, err := padHopInfo(
1✔
273
                hopDataSet, true, record.AverageDummyHopPayloadSize,
1✔
274
        )
1✔
275
        if err != nil {
1✔
276
                return nil, err
×
277
        }
×
278

279
        // Derive an ephemeral session key.
280
        sessionKey, err := btcec.NewPrivateKey()
1✔
281
        if err != nil {
1✔
282
                return nil, err
×
283
        }
×
284

285
        // Encrypt the hop info.
286
        blindedPathInfo, err := sphinx.BuildBlindedPath(sessionKey, paymentPath)
1✔
287
        if err != nil {
1✔
288
                return nil, err
×
289
        }
×
290
        blindedPath := blindedPathInfo.Path
1✔
291

1✔
292
        if len(blindedPath.BlindedHops) < 1 {
1✔
293
                return nil, fmt.Errorf("blinded path must have at least one " +
×
294
                        "hop")
×
295
        }
×
296

297
        // Overwrite the introduction point's blinded pub key with the real
298
        // pub key since then we can use this more compact format in the
299
        // invoice without needing to encode the un-used blinded node pub key of
300
        // the intro node.
301
        blindedPath.BlindedHops[0].BlindedNodePub =
1✔
302
                blindedPath.IntroductionPoint
1✔
303

1✔
304
        // Now construct a z32 blinded path.
1✔
305
        return &zpay32.BlindedPaymentPath{
1✔
306
                FeeBaseMsat:                 uint32(baseFee),
1✔
307
                FeeRate:                     feeRate,
1✔
308
                CltvExpiryDelta:             cltvDelta,
1✔
309
                HTLCMinMsat:                 uint64(minHTLC),
1✔
310
                HTLCMaxMsat:                 uint64(maxHTLC),
1✔
311
                Features:                    lnwire.EmptyFeatureVector(),
1✔
312
                FirstEphemeralBlindingPoint: blindedPath.BlindingPoint,
1✔
313
                Hops:                        blindedPath.BlindedHops,
1✔
314
        }, nil
1✔
315
}
316

317
// hopRelayInfo packages together the relay info to send to hop on a blinded
318
// path along with the pub key of that hop and the SCID that the hop should
319
// forward the payment on to.
320
type hopRelayInfo struct {
321
        hopPubKey      route.Vertex
322
        nextSCID       lnwire.ShortChannelID
323
        relayInfo      *record.PaymentRelayInfo
324
        nextHopIsDummy bool
325
}
326

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

1✔
360
        var (
1✔
361
                // The first pub key is that of the introduction node.
1✔
362
                hopSource = path.introNode
1✔
363

1✔
364
                // A collection of the policy values of real hops on the path.
1✔
365
                policies = make(map[uint64]*BlindedHopPolicy)
1✔
366

1✔
367
                hasDummyHops bool
1✔
368
        )
1✔
369

1✔
370
        // On this first iteration, we just collect policy values of the real
1✔
371
        // hops on the path.
1✔
372
        for _, hop := range path.hops {
2✔
373
                // Once we have hit a dummy hop, all hops after will be dummy
1✔
374
                // hops too.
1✔
375
                if hop.isDummy {
2✔
376
                        hasDummyHops = true
1✔
377

1✔
378
                        break
1✔
379
                }
380

381
                // For real hops, retrieve the channel policy for this hop's
382
                // channel ID in the direction pointing away from the hopSource
383
                // node.
384
                policy, err := getNodeChannelPolicy(
1✔
385
                        cfg, hop.channelID, hopSource,
1✔
386
                )
1✔
387
                if err != nil {
1✔
UNCOV
388
                        return nil, 0, 0, err
×
UNCOV
389
                }
×
390

391
                policies[hop.channelID] = policy
1✔
392

1✔
393
                // This hop's pub key will be the policy creator for the next
1✔
394
                // hop.
1✔
395
                hopSource = hop.pubKey
1✔
396
        }
397

398
        var (
1✔
399
                dummyHopPolicy *BlindedHopPolicy
1✔
400
                err            error
1✔
401
        )
1✔
402

1✔
403
        // If the path does have dummy hops, we need to decide which policy
1✔
404
        // values to use for these hops.
1✔
405
        if hasDummyHops {
2✔
406
                dummyHopPolicy, err = computeDummyHopPolicy(
1✔
407
                        cfg.DefaultDummyHopPolicy, cfg.FetchOurOpenChannels,
1✔
408
                        policies,
1✔
409
                )
1✔
410
                if err != nil {
1✔
411
                        return nil, 0, 0, err
×
412
                }
×
413
        }
414

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

1✔
432
                if !hop.isDummy {
2✔
433
                        policy, ok = policies[hop.channelID]
1✔
434
                        if !ok {
1✔
435
                                return nil, 0, 0, fmt.Errorf("no cached "+
×
436
                                        "policy found for channel ID: %d",
×
437
                                        hop.channelID)
×
438
                        }
×
439
                }
440

441
                if policy.MinHTLCMsat > cfg.ValueMsat {
1✔
442
                        return nil, 0, 0, fmt.Errorf("%w: minHTLC of hop "+
×
443
                                "policy larger than payment amt: sentAmt(%v), "+
×
444
                                "minHTLC(%v)", errInvalidBlindedPath,
×
445
                                cfg.ValueMsat, policy.MinHTLCMsat)
×
446
                }
×
447

448
                bufferPolicy, err := cfg.AddPolicyBuffer(policy)
1✔
449
                if err != nil {
1✔
450
                        return nil, 0, 0, err
×
451
                }
×
452

453
                // We only use the new buffered policy if the new minHTLC value
454
                // does not violate the sender amount.
455
                //
456
                // NOTE: We don't check this for maxHTLC, because the payment
457
                // amount can always be splitted using MPP.
458
                if bufferPolicy.MinHTLCMsat <= cfg.ValueMsat {
2✔
459
                        policy = bufferPolicy
1✔
460
                }
1✔
461

462
                // If this is the first policy we are collecting, then use this
463
                // policy to set the base values for min/max htlc.
464
                if len(hops) == 0 {
2✔
465
                        minHTLC = policy.MinHTLCMsat
1✔
466
                        maxHTLC = policy.MaxHTLCMsat
1✔
467
                } else {
2✔
468
                        if policy.MinHTLCMsat > minHTLC {
1✔
469
                                minHTLC = policy.MinHTLCMsat
×
470
                        }
×
471

472
                        if policy.MaxHTLCMsat < maxHTLC {
1✔
473
                                maxHTLC = policy.MaxHTLCMsat
×
474
                        }
×
475
                }
476

477
                // From the policy values for this hop, we can collect the
478
                // payment relay info that we will send to this hop.
479
                hops = append(hops, &hopRelayInfo{
1✔
480
                        hopPubKey: hopSource,
1✔
481
                        nextSCID:  lnwire.NewShortChanIDFromInt(hop.channelID),
1✔
482
                        relayInfo: &record.PaymentRelayInfo{
1✔
483
                                FeeRate:         policy.FeeRate,
1✔
484
                                BaseFee:         policy.BaseFee,
1✔
485
                                CltvExpiryDelta: policy.CLTVExpiryDelta,
1✔
486
                        },
1✔
487
                        nextHopIsDummy: hop.isDummy,
1✔
488
                })
1✔
489

1✔
490
                // This hop's pub key will be the policy creator for the next
1✔
491
                // hop.
1✔
492
                hopSource = hop.pubKey
1✔
493
        }
494

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

504
        return hops, minHTLC, maxHTLC, nil
1✔
505
}
506

507
// buildDummyRouteData constructs the record.BlindedRouteData struct for the
508
// given a hop in a blinded route where the following hop is a dummy hop.
509
func buildDummyRouteData(node route.Vertex, relayInfo *record.PaymentRelayInfo,
510
        constraints *record.PaymentConstraints) (*hopData, error) {
1✔
511

1✔
512
        nodeID, err := btcec.ParsePubKey(node[:])
1✔
513
        if err != nil {
1✔
514
                return nil, err
×
515
        }
×
516

517
        return &hopData{
1✔
518
                data: record.NewDummyHopRouteData(
1✔
519
                        nodeID, *relayInfo, *constraints,
1✔
520
                ),
1✔
521
                nodeID: nodeID,
1✔
522
        }, nil
1✔
523
}
524

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

1✔
535
        numPolicies := len(policies)
1✔
536

1✔
537
        // If there are no real policies to calculate an average policy from,
1✔
538
        // then we use the default. The only thing we need to calculate here
1✔
539
        // though is the MaxHTLC value.
1✔
540
        if numPolicies == 0 {
2✔
541
                chans, err := fetchOurChannels()
1✔
542
                if err != nil {
1✔
543
                        return nil, err
×
544
                }
×
545

546
                if len(chans) == 0 {
1✔
547
                        return nil, fmt.Errorf("node has no channels to " +
×
548
                                "receive on")
×
549
                }
×
550

551
                // Calculate the average channel capacity and use this as the
552
                // MaxHTLC value.
553
                var maxHTLC btcutil.Amount
1✔
554
                for _, c := range chans {
2✔
555
                        maxHTLC += c.Capacity
1✔
556
                }
1✔
557

558
                maxHTLC = btcutil.Amount(float64(maxHTLC) / float64(len(chans)))
1✔
559

1✔
560
                return &BlindedHopPolicy{
1✔
561
                        CLTVExpiryDelta: defaultPolicy.CLTVExpiryDelta,
1✔
562
                        FeeRate:         defaultPolicy.FeeRate,
1✔
563
                        BaseFee:         defaultPolicy.BaseFee,
1✔
564
                        MinHTLCMsat:     defaultPolicy.MinHTLCMsat,
1✔
565
                        MaxHTLCMsat:     lnwire.NewMSatFromSatoshis(maxHTLC),
1✔
566
                }, nil
1✔
567
        }
568

569
        var avgPolicy BlindedHopPolicy
1✔
570

1✔
571
        for _, policy := range policies {
2✔
572
                avgPolicy.MinHTLCMsat += policy.MinHTLCMsat
1✔
573
                avgPolicy.MaxHTLCMsat += policy.MaxHTLCMsat
1✔
574
                avgPolicy.BaseFee += policy.BaseFee
1✔
575
                avgPolicy.FeeRate += policy.FeeRate
1✔
576
                avgPolicy.CLTVExpiryDelta += policy.CLTVExpiryDelta
1✔
577
        }
1✔
578

579
        avgPolicy.MinHTLCMsat = lnwire.MilliSatoshi(
1✔
580
                float64(avgPolicy.MinHTLCMsat) / float64(numPolicies),
1✔
581
        )
1✔
582
        avgPolicy.MaxHTLCMsat = lnwire.MilliSatoshi(
1✔
583
                float64(avgPolicy.MaxHTLCMsat) / float64(numPolicies),
1✔
584
        )
1✔
585
        avgPolicy.BaseFee = lnwire.MilliSatoshi(
1✔
586
                float64(avgPolicy.BaseFee) / float64(numPolicies),
1✔
587
        )
1✔
588
        avgPolicy.FeeRate = uint32(
1✔
589
                float64(avgPolicy.FeeRate) / float64(numPolicies),
1✔
590
        )
1✔
591
        avgPolicy.CLTVExpiryDelta = uint16(
1✔
592
                float64(avgPolicy.CLTVExpiryDelta) / float64(numPolicies),
1✔
593
        )
1✔
594

1✔
595
        return &avgPolicy, nil
1✔
596
}
597

598
// buildHopRouteData constructs the record.BlindedRouteData struct for the given
599
// non-final hop on a blinded path and packages it with the node's ID.
600
func buildHopRouteData(node route.Vertex, scid lnwire.ShortChannelID,
601
        relayInfo *record.PaymentRelayInfo,
602
        constraints *record.PaymentConstraints) (*hopData, error) {
1✔
603

1✔
604
        // Wrap up the data we want to send to this hop.
1✔
605
        blindedRouteHopData := record.NewNonFinalBlindedRouteData(
1✔
606
                scid, nil, *relayInfo, constraints, nil,
1✔
607
        )
1✔
608

1✔
609
        nodeID, err := btcec.ParsePubKey(node[:])
1✔
610
        if err != nil {
1✔
611
                return nil, err
×
612
        }
×
613

614
        return &hopData{
1✔
615
                data:   blindedRouteHopData,
1✔
616
                nodeID: nodeID,
1✔
617
        }, nil
1✔
618
}
619

620
// buildFinalHopRouteData constructs the record.BlindedRouteData struct for the
621
// final hop and packages it with the real node ID of the node it is intended
622
// for.
623
func buildFinalHopRouteData(node route.Vertex, pathID []byte,
624
        constraints *record.PaymentConstraints) (*hopData, error) {
1✔
625

1✔
626
        blindedRouteHopData := record.NewFinalHopBlindedRouteData(
1✔
627
                constraints, pathID,
1✔
628
        )
1✔
629
        nodeID, err := btcec.ParsePubKey(node[:])
1✔
630
        if err != nil {
1✔
631
                return nil, err
×
632
        }
×
633

634
        return &hopData{
1✔
635
                data:   blindedRouteHopData,
1✔
636
                nodeID: nodeID,
1✔
637
        }, nil
1✔
638
}
639

640
// getNodeChanPolicy fetches the routing policy info for the given channel and
641
// node pair.
642
func getNodeChannelPolicy(cfg *BuildBlindedPathCfg, chanID uint64,
643
        nodeID route.Vertex) (*BlindedHopPolicy, error) {
1✔
644

1✔
645
        // Attempt to fetch channel updates for the given channel. We will have
1✔
646
        // at most two updates for a given channel.
1✔
647
        _, update1, update2, err := cfg.FetchChannelEdgesByID(chanID)
1✔
648
        if err != nil {
1✔
UNCOV
649
                return nil, err
×
UNCOV
650
        }
×
651

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

661
        case update2 != nil && !bytes.Equal(update2.ToNode[:], nodeID[:]):
1✔
662
                policy = update2
1✔
663

664
        default:
×
665
                return nil, fmt.Errorf("no channel updates found from node "+
×
666
                        "%s for channel %d", nodeID, chanID)
×
667
        }
668

669
        return &BlindedHopPolicy{
1✔
670
                CLTVExpiryDelta: policy.TimeLockDelta,
1✔
671
                FeeRate:         uint32(policy.FeeProportionalMillionths),
1✔
672
                BaseFee:         policy.FeeBaseMSat,
1✔
673
                MinHTLCMsat:     policy.MinHTLC,
1✔
674
                MaxHTLCMsat:     policy.MaxHTLC,
1✔
675
        }, nil
1✔
676
}
677

678
// candidatePath holds all the information about a route to this node that we
679
// need in order to build a blinded route.
680
type candidatePath struct {
681
        introNode   route.Vertex
682
        finalNodeID route.Vertex
683
        hops        []*blindedPathHop
684
}
685

686
// String returns a string representation of the candidatePath which can be
687
// useful for logging and debugging.
688
func (c *candidatePath) String() string {
1✔
689
        str := fmt.Sprintf("[%s (intro node)]", c.introNode)
1✔
690

1✔
691
        for _, hop := range c.hops {
2✔
692
                if hop.isDummy {
2✔
693
                        str += "--->[dummy hop]"
1✔
694
                        continue
1✔
695
                }
696

697
                str += fmt.Sprintf("--<%d>-->[%s]", hop.channelID, hop.pubKey)
1✔
698
        }
699

700
        return str
1✔
701
}
702

703
// padWithDummyHops will append n dummy hops to the candidatePath hop set. The
704
// pub key for the dummy hop will be the same as the pub key for the final hop
705
// of the path. That way, the final hop will be able to decrypt the data
706
// encrypted for each dummy hop.
707
func (c *candidatePath) padWithDummyHops(n uint8) {
1✔
708
        for len(c.hops) < int(n) {
2✔
709
                c.hops = append(c.hops, &blindedPathHop{
1✔
710
                        pubKey:  c.finalNodeID,
1✔
711
                        isDummy: true,
1✔
712
                })
1✔
713
        }
1✔
714
}
715

716
// blindedPathHop holds the information we need to know about a hop in a route
717
// in order to use it in the construction of a blinded path.
718
type blindedPathHop struct {
719
        // pubKey is the real pub key of a node on a blinded path.
720
        pubKey route.Vertex
721

722
        // channelID is the channel along which the previous hop should forward
723
        // their HTLC in order to reach this hop.
724
        channelID uint64
725

726
        // isDummy is true if this hop is an appended dummy hop.
727
        isDummy bool
728
}
729

730
// extractCandidatePath extracts the data it needs from the given route.Route in
731
// order to construct a candidatePath.
732
func extractCandidatePath(path *route.Route) *candidatePath {
1✔
733
        var (
1✔
734
                hops      = make([]*blindedPathHop, len(path.Hops))
1✔
735
                finalNode = path.SourcePubKey
1✔
736
        )
1✔
737
        for i, hop := range path.Hops {
2✔
738
                hops[i] = &blindedPathHop{
1✔
739
                        pubKey:    hop.PubKeyBytes,
1✔
740
                        channelID: hop.ChannelID,
1✔
741
                }
1✔
742

1✔
743
                if i == len(path.Hops)-1 {
2✔
744
                        finalNode = hop.PubKeyBytes
1✔
745
                }
1✔
746
        }
747

748
        return &candidatePath{
1✔
749
                introNode:   path.SourcePubKey,
1✔
750
                finalNodeID: finalNode,
1✔
751
                hops:        hops,
1✔
752
        }
1✔
753
}
754

755
// BlindedHopPolicy holds the set of relay policy values to use for a channel
756
// in a blinded path.
757
type BlindedHopPolicy struct {
758
        CLTVExpiryDelta uint16
759
        FeeRate         uint32
760
        BaseFee         lnwire.MilliSatoshi
761
        MinHTLCMsat     lnwire.MilliSatoshi
762
        MaxHTLCMsat     lnwire.MilliSatoshi
763
}
764

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

1✔
774
        if incMultiplier < 1 {
1✔
UNCOV
775
                return nil, fmt.Errorf("blinded path policy increase " +
×
UNCOV
776
                        "multiplier must be greater than or equal to 1")
×
UNCOV
777
        }
×
778

779
        if decMultiplier < 0 || decMultiplier > 1 {
1✔
UNCOV
780
                return nil, fmt.Errorf("blinded path policy decrease " +
×
UNCOV
781
                        "multiplier must be in the range [0;1]")
×
UNCOV
782
        }
×
783

784
        var (
1✔
785
                minHTLCMsat = lnwire.MilliSatoshi(
1✔
786
                        float64(policy.MinHTLCMsat) * incMultiplier,
1✔
787
                )
1✔
788
                maxHTLCMsat = lnwire.MilliSatoshi(
1✔
789
                        float64(policy.MaxHTLCMsat) * decMultiplier,
1✔
790
                )
1✔
791
        )
1✔
792

1✔
793
        // Make sure the new minimum is not more than the original maximum.
1✔
794
        // If it is, then just stick to the original minimum.
1✔
795
        if minHTLCMsat > policy.MaxHTLCMsat {
1✔
UNCOV
796
                minHTLCMsat = policy.MinHTLCMsat
×
UNCOV
797
        }
×
798

799
        // Make sure the new maximum is not less than the original minimum.
800
        // If it is, then just stick to the original maximum.
801
        if maxHTLCMsat < policy.MinHTLCMsat {
1✔
UNCOV
802
                maxHTLCMsat = policy.MaxHTLCMsat
×
UNCOV
803
        }
×
804

805
        // Also ensure that the new htlc bounds make sense. If the new minimum
806
        // is greater than the new maximum, then just let both to their original
807
        // values.
808
        if minHTLCMsat > maxHTLCMsat {
1✔
UNCOV
809
                minHTLCMsat = policy.MinHTLCMsat
×
UNCOV
810
                maxHTLCMsat = policy.MaxHTLCMsat
×
UNCOV
811
        }
×
812

813
        return &BlindedHopPolicy{
1✔
814
                CLTVExpiryDelta: uint16(
1✔
815
                        float64(policy.CLTVExpiryDelta) * incMultiplier,
1✔
816
                ),
1✔
817
                FeeRate: uint32(
1✔
818
                        float64(policy.FeeRate) * incMultiplier,
1✔
819
                ),
1✔
820
                BaseFee: lnwire.MilliSatoshi(
1✔
821
                        float64(policy.BaseFee) * incMultiplier,
1✔
822
                ),
1✔
823
                MinHTLCMsat: minHTLCMsat,
1✔
824
                MaxHTLCMsat: maxHTLCMsat,
1✔
825
        }, nil
1✔
826
}
827

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

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

1✔
847
                totalFeeBase = calcNextTotalBaseFee(
1✔
848
                        totalFeeBase, info.BaseFee, info.FeeRate,
1✔
849
                )
1✔
850

1✔
851
                totalFeeProp = calcNextTotalFeeRate(totalFeeProp, info.FeeRate)
1✔
852

1✔
853
                totalCLTV += info.CltvExpiryDelta
1✔
854
        }
1✔
855

856
        return totalFeeBase, totalFeeProp, totalCLTV
1✔
857
}
858

859
// calcNextTotalBaseFee takes the current total accumulated base fee of a
860
// blinded path at hop `n` along with the fee rate and base fee of the hop at
861
// `n+1` and uses these to calculate the accumulated base fee at hop `n+1`.
862
func calcNextTotalBaseFee(currentTotal, hopBaseFee lnwire.MilliSatoshi,
863
        hopFeeRate uint32) lnwire.MilliSatoshi {
1✔
864

1✔
865
        numerator := (uint32(hopBaseFee) * oneMillion) +
1✔
866
                (uint32(currentTotal) * (oneMillion + hopFeeRate)) +
1✔
867
                oneMillion - 1
1✔
868

1✔
869
        return lnwire.MilliSatoshi(numerator / oneMillion)
1✔
870
}
1✔
871

872
// calculateNextTotalFeeRate takes the current total accumulated fee rate of a
873
// blinded path at hop `n` along with the fee rate of the hop at `n+1` and uses
874
// these to calculate the accumulated fee rate at hop `n+1`.
875
func calcNextTotalFeeRate(currentTotal, hopFeeRate uint32) uint32 {
1✔
876
        numerator := (currentTotal+hopFeeRate)*oneMillion +
1✔
877
                currentTotal*hopFeeRate + oneMillion - 1
1✔
878

1✔
879
        return numerator / oneMillion
1✔
880
}
1✔
881

882
// hopData packages the record.BlindedRouteData for a hop on a blinded path with
883
// the real node ID of that hop.
884
type hopData struct {
885
        data   *record.BlindedRouteData
886
        nodeID *btcec.PublicKey
887
}
888

889
// padStats can be used to keep track of various pieces of data that we collect
890
// during a call to padHopInfo. This is useful for logging and for test
891
// assertions.
892
type padStats struct {
893
        minPayloadSize  int
894
        maxPayloadSize  int
895
        finalPaddedSize int
896
        numIterations   int
897
}
898

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

1✔
916
        var (
1✔
917
                paymentPath = make([]*sphinx.HopInfo, len(hopInfo))
1✔
918
                stats       = padStats{finalPaddedSize: minSize}
1✔
919
        )
1✔
920

1✔
921
        // Pre-pad each payload with zero byte padding (if it does not yet have
1✔
922
        // padding) to save a couple of iterations in the majority of cases.
1✔
923
        if prePad {
2✔
924
                for _, info := range hopInfo {
2✔
925
                        if info.data.Padding.IsSome() {
1✔
926
                                continue
×
927
                        }
928

929
                        info.data.PadBy(0)
1✔
930
                }
931
        }
932

933
        for {
2✔
934
                stats.numIterations++
1✔
935

1✔
936
                // On each iteration of the loop, we first determine the
1✔
937
                // current largest encoded data blob size. This will be the
1✔
938
                // size we aim to get the others to match.
1✔
939
                var (
1✔
940
                        maxLen = minSize
1✔
941
                        minLen = math.MaxInt8
1✔
942
                )
1✔
943
                for i, hop := range hopInfo {
2✔
944
                        plainText, err := record.EncodeBlindedRouteData(
1✔
945
                                hop.data,
1✔
946
                        )
1✔
947
                        if err != nil {
1✔
948
                                return nil, nil, err
×
949
                        }
×
950

951
                        if len(plainText) > maxLen {
2✔
952
                                maxLen = len(plainText)
1✔
953

1✔
954
                                // Update the stats to take note of this new
1✔
955
                                // max since this may be the final max that all
1✔
956
                                // payloads will be padded to.
1✔
957
                                stats.finalPaddedSize = maxLen
1✔
958
                        }
1✔
959
                        if len(plainText) < minLen {
2✔
960
                                minLen = len(plainText)
1✔
961
                        }
1✔
962

963
                        paymentPath[i] = &sphinx.HopInfo{
1✔
964
                                NodePub:   hop.nodeID,
1✔
965
                                PlainText: plainText,
1✔
966
                        }
1✔
967
                }
968

969
                // If this is our first iteration, then we take note of the min
970
                // and max lengths of the payloads pre-padding for logging
971
                // later.
972
                if stats.numIterations == 1 {
2✔
973
                        stats.minPayloadSize = minLen
1✔
974
                        stats.maxPayloadSize = maxLen
1✔
975
                }
1✔
976

977
                // Now we iterate over them again and determine which ones we
978
                // need to add padding to.
979
                var numEqual int
1✔
980
                for i, hop := range hopInfo {
2✔
981
                        plainText := paymentPath[i].PlainText
1✔
982

1✔
983
                        // If the plaintext length is equal to the desired
1✔
984
                        // length, then we can continue. We use numEqual to
1✔
985
                        // keep track of how many have the same length.
1✔
986
                        if len(plainText) == maxLen {
2✔
987
                                numEqual++
1✔
988

1✔
989
                                continue
1✔
990
                        }
991

992
                        // If we previously added padding to this hop, we keep
993
                        // the length of that initial padding too.
994
                        var existingPadding int
1✔
995
                        hop.data.Padding.WhenSome(
1✔
996
                                func(p tlv.RecordT[tlv.TlvType1, []byte]) {
2✔
997
                                        existingPadding = len(p.Val)
1✔
998
                                },
1✔
999
                        )
1000

1001
                        // Add some padding bytes to the hop.
1002
                        hop.data.PadBy(
1✔
1003
                                existingPadding + maxLen - len(plainText),
1✔
1004
                        )
1✔
1005
                }
1006

1007
                // If all the payloads have the same length, we can exit the
1008
                // loop.
1009
                if numEqual == len(hopInfo) {
2✔
1010
                        break
1✔
1011
                }
1012
        }
1013

1014
        log.Debugf("Finished padding %d blinded path payloads to %d bytes "+
1✔
1015
                "each where the pre-padded min and max sizes were %d and %d "+
1✔
1016
                "bytes respectively", len(hopInfo), stats.finalPaddedSize,
1✔
1017
                stats.minPayloadSize, stats.maxPayloadSize)
1✔
1018

1✔
1019
        return paymentPath, &stats, nil
1✔
1020
}
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