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

lightningnetwork / lnd / 19027031130

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

Pull #9334

github

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

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

29175 existing lines in 461 files now uncovered.

99696 of 175144 relevant lines covered (56.92%)

1.77 hits per line

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

75.35
/lnrpc/invoicesrpc/addinvoice.go
1
package invoicesrpc
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "errors"
8
        "fmt"
9
        "math"
10
        mathRand "math/rand"
11
        "sort"
12
        "time"
13

14
        "github.com/btcsuite/btcd/btcec/v2"
15
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
16
        "github.com/btcsuite/btcd/btcutil"
17
        "github.com/btcsuite/btcd/chaincfg"
18
        "github.com/btcsuite/btcd/chaincfg/chainhash"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/lightningnetwork/lnd/channeldb"
21
        "github.com/lightningnetwork/lnd/graph/db/models"
22
        "github.com/lightningnetwork/lnd/invoices"
23
        "github.com/lightningnetwork/lnd/lntypes"
24
        "github.com/lightningnetwork/lnd/lnutils"
25
        "github.com/lightningnetwork/lnd/lnwire"
26
        "github.com/lightningnetwork/lnd/netann"
27
        "github.com/lightningnetwork/lnd/routing"
28
        "github.com/lightningnetwork/lnd/routing/blindedpath"
29
        "github.com/lightningnetwork/lnd/routing/route"
30
        "github.com/lightningnetwork/lnd/zpay32"
31
)
32

33
const (
34
        // DefaultInvoiceExpiry is the default invoice expiry for new MPP
35
        // invoices.
36
        DefaultInvoiceExpiry = 24 * time.Hour
37

38
        // DefaultAMPInvoiceExpiry is the default invoice expiry for new AMP
39
        // invoices.
40
        DefaultAMPInvoiceExpiry = 30 * 24 * time.Hour
41

42
        // hopHintFactor is factor by which we scale the total amount of
43
        // inbound capacity we want our hop hints to represent, allowing us to
44
        // have some leeway if peers go offline.
45
        hopHintFactor = 2
46

47
        // maxHopHints is the maximum number of hint paths that will be included
48
        // in an invoice.
49
        maxHopHints = 20
50
)
51

52
// AddInvoiceConfig contains dependencies for invoice creation.
53
type AddInvoiceConfig struct {
54
        // AddInvoice is called to add the invoice to the registry.
55
        AddInvoice func(ctx context.Context, invoice *invoices.Invoice,
56
                paymentHash lntypes.Hash) (uint64, error)
57

58
        // IsChannelActive is used to generate valid hop hints.
59
        IsChannelActive func(chanID lnwire.ChannelID) bool
60

61
        // ChainParams are required to properly decode invoice payment requests
62
        // that are marshalled over rpc.
63
        ChainParams *chaincfg.Params
64

65
        // NodeSigner is an implementation of the MessageSigner implementation
66
        // that's backed by the identity private key of the running lnd node.
67
        NodeSigner *netann.NodeSigner
68

69
        // DefaultCLTVExpiry is the default invoice expiry if no values is
70
        // specified.
71
        DefaultCLTVExpiry uint32
72

73
        // ChanDB is a global boltdb instance which is needed to access the
74
        // channel graph.
75
        ChanDB *channeldb.ChannelStateDB
76

77
        // Graph gives the invoice server access to various graph related
78
        // queries.
79
        Graph GraphSource
80

81
        // GenInvoiceFeatures returns a feature containing feature bits that
82
        // should be advertised on freshly generated invoices.
83
        GenInvoiceFeatures func() *lnwire.FeatureVector
84

85
        // GenAmpInvoiceFeatures returns a feature containing feature bits that
86
        // should be advertised on freshly generated AMP invoices.
87
        GenAmpInvoiceFeatures func() *lnwire.FeatureVector
88

89
        // GetAlias allows the peer's alias SCID to be retrieved for private
90
        // option_scid_alias channels.
91
        GetAlias func(lnwire.ChannelID) (lnwire.ShortChannelID, error)
92

93
        // BestHeight returns the current best block height that this node is
94
        // aware of.
95
        BestHeight func() (uint32, error)
96

97
        // QueryBlindedRoutes can be used to generate a few routes to this node
98
        // that can then be used in the construction of a blinded payment path.
99
        QueryBlindedRoutes func(lnwire.MilliSatoshi) ([]*route.Route, error)
100
}
101

102
// AddInvoiceData contains the required data to create a new invoice.
103
type AddInvoiceData struct {
104
        // An optional memo to attach along with the invoice. Used for record
105
        // keeping purposes for the invoice's creator, and will also be set in
106
        // the description field of the encoded payment request if the
107
        // description_hash field is not being used.
108
        Memo string
109

110
        // The preimage which will allow settling an incoming HTLC payable to
111
        // this preimage. If Preimage is set, Hash should be nil. If both
112
        // Preimage and Hash are nil, a random preimage is generated.
113
        Preimage *lntypes.Preimage
114

115
        // The hash of the preimage. If Hash is set, Preimage should be nil.
116
        // This condition indicates that we have a 'hold invoice' for which the
117
        // htlc will be accepted and held until the preimage becomes known.
118
        Hash *lntypes.Hash
119

120
        // The value of this invoice in millisatoshis.
121
        Value lnwire.MilliSatoshi
122

123
        // Hash (SHA-256) of a description of the payment. Used if the
124
        // description of payment (memo) is too long to naturally fit within the
125
        // description field of an encoded payment request.
126
        DescriptionHash []byte
127

128
        // Payment request expiry time in seconds. Default is 3600 (1 hour).
129
        Expiry int64
130

131
        // Fallback on-chain address.
132
        FallbackAddr string
133

134
        // Delta to use for the time-lock of the CLTV extended to the final hop.
135
        CltvExpiry uint64
136

137
        // Whether this invoice should include routing hints for private
138
        // channels.
139
        Private bool
140

141
        // HodlInvoice signals that this invoice shouldn't be settled
142
        // immediately upon receiving the payment.
143
        HodlInvoice bool
144

145
        // Amp signals whether or not to create an AMP invoice.
146
        //
147
        // NOTE: Preimage should always be set to nil when this value is true.
148
        Amp bool
149

150
        // BlindedPathCfg holds the config values to use when constructing
151
        // blinded paths to add to the invoice. A non-nil BlindedPathCfg signals
152
        // that this invoice should disguise the location of the recipient by
153
        // adding blinded payment paths to the invoice instead of revealing the
154
        // destination node's real pub key.
155
        BlindedPathCfg *BlindedPathConfig
156

157
        // RouteHints are optional route hints that can each be individually
158
        // used to assist in reaching the invoice's destination.
159
        RouteHints [][]zpay32.HopHint
160
}
161

