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

lightningnetwork / lnd / 13980275562

20 Mar 2025 10:06PM UTC coverage: 58.6% (-10.2%) from 68.789%
13980275562

Pull #9623

github

web-flow
Merge b9b960345 into 09b674508
Pull Request #9623: Size msg test msg

0 of 1518 new or added lines in 42 files covered. (0.0%)

26603 existing lines in 443 files now uncovered.

96807 of 165200 relevant lines covered (58.6%)

1.82 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) {
3✔
206

3✔
207
        if d.Amp {
6✔
208
                return d.ampPaymentHashAndPreimage()
3✔
209
        }
3✔
210

211
        return d.mppPaymentHashAndPreimage()
3✔
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) {
3✔
218

3✔
219
        switch {
3✔
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:
3✔
232
                var paymentHash lntypes.Hash
3✔
233
                if _, err := rand.Read(paymentHash[:]); err != nil {
3✔
234
                        return nil, lntypes.Hash{}, err
×
235
                }
×
236

237
                return nil, paymentHash, nil
3✔
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) {
3✔
245

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

3✔
251
        switch {
3✔
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:
3✔
260
                paymentPreimage = &lntypes.Preimage{}
3✔
261
                if _, err := rand.Read(paymentPreimage[:]); err != nil {
3✔
262
                        return nil, lntypes.Hash{}, err
×
263
                }
×
264
                paymentHash = paymentPreimage.Hash()
3✔
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:
3✔
269
                paymentHash = *d.Hash
3✔
270

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

278
        return paymentPreimage, paymentHash, nil
3✔
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) {
3✔
286

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

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

294
        paymentPreimage, paymentHash, err := invoice.paymentHashAndPreimage()
3✔
295
        if err != nil {
3✔
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 {
3✔
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 &&
3✔
307
                len(invoice.DescriptionHash) != 32 {
3✔
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)
3✔
316

3✔
317
        switch {
3✔
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
3✔
332

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

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

347
        // If specified, add a fallback address to the payment request.
348
        if len(invoice.FallbackAddr) > 0 {
3✔
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
3✔
366
        switch {
3✔
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:
3✔
386
                expiry = DefaultInvoiceExpiry
3✔
387

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

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

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

408
        if invoice.CltvExpiry > routing.MaxCLTVDelta {
3✔
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)
3✔
417
        if invoice.CltvExpiry != 0 {
6✔
418
                // Disallow user-chosen final CLTV deltas below the required
3✔
419
                // minimum.
3✔
420
                if invoice.CltvExpiry < routing.MinCLTVDelta {
3✔
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
3✔
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 {
6✔
433
                options = append(options, zpay32.CLTVExpiry(cltvExpiryDelta))
3✔
434
        }
3✔
435

436
        // We make sure that the given invoice routing hints number is within
437
        // the valid range
438
        if len(invoice.RouteHints) > maxHopHints {
3✔
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 {
6✔
445
                if blind {
3✔
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 {
6✔
452
                        if len(hint) == 0 {
3✔
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)
3✔
459
                if invoice.Private {
6✔
460
                        totalHopHints = maxHopHints
3✔
461
                }
3✔
462

463
                hopHintsCfg := newSelectHopHintsCfg(cfg, totalHopHints)
3✔
464
                hopHints, err := PopulateHopHints(
3✔
465
                        hopHintsCfg, amtMSat, invoice.RouteHints,
3✔
466
                )
3✔
467
                if err != nil {
3✔
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 {
6✔
475
                        routeHint := zpay32.RouteHint(hopHint)
3✔
476

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

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

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

504
        if blind {
6✔
505
                blindCfg := invoice.BlindedPathCfg
3✔
506

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

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

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

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

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

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

569
        payReqString, err := payReq.Encode(zpay32.MessageSigner{
3✔
570
                SignCompact: func(msg []byte) ([]byte, error) {
6✔
571
                        // For an invoice without a blinded path, the main node
3✔
572
                        // key is used to sign the invoice so that the sender
3✔
573
                        // can derive the true pub key of the recipient.
3✔
574
                        if !blind {
6✔
575
                                return cfg.NodeSigner.SignMessageCompact(
3✔
576
                                        msg, false,
3✔
577
                                )
3✔
578
                        }
3✔
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()
3✔
585
                        if err != nil {
3✔
586
                                return nil, err
×
587
                        }
×
588

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

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

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

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

622
        return &paymentHash, newInvoice, nil
3✔
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) {
3✔
629

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

636
        // Make sure the channel is active.
637
        if !channel.IsActive {
6✔
638
                log.Debugf("Skipping channel %v due to not "+
3✔
639
                        "being eligible to forward payments",
3✔
640
                        channel.ShortChannelID)
3✔
641
                return nil, false
3✔
642
        }
3✔
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
3✔
650
        copy(remotePub[:], channel.RemotePubkey.SerializeCompressed())
3✔
651
        isRemoteNodePublic, err := cfg.IsPublicNode(remotePub)
3✔
652
        if err != nil {
3✔
653
                log.Errorf("Unable to determine if node %x "+
×
654
                        "is advertised: %v", remotePub, err)
×
655
                return nil, false
×
656
        }
×
657

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

665
        // Fetch the policies for each end of the channel.
666
        info, p1, p2, err := cfg.FetchChannelEdgesByID(channel.ShortChannelID)
3✔
667
        if err != nil {
3✔
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
3✔
684
        if bytes.Equal(remotePub[:], info.NodeKey1Bytes[:]) {
6✔
685
                remotePolicy = p1
3✔
686
        } else {
6✔
687
                remotePolicy = p2
3✔
688
        }
3✔
689

690
        return remotePolicy, true
3✔
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 {
3✔
726
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
727

3✔
728
        return &HopHintInfo{
3✔
729
                IsPublic:         isPublic,
3✔
730
                IsActive:         isActive,
3✔
731
                FundingOutpoint:  c.FundingOutpoint,
3✔
732
                RemotePubkey:     c.IdentityPub,
3✔
733
                RemoteBalance:    c.LocalCommitment.RemoteBalance,
3✔
734
                ShortChannelID:   c.ShortChannelID.ToUint64(),
3✔
735
                ConfirmedScidZC:  c.ZeroConfRealScid().ToUint64(),
3✔
736
                ScidAliasFeature: c.ChanType.HasScidAliasFeature(),
3✔
737
        }
3✔
738
}
3✔
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 {
3✔
744

3✔
745
        return zpay32.HopHint{
3✔
746
                NodeID:      hopHintInfo.RemotePubkey,
3✔
747
                ChannelID:   hopHintInfo.ShortChannelID,
3✔
748
                FeeBaseMSat: uint32(chanPolicy.FeeBaseMSat),
3✔
749
                FeeProportionalMillionths: uint32(
3✔
750
                        chanPolicy.FeeProportionalMillionths,
3✔
751
                ),
3✔
752
                CLTVExpiryDelta: chanPolicy.TimeLockDelta,
3✔
753
        }
3✔
754
}
3✔
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 {
3✔
788

3✔
789
        return &SelectHopHintsCfg{
3✔
790
                FetchAllChannels:      invoicesCfg.ChanDB.FetchAllChannels,
3✔
791
                IsChannelActive:       invoicesCfg.IsChannelActive,
3✔
792
                IsPublicNode:          invoicesCfg.Graph.IsPublicNode,
3✔
793
                FetchChannelEdgesByID: invoicesCfg.Graph.FetchChannelEdgesByID,
3✔
794
                GetAlias:              invoicesCfg.GetAlias,
3✔
795
                MaxHopHints:           maxHopHints,
3✔
796
        }
3✔
797
}
3✔
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 {
3✔
810

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

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

822
        return false
3✔
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) {
3✔
830

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

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

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

3✔
854
        return privateChannels, nil
3✔
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) {
3✔
863

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

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

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

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

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

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

890
                hopHintInfo.ShortChannelID = alias.ToUint64()
3✔
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)
3✔
896
        return hopHint, hopHintInfo.RemoteBalance, true
3✔
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 {
3✔
908

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

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

3✔
923
                if include {
6✔
924
                        // Now that we now this channel use usable, add it as a hop
3✔
925
                        // hint and the indexes we'll use later.
3✔
926
                        hopHints = append(hopHints, []zpay32.HopHint{hopHint})
3✔
927
                        currentBandwidth += remoteBalance
3✔
928
                        nHintsLeft--
3✔
929
                }
3✔
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(
3✔
936
                len(hopHints), func(i, j int) {
3✔
UNCOV
937
                        hopHints[i], hopHints[j] = hopHints[j], hopHints[i]
×
UNCOV
938
                },
×
939
        )
940
        return hopHints
3✔
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) {
3✔
950

3✔
951
        hopHints := forcedHints
3✔
952

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

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

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

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

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