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

lightningnetwork / lnd / 14885280210

07 May 2025 01:59PM UTC coverage: 58.038% (-11.0%) from 68.992%
14885280210

Pull #9789

github

web-flow
Merge b72813120 into 67a40c90a
Pull Request #9789: multi: use updated TLV SizeFunc signature

3 of 6 new or added lines in 2 files covered. (50.0%)

29137 existing lines in 453 files now uncovered.

96491 of 166256 relevant lines covered (58.04%)

1.22 hits per line

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

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

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

2✔
207
        if d.Amp {
4✔
208
                return d.ampPaymentHashAndPreimage()
2✔
209
        }
2✔
210

211
        return d.mppPaymentHashAndPreimage()
2✔
212
}
213

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

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

225
        // If a specific hash was requested, use that.
226
        case d.Hash != nil:
×
227
                return nil, *d.Hash, nil
×
228

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

237
                return nil, paymentHash, nil
2✔
238
        }
239
}
240

241
// mppPaymentHashAndPreimage returns the payment hash and preimage to use for an
242
// MPP invoice.
243
func (d *AddInvoiceData) mppPaymentHashAndPreimage() (*lntypes.Preimage,
244
        lntypes.Hash, error) {
2✔
245

2✔
246
        var (
2✔
247
                paymentPreimage *lntypes.Preimage
2✔
248
                paymentHash     lntypes.Hash
2✔
249
        )
2✔
250

2✔
251
        switch {
2✔
252

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

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

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

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

278
        return paymentPreimage, paymentHash, nil
2✔
279
}
280

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

2✔
287
        blind := invoice.BlindedPathCfg != nil
2✔
288

2✔
289
        if invoice.Amp && blind {
2✔
290
                return nil, nil, fmt.Errorf("AMP invoices with blinded paths " +
×
291
                        "are not yet supported")
×
292
        }
×
293

294
        paymentPreimage, paymentHash, err := invoice.paymentHashAndPreimage()
2✔
295
        if err != nil {
2✔
296
                return nil, nil, err
×
297
        }
×
298

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

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

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

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

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

331
        amtMSat := invoice.Value
2✔
332

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

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

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

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

362
                options = append(options, zpay32.FallbackAddr(addr))
×
363
        }
364

365
        var expiry time.Duration
2✔
366
        switch {
2✔
367
        // An invoice expiry has been provided by the caller.
368
        case invoice.Expiry > 0:
×
369

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

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

382
                expiry = time.Duration(invoice.Expiry) * time.Second
×
383

384
        // If no custom expiry is provided, use the default MPP expiry.
385
        case !invoice.Amp:
2✔
386
                expiry = DefaultInvoiceExpiry
2✔
387

388
        // Otherwise, use the default AMP expiry.
389
        default:
2✔
390
                expiry = DefaultAMPInvoiceExpiry
2✔
391
        }
392

393
        options = append(options, zpay32.Expiry(expiry))
2✔
394

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

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

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

426
                cltvExpiryDelta = invoice.CltvExpiry
2✔
427
        }
428

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

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

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

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

458
                totalHopHints := len(invoice.RouteHints)
2✔
459
                if invoice.Private {
4✔
460
                        totalHopHints = maxHopHints
2✔
461
                }
2✔
462

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

472
                // Convert our set of selected hop hints into route
473
                // hints and add to our invoice options.
474
                for _, hopHint := range hopHints {
4✔
475
                        routeHint := zpay32.RouteHint(hopHint)
2✔
476

2✔
477
                        options = append(
2✔
478
                                options, routeHint,
2✔
479
                        )
2✔
480
                }
2✔
481
        }
482

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

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

504
        if blind {
4✔
505
                blindCfg := invoice.BlindedPathCfg
2✔
506

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

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

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

2✔
537
                                        //nolint:ll
2✔
538
                                        return blindedpath.AddPolicyBuffer(
2✔
539
                                                p, blindCfg.RoutePolicyIncrMultiplier,
2✔
540
                                                blindCfg.RoutePolicyDecrMultiplier,
2✔
541
                                        )
2✔
542
                                },
2✔
543
                                MinNumHops:            blindCfg.MinNumPathHops,