162
// BlindedPathConfig holds the configuration values required for blinded path
163
// generation for invoices.
164
type BlindedPathConfig struct {
165
        // RoutePolicyIncrMultiplier is the amount by which policy values for
166
        // hops in a blinded route will be bumped to avoid easy probing. For
167
        // example, a multiplier of 1.1 will bump all appropriate the values
168
        // (base fee, fee rate, CLTV delta and min HLTC) by 10%.
169
        RoutePolicyIncrMultiplier float64
170

171
        // RoutePolicyDecrMultiplier is the amount by which appropriate policy
172
        // values for hops in a blinded route will be decreased to avoid easy
173
        // probing. For example, a multiplier of 0.9 will reduce appropriate
174
        // values (like maximum HTLC) by 10%.
175
        RoutePolicyDecrMultiplier float64
176

177
        // MinNumPathHops is the minimum number of hops that a blinded path
178
        // should be. Dummy hops will be used to pad any route with a length
179
        // less than this.
180
        MinNumPathHops uint8
181

182
        // DefaultDummyHopPolicy holds the default policy values to use for
183
        // dummy hops in a blinded path in the case where they cant be derived
184
        // through other means.
185
        DefaultDummyHopPolicy *blindedpath.BlindedHopPolicy
186

187
        // MaxNumPaths is the maximum number of blinded paths to select.
188
        MaxNumPaths uint8
189
}
190

191
// paymentHashAndPreimage returns the payment hash and preimage for this invoice
192
// depending on the configuration.
193
//
194
// For AMP invoices (when Amp flag is true), this method always returns a nil
195
// preimage. The hash value can be set externally by the user using the Hash
196
// field, or one will be generated randomly. The payment hash here only serves
197
// as a unique identifier for insertion into the invoice index, as there is
198
// no universal preimage for an AMP payment.
199
//
200
// For MPP invoices (when Amp flag is false), this method may return nil
201
// preimage when create a hodl invoice, but otherwise will always return a
202
// non-nil preimage and the corresponding payment hash. The valid combinations
203
// are parsed as follows:
204
//   - Preimage == nil && Hash == nil -> (random preimage, H(random preimage))
205
//   - Preimage != nil && Hash == nil -> (Preimage, H(Preimage))
206
//   - Preimage == nil && Hash != nil -> (nil, Hash)
207
func (d *AddInvoiceData) paymentHashAndPreimage() (
208
        *lntypes.Preimage, lntypes.Hash, error) {
3✔
209

3✔
210
        if d.Amp {
6✔
211
                return d.ampPaymentHashAndPreimage()
3✔
212
        }
3✔
213

214
        return d.mppPaymentHashAndPreimage()
3✔
215
}
216

217
// ampPaymentHashAndPreimage returns the payment hash to use for an AMP invoice.
218
// The preimage will always be nil.
219
func (d *AddInvoiceData) ampPaymentHashAndPreimage() (*lntypes.Preimage,
220
        lntypes.Hash, error) {
3✔
221

3✔
222
        switch {
3✔
223
        // Preimages cannot be set on AMP invoice.
224
        case d.Preimage != nil:
×
225
                return nil, lntypes.Hash{},
×
226
                        errors.New("preimage set on AMP invoice")
×
227

228
        // If a specific hash was requested, use that.
229
        case d.Hash != nil:
×
230
                return nil, *d.Hash, nil
×
231

232
        // Otherwise generate a random hash value, just needs to be unique to be
233
        // added to the invoice index.
234
        default:
3✔
235
                var paymentHash lntypes.Hash
3✔
236
                if _, err := rand.Read(paymentHash[:]); err != nil {
3✔
237
                        return nil, lntypes.Hash{}, err
×
238
                }
×
239

240
                return nil, paymentHash, nil
3✔
241
        }
242
}
243

244
// mppPaymentHashAndPreimage returns the payment hash and preimage to use for an
245
// MPP invoice.
246
func (d *AddInvoiceData) mppPaymentHashAndPreimage() (*lntypes.Preimage,
247
        lntypes.Hash, error) {
3✔
248

3✔
249
        var (
3✔
250
                paymentPreimage *lntypes.Preimage
3✔
251
                paymentHash     lntypes.Hash
3✔
252
        )
3✔
253

3✔
254
        switch {
3✔
255

256
        // Only either preimage or hash can be set.
257
        case d.Preimage != nil && d.Hash != nil:
×
258
                return nil, lntypes.Hash{},
×
259
                        errors.New("preimage and hash both set")
×
260

261
        // If no hash or preimage is given, generate a random preimage.
262
        case d.Preimage == nil && d.Hash == nil:
3✔
263
                paymentPreimage = &lntypes.Preimage{}
3✔
264
                if _, err := rand.Read(paymentPreimage[:]); err != nil {
3✔
265
                        return nil, lntypes.Hash{}, err
×
266
                }
×
267
                paymentHash = paymentPreimage.Hash()
3✔
268

269
        // If just a hash is given, we create a hold invoice by setting the
270
        // preimage to unknown.
271
        case d.Preimage == nil && d.Hash != nil:
3✔
272
                paymentHash = *d.Hash
3✔
273

274
        // A specific preimage was supplied. Use that for the invoice.
275
        case d.Preimage != nil && d.Hash == nil:
3✔
276
                preimage := *d.Preimage
3✔
277
                paymentPreimage = &preimage
3✔
278
                paymentHash = d.Preimage.Hash()
3✔
279
        }
280

281
        return paymentPreimage, paymentHash, nil
3✔
282
}
283

