2019-01-14 19:56:59 +03:00
|
|
|
package invoicesrpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"crypto/rand"
|
2018-10-05 11:14:56 +03:00
|
|
|
"errors"
|
2019-01-14 19:56:59 +03:00
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/btcsuite/btcd/chaincfg"
|
2020-06-28 16:51:42 +03:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2020-08-11 02:18:48 +03:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2019-01-14 19:56:59 +03:00
|
|
|
"github.com/btcsuite/btcutil"
|
|
|
|
"github.com/davecgh/go-spew/spew"
|
2018-10-05 11:14:56 +03:00
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
2018-10-05 11:14:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lntypes"
|
2019-01-14 19:56:59 +03:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2018-10-05 11:14:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/netann"
|
2020-07-24 23:13:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/routing"
|
2018-10-05 11:14:56 +03:00
|
|
|
"github.com/lightningnetwork/lnd/zpay32"
|
2019-01-14 19:56:59 +03:00
|
|
|
)
|
|
|
|
|
2021-05-27 04:10:58 +03:00
|
|
|
const (
|
|
|
|
// DefaultInvoiceExpiry is the default invoice expiry for new MPP
|
|
|
|
// invoices.
|
|
|
|
DefaultInvoiceExpiry = 24 * time.Hour
|
|
|
|
|
|
|
|
// DefaultAMPInvoiceExpiry is the default invoice expiry for new AMP
|
|
|
|
// invoices.
|
|
|
|
DefaultAMPInvoiceExpiry = 30 * 24 * time.Hour
|
|
|
|
)
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
// AddInvoiceConfig contains dependencies for invoice creation.
|
|
|
|
type AddInvoiceConfig struct {
|
|
|
|
// AddInvoice is called to add the invoice to the registry.
|
|
|
|
AddInvoice func(invoice *channeldb.Invoice, paymentHash lntypes.Hash) (
|
|
|
|
uint64, error)
|
|
|
|
|
|
|
|
// IsChannelActive is used to generate valid hop hints.
|
|
|
|
IsChannelActive func(chanID lnwire.ChannelID) bool
|
|
|
|
|
|
|
|
// ChainParams are required to properly decode invoice payment requests
|
|
|
|
// that are marshalled over rpc.
|
|
|
|
ChainParams *chaincfg.Params
|
|
|
|
|
|
|
|
// NodeSigner is an implementation of the MessageSigner implementation
|
|
|
|
// that's backed by the identity private key of the running lnd node.
|
|
|
|
NodeSigner *netann.NodeSigner
|
|
|
|
|
|
|
|
// DefaultCLTVExpiry is the default invoice expiry if no values is
|
|
|
|
// specified.
|
|
|
|
DefaultCLTVExpiry uint32
|
|
|
|
|
|
|
|
// ChanDB is a global boltdb instance which is needed to access the
|
|
|
|
// channel graph.
|
|
|
|
ChanDB *channeldb.DB
|
2019-12-11 00:09:52 +03:00
|
|
|
|
2020-10-26 16:14:15 +03:00
|
|
|
// Graph holds a reference to the ChannelGraph database.
|
|
|
|
Graph *channeldb.ChannelGraph
|
|
|
|
|
2019-12-11 00:09:52 +03:00
|
|
|
// GenInvoiceFeatures returns a feature containing feature bits that
|
|
|
|
// should be advertised on freshly generated invoices.
|
|
|
|
GenInvoiceFeatures func() *lnwire.FeatureVector
|
2021-05-06 19:15:01 +03:00
|
|
|
|
|
|
|
// GenAmpInvoiceFeatures returns a feature containing feature bits that
|
|
|
|
// should be advertised on freshly generated AMP invoices.
|
|
|
|
GenAmpInvoiceFeatures func() *lnwire.FeatureVector
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2019-01-15 12:06:48 +03:00
|
|
|
// AddInvoiceData contains the required data to create a new invoice.
|
|
|
|
type AddInvoiceData struct {
|
|
|
|
// An optional memo to attach along with the invoice. Used for record
|
|
|
|
// keeping purposes for the invoice's creator, and will also be set in
|
|
|
|
// the description field of the encoded payment request if the
|
|
|
|
// description_hash field is not being used.
|
|
|
|
Memo string
|
|
|
|
|
|
|
|
// The preimage which will allow settling an incoming HTLC payable to
|
2018-10-05 11:14:56 +03:00
|
|
|
// this preimage. If Preimage is set, Hash should be nil. If both
|
|
|
|
// Preimage and Hash are nil, a random preimage is generated.
|
2019-01-15 12:06:48 +03:00
|
|
|
Preimage *lntypes.Preimage
|
|
|
|
|
2018-10-05 11:14:56 +03:00
|
|
|
// The hash of the preimage. If Hash is set, Preimage should be nil.
|
|
|
|
// This condition indicates that we have a 'hold invoice' for which the
|
|
|
|
// htlc will be accepted and held until the preimage becomes known.
|
|
|
|
Hash *lntypes.Hash
|
|
|
|
|
2019-11-15 10:59:14 +03:00
|
|
|
// The value of this invoice in millisatoshis.
|
|
|
|
Value lnwire.MilliSatoshi
|
2019-01-15 12:06:48 +03:00
|
|
|
|
|
|
|
// Hash (SHA-256) of a description of the payment. Used if the
|
|
|
|
// description of payment (memo) is too long to naturally fit within the
|
|
|
|
// description field of an encoded payment request.
|
|
|
|
DescriptionHash []byte
|
|
|
|
|
|
|
|
// Payment request expiry time in seconds. Default is 3600 (1 hour).
|
|
|
|
Expiry int64
|
|
|
|
|
|
|
|
// Fallback on-chain address.
|
|
|
|
FallbackAddr string
|
|
|
|
|
|
|
|
// Delta to use for the time-lock of the CLTV extended to the final hop.
|
|
|
|
CltvExpiry uint64
|
|
|
|
|
|
|
|
// Whether this invoice should include routing hints for private
|
|
|
|
// channels.
|
|
|
|
Private bool
|
2020-04-08 14:47:10 +03:00
|
|
|
|
|
|
|
// HodlInvoice signals that this invoice shouldn't be settled
|
|
|
|
// immediately upon receiving the payment.
|
|
|
|
HodlInvoice bool
|
2019-11-03 16:00:27 +03:00
|
|
|
|
2021-05-06 19:15:15 +03:00
|
|
|
// Amp signals whether or not to create an AMP invoice.
|
|
|
|
//
|
|
|
|
// NOTE: Preimage should always be set to nil when this value is true.
|
|
|
|
Amp bool
|
|
|
|
|
2019-11-03 16:00:27 +03:00
|
|
|
// RouteHints are optional route hints that can each be individually used
|
|
|
|
// to assist in reaching the invoice's destination.
|
|
|
|
RouteHints [][]zpay32.HopHint
|
2019-01-15 12:06:48 +03:00
|
|
|
}
|
|
|
|
|
2021-05-06 19:13:54 +03:00
|
|
|
// paymentHashAndPreimage returns the payment hash and preimage for this invoice
|
|
|
|
// depending on the configuration.
|
|
|
|
//
|
2021-05-06 19:15:15 +03:00
|
|
|
// For AMP invoices (when Amp flag is true), this method always returns a nil
|
|
|
|
// preimage. The hash value can be set externally by the user using the Hash
|
|
|
|
// field, or one will be generated randomly. The payment hash here only serves
|
|
|
|
// as a unique identifier for insertion into the invoice index, as there is
|
|
|
|
// no universal preimage for an AMP payment.
|
|
|
|
//
|
2021-05-06 19:13:54 +03:00
|
|
|
// For MPP invoices (when Amp flag is false), this method may return nil
|
|
|
|
// preimage when create a hodl invoice, but otherwise will always return a
|
|
|
|
// non-nil preimage and the corresponding payment hash. The valid combinations
|
|
|
|
// are parsed as follows:
|
|
|
|
// - Preimage == nil && Hash == nil -> (random preimage, H(random preimage))
|
|
|
|
// - Preimage != nil && Hash == nil -> (Preimage, H(Preimage))
|
|
|
|
// - Preimage == nil && Hash != nil -> (nil, Hash)
|
|
|
|
func (d *AddInvoiceData) paymentHashAndPreimage() (
|
|
|
|
*lntypes.Preimage, lntypes.Hash, error) {
|
2019-01-14 19:56:59 +03:00
|
|
|
|
2021-05-06 19:15:15 +03:00
|
|
|
if d.Amp {
|
|
|
|
return d.ampPaymentHashAndPreimage()
|
|
|
|
}
|
|
|
|
|
|
|
|
return d.mppPaymentHashAndPreimage()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ampPaymentHashAndPreimage returns the payment hash to use for an AMP invoice.
|
|
|
|
// The preimage will always be nil.
|
|
|
|
func (d *AddInvoiceData) ampPaymentHashAndPreimage() (*lntypes.Preimage, lntypes.Hash, error) {
|
|
|
|
switch {
|
|
|
|
|
|
|
|
// Preimages cannot be set on AMP invoice.
|
|
|
|
case d.Preimage != nil:
|
|
|
|
return nil, lntypes.Hash{},
|
|
|
|
errors.New("preimage set on AMP invoice")
|
|
|
|
|
|
|
|
// If a specific hash was requested, use that.
|
|
|
|
case d.Hash != nil:
|
|
|
|
return nil, *d.Hash, nil
|
|
|
|
|
|
|
|
// Otherwise generate a random hash value, just needs to be unique to be
|
|
|
|
// added to the invoice index.
|
|
|
|
default:
|
|
|
|
var paymentHash lntypes.Hash
|
|
|
|
if _, err := rand.Read(paymentHash[:]); err != nil {
|
|
|
|
return nil, lntypes.Hash{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, paymentHash, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// mppPaymentHashAndPreimage returns the payment hash and preimage to use for an
|
|
|
|
// MPP invoice.
|
|
|
|
func (d *AddInvoiceData) mppPaymentHashAndPreimage() (*lntypes.Preimage, lntypes.Hash, error) {
|
2018-10-05 11:14:56 +03:00
|
|
|
var (
|
2020-04-08 14:47:10 +03:00
|
|
|
paymentPreimage *lntypes.Preimage
|
2018-10-05 11:14:56 +03:00
|
|
|
paymentHash lntypes.Hash
|
|
|
|
)
|
|
|
|
|
|
|
|
switch {
|
|
|
|
|
|
|
|
// Only either preimage or hash can be set.
|
2021-05-06 19:13:54 +03:00
|
|
|
case d.Preimage != nil && d.Hash != nil:
|
|
|
|
return nil, lntypes.Hash{},
|
2018-10-05 11:14:56 +03:00
|
|
|
errors.New("preimage and hash both set")
|
|
|
|
|
|
|
|
// If no hash or preimage is given, generate a random preimage.
|
2021-05-06 19:13:54 +03:00
|
|
|
case d.Preimage == nil && d.Hash == nil:
|
2020-04-08 14:47:10 +03:00
|
|
|
paymentPreimage = &lntypes.Preimage{}
|
2019-01-14 19:56:59 +03:00
|
|
|
if _, err := rand.Read(paymentPreimage[:]); err != nil {
|
2021-05-06 19:13:54 +03:00
|
|
|
return nil, lntypes.Hash{}, err
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
2018-10-05 11:14:56 +03:00
|
|
|
paymentHash = paymentPreimage.Hash()
|
|
|
|
|
|
|
|
// If just a hash is given, we create a hold invoice by setting the
|
|
|
|
// preimage to unknown.
|
2021-05-06 19:13:54 +03:00
|
|
|
case d.Preimage == nil && d.Hash != nil:
|
|
|
|
paymentHash = *d.Hash
|
2018-10-05 11:14:56 +03:00
|
|
|
|
|
|
|
// A specific preimage was supplied. Use that for the invoice.
|
2021-05-06 19:13:54 +03:00
|
|
|
case d.Preimage != nil && d.Hash == nil:
|
|
|
|
preimage := *d.Preimage
|
2020-04-08 14:47:10 +03:00
|
|
|
paymentPreimage = &preimage
|
2021-05-06 19:13:54 +03:00
|
|
|
paymentHash = d.Preimage.Hash()
|
|
|
|
}
|
|
|
|
|
|
|
|
return paymentPreimage, paymentHash, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddInvoice attempts to add a new invoice to the invoice database. Any
|
|
|
|
// duplicated invoices are rejected, therefore all invoices *must* have a
|
|
|
|
// unique payment preimage.
|
|
|
|
func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig,
|
|
|
|
invoice *AddInvoiceData) (*lntypes.Hash, *channeldb.Invoice, error) {
|
|
|
|
|
|
|
|
paymentPreimage, paymentHash, err := invoice.paymentHashAndPreimage()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// The size of the memo, receipt and description hash attached must not
|
|
|
|
// exceed the maximum values for either of the fields.
|
|
|
|
if len(invoice.Memo) > channeldb.MaxMemoSize {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("memo too large: %v bytes "+
|
2019-01-14 19:56:59 +03:00
|
|
|
"(maxsize=%v)", len(invoice.Memo), channeldb.MaxMemoSize)
|
|
|
|
}
|
|
|
|
if len(invoice.DescriptionHash) > 0 && len(invoice.DescriptionHash) != 32 {
|
2019-09-11 17:09:52 +03:00
|
|
|
return nil, nil, fmt.Errorf("description hash is %v bytes, must be 32",
|
|
|
|
len(invoice.DescriptionHash))
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2020-04-22 02:42:52 +03:00
|
|
|
// We set the max invoice amount to 100k BTC, which itself is several
|
|
|
|
// multiples off the current block reward.
|
|
|
|
maxInvoiceAmt := btcutil.Amount(btcutil.SatoshiPerBitcoin * 100000)
|
|
|
|
|
|
|
|
switch {
|
2019-01-14 19:56:59 +03:00
|
|
|
// The value of the invoice must not be negative.
|
2020-04-22 08:16:05 +03:00
|
|
|
case int64(invoice.Value) < 0:
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("payments of negative value "+
|
2020-04-22 08:16:05 +03:00
|
|
|
"are not allowed, value is %v", int64(invoice.Value))
|
2020-04-22 02:42:52 +03:00
|
|
|
|
|
|
|
// Also ensure that the invoice is actually realistic, while preventing
|
|
|
|
// any issues due to underflow.
|
|
|
|
case invoice.Value.ToSatoshis() > maxInvoiceAmt:
|
|
|
|
return nil, nil, fmt.Errorf("invoice amount %v is "+
|
|
|
|
"too large, max is %v", invoice.Value.ToSatoshis(),
|
|
|
|
maxInvoiceAmt)
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2019-11-15 10:59:14 +03:00
|
|
|
amtMSat := invoice.Value
|
2019-01-14 19:56:59 +03:00
|
|
|
|
|
|
|
// We also create an encoded payment request which allows the
|
|
|
|
// caller to compactly send the invoice to the payer. We'll create a
|
|
|
|
// list of options to be added to the encoded payment request. For now
|
|
|
|
// we only support the required fields description/description_hash,
|
|
|
|
// expiry, fallback address, and the amount field.
|
|
|
|
var options []func(*zpay32.Invoice)
|
|
|
|
|
|
|
|
// We only include the amount in the invoice if it is greater than 0.
|
|
|
|
// By not including the amount, we enable the creation of invoices that
|
|
|
|
// allow the payee to specify the amount of satoshis they wish to send.
|
|
|
|
if amtMSat > 0 {
|
|
|
|
options = append(options, zpay32.Amount(amtMSat))
|
|
|
|
}
|
|
|
|
|
|
|
|
// If specified, add a fallback address to the payment request.
|
|
|
|
if len(invoice.FallbackAddr) > 0 {
|
|
|
|
addr, err := btcutil.DecodeAddress(invoice.FallbackAddr,
|
|
|
|
cfg.ChainParams)
|
|
|
|
if err != nil {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("invalid fallback address: %v",
|
2019-01-14 19:56:59 +03:00
|
|
|
err)
|
|
|
|
}
|
|
|
|
options = append(options, zpay32.FallbackAddr(addr))
|
|
|
|
}
|
|
|
|
|
2021-05-27 04:10:58 +03:00
|
|
|
switch {
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
// If expiry is set, specify it. If it is not provided, no expiry time
|
|
|
|
// will be explicitly added to this payment request, which will imply
|
|
|
|
// the default 3600 seconds.
|
2021-05-27 04:10:58 +03:00
|
|
|
case invoice.Expiry > 0:
|
2019-01-14 19:56:59 +03:00
|
|
|
|
|
|
|
// We'll ensure that the specified expiry is restricted to sane
|
|
|
|
// number of seconds. As a result, we'll reject an invoice with
|
|
|
|
// an expiry greater than 1 year.
|
|
|
|
maxExpiry := time.Hour * 24 * 365
|
|
|
|
expSeconds := invoice.Expiry
|
|
|
|
|
|
|
|
if float64(expSeconds) > maxExpiry.Seconds() {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("expiry of %v seconds "+
|
2019-01-14 19:56:59 +03:00
|
|
|
"greater than max expiry of %v seconds",
|
|
|
|
float64(expSeconds), maxExpiry.Seconds())
|
|
|
|
}
|
|
|
|
|
|
|
|
expiry := time.Duration(invoice.Expiry) * time.Second
|
|
|
|
options = append(options, zpay32.Expiry(expiry))
|
2021-05-27 04:10:58 +03:00
|
|
|
|
|
|
|
// If no custom expiry is provided, use the default MPP expiry.
|
|
|
|
case !invoice.Amp:
|
|
|
|
options = append(options, zpay32.Expiry(DefaultInvoiceExpiry))
|
|
|
|
|
|
|
|
// Otherwise, use the default AMP expiry.
|
|
|
|
default:
|
|
|
|
options = append(options, zpay32.Expiry(DefaultAMPInvoiceExpiry))
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If the description hash is set, then we add it do the list of options.
|
|
|
|
// If not, use the memo field as the payment request description.
|
|
|
|
if len(invoice.DescriptionHash) > 0 {
|
|
|
|
var descHash [32]byte
|
|
|
|
copy(descHash[:], invoice.DescriptionHash[:])
|
|
|
|
options = append(options, zpay32.DescriptionHash(descHash))
|
|
|
|
} else {
|
|
|
|
// Use the memo field as the description. If this is not set
|
|
|
|
// this will just be an empty string.
|
|
|
|
options = append(options, zpay32.Description(invoice.Memo))
|
|
|
|
}
|
|
|
|
|
|
|
|
// We'll use our current default CLTV value unless one was specified as
|
|
|
|
// an option on the command line when creating an invoice.
|
|
|
|
switch {
|
|
|
|
case invoice.CltvExpiry > math.MaxUint16:
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("CLTV delta of %v is too large, max "+
|
2019-01-14 19:56:59 +03:00
|
|
|
"accepted is: %v", invoice.CltvExpiry, math.MaxUint16)
|
|
|
|
case invoice.CltvExpiry != 0:
|
2020-07-24 23:13:56 +03:00
|
|
|
// Disallow user-chosen final CLTV deltas below the required
|
|
|
|
// minimum.
|
|
|
|
if invoice.CltvExpiry < routing.MinCLTVDelta {
|
|
|
|
return nil, nil, fmt.Errorf("CLTV delta of %v must be "+
|
|
|
|
"greater than minimum of %v",
|
|
|
|
routing.MinCLTVDelta, invoice.CltvExpiry)
|
|
|
|
}
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
options = append(options,
|
|
|
|
zpay32.CLTVExpiry(invoice.CltvExpiry))
|
|
|
|
default:
|
|
|
|
// TODO(roasbeef): assumes set delta between versions
|
|
|
|
defaultDelta := cfg.DefaultCLTVExpiry
|
|
|
|
options = append(options, zpay32.CLTVExpiry(uint64(defaultDelta)))
|
|
|
|
}
|
|
|
|
|
2019-11-03 16:00:27 +03:00
|
|
|
// We make sure that the given invoice routing hints number is within the
|
|
|
|
// valid range
|
|
|
|
if len(invoice.RouteHints) > 20 {
|
|
|
|
return nil, nil, fmt.Errorf("number of routing hints must not exceed " +
|
|
|
|
"maximum of 20")
|
|
|
|
}
|
|
|
|
|
|
|
|
// We continue by populating the requested routing hints indexing their
|
|
|
|
// corresponding channels so we won't duplicate them.
|
|
|
|
forcedHints := make(map[uint64]struct{})
|
|
|
|
for _, h := range invoice.RouteHints {
|
|
|
|
if len(h) == 0 {
|
|
|
|
return nil, nil, fmt.Errorf("number of hop hint within a route must " +
|
|
|
|
"be positive")
|
|
|
|
}
|
|
|
|
options = append(options, zpay32.RouteHint(h))
|
|
|
|
|
|
|
|
// Only this first hop is our direct channel.
|
|
|
|
forcedHints[h[0].ChannelID] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
// If we were requested to include routing hints in the invoice, then
|
|
|
|
// we'll fetch all of our available private channels and create routing
|
|
|
|
// hints for them.
|
|
|
|
if invoice.Private {
|
|
|
|
openChannels, err := cfg.ChanDB.FetchAllChannels()
|
|
|
|
if err != nil {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, fmt.Errorf("could not fetch all channels")
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2020-08-12 03:48:14 +03:00
|
|
|
if len(openChannels) > 0 {
|
2019-11-03 16:00:27 +03:00
|
|
|
// We filter the channels by excluding the ones that were specified by
|
|
|
|
// the caller and were already added.
|
|
|
|
var filteredChannels []*channeldb.OpenChannel
|
|
|
|
for _, c := range openChannels {
|
|
|
|
if _, ok := forcedHints[c.ShortChanID().ToUint64()]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
filteredChannels = append(filteredChannels, c)
|
|
|
|
}
|
|
|
|
|
2020-08-12 03:48:14 +03:00
|
|
|
// We'll restrict the number of individual route hints
|
|
|
|
// to 20 to avoid creating overly large invoices.
|
2019-11-03 16:00:27 +03:00
|
|
|
numMaxHophints := 20 - len(forcedHints)
|
2020-08-12 03:48:14 +03:00
|
|
|
hopHints := selectHopHints(
|
2019-11-03 16:00:27 +03:00
|
|
|
amtMSat, cfg, filteredChannels, numMaxHophints,
|
2020-08-12 03:48:14 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
options = append(options, hopHints...)
|
|
|
|
}
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2019-12-11 00:09:52 +03:00
|
|
|
// Set our desired invoice features and add them to our list of options.
|
2021-05-06 19:15:15 +03:00
|
|
|
var invoiceFeatures *lnwire.FeatureVector
|
|
|
|
if invoice.Amp {
|
|
|
|
invoiceFeatures = cfg.GenAmpInvoiceFeatures()
|
|
|
|
} else {
|
|
|
|
invoiceFeatures = cfg.GenInvoiceFeatures()
|
|
|
|
}
|
2019-11-22 13:24:28 +03:00
|
|
|
options = append(options, zpay32.Features(invoiceFeatures))
|
|
|
|
|
2019-12-05 18:59:31 +03:00
|
|
|
// Generate and set a random payment address for this invoice. If the
|
|
|
|
// sender understands payment addresses, this can be used to avoid
|
|
|
|
// intermediaries probing the receiver.
|
|
|
|
var paymentAddr [32]byte
|
|
|
|
if _, err := rand.Read(paymentAddr[:]); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
options = append(options, zpay32.PaymentAddr(paymentAddr))
|
|
|
|
|
2019-01-14 19:56:59 +03:00
|
|
|
// Create and encode the payment request as a bech32 (zpay32) string.
|
|
|
|
creationDate := time.Now()
|
|
|
|
payReq, err := zpay32.NewInvoice(
|
2018-10-05 11:14:56 +03:00
|
|
|
cfg.ChainParams, paymentHash, creationDate, options...,
|
2019-01-14 19:56:59 +03:00
|
|
|
)
|
|
|
|
if err != nil {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, err
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
payReqString, err := payReq.Encode(
|
|
|
|
zpay32.MessageSigner{
|
2020-06-28 16:51:42 +03:00
|
|
|
SignCompact: func(msg []byte) ([]byte, error) {
|
|
|
|
hash := chainhash.HashB(msg)
|
|
|
|
return cfg.NodeSigner.SignDigestCompact(hash)
|
|
|
|
},
|
2019-01-14 19:56:59 +03:00
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, err
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
newInvoice := &channeldb.Invoice{
|
|
|
|
CreationDate: creationDate,
|
|
|
|
Memo: []byte(invoice.Memo),
|
|
|
|
PaymentRequest: []byte(payReqString),
|
|
|
|
Terms: channeldb.ContractTerm{
|
2019-11-22 13:25:02 +03:00
|
|
|
FinalCltvDelta: int32(payReq.MinFinalCLTVExpiry()),
|
|
|
|
Expiry: payReq.Expiry(),
|
2019-01-14 19:56:59 +03:00
|
|
|
Value: amtMSat,
|
|
|
|
PaymentPreimage: paymentPreimage,
|
2019-12-05 18:59:31 +03:00
|
|
|
PaymentAddr: paymentAddr,
|
2019-11-22 13:24:28 +03:00
|
|
|
Features: invoiceFeatures,
|
2019-01-14 19:56:59 +03:00
|
|
|
},
|
2020-04-08 14:47:10 +03:00
|
|
|
HodlInvoice: invoice.HodlInvoice,
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Tracef("[addinvoice] adding new invoice %v",
|
|
|
|
newLogClosure(func() string {
|
|
|
|
return spew.Sdump(newInvoice)
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
|
|
|
// With all sanity checks passed, write the invoice to the database.
|
2018-10-05 11:14:56 +03:00
|
|
|
_, err = cfg.AddInvoice(newInvoice, paymentHash)
|
2019-01-14 19:56:59 +03:00
|
|
|
if err != nil {
|
2019-01-15 12:06:48 +03:00
|
|
|
return nil, nil, err
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
|
|
|
|
2018-10-05 11:14:56 +03:00
|
|
|
return &paymentHash, newInvoice, nil
|
2019-01-14 19:56:59 +03:00
|
|
|
}
|
2020-08-11 02:06:39 +03:00
|
|
|
|
2020-08-12 03:38:26 +03:00
|
|
|
// chanCanBeHopHint returns true if the target channel is eligible to be a hop
|
|
|
|
// hint.
|
2020-10-26 16:14:15 +03:00
|
|
|
func chanCanBeHopHint(channel *channeldb.OpenChannel, cfg *AddInvoiceConfig) (
|
|
|
|
*channeldb.ChannelEdgePolicy, bool) {
|
2020-08-12 03:38:26 +03:00
|
|
|
|
|
|
|
// Since we're only interested in our private channels, we'll skip
|
|
|
|
// public ones.
|
|
|
|
isPublic := channel.ChannelFlags&lnwire.FFAnnounceChannel != 0
|
|
|
|
if isPublic {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure the channel is active.
|
|
|
|
chanPoint := lnwire.NewChanIDFromOutPoint(
|
|
|
|
&channel.FundingOutpoint,
|
|
|
|
)
|
|
|
|
if !cfg.IsChannelActive(chanPoint) {
|
|
|
|
log.Debugf("Skipping channel %v due to not "+
|
|
|
|
"being eligible to forward payments",
|
|
|
|
chanPoint)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// To ensure we don't leak unadvertised nodes, we'll make sure our
|
|
|
|
// counterparty is publicly advertised within the network. Otherwise,
|
|
|
|
// we'll end up leaking information about nodes that intend to stay
|
|
|
|
// unadvertised, like in the case of a node only having private
|
|
|
|
// channels.
|
|
|
|
var remotePub [33]byte
|
|
|
|
copy(remotePub[:], channel.IdentityPub.SerializeCompressed())
|
2020-10-26 16:14:15 +03:00
|
|
|
isRemoteNodePublic, err := cfg.Graph.IsPublicNode(remotePub)
|
2020-08-12 03:38:26 +03:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Unable to determine if node %x "+
|
|
|
|
"is advertised: %v", remotePub, err)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
if !isRemoteNodePublic {
|
|
|
|
log.Debugf("Skipping channel %v due to "+
|
|
|
|
"counterparty %x being unadvertised",
|
|
|
|
chanPoint, remotePub)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch the policies for each end of the channel.
|
|
|
|
chanID := channel.ShortChanID().ToUint64()
|
2020-10-26 16:14:15 +03:00
|
|
|
info, p1, p2, err := cfg.Graph.FetchChannelEdgesByID(chanID)
|
2020-08-12 03:38:26 +03:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Unable to fetch the routing "+
|
|
|
|
"policies for the edges of the channel "+
|
|
|
|
"%v: %v", chanPoint, err)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now, we'll need to determine which is the correct policy for HTLCs
|
|
|
|
// being sent from the remote node.
|
|
|
|
var remotePolicy *channeldb.ChannelEdgePolicy
|
|
|
|
if bytes.Equal(remotePub[:], info.NodeKey1Bytes[:]) {
|
|
|
|
remotePolicy = p1
|
|
|
|
} else {
|
|
|
|
remotePolicy = p2
|
|
|
|
}
|
|
|
|
|
|
|
|
return remotePolicy, true
|
|
|
|
}
|
|
|
|
|
2020-08-13 03:43:55 +03:00
|
|
|
// addHopHint creates a hop hint out of the passed channel and channel policy.
|
|
|
|
// The new hop hint is appended to the passed slice.
|
2020-08-11 02:18:48 +03:00
|
|
|
func addHopHint(hopHints *[]func(*zpay32.Invoice),
|
2020-08-13 03:43:55 +03:00
|
|
|
channel *channeldb.OpenChannel, chanPolicy *channeldb.ChannelEdgePolicy) {
|
|
|
|
|
|
|
|
hopHint := zpay32.HopHint{
|
|
|
|
NodeID: channel.IdentityPub,
|
|
|
|
ChannelID: channel.ShortChanID().ToUint64(),
|
|
|
|
FeeBaseMSat: uint32(chanPolicy.FeeBaseMSat),
|
|
|
|
FeeProportionalMillionths: uint32(
|
|
|
|
chanPolicy.FeeProportionalMillionths,
|
|
|
|
),
|
|
|
|
CLTVExpiryDelta: chanPolicy.TimeLockDelta,
|
|
|
|
}
|
2020-08-11 02:18:48 +03:00
|
|
|
*hopHints = append(
|
|
|
|
*hopHints, zpay32.RouteHint([]zpay32.HopHint{hopHint}),
|
2020-08-13 03:43:55 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-08-11 02:18:48 +03:00
|
|
|
// selectHopHints will select up to numMaxHophints from the set of passed open
|
2020-08-11 02:06:39 +03:00
|
|
|
// channels. The set of hop hints will be returned as a slice of functional
|
|
|
|
// options that'll append the route hint to the set of all route hints.
|
2020-08-11 02:18:48 +03:00
|
|
|
//
|
|
|
|
// TODO(roasbeef): do proper sub-set sum max hints usually << numChans
|
2020-08-11 02:06:39 +03:00
|
|
|
func selectHopHints(amtMSat lnwire.MilliSatoshi, cfg *AddInvoiceConfig,
|
|
|
|
openChannels []*channeldb.OpenChannel,
|
|
|
|
numMaxHophints int) []func(*zpay32.Invoice) {
|
|
|
|
|
2020-08-11 02:18:48 +03:00
|
|
|
// We'll add our hop hints in two passes, first we'll add all channels
|
|
|
|
// that are eligible to be hop hints, and also have a local balance
|
|
|
|
// above the payment amount.
|
|
|
|
var totalHintBandwidth lnwire.MilliSatoshi
|
|
|
|
hopHintChans := make(map[wire.OutPoint]struct{})
|
2020-08-11 02:06:39 +03:00
|
|
|
hopHints := make([]func(*zpay32.Invoice), 0, numMaxHophints)
|
|
|
|
for _, channel := range openChannels {
|
2020-08-11 02:18:48 +03:00
|
|
|
// If this channel can't be a hop hint, then skip it.
|
2020-10-26 16:14:15 +03:00
|
|
|
edgePolicy, canBeHopHint := chanCanBeHopHint(channel, cfg)
|
2020-08-11 02:18:48 +03:00
|
|
|
if edgePolicy == nil || !canBeHopHint {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Similarly, in this first pass, we'll ignore all channels in
|
|
|
|
// isolation can't satisfy this payment.
|
|
|
|
if channel.LocalCommitment.RemoteBalance < amtMSat {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that we now this channel use usable, add it as a hop
|
|
|
|
// hint and the indexes we'll use later.
|
|
|
|
addHopHint(&hopHints, channel, edgePolicy)
|
|
|
|
|
|
|
|
hopHintChans[channel.FundingOutpoint] = struct{}{}
|
|
|
|
totalHintBandwidth += channel.LocalCommitment.RemoteBalance
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we have enough hop hints at this point, then we'll exit early.
|
|
|
|
// Otherwise, we'll continue to add more that may help out mpp users.
|
|
|
|
if len(hopHints) >= numMaxHophints {
|
|
|
|
return hopHints
|
|
|
|
}
|
|
|
|
|
|
|
|
// In this second pass we'll add channels, and we'll either stop when
|
|
|
|
// we have 20 hop hints, we've run through all the available channels,
|
|
|
|
// or if the sum of available bandwidth in the routing hints exceeds 2x
|
|
|
|
// the payment amount. We do 2x here to account for a margin of error
|
|
|
|
// if some of the selected channels no longer become operable.
|
|
|
|
hopHintFactor := lnwire.MilliSatoshi(2)
|
|
|
|
for i := 0; i < len(openChannels); i++ {
|
|
|
|
// If we hit either of our early termination conditions, then
|
|
|
|
// we'll break the loop here.
|
|
|
|
if totalHintBandwidth > amtMSat*hopHintFactor ||
|
|
|
|
len(hopHints) >= numMaxHophints {
|
|
|
|
|
2020-08-11 02:06:39 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2020-08-11 02:18:48 +03:00
|
|
|
channel := openChannels[i]
|
|
|
|
|
|
|
|
// Skip the channel if we already selected it.
|
|
|
|
if _, ok := hopHintChans[channel.FundingOutpoint]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the channel can't be a hop hint, then we'll skip it.
|
2020-08-12 03:38:26 +03:00
|
|
|
// Otherwise, we'll use the policy information to populate the
|
|
|
|
// hop hint.
|
2020-10-26 16:14:15 +03:00
|
|
|
remotePolicy, canBeHopHint := chanCanBeHopHint(channel, cfg)
|
2020-08-13 03:43:55 +03:00
|
|
|
if !canBeHopHint || remotePolicy == nil {
|
2020-08-11 02:06:39 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Include the route hint in our set of options that will be
|
|
|
|
// used when creating the invoice.
|
2020-08-11 02:18:48 +03:00
|
|
|
addHopHint(&hopHints, channel, remotePolicy)
|
2020-08-11 02:06:39 +03:00
|
|
|
|
2020-08-11 02:18:48 +03:00
|
|
|
// As we've just added a new hop hint, we'll accumulate it's
|
|
|
|
// available balance now to update our tally.
|
|
|
|
//
|
|
|
|
// TODO(roasbeef): have a cut off based on min bandwidth?
|
|
|
|
totalHintBandwidth += channel.LocalCommitment.RemoteBalance
|
2020-08-11 02:06:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return hopHints
|
|
|
|
}
|