544
                                DefaultDummyHopPolicy: blindCfg.DefaultDummyHopPolicy,
545
                        },
546
                )
547
                if err != nil {
2✔
548
                        return nil, nil, err
×
549
                }
×
550

551
                for _, path := range paths {
4✔
552
                        options = append(options, zpay32.WithBlindedPaymentPath(
2✔
553
                                path,
2✔
554
                        ))
2✔
555
                }
2✔
556
        } else {
2✔
557
                options = append(options, zpay32.PaymentAddr(paymentAddr))
2✔
558
        }
2✔
559

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

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

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

589
                        return ecdsa.SignCompact(
2✔
590
                                ephemKey, chainhash.HashB(msg), true,
2✔
591
                        ), nil
2✔
592
                },
593
        })
594
        if err != nil {
2✔
595
                return nil, nil, err
×
596
        }
×
597

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

2✔
613
        log.Tracef("[addinvoice] adding new invoice %v",
2✔
614
                lnutils.SpewLogClosure(newInvoice))
2✔
615

2✔
616
        // With all sanity checks passed, write the invoice to the database.
2✔
617
        _, err = cfg.AddInvoice(ctx, newInvoice, paymentHash)
2✔
618
        if err != nil {
2✔
619
                return nil, nil, err
×
620
        }
×
621

622
        return &paymentHash, newInvoice, nil
2✔
623
}
624

625
// chanCanBeHopHint returns true if the target channel is eligible to be a hop
626
// hint.
627
func chanCanBeHopHint(channel *HopHintInfo, cfg *SelectHopHintsCfg) (
628
        *models.ChannelEdgePolicy, bool) {
2✔
629

2✔
630
        // Since we're only interested in our private channels, we'll skip
2✔
631
        // public ones.
2✔
632
        if channel.IsPublic {
2✔
UNCOV
633
                return nil, false
×
UNCOV
634
        }
×
635

636
        // Make sure the channel is active.
637
        if !channel.IsActive {
4✔
638
                log.Debugf("Skipping channel %v due to not "+
2✔
639
                        "being eligible to forward payments",
2✔
640
                        channel.ShortChannelID)
2✔
641
                return nil, false
2✔
642
        }
2✔
643

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

658
        if !isRemoteNodePublic {
4✔
659
                log.Debugf("Skipping channel %v due to "+
2✔
660
                        "counterparty %x being unadvertised",
2✔
661
                        channel.ShortChannelID, remotePub)
2✔
662
                return nil, false
2✔
663
        }
2✔
664

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

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

690
        return remotePolicy, true
2✔
691
}
692

693
// HopHintInfo contains the channel information required to create a hop hint.
694
type HopHintInfo struct {
695
        // IsPublic indicates whether a channel is advertised to the network.
696
        IsPublic bool
697

698
        // IsActive indicates whether the channel is online and available for
699
        // use.
700
        IsActive bool
701

702
        // FundingOutpoint is the funding txid:index for the channel.
703
        FundingOutpoint wire.OutPoint
704

705
        // RemotePubkey is the public key of the remote party that this channel
706
        // is in.
707
        RemotePubkey *btcec.PublicKey
708

709
        // RemoteBalance is the remote party's balance (our current incoming
710
        // capacity).
711
        RemoteBalance lnwire.MilliSatoshi
712

713
        // ShortChannelID is the short channel ID of the channel.
714
        ShortChannelID uint64
715

716
        // ConfirmedScidZC is the confirmed SCID of a zero-conf channel. This
717
        // may be used for looking up a channel in the graph.
718
        ConfirmedScidZC uint64
719

720
        // ScidAliasFeature denotes whether the channel has negotiated the
721
        // option-scid-alias feature bit.
722
        ScidAliasFeature bool
723
}
724

725
func newHopHintInfo(c *channeldb.OpenChannel, isActive bool) *HopHintInfo {
2✔
726
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
2✔
727

2✔
728
        return &HopHintInfo{
2✔
729
                IsPublic:         isPublic,
2✔
730
                IsActive:         isActive,
2✔
731
                FundingOutpoint:  c.FundingOutpoint,
2✔
732
                RemotePubkey:     c.IdentityPub,
2✔
733
                RemoteBalance:    c.LocalCommitment.RemoteBalance,
2✔
734
                ShortChannelID:   c.ShortChannelID.ToUint64(),
2✔
735
                ConfirmedScidZC:  c.ZeroConfRealScid().ToUint64(),
2✔
736
                ScidAliasFeature: c.ChanType.HasScidAliasFeature(),
2✔
737
        }
2✔
738
}
2✔
739