284
// AddInvoice attempts to add a new invoice to the invoice database. Any
285
// duplicated invoices are rejected, therefore all invoices *must* have a
286
// unique payment preimage.
287
func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig,
288
        invoice *AddInvoiceData) (*lntypes.Hash, *invoices.Invoice, error) {
3✔
289

3✔
290
        blind := invoice.BlindedPathCfg != nil
3✔
291

3✔
292
        if invoice.Amp && blind {
3✔
293
                return nil, nil, fmt.Errorf("AMP invoices with blinded paths " +
×
294
                        "are not yet supported")
×
295
        }
×
296

297
        paymentPreimage, paymentHash, err := invoice.paymentHashAndPreimage()
3✔
298
        if err != nil {
3✔
299
                return nil, nil, err
×
300
        }
×
301

302
        // The size of the memo, receipt and description hash attached must not
303
        // exceed the maximum values for either of the fields.
304
        if len(invoice.Memo) > invoices.MaxMemoSize {
3✔
305
                return nil, nil, fmt.Errorf("memo too large: %v bytes "+
×
306
                        "(maxsize=%v)", len(invoice.Memo),
×
307
                        invoices.MaxMemoSize)
×
308
        }
×
309
        if len(invoice.DescriptionHash) > 0 &&
3✔
310
                len(invoice.DescriptionHash) != 32 {
3✔
311

×
312
                return nil, nil, fmt.Errorf("description hash is %v bytes, "+
×
313
                        "must be 32", len(invoice.DescriptionHash))
×
314
        }
×
315

316
        // We set the max invoice amount to 100k BTC, which itself is several
317
        // multiples off the current block reward.
318
        maxInvoiceAmt := btcutil.Amount(btcutil.SatoshiPerBitcoin * 100000)
3✔
319

3✔
320
        switch {
3✔
321
        // The value of the invoice must not be negative.
322
        case int64(invoice.Value) < 0:
×
323
                return nil, nil, fmt.Errorf("payments of negative value "+
×
324
                        "are not allowed, value is %v", int64(invoice.Value))
×
325

326
        // Also ensure that the invoice is actually realistic, while preventing
327
        // any issues due to underflow.
328
        case invoice.Value.ToSatoshis() > maxInvoiceAmt:
×
329
                return nil, nil, fmt.Errorf("invoice amount %v is "+
×
330
                        "too large, max is %v", invoice.Value.ToSatoshis(),
×
331
                        maxInvoiceAmt)
×
332
        }
333

334
        amtMSat := invoice.Value
3✔
335

3✔
336
        // We also create an encoded payment request which allows the
3✔
337
        // caller to compactly send the invoice to the payer. We'll create a
3✔
338
        // list of options to be added to the encoded payment request. For now
3✔
339
        // we only support the required fields description/description_hash,
3✔
340
        // expiry, fallback address, and the amount field.
3✔
341
        var options []func(*zpay32.Invoice)
3✔
342

3✔
343
        // We only include the amount in the invoice if it is greater than 0.
3✔
344
        // By not including the amount, we enable the creation of invoices that
3✔
345
        // allow the payer to specify the amount of satoshis they wish to send.
3✔
346
        if amtMSat > 0 {
6✔
347
                options = append(options, zpay32.Amount(amtMSat))
3✔
348
        }
3✔
349

350
        // If specified, add a fallback address to the payment request.
351
        if len(invoice.FallbackAddr) > 0 {
3✔
352
                addr, err := btcutil.DecodeAddress(
×
353
                        invoice.FallbackAddr, cfg.ChainParams,
×
354
                )
×
355
                if err != nil {
×
356
                        return nil, nil, fmt.Errorf("invalid fallback "+
×
357
                                "address: %v", err)
×
358
                }
×
359

360
                if !addr.IsForNet(cfg.ChainParams) {
×
361
                        return nil, nil, fmt.Errorf("fallback address is not "+
×
362
                                "for %s", cfg.ChainParams.Name)
×
363
                }
×
364

365
                options = append(options, zpay32.FallbackAddr(addr))
×
366
        }
367

368
        var expiry time.Duration
3✔
369
        switch {
3✔
370
        // An invoice expiry has been provided by the caller.
371
        case invoice.Expiry > 0:
×
372

×
373
                // We'll ensure that the specified expiry is restricted to sane
×
374
                // number of seconds. As a result, we'll reject an invoice with
×
375
                // an expiry greater than 1 year.
×
376
                maxExpiry := time.Hour * 24 * 365
×
377
                expSeconds := invoice.Expiry
×
378

×
379
                if float64(expSeconds) > maxExpiry.Seconds() {
×
380
                        return nil, nil, fmt.Errorf("expiry of %v seconds "+
×
381
                                "greater than max expiry of %v seconds",
×
382
                                float64(expSeconds), maxExpiry.Seconds())
×
383
                }
×
384

385
                expiry = time.Duration(invoice.Expiry) * time.Second
×
386

387
        // If no custom expiry is provided, use the default MPP expiry.
388
        case !invoice.Amp:
3✔
389
                expiry = DefaultInvoiceExpiry
3✔
390

391
        // Otherwise, use the default AMP expiry.
392
        default:
3✔
393
                expiry = DefaultAMPInvoiceExpiry
3✔
394
        }
395

396
        options = append(options, zpay32.Expiry(expiry))
3✔
397

3✔
398
        // If the description hash is set, then we add it do the list of
3✔
399
        // options. If not, use the memo field as the payment request
3✔
400
        // description.
3✔
401
        if len(invoice.DescriptionHash) > 0 {
3✔
402
                var descHash [32]byte
×
403
                copy(descHash[:], invoice.DescriptionHash[:])
×
404
                options = append(options, zpay32.DescriptionHash(descHash))
×
405
        } else {
3✔
406
                // Use the memo field as the description. If this is not set
3✔
407
                // this will just be an empty string.
3✔
408
                options = append(options, zpay32.Description(invoice.Memo))
3✔
409
        }
3✔
410

411
        if invoice.CltvExpiry > routing.MaxCLTVDelta {
3✔
412
                return nil, nil, fmt.Errorf("CLTV delta of %v is too large, "+
×
413
                        "max accepted is: %v", invoice.CltvExpiry,
×
414
                        math.MaxUint16)
×
415
        }
×
416

417
        // We'll use our current default CLTV value unless one was specified as
418
        // an option on the command line when creating an invoice.
419
        cltvExpiryDelta := uint64(cfg.DefaultCLTVExpiry)
3✔
420
        if invoice.CltvExpiry != 0 {
6✔
421
                // Disallow user-chosen final CLTV deltas below the required
3✔
422
                // minimum.
3✔
423
                if invoice.CltvExpiry < routing.MinCLTVDelta {
3✔
424
                        return nil, nil, fmt.Errorf("CLTV delta of %v must be "+
×
425
                                "greater than minimum of %v",
×
426
                                invoice.CltvExpiry, routing.MinCLTVDelta)
×
427
                }
×
428

429
                cltvExpiryDelta = invoice.CltvExpiry
3✔
430
        }
431

432
        // Only include a final CLTV expiry delta if this is not a blinded
433
        // invoice. In a blinded invoice, this value will be added to the total
434
        // blinded route CLTV delta value
435
        if !blind {
6✔
436
                options = append(options, zpay32.CLTVExpiry(cltvExpiryDelta))
3✔
437
        }
3✔
438

439
        // We make sure that the given invoice routing hints number is within
440
        // the valid range
441
        if len(invoice.RouteHints) > maxHopHints {
3✔
442
                return nil, nil, fmt.Errorf("number of routing hints must "+
×
443
                        "not exceed maximum of %v", maxHopHints)
×
444
        }
×
445

446
        // Include route hints if needed.
447
        if len(invoice.RouteHints) > 0 || invoice.Private {
6✔
448
                if blind {
3✔
449
                        return nil, nil, fmt.Errorf("can't set both hop " +
×
450
                                "hints and add blinded payment paths")
×
451
                }
×
452

453
                // Validate provided hop hints.
454
                for _, hint := range invoice.RouteHints {
6✔
455
                        if len(hint) == 0 {
3✔
456
                                return nil, nil, fmt.Errorf("number of hop " +
×
457
                                        "hint within a route must be positive")
×
458
                        }
×
459
                }
460

461
                totalHopHints := len(invoice.RouteHints)
3✔
462
                if invoice.Private {
6✔
463
                        totalHopHints = maxHopHints
3✔
464
                }
3✔
465

466
                hopHintsCfg := newSelectHopHintsCfg(cfg, totalHopHints)
3✔
467
                hopHints, err := PopulateHopHints(
3✔
468
                        hopHintsCfg, amtMSat, invoice.RouteHints,
3✔
469
                )
3✔
470
                if err != nil {
3✔
471
                        return nil, nil, fmt.Errorf("unable to populate hop "+
×
472
                                "hints: %v", err)
×
473
                }
×
474

475
                // Convert our set of selected hop hints into route
476
                // hints and add to our invoice options.
477
                for _, hopHint := range hopHints {
6✔
478
                        routeHint := zpay32.RouteHint(hopHint)
3✔
479

3✔
480
                        options = append(
3✔
481
                                options, routeHint,
3✔
482
                        )
3✔
483
                }
3✔
484
        }
485

486
        // Set our desired invoice features and add them to our list of options.
487
        var invoiceFeatures *lnwire.FeatureVector
3✔
488
        if invoice.Amp {
6✔
489
                invoiceFeatures = cfg.GenAmpInvoiceFeatures()
3✔
490
        } else {
6✔
491
                invoiceFeatures = cfg.GenInvoiceFeatures()
3✔
492
        }
3✔
493
        options = append(options, zpay32.Features(invoiceFeatures))
3✔
494

3✔
495
        // Generate and set a random payment address for this payment. If the
3✔
496
        // sender understands payment addresses, this can be used to avoid
3✔
497
        // intermediaries probing the receiver. If the invoice does not have
3✔
498
        // blinded paths, then this will be encoded in the invoice itself.
3✔
499
        // Otherwise, it will instead be embedded in the encrypted recipient
3✔
500
        // data of blinded paths. In the blinded path case, this will be used
3✔
501
        // for the PathID.
3✔
502
        var paymentAddr [32]byte
3✔
503
        if _, err := rand.Read(paymentAddr[:]); err != nil {
3✔
504
                return nil, nil, err
×
505
        }
×
506

507
        if blind {
6✔
508
                blindCfg := invoice.BlindedPathCfg
3✔
509

3✔
510
                // Use the 10-min-per-block assumption to get a rough estimate
3✔
511
                // of the number of blocks until the invoice expires. We want
3✔
512
                // to make sure that the blinded path definitely does not expire
3✔
513
                // before the invoice does, and so we add a healthy buffer.
3✔
514
                invoiceExpiry := uint32(expiry.Minutes() / 10)
3✔
515
                blindedPathExpiry := invoiceExpiry * 2
3✔
516

3✔
517
                // Add BlockPadding to the finalCltvDelta so that the receiving
3✔
518
                // node does not reject the HTLC if some blocks are mined while
3✔
519
                // the payment is in-flight. Note that unlike vanilla invoices,
3✔
520
                // with blinded paths, the recipient is responsible for adding
3✔
521
                // this block padding instead of the sender.
3✔
522
                finalCLTVDelta := uint32(cltvExpiryDelta)
3✔
523
                finalCLTVDelta += uint32(routing.BlockPadding)
3✔
524

3✔
525
                //nolint:ll
3✔
526
                paths, err := blindedpath.BuildBlindedPaymentPaths(
3✔
527
                        &blindedpath.BuildBlindedPathCfg{
3✔
528
                                FindRoutes:              cfg.QueryBlindedRoutes,
3✔
529
                                FetchChannelEdgesByID:   cfg.Graph.FetchChannelEdgesByID,
3✔
530
                                FetchOurOpenChannels:    cfg.ChanDB.FetchAllOpenChannels,
3✔
531
                                PathID:                  paymentAddr[:],
3✔
532
                                ValueMsat:               invoice.Value,
3✔
533
                                BestHeight:              cfg.BestHeight,
3✔
534
                                MinFinalCLTVExpiryDelta: finalCLTVDelta,
3✔
535
                                BlocksUntilExpiry:       blindedPathExpiry,
3✔
536
                                AddPolicyBuffer: func(
3✔
537
                                        p *blindedpath.BlindedHopPolicy) (
3✔
538
                                        *blindedpath.BlindedHopPolicy, error) {
6✔
539

3✔
540
                                        //nolint:ll
3✔
541
                                        return blindedpath.AddPolicyBuffer(
3✔
542
                                                p, blindCfg.RoutePolicyIncrMultiplier,
3✔
543
                                                blindCfg.RoutePolicyDecrMultiplier,
3✔
544
                                        )
3✔
545
                                },
3✔
546
                                MinNumHops:            blindCfg.MinNumPathHops,
547
                                DefaultDummyHopPolicy: blindCfg.DefaultDummyHopPolicy,
548
                                MaxNumPaths:           blindCfg.MaxNumPaths,
549
                        },
550
                )
551
                if err != nil {
6✔
552
                        return nil, nil, err
3✔
553
                }
3✔
554

555
                for _, path := range paths {
6✔
556
                        options = append(options, zpay32.WithBlindedPaymentPath(
3✔
557
                                path,
3✔
558
                        ))
3✔
559
                }
3✔
560
        } else {
3✔
561
                options = append(options, zpay32.PaymentAddr(paymentAddr))
3✔
562
        }
3✔
563

564
        // Create and encode the payment request as a bech32 (zpay32) string.
565
        creationDate := time.Now()
3✔
566
        payReq, err := zpay32.NewInvoice(
3✔
567
                cfg.ChainParams, paymentHash, creationDate, options...,
3✔
568
        )
3✔
569
        if err != nil {
3✔
570
                return nil, nil, err
×
571
        }
×
572

573
        payReqString, err := payReq.Encode(zpay32.MessageSigner{
3✔
574
                SignCompact: func(msg []byte) ([]byte, error) {
6✔
575
                        // For an invoice without a blinded path, the main node
3✔
576
                        // key is used to sign the invoice so that the sender
3✔
577
                        // can derive the true pub key of the recipient.
3✔
578
                        if !blind {
6✔
579
                                return cfg.NodeSigner.SignMessageCompact(
3✔
580
                                        msg, false,
3✔
581
                                )
3✔
582
                        }
3✔
583

584
                        // For an invoice with a blinded path, we use an
585
                        // ephemeral key to sign the invoice since we don't want
586
                        // the sender to be able to know the real pub key of
587
                        // the recipient.
588
                        ephemKey, err := btcec.NewPrivateKey()
3✔
589
                        if err != nil {
3✔
590
                                return nil, err
×
591
                        }
×
592

593
                        return ecdsa.SignCompact(
3✔
594
                                ephemKey, chainhash.HashB(msg), true,
3✔
595
                        ), nil
3✔
596
                },
597
        })
598
        if err != nil {
3✔
599
                return nil, nil, err
×
600
        }
×
601

602
        newInvoice := &invoices.Invoice{
3✔
603
                CreationDate:   creationDate,
3✔
604
                Memo:           []byte(invoice.Memo),
3✔
605
                PaymentRequest: []byte(payReqString),
3✔
606
                Terms: invoices.ContractTerm{
3✔
607
                        FinalCltvDelta:  int32(payReq.MinFinalCLTVExpiry()),
3✔
608
                        Expiry:          payReq.Expiry(),
3✔
609
                        Value:           amtMSat,
3✔
610
                        PaymentPreimage: paymentPreimage,
3✔
611
                        PaymentAddr:     paymentAddr,
3✔
612
                        Features:        invoiceFeatures,
3✔
613
                },
3✔
614
                HodlInvoice: invoice.HodlInvoice,
3✔
615
        }
3✔
616

3✔
617
        log.Tracef("[addinvoice] adding new invoice %v",
3✔
618
                lnutils.SpewLogClosure(newInvoice))
3✔
619

3✔
620
        // With all sanity checks passed, write the invoice to the database.
3✔
621
        _, err = cfg.AddInvoice(ctx, newInvoice, paymentHash)
3✔
622
        if err != nil {
3✔
623
                return nil, nil, err
×
624
        }
×
625

626
        return &paymentHash, newInvoice, nil
3✔
627
}
628

629
// chanCanBeHopHint returns true if the target channel is eligible to be a hop
630
// hint.
631
func chanCanBeHopHint(channel *HopHintInfo, cfg *SelectHopHintsCfg) (
632
        *models.ChannelEdgePolicy, bool) {
3✔
633

3✔
634
        // Since we're only interested in our private channels, we'll skip
3✔
635
        // public ones.
3✔
636
        if channel.IsPublic {
3✔
UNCOV
637
                return nil, false
×
UNCOV
638
        }
×
639

640
        // Make sure the channel is active.
641
        if !channel.IsActive {
6✔
642
                log.Debugf("Skipping channel %v due to not "+
3✔
643
                        "being eligible to forward payments",
3✔
644
                        channel.ShortChannelID)
3✔
645
                return nil, false
3✔
646
        }
3✔
647

648
        // To ensure we don't leak unadvertised nodes, we'll make sure our
649
        // counterparty is publicly advertised within the network.  Otherwise,
650
        // we'll end up leaking information about nodes that intend to stay
651
        // unadvertised, like in the case of a node only having private
652
        // channels.
653
        var remotePub [33]byte
3✔
654
        copy(remotePub[:], channel.RemotePubkey.SerializeCompressed())
3✔
655
        isRemoteNodePublic, err := cfg.IsPublicNode(remotePub)
3✔
656
        if err != nil {
3✔
657
                log.Errorf("Unable to determine if node %x "+
×
658
                        "is advertised: %v", remotePub, err)
×
659
                return nil, false
×
660
        }
×
661

662
        if !isRemoteNodePublic {
6✔
663
                log.Debugf("Skipping channel %v due to "+
3✔
664
                        "counterparty %x being unadvertised",
3✔
665
                        channel.ShortChannelID, remotePub)
3✔
666
                return nil, false
3✔
667
        }
3✔
668

669
        // Fetch the policies for each end of the channel.
670
        info, p1, p2, err := cfg.FetchChannelEdgesByID(channel.ShortChannelID)
3✔
671
        if err != nil {
3✔
UNCOV
672
                // In the case of zero-conf channels, it may be the case that
×
UNCOV
673
                // the alias SCID was deleted from the graph, and replaced by
×
UNCOV
674
                // the confirmed SCID. Check the Graph for the confirmed SCID.
×
UNCOV
675
                confirmedScid := channel.ConfirmedScidZC
×
UNCOV
676
                info, p1, p2, err = cfg.FetchChannelEdgesByID(confirmedScid)
×
UNCOV
677
                if err != nil {
×
UNCOV
678
                        log.Errorf("Unable to fetch the routing policies for "+
×
UNCOV
679
                                "the edges of the channel %v: %v",
×
UNCOV
680
                                channel.ShortChannelID, err)
×
UNCOV
681
                        return nil, false
×
UNCOV
682
                }
×
683
        }
684

685
        // Now, we'll need to determine which is the correct policy for HTLCs
686
        // being sent from the remote node.
687
        var remotePolicy *models.ChannelEdgePolicy
3✔
688
        if bytes.Equal(remotePub[:], info.NodeKey1Bytes[:]) {
6✔
689
                remotePolicy = p1
3✔
690
        } else {
6✔
691
                remotePolicy = p2
3✔
692
        }
3✔
693

694
        return remotePolicy, true
3✔
695
}
696