740
// newHopHint returns a new hop hint using the relevant data from a hopHintInfo
741
// and a ChannelEdgePolicy.
742
func newHopHint(hopHintInfo *HopHintInfo,
743
        chanPolicy *models.ChannelEdgePolicy) zpay32.HopHint {
2✔
744

2✔
745
        return zpay32.HopHint{
2✔
746
                NodeID:      hopHintInfo.RemotePubkey,
2✔
747
                ChannelID:   hopHintInfo.ShortChannelID,
2✔
748
                FeeBaseMSat: uint32(chanPolicy.FeeBaseMSat),
2✔
749
                FeeProportionalMillionths: uint32(
2✔
750
                        chanPolicy.FeeProportionalMillionths,
2✔
751
                ),
2✔
752
                CLTVExpiryDelta: chanPolicy.TimeLockDelta,
2✔
753
        }
2✔
754
}
2✔
755

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

764
        // FetchChannelEdgesByID attempts to lookup the two directed edges for
765
        // the channel identified by the channel ID.
766
        FetchChannelEdgesByID func(chanID uint64) (*models.ChannelEdgeInfo,
767
                *models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
768
                error)
769

770
        // GetAlias allows the peer's alias SCID to be retrieved for private
771
        // option_scid_alias channels.
772
        GetAlias func(lnwire.ChannelID) (lnwire.ShortChannelID, error)
773

774
        // FetchAllChannels retrieves all open channels currently stored
775
        // within the database.
776
        FetchAllChannels func() ([]*channeldb.OpenChannel, error)
777

778
        // IsChannelActive checks whether the channel identified by the provided
779
        // ChannelID is considered active.
780
        IsChannelActive func(chanID lnwire.ChannelID) bool
781

782
        // MaxHopHints is the maximum number of hop hints we are interested in.
783
        MaxHopHints int
784
}
785

786
func newSelectHopHintsCfg(invoicesCfg *AddInvoiceConfig,
787
        maxHopHints int) *SelectHopHintsCfg {
2✔
788

2✔
789
        return &SelectHopHintsCfg{
2✔
790
                FetchAllChannels:      invoicesCfg.ChanDB.FetchAllChannels,
2✔
791
                IsChannelActive:       invoicesCfg.IsChannelActive,
2✔
792
                IsPublicNode:          invoicesCfg.Graph.IsPublicNode,
2✔
793
                FetchChannelEdgesByID: invoicesCfg.Graph.FetchChannelEdgesByID,
2✔
794
                GetAlias:              invoicesCfg.GetAlias,
2✔
795
                MaxHopHints:           maxHopHints,
2✔
796
        }
2✔
797
}
2✔
798

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

2✔
811
        if nHintsLeft <= 0 {
2✔
UNCOV
812
                log.Debugf("Reached targeted number of hop hints")
×
UNCOV
813
                return true
×
UNCOV
814
        }
×
815

816
        if targetAmount != 0 && currentAmount >= targetAmount {
4✔
817
                log.Debugf("Total hint amount: %v has reached target hint "+
2✔
818
                        "bandwidth: %v", currentAmount, targetAmount)
2✔
819
                return true
2✔
820
        }
2✔
821

822
        return false
2✔
823
}
824

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

2✔
831
        // TODO(positiveblue): get the channels slice already filtered by
2✔
832
        // private == true and sorted by RemoteBalance?
2✔
833
        openChannels, err := cfg.FetchAllChannels()
2✔
834
        if err != nil {
2✔
835
                return nil, err
×
836
        }
×
837

838
        privateChannels := make([]*channeldb.OpenChannel, 0, len(openChannels))
2✔
839
        for _, oc := range openChannels {
4✔
840
                isPublic := oc.ChannelFlags&lnwire.FFAnnounceChannel != 0
2✔
841
                if !isPublic {
4✔
842
                        privateChannels = append(privateChannels, oc)
2✔
843
                }
2✔
844
        }