697
// HopHintInfo contains the channel information required to create a hop hint.
698
type HopHintInfo struct {
699
        // IsPublic indicates whether a channel is advertised to the network.
700
        IsPublic bool
701

702
        // IsActive indicates whether the channel is online and available for
703
        // use.
704
        IsActive bool
705

706
        // FundingOutpoint is the funding txid:index for the channel.
707
        FundingOutpoint wire.OutPoint
708

709
        // RemotePubkey is the public key of the remote party that this channel
710
        // is in.
711
        RemotePubkey *btcec.PublicKey
712

713
        // RemoteBalance is the remote party's balance (our current incoming
714
        // capacity).
715
        RemoteBalance lnwire.MilliSatoshi
716

717
        // ShortChannelID is the short channel ID of the channel.
718
        ShortChannelID uint64
719

720
        // ConfirmedScidZC is the confirmed SCID of a zero-conf channel. This
721
        // may be used for looking up a channel in the graph.
722
        ConfirmedScidZC uint64
723

724
        // ScidAliasFeature denotes whether the channel has negotiated the
725
        // option-scid-alias feature bit.
726
        ScidAliasFeature bool
727
}
728

729
func newHopHintInfo(c *channeldb.OpenChannel, isActive bool) *HopHintInfo {
3✔
730
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
731

3✔
732
        return &HopHintInfo{
3✔
733
                IsPublic:         isPublic,
3✔
734
                IsActive:         isActive,
3✔
735
                FundingOutpoint:  c.FundingOutpoint,
3✔
736
                RemotePubkey:     c.IdentityPub,
3✔
737
                RemoteBalance:    c.LocalCommitment.RemoteBalance,
3✔
738
                ShortChannelID:   c.ShortChannelID.ToUint64(),
3✔
739
                ConfirmedScidZC:  c.ZeroConfRealScid().ToUint64(),
3✔
740
                ScidAliasFeature: c.ChanType.HasScidAliasFeature(),
3✔
741
        }
3✔
742
}
3✔
743

744
// newHopHint returns a new hop hint using the relevant data from a hopHintInfo
745
// and a ChannelEdgePolicy.
746
func newHopHint(hopHintInfo *HopHintInfo,
747
        chanPolicy *models.ChannelEdgePolicy) zpay32.HopHint {
3✔
748

3✔
749
        return zpay32.HopHint{
3✔
750
                NodeID:      hopHintInfo.RemotePubkey,
3✔
751
                ChannelID:   hopHintInfo.ShortChannelID,
3✔
752
                FeeBaseMSat: uint32(chanPolicy.FeeBaseMSat),
3✔
753
                FeeProportionalMillionths: uint32(
3✔
754
                        chanPolicy.FeeProportionalMillionths,
3✔
755
                ),
3✔
756
                CLTVExpiryDelta: chanPolicy.TimeLockDelta,
3✔
757
        }
3✔
758
}
3✔
759

760
// SelectHopHintsCfg contains the dependencies required to obtain hop hints
761
// for an invoice.
762
type SelectHopHintsCfg struct {
763
        // IsPublicNode is returns a bool indicating whether the node with the
764
        // given public key is seen as a public node in the graph from the
765
        // graph's source node's point of view.
766
        IsPublicNode func(pubKey [33]byte) (bool, error)
767

768
        // FetchChannelEdgesByID attempts to lookup the two directed edges for
769
        // the channel identified by the channel ID.
770
        FetchChannelEdgesByID func(chanID uint64) (*models.ChannelEdgeInfo,
771
                *models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
772
                error)
773

774
        // GetAlias allows the peer's alias SCID to be retrieved for private
775
        // option_scid_alias channels.
776
        GetAlias func(lnwire.ChannelID) (lnwire.ShortChannelID, error)
777

778
        // FetchAllChannels retrieves all open channels currently stored
779
        // within the database.
780
        FetchAllChannels func() ([]*channeldb.OpenChannel, error)
781

782
        // IsChannelActive checks whether the channel identified by the provided
783
        // ChannelID is considered active.
784
        IsChannelActive func(chanID lnwire.ChannelID) bool
785

786
        // MaxHopHints is the maximum number of hop hints we are interested in.
787
        MaxHopHints int
788
}
789