845

846
        // Sort the channels in descending remote balance.
847
        compareRemoteBalance := func(i, j int) bool {
4✔
848
                iBalance := privateChannels[i].LocalCommitment.RemoteBalance
2✔
849
                jBalance := privateChannels[j].LocalCommitment.RemoteBalance
2✔
850
                return iBalance > jBalance
2✔
851
        }
2✔
852
        sort.Slice(privateChannels, compareRemoteBalance)
2✔
853

2✔
854
        return privateChannels, nil
2✔
855
}
856

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

2✔
864
        if _, ok := alreadyIncluded[channel.ShortChannelID.ToUint64()]; ok {
2✔
UNCOV
865
                return zpay32.HopHint{}, 0, false
×
UNCOV
866
        }
×
867

868
        chanID := lnwire.NewChanIDFromOutPoint(
2✔
869
                channel.FundingOutpoint,
2✔
870
        )
2✔
871

2✔
872
        hopHintInfo := newHopHintInfo(channel, cfg.IsChannelActive(chanID))
2✔
873

2✔
874
        // If this channel can't be a hop hint, then skip it.
2✔
875
        edgePolicy, canBeHopHint := chanCanBeHopHint(hopHintInfo, cfg)
2✔
876
        if edgePolicy == nil || !canBeHopHint {
4✔
877
                return zpay32.HopHint{}, 0, false
2✔
878
        }
2✔
879

880
        if hopHintInfo.ScidAliasFeature {
4✔
881
                alias, err := cfg.GetAlias(chanID)
2✔
882
                if err != nil {
2✔
883
                        return zpay32.HopHint{}, 0, false
×
884
                }
×
885

886
                if alias.IsDefault() || alreadyIncluded[alias.ToUint64()] {
2✔
UNCOV
887
                        return zpay32.HopHint{}, 0, false
×
UNCOV
888
                }
×
889

890
                hopHintInfo.ShortChannelID = alias.ToUint64()
2✔
891
        }
892

893
        // Now that we know this channel use usable, add it as a hop hint and
894
        // the indexes we'll use later.
895
        hopHint := newHopHint(hopHintInfo, edgePolicy)
2✔
896
        return hopHint, hopHintInfo.RemoteBalance, true
2✔
897
}
898

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

2✔
909
        currentBandwidth := lnwire.MilliSatoshi(0)
2✔
910
        hopHints := make([][]zpay32.HopHint, 0, nHintsLeft)
2✔
911
        for _, channel := range potentialHints {
4✔
912
                enoughHopHints := sufficientHints(
2✔
913
                        nHintsLeft, currentBandwidth, targetBandwidth,
2✔
914
                )
2✔
915
                if enoughHopHints {
4✔
916
                        return hopHints
2✔
917
                }
2✔
918

919
                hopHint, remoteBalance, include := shouldIncludeChannel(
2✔
920
                        cfg, channel, alreadyIncluded,
2✔
921
                )
2✔
922

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

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

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

2✔
951
        hopHints := forcedHints
2✔
952

2✔
953
        // If we already have enough hints we don't need to add any more.
2✔
954
        nHintsLeft := cfg.MaxHopHints - len(hopHints)
2✔
955
        if nHintsLeft <= 0 {
4✔
956
                return hopHints, nil
2✔
957
        }
2✔
958

959
        alreadyIncluded := make(map[uint64]bool)
2✔
960
        for _, hopHint := range hopHints {
2✔
961
                alreadyIncluded[hopHint[0].ChannelID] = true
×
962
        }
×
963

964
        potentialHints, err := getPotentialHints(cfg)
2✔
965
        if err != nil {
2✔
966
                return nil, err
×
967
        }
×
968

969
        targetBandwidth := amtMSat * hopHintFactor
2✔
970
        selectedHints := selectHopHints(
2✔
971
                cfg, nHintsLeft, targetBandwidth, potentialHints,
2✔
972
                alreadyIncluded,
2✔
973
        )
2✔
974

2✔
975
        hopHints = append(hopHints, selectedHints...)
2✔
976
        return hopHints, nil
2✔
977
}
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