790
func newSelectHopHintsCfg(invoicesCfg *AddInvoiceConfig,
791
        maxHopHints int) *SelectHopHintsCfg {
3✔
792

3✔
793
        return &SelectHopHintsCfg{
3✔
794
                FetchAllChannels:      invoicesCfg.ChanDB.FetchAllChannels,
3✔
795
                IsChannelActive:       invoicesCfg.IsChannelActive,
3✔
796
                IsPublicNode:          invoicesCfg.Graph.IsPublicNode,
3✔
797
                FetchChannelEdgesByID: invoicesCfg.Graph.FetchChannelEdgesByID,
3✔
798
                GetAlias:              invoicesCfg.GetAlias,
3✔
799
                MaxHopHints:           maxHopHints,
3✔
800
        }
3✔
801
}
3✔
802

803
// sufficientHints checks whether we have sufficient hop hints, based on the
804
// any of the following criteria:
805
//   - Hop hint count: the number of hints have reach our max target.
806
//   - Total incoming capacity (for non-zero invoice amounts): the sum of the
807
//     remote balance amount in the hints is bigger of equal than our target
808
//     (currently twice the invoice amount)
809
//
810
// We limit our number of hop hints like this to keep our invoice size down,
811
// and to avoid leaking all our private channels when we don't need to.
812
func sufficientHints(nHintsLeft int, currentAmount,
813
        targetAmount lnwire.MilliSatoshi) bool {
3✔
814

3✔
815
        if nHintsLeft <= 0 {
3✔
UNCOV
816
                log.Debugf("Reached targeted number of hop hints")
×
UNCOV
817
                return true
×
UNCOV
818
        }
×
819

820
        if targetAmount != 0 && currentAmount >= targetAmount {
6✔
821
                log.Debugf("Total hint amount: %v has reached target hint "+
3✔
822
                        "bandwidth: %v", currentAmount, targetAmount)
3✔
823
                return true
3✔
824
        }
3✔
825

826
        return false
3✔
827
}
828

829
// getPotentialHints returns a slice of open channels that should be considered
830
// for the hopHint list in an invoice. The slice is sorted in descending order
831
// based on the remote balance.
832
func getPotentialHints(cfg *SelectHopHintsCfg) ([]*channeldb.OpenChannel,
833
        error) {
3✔
834

3✔
835
        // TODO(positiveblue): get the channels slice already filtered by
3✔
836
        // private == true and sorted by RemoteBalance?
3✔
837
        openChannels, err := cfg.FetchAllChannels()
3✔
838
        if err != nil {
3✔
839
                return nil, err
×
840
        }
×
841

842
        privateChannels := make([]*channeldb.OpenChannel, 0, len(openChannels))
3✔
843
        for _, oc := range openChannels {
6✔
844
                isPublic := oc.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
845
                if !isPublic {
6✔
846
                        privateChannels = append(privateChannels, oc)
3✔
847
                }
3✔
848
        }
849

850
        // Sort the channels in descending remote balance.
851
        compareRemoteBalance := func(i, j int) bool {
6✔
852
                iBalance := privateChannels[i].LocalCommitment.RemoteBalance
3✔
853
                jBalance := privateChannels[j].LocalCommitment.RemoteBalance
3✔
854
                return iBalance > jBalance
3✔
855
        }
3✔
856
        sort.Slice(privateChannels, compareRemoteBalance)
3✔
857

3✔
858
        return privateChannels, nil
3✔
859
}
860

861
// shouldIncludeChannel returns true if the channel passes all the checks to
862
// be a hopHint in a given invoice.
863
func shouldIncludeChannel(cfg *SelectHopHintsCfg,
864
        channel *channeldb.OpenChannel,
865
        alreadyIncluded map[uint64]bool) (zpay32.HopHint, lnwire.MilliSatoshi,
866
        bool) {
3✔
867

3✔
868
        if _, ok := alreadyIncluded[channel.ShortChannelID.ToUint64()]; ok {
3✔
UNCOV
869
                return zpay32.HopHint{}, 0, false
×
UNCOV
870
        }
×
871

872
        chanID := lnwire.NewChanIDFromOutPoint(
3✔
873
                channel.FundingOutpoint,
3✔
874
        )
3✔
875

3✔
876
        hopHintInfo := newHopHintInfo(channel, cfg.IsChannelActive(chanID))
3✔
877

3✔
878
        // If this channel can't be a hop hint, then skip it.
3✔
879
        edgePolicy, canBeHopHint := chanCanBeHopHint(hopHintInfo, cfg)
3✔
880
        if edgePolicy == nil || !canBeHopHint {
6✔
881
                return zpay32.HopHint{}, 0, false
3✔
882
        }
3✔
883

884
        if hopHintInfo.ScidAliasFeature {
6✔
885
                alias, err := cfg.GetAlias(chanID)
3✔
886
                if err != nil {
3✔
887
                        return zpay32.HopHint{}, 0, false
×
888
                }
×
889

890
                if alias.IsDefault() || alreadyIncluded[alias.ToUint64()] {
3✔
UNCOV
891
                        return zpay32.HopHint{}, 0, false
×
UNCOV
892
                }
×
893

894
                hopHintInfo.ShortChannelID = alias.ToUint64()
3✔
895
        }
896

897
        // Now that we know this channel use usable, add it as a hop hint and
898
        // the indexes we'll use later.
899
        hopHint := newHopHint(hopHintInfo, edgePolicy)
3✔
900
        return hopHint, hopHintInfo.RemoteBalance, true
3✔
901
}
902

903
// selectHopHints iterates a list of potential hints selecting the valid hop
904
// hints until we have enough hints or run out of channels.
905
//
906
// NOTE: selectHopHints expects potentialHints to be already sorted in
907
// descending priority.
908
func selectHopHints(cfg *SelectHopHintsCfg, nHintsLeft int,
909
        targetBandwidth lnwire.MilliSatoshi,
910
        potentialHints []*channeldb.OpenChannel,
911
        alreadyIncluded map[uint64]bool) [][]zpay32.HopHint {
3✔
912

3✔
913
        currentBandwidth := lnwire.MilliSatoshi(0)
3✔
914
        hopHints := make([][]zpay32.HopHint, 0, nHintsLeft)
3✔
915
        for _, channel := range potentialHints {
6✔
916
                enoughHopHints := sufficientHints(
3✔
917
                        nHintsLeft, currentBandwidth, targetBandwidth,
3✔
918
                )
3✔
919
                if enoughHopHints {
6✔
920
                        return hopHints
3✔
921
                }
3✔
922

923
                hopHint, remoteBalance, include := shouldIncludeChannel(
3✔
924
                        cfg, channel, alreadyIncluded,
3✔
925
                )
3✔
926

3✔
927
                if include {
6✔
928
                        // Now that we now this channel use usable, add it as a hop
3✔
929
                        // hint and the indexes we'll use later.
3✔
930
                        hopHints = append(hopHints, []zpay32.HopHint{hopHint})
3✔
931
                        currentBandwidth += remoteBalance
3✔
932
                        nHintsLeft--
3✔
933
                }
3✔
934
        }
935

936
        // We do not want to leak information about how our remote balance is
937
        // distributed in our private channels. We shuffle the selected ones
938
        // here so they do not appear in order in the invoice.
939
        mathRand.Shuffle(
3✔
940
                len(hopHints), func(i, j int) {
3✔
UNCOV
941
                        hopHints[i], hopHints[j] = hopHints[j], hopHints[i]
×
UNCOV
942
                },
×
943
        )
944
        return hopHints
3✔
945
}
946

947
// PopulateHopHints will select up to cfg.MaxHophints from the current open
948
// channels. The set of hop hints will be returned as a slice of functional
949
// options that'll append the route hint to the set of all route hints.
950
//
951
// TODO(roasbeef): do proper sub-set sum max hints usually << numChans.
952
func PopulateHopHints(cfg *SelectHopHintsCfg, amtMSat lnwire.MilliSatoshi,
953
        forcedHints [][]zpay32.HopHint) ([][]zpay32.HopHint, error) {
3✔
954

3✔
955
        hopHints := forcedHints
3✔
956

3✔
957
        // If we already have enough hints we don't need to add any more.
3✔
958
        nHintsLeft := cfg.MaxHopHints - len(hopHints)
3✔
959
        if nHintsLeft <= 0 {
6✔
960
                return hopHints, nil
3✔
961
        }
3✔
962

963
        alreadyIncluded := make(map[uint64]bool)
3✔
964
        for _, hopHint := range hopHints {
3✔
965
                alreadyIncluded[hopHint[0].ChannelID] = true
×
966
        }
×
967

968
        potentialHints, err := getPotentialHints(cfg)
3✔
969
        if err != nil {
3✔
970
                return nil, err
×
971
        }
×
972

973
        targetBandwidth := amtMSat * hopHintFactor
3✔
974
        selectedHints := selectHopHints(
3✔
975
                cfg, nHintsLeft, targetBandwidth, potentialHints,
3✔
976
                alreadyIncluded,
3✔
977
        )
3✔
978

3✔
979
        hopHints = append(hopHints, selectedHints...)
3✔
980
        return hopHints, nil
3✔
981
}
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