Merge pull request #11307 from bitromortac/20261008-41a8-dispatch
What changed, and why it matters
This commit adds new code to LND that lets a node create and cryptographically sign BOLT 12 invoices. It also changes how invoice signing works so that signing can be done by a remote signer that never sees the node's private key. The change is a feature addition, not a fix for a known bug or vulnerability. There is no evidence in the commit message or diff that the project treats this as a security patch.
Review the new BOLT 12 invoice generation and signing code as part of normal secure-development practice. Pay particular attention to the remote-signing path, the validation of invoice fields before signing, and the handling of blinded paths and amounts. No urgent patch is indicated by this commit alone.
Security signals we found
New signing path for BOLT 12 invoices using BIP-340 Schnorr tagged hashes
Separation of Merkle-root computation from raw-key signing to support remote signing
Validation before signing: writer requirements, missing amount, quantity overflow, currency conversion
Refusal to generate invoices for offers with offer_paths but no offer_issuer_id to avoid identity leakage
Use of crypto/rand for preimage and path_id generation
No explicit security bug or CVE referenced in commit or diff
Evidence from the diff
The commit introduces bolt12handler.GenerateInvoice, which builds a BOLT 12 invoice from an invoice request, adds blinded payment paths, and signs the invoice. It splits the existing bolt12.SignInvoice into InvoiceSigningRoot (Merkle root computation/validation) and a tagged signing step, exposing InvoiceSignatureTag so that remote signers can produce the same signature without holding the raw private key. A KeyRingSigner is added that delegates to keychain.MessageSignerRing.SignMessageSchnorr. The code includes validation such as refusing to sign invoices that break writer requirements, rejecting offers with paths but no issuer ID, and checking amount/quantity overflow. Tests cover happy path, amount handling, path builder fallback, issuer ID checks, and signature verification.
Changed components
bolt12/signature.gobolt12handler/generate.gobolt12handler/keyring_signer.gobolt12handler/signer.gobolt12handler/log.golog.goInspect captured patch +1197 / −7
### bolt12/signature.go
@@ -25,6 +25,11 @@ const (
tagFieldSignature = "signature"
)
+// InvoiceSignatureTag is the BIP-340 tag of an invoice signature. The
+// signature covers the tagged hash of the root that InvoiceSigningRoot returns.
+const InvoiceSignatureTag = signatureTagPrefix + tagMsgInvoice +
+ tagFieldSignature
+
// ErrInvalidSignature is returned by verifyInvoice and verifyInvoiceRequest
// when the BIP-340 Schnorr signature does not validate against the message's
// Merkle root and signing key.
@@ -145,19 +150,27 @@ func SignInvoice(inv *Invoice, privKey *btcec.PrivateKey) ([64]byte, error) {
return [64]byte{}, ErrNilPrivateKey
}
+ root, err := InvoiceSigningRoot(inv)
+ if err != nil {
+ return [64]byte{}, err
+ }
+
+ return signMessage(tagMsgInvoice, tagFieldSignature, root, privKey)
+}
+
+// InvoiceSigningRoot returns the Merkle root that the invoice signature
+// covers. A signer without the raw private key, such as a remote signer, signs
+// it under InvoiceSignatureTag. It returns an error for an invoice that breaks
+// the writer requirements.
+func InvoiceSigningRoot(inv *Invoice) ([32]byte, error) {
// A signature over a message that breaks the writer requirements is
// worthless: the peer rejects it on read. Refusing here keeps a key
// from signing bytes no correct reader accepts.
if err := validateInvoiceWrite(inv); err != nil {
- return [64]byte{}, fmt.Errorf("validate invoice: %w", err)
+ return [32]byte{}, fmt.Errorf("validate invoice: %w", err)
}
- root, err := merkleRoot(signableTLVs(inv.AllRecords()))
- if err != nil {
- return [64]byte{}, err
- }
-
- return signMessage(tagMsgInvoice, tagFieldSignature, root, privKey)
+ return merkleRoot(signableTLVs(inv.AllRecords()))
}
// verifyInvoice verifies the signature on an invoice using its invoice_node_id
### bolt12/signature_test.go
@@ -7,6 +7,8 @@ import (
"testing"
"github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr"
+ "github.com/btcsuite/btcd/chainhash/v2"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
@@ -486,3 +488,35 @@ func TestVerifyInvoiceRequestDirect(t *testing.T) {
})
}
}
+
+// TestInvoiceSigningRoot verifies that a signature over the tagged hash of
+// InvoiceSigningRoot is a valid invoice signature. A signer without the raw
+// key signs in this way.
+func TestInvoiceSigningRoot(t *testing.T) {
+ t.Parallel()
+
+ bobPriv, _ := bobKey()
+ inv := validInvoice(t)
+
+ root, err := InvoiceSigningRoot(inv)
+ require.NoError(t, err)
+
+ digest := chainhash.TaggedHash([]byte(InvoiceSignatureTag), root[:])
+ sig, err := schnorr.Sign(bobPriv, digest[:])
+ require.NoError(t, err)
+
+ inv.Signature = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType240, [64]byte](
+ [64]byte(sig.Serialize()),
+ ),
+ )
+ require.NoError(t, verifyInvoice(inv))
+
+ // The root function runs the writer validation, so an invoice that
+ // breaks it has no root to sign.
+ inv.InvoiceNodeID = tlv.OptionalRecordT[
+ tlv.TlvType176, *btcec.PublicKey,
+ ]{}
+ _, err = InvoiceSigningRoot(inv)
+ require.Error(t, err)
+}
### bolt12handler/generate.go
@@ -0,0 +1,420 @@
+package bolt12handler
+
+import (
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "math/bits"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/tlv"
+)
+
+var (
+ // errAmountOverflow is returned when offer_amount times
+ // invreq_quantity does not fit in a uint64.
+ errAmountOverflow = errors.New("invoice amount overflows uint64")
+
+ // errOfferWithoutIssuerID is returned for an offer that has
+ // offer_paths but no offer_issuer_id. Its invoice must use the blinded
+ // node id of the arrival path, which GenerateInvoice does not support
+ // yet.
+ errOfferWithoutIssuerID = errors.New("offer without " +
+ "offer_issuer_id is not supported")
+
+ // errCurrencyConversion is returned when the invoice amount needs a
+ // conversion from offer_currency to msat. The handler has no exchange
+ // rate.
+ errCurrencyConversion = errors.New("offer_currency amount needs " +
+ "conversion to msat")
+)
+
+// InvoiceConfig holds the dependencies and node settings of GenerateInvoice.
+type InvoiceConfig struct {
+ // Signer signs the invoice with the node identity key.
+ Signer NodeSigner
+
+ // PathBuilder constructs the blinded payment paths. If it is nil, the
+ // invoice uses a single-hop blinded path to this node.
+ PathBuilder PaymentPathBuilder
+
+ // Clock provides the invoice creation time.
+ Clock clock.Clock
+
+ // FinalCLTVDelta is the final CLTV delta that this node requires for
+ // a payment. The daemon passes the same value as for BOLT 11 invoices.
+ // The payment paths add routing.BlockPadding to it.
+ FinalCLTVDelta uint16
+}
+
+// Validate returns an error if a required dependency of the config is not
+// set. PathBuilder is optional.
+func (c *InvoiceConfig) Validate() error {
+ switch {
+ case c.Signer == nil:
+ return errors.New("invoice config has no signer")
+
+ case c.Clock == nil:
+ return errors.New("invoice config has no clock")
+ }
+
+ return nil
+}
+
+// PaymentPathResult contains the blinded payment paths and corresponding pay
+// info for a BOLT 12 invoice.
+type PaymentPathResult struct {
+ // Paths contains the blinded payment paths for the invoice.
+ Paths []lnwire.BlindedPath
+
+ // PayInfos contains the fee and CLTV policy for each path.
+ PayInfos []bolt12.BlindedPayInfo
+}
+
+// PaymentPathBuilder constructs blinded payment paths for a BOLT 12 invoice.
+// The builder receives the invoice amount and a path_id to embed in the final
+// hop's encrypted data.
+type PaymentPathBuilder interface {
+ // BuildPaymentPaths returns blinded payment paths suitable for
+ // embedding in a BOLT 12 invoice.
+ BuildPaymentPaths(amountMsat uint64,
+ pathID []byte) (*PaymentPathResult, error)
+}
+
+// InvoiceResult contains the output of invoice generation.
+type InvoiceResult struct {
+ // Invoice is the generated BOLT 12 invoice.
+ Invoice *bolt12.Invoice
+
+ // Encoded is the bech32-encoded invoice string (lni1...).
+ Encoded string
+
+ // Preimage is the 32-byte payment preimage.
+ Preimage lntypes.Preimage
+
+ // PaymentHash is the SHA256 of the preimage.
+ PaymentHash lntypes.Hash
+
+ // PathID is the 32-byte path identifier embedded in the blinded path.
+ // Used as payment_addr for invoice lookup.
+ PathID [32]byte
+}
+
+// GenerateInvoice creates a BOLT 12 invoice in response to a validated invoice
+// request. The invoice mirrors the request, and the node identity key signs
+// it. If cfg.PathBuilder is nil or fails, a single-hop blinded path is used as
+// fallback.
+func GenerateInvoice(cfg *InvoiceConfig,
+ ir *bolt12.InvoiceRequest) (*InvoiceResult, error) {
+
+ if err := cfg.Validate(); err != nil {
+ return nil, err
+ }
+
+ // The invoice_node_id is always the node identity key. For an offer
+ // without offer_issuer_id, the payer expects the blinded node id of
+ // the arrival path, so such an invoice would fail and show our
+ // identity.
+ //
+ // TODO: Sign with the blinded node id key to support these offers.
+ if ir.OfferPaths.IsSome() && !ir.OfferIssuerID.IsSome() {
+ return nil, errOfferWithoutIssuerID
+ }
+
+ var preimage lntypes.Preimage
+ if _, err := rand.Read(preimage[:]); err != nil {
+ return nil, fmt.Errorf("generate preimage: %w", err)
+ }
+ paymentHash := preimage.Hash()
+
+ var pathID [32]byte
+ if _, err := rand.Read(pathID[:]); err != nil {
+ return nil, fmt.Errorf("generate path_id: %w", err)
+ }
+
+ invoiceAmount, err := computeInvoiceAmount(ir)
+ if err != nil {
+ return nil, err
+ }
+
+ var pathResult *PaymentPathResult
+ if cfg.PathBuilder != nil {
+ pathResult, err = cfg.PathBuilder.BuildPaymentPaths(
+ invoiceAmount, pathID[:],
+ )
+ switch {
+ case err != nil:
+ log.Debugf("Multi-hop payment path construction "+
+ "failed, falling back to single-hop: %v",
+ err)
+
+ pathResult = nil
+
+ case pathResult != nil && len(pathResult.Paths) == 0:
+ log.Debugf("Multi-hop payment path construction " +
+ "returned no paths, falling back to single-hop")
+
+ pathResult = nil
+ }
+ }
+
+ // The single-hop path keeps the offer payable when the builder finds
+ // no path through a peer. It names our node as the introduction node.
+ // This shows nothing new, because GenerateInvoice only answers an
+ // offer that names our node in offer_issuer_id.
+ //
+ // TODO: A blinded offer hides our node, so its invoice must fail here
+ // instead of using the single-hop path.
+ if pathResult == nil {
+ path, pathErr := buildSingleHopBlindedPath(
+ cfg.Signer.NodePubKey(), pathID[:],
+ )
+ if pathErr != nil {
+ return nil, fmt.Errorf("build single-hop path: %w",
+ pathErr)
+ }
+
+ log.Debugf("Using single-hop blinded payment path")
+
+ pathResult = &PaymentPathResult{
+ Paths: []lnwire.BlindedPath{path},
+ PayInfos: []bolt12.BlindedPayInfo{{
+ FeeBaseMsat: 0,
+ FeeProportionalMillionths: 0,
+ // Add BlockPadding so that the receiver does
+ // not reject the HTLC if blocks are mined while
+ // the payment is in flight. With blinded paths,
+ // the receiver adds this padding, not the
+ // sender.
+ CltvExpiryDelta: cfg.FinalCLTVDelta +
+ routing.BlockPadding,
+ HtlcMinimumMsat: 0,
+ HtlcMaximumMsat: invoiceAmount,
+ }},
+ }
+ } else {
+ log.Debugf("Using multi-hop blinded payment path with "+
+ "%d path(s)", len(pathResult.Paths))
+ }
+
+ inv := buildInvoiceFromRequest(
+ ir, cfg.Signer.NodePubKey(), paymentHash, pathResult,
+ invoiceAmount, cfg.Clock.Now(),
+ )
+
+ signedInv, encoded, err := signAndEncode(inv, cfg.Signer)
+ if err != nil {
+ return nil, fmt.Errorf("sign invoice: %w", err)
+ }
+
+ return &InvoiceResult{
+ Invoice: signedInv,
+ Encoded: encoded,
+ Preimage: preimage,
+ PaymentHash: paymentHash,
+ PathID: pathID,
+ }, nil
+}
+
+// buildInvoiceFromRequest constructs a bolt12.Invoice by mirroring the request
+// fields and adding invoice-specific fields.
+func buildInvoiceFromRequest(ir *bolt12.InvoiceRequest,
+ nodePubKey *btcec.PublicKey, paymentHash lntypes.Hash,
+ pathResult *PaymentPathResult,
+ invoiceAmount uint64, now time.Time) *bolt12.Invoice {
+
+ // The codec mirrors the request, including unknown TLVs in the signed
+ // range. The payer's byte-for-byte check requires them, and a
+ // field-by-field copy could not reach them.
+ inv := bolt12.NewInvoiceFromRequest(ir)
+
+ inv.InvoiceCreatedAt = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType164, bolt12.TUint64]{
+ Val: bolt12.TUint64(now.Unix()),
+ },
+ )
+
+ // TODO: Support a custom invoice expiry from the config. Set
+ // invoice_relative_expiry here, and store the invoice with the same
+ // expiry.
+ amt := bolt12.TUint64(invoiceAmount)
+ inv.InvoiceAmount = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType170, bolt12.TUint64]{
+ Val: amt,
+ },
+ )
+
+ inv.InvoicePaymentHash = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType168, [32]byte](paymentHash),
+ )
+
+ inv.InvoiceNodeID = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType176](nodePubKey),
+ )
+
+ inv.InvoicePaths = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType160, lnwire.BlindedPaths]{
+ Val: lnwire.BlindedPaths{
+ Paths: pathResult.Paths,
+ },
+ },
+ )
+
+ // One blinded pay info entry per payment path.
+ inv.InvoiceBlindedPay = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType162, bolt12.BlindedPayInfos]{
+ Val: bolt12.BlindedPayInfos{
+ Infos: pathResult.PayInfos,
+ },
+ },
+ )
+
+ // Advertise OPT_BASIC_MPP so payers can split a payment that exceeds
+ // the capacity of one channel.
+ inv.InvoiceFeatures = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType174, lnwire.RawFeatureVector]{
+ Val: *lnwire.NewRawFeatureVector(lnwire.MPPOptional),
+ },
+ )
+
+ return inv
+}
+
+// computeInvoiceAmount returns the amount the invoice must pay. The request's
+// invreq_amount takes precedence. Without it, the amount comes from the offer,
+// and a currency offer or an overflowing product returns an error.
+func computeInvoiceAmount(ir *bolt12.InvoiceRequest) (uint64, error) {
+ // An absent invreq_quantity means one item. Like CLN, reject an
+ // explicit zero, even when invreq_amount sets the amount.
+ quantity := uint64(ir.InvreqQuantity.ValOpt().UnwrapOr(1))
+ if quantity == 0 {
+ return 0, bolt12.ErrQuantityZero
+ }
+
+ if ir.InvreqAmount.IsSome() {
+ return uint64(ir.InvreqAmount.ValOpt().UnwrapOr(0)), nil
+ }
+
+ // The offer_amount unit is offer_currency when that field is set, so
+ // it is not a msat value.
+ //
+ // TODO: Support offers priced in a currency. This needs an exchange
+ // rate to convert offer_amount to msat.
+ if ir.OfferCurrency.IsSome() {
+ return 0, errCurrencyConversion
+ }
+
+ // BOLT 12 requires invreq_amount for an offer without offer_amount.
+ if !ir.OfferAmount.IsSome() {
+ return 0, bolt12.ErrMissingAmount
+ }
+
+ // The reader's overflow check runs only when invreq_amount is set, so
+ // a payer could otherwise pick a quantity that wraps the product.
+ return expectedOfferAmount(
+ uint64(ir.OfferAmount.ValOpt().UnwrapOr(0)), quantity,
+ )
+}
+
+// expectedOfferAmount returns offer_amount times the quantity, the expected
+// amount of an offer priced in the chain's currency.
+func expectedOfferAmount(offerAmount, quantity uint64) (uint64, error) {
+ hi, amount := bits.Mul64(offerAmount, quantity)
+ if hi != 0 {
+ return 0, errAmountOverflow
+ }
+
+ return amount, nil
+}
+
+// buildSingleHopBlindedPath creates a single-hop blinded payment path for the
+// direct-peer case. The introduction node is the receiver itself, and the
+// single hop's encrypted data carries the path_id for invoice lookup.
+func buildSingleHopBlindedPath(nodePubKey *btcec.PublicKey,
+ pathID []byte) (lnwire.BlindedPath, error) {
+
+ sessionKey, err := btcec.NewPrivateKey()
+ if err != nil {
+ return lnwire.BlindedPath{}, fmt.Errorf("generate session "+
+ "key: %w", err)
+ }
+
+ // The path_id lets the receiver match the incoming HTLC to the invoice.
+ routeData := record.NewFinalHopBlindedRouteData(nil, pathID)
+ plainText, err := record.EncodeBlindedRouteData(routeData)
+ if err != nil {
+ return lnwire.BlindedPath{}, fmt.Errorf("encode route data: %w",
+ err)
+ }
+
+ hops := []*sphinx.HopInfo{
+ {
+ NodePub: nodePubKey,
+ PlainText: plainText,
+ },
+ }
+
+ blindedPath, err := sphinx.BuildBlindedPath(sessionKey, hops)
+ if err != nil {
+ return lnwire.BlindedPath{}, fmt.Errorf("build blinded "+
+ "path: %w", err)
+ }
+
+ path := blindedPath.Path
+
+ bolt12Hops := make([]lnwire.BlindedHop, len(path.BlindedHops))
+ for i, hop := range path.BlindedHops {
+ bolt12Hops[i] = lnwire.BlindedHop{
+ BlindedNodeID: hop.BlindedNodePub,
+ EncryptedData: hop.CipherText,
+ }
+ }
+
+ introNode, err := lnwire.NewPubkeyIntro(nodePubKey)
+ if err != nil {
+ return lnwire.BlindedPath{}, err
+ }
+
+ return lnwire.BlindedPath{
+ IntroductionNode: introNode,
+ BlindingPoint: path.BlindingPoint,
+ Hops: bolt12Hops,
+ }, nil
+}
+
+// signAndEncode attaches the signature to inv in place and returns the bech32
+// string of the signed invoice.
+func signAndEncode(inv *bolt12.Invoice, signer NodeSigner) (*bolt12.Invoice,
+ string, error) {
+
+ // The root function runs the writer validation, so a malformed invoice
+ // fails before a key signs it.
+ root, err := bolt12.InvoiceSigningRoot(inv)
+ if err != nil {
+ return nil, "", err
+ }
+
+ sig, err := signer.SignInvoiceRoot(root)
+ if err != nil {
+ return nil, "", fmt.Errorf("sign: %w", err)
+ }
+
+ inv.Signature = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType240, [64]byte](sig),
+ )
+
+ encoded, err := bolt12.EncodeInvoiceString(inv)
+ if err != nil {
+ return nil, "", err
+ }
+
+ return inv, encoded, nil
+}
### bolt12handler/generate_test.go
@@ -0,0 +1,424 @@
+package bolt12handler
+
+import (
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestGenerateInvoice_HappyPath verifies that a valid invoice is generated from
+// a well-formed invoice request.
+func TestGenerateInvoice_HappyPath(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+
+ result, err := GenerateInvoice(testInvoiceConfig(nodeKey), ir)
+ require.NoError(t, err)
+
+ require.NotEmpty(t, result.Encoded)
+ require.NotEqual(t, lntypes.Preimage{}, result.Preimage)
+ require.NotEqual(t, lntypes.Hash{}, result.PaymentHash)
+ require.NotEqual(t, [32]byte{}, result.PathID)
+
+ require.Equal(t, result.Preimage.Hash(), result.PaymentHash)
+
+ // The string decodes through the reader gates, which include the
+ // signature check.
+ decoded, err := bolt12.DecodeInvoiceString(
+ result.Encoded, time.Now(), testChainHash(),
+ )
+ require.NoError(t, err)
+
+ // The payer checks the invoice against its own request and against
+ // the issuer key of the offer.
+ err = bolt12.ValidateInvoiceForPayment(
+ decoded, ir, time.Now(), testChainHash(),
+ bolt12.InvoiceKnownFeatures{
+ Invoice: bolt12.Bolt12Features,
+ Blinded: bolt12.Bolt12Features,
+ },
+ nodeKey.PubKey(),
+ )
+ require.NoError(t, err)
+
+ require.EqualValues(t, 10000, decoded.InvoiceAmount.UnwrapOrFailV(t))
+ require.EqualValues(
+ t, testNow.Unix(), decoded.InvoiceCreatedAt.UnwrapOrFailV(t),
+ )
+ require.Equal(
+ t, nodeKey.PubKey(), decoded.InvoiceNodeID.UnwrapOrFailV(t),
+ )
+
+ // Verify mirrored fields.
+ require.Equal(
+ t, "test offer",
+ string(decoded.OfferDescription.UnwrapOrFailV(t)),
+ )
+ require.Equal(
+ t, payerKey.PubKey(), decoded.InvreqPayerID.UnwrapOrFailV(t),
+ )
+}
+
+// TestGenerateInvoiceAmount verifies that the invoice amount follows the
+// precedence of computeInvoiceAmount.
+func TestGenerateInvoiceAmount(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ offerAmount uint64
+ invreqAmount uint64
+ quantity fn.Option[uint64]
+ currency string
+ want uint64
+ wantErr error
+ }{
+ {
+ name: "fixed offer amount",
+ offerAmount: 10000,
+ want: 10000,
+ },
+ {
+ name: "invreq amount above offer amount",
+ offerAmount: 10000,
+ invreqAmount: 15000,
+ want: 15000,
+ },
+ {
+ name: "invreq amount without offer amount",
+ invreqAmount: 25000,
+ want: 25000,
+ },
+ {
+ name: "offer amount times quantity",
+ offerAmount: 1000,
+ quantity: fn.Some[uint64](5),
+ want: 5000,
+ },
+ {
+ name: "offer amount times quantity overflows",
+ offerAmount: 1 << 63,
+ quantity: fn.Some[uint64](2),
+ wantErr: errAmountOverflow,
+ },
+ {
+ name: "explicit zero quantity",
+ offerAmount: 1000,
+ invreqAmount: 1000,
+ quantity: fn.Some[uint64](0),
+ wantErr: bolt12.ErrQuantityZero,
+ },
+ {
+ name: "currency offer amount without invreq",
+ offerAmount: 5,
+ currency: "USD",
+ wantErr: errCurrencyConversion,
+ },
+ {
+ name: "no offer amount and no invreq amount",
+ wantErr: bolt12.ErrMissingAmount,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, tc.offerAmount)
+
+ // The request copies the offer fields, so the quantity
+ // cap must be on the offer before the request exists.
+ // No validator runs on this fixture.
+ if tc.quantity.IsSome() {
+ setQuantityMax(offer, 10)
+ }
+ if tc.currency != "" {
+ offer.OfferCurrency = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType6](
+ tlv.Blob(tc.currency),
+ ),
+ )
+ }
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ ir := testInvoiceRequest(
+ t, offer, payerKey, tc.invreqAmount,
+ )
+ tc.quantity.WhenSome(func(q uint64) {
+ ir.InvreqQuantity = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType86](
+ bolt12.TUint64(q),
+ ),
+ )
+ })
+
+ result, err := GenerateInvoice(
+ testInvoiceConfig(nodeKey), ir,
+ )
+ if tc.wantErr != nil {
+ require.ErrorIs(t, err, tc.wantErr)
+ return
+ }
+ require.NoError(t, err)
+
+ decoded, err := bolt12.DecodeInvoiceString(
+ result.Encoded, time.Now(), testChainHash(),
+ )
+ require.NoError(t, err)
+
+ require.EqualValues(
+ t, tc.want,
+ decoded.InvoiceAmount.UnwrapOrFailV(t),
+ )
+ })
+ }
+}
+
+// TestGenerateInvoice_BlindedPath verifies that the generated invoice includes
+// a blinded payment path with a path_id.
+func TestGenerateInvoice_BlindedPath(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+
+ result, err := GenerateInvoice(testInvoiceConfig(nodeKey), ir)
+ require.NoError(t, err)
+
+ decoded, err := bolt12.DecodeInvoiceString(
+ result.Encoded, time.Now(), testChainHash(),
+ )
+ require.NoError(t, err)
+
+ paths := decoded.InvoicePaths.UnwrapOrFailV(t).Paths
+ require.Len(t, paths, 1)
+ require.Len(t, paths[0].Hops, 1)
+
+ // The single hop's encrypted data contains the path_id in encrypted
+ // form.
+ require.NotEmpty(t, paths[0].Hops[0].EncryptedData)
+
+ require.Len(t, decoded.InvoiceBlindedPay.UnwrapOrFailV(t).Infos, 1)
+}
+
+// fakePathBuilder is a PaymentPathBuilder that returns a fixed result and
+// records its arguments.
+type fakePathBuilder struct {
+ result *PaymentPathResult
+ err error
+
+ gotAmount uint64
+ gotPathID []byte
+}
+
+// BuildPaymentPaths returns the fixed result and error.
+func (f *fakePathBuilder) BuildPaymentPaths(amountMsat uint64,
+ pathID []byte) (*PaymentPathResult, error) {
+
+ f.gotAmount = amountMsat
+ f.gotPathID = pathID
+
+ return f.result, f.err
+}
+
+// TestGenerateInvoicePathBuilder verifies that GenerateInvoice uses the paths
+// of the builder, and uses the single-hop path when the builder fails or
+// returns no paths.
+func TestGenerateInvoicePathBuilder(t *testing.T) {
+ t.Parallel()
+
+ // A fee that the single-hop fallback never sets marks the builder's
+ // pay info.
+ const builderFee = 7
+
+ tests := []struct {
+ name string
+ builderErr error
+ noResult bool
+ noPaths bool
+ wantFeeBase uint32
+ wantFallback bool
+ }{
+ {
+ name: "builder paths",
+ wantFeeBase: builderFee,
+ },
+ {
+ name: "builder error",
+ builderErr: errors.New("no route"),
+ wantFallback: true,
+ },
+ {
+ name: "builder without result",
+ noResult: true,
+ wantFallback: true,
+ },
+ {
+ name: "builder with zero paths",
+ noPaths: true,
+ wantFallback: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ ir := testInvoiceRequest(t, offer, payerKey, 0)
+
+ path, err := buildSingleHopBlindedPath(
+ nodeKey.PubKey(), []byte{1},
+ )
+ require.NoError(t, err)
+
+ builder := &fakePathBuilder{err: tc.builderErr}
+ if !tc.noResult {
+ builder.result = &PaymentPathResult{
+ Paths: []lnwire.BlindedPath{path},
+ PayInfos: []bolt12.BlindedPayInfo{{
+ FeeBaseMsat: builderFee,
+ HtlcMaximumMsat: 10000,
+ }},
+ }
+ }
+ if tc.noPaths {
+ builder.result = &PaymentPathResult{}
+ }
+
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathBuilder = builder
+
+ result, err := GenerateInvoice(cfg, ir)
+ require.NoError(t, err)
+
+ require.EqualValues(t, 10000, builder.gotAmount)
+ require.Equal(t, result.PathID[:], builder.gotPathID)
+
+ decoded, err := bolt12.DecodeInvoiceString(
+ result.Encoded, time.Now(), testChainHash(),
+ )
+ require.NoError(t, err)
+
+ payInfos := decoded.InvoiceBlindedPay.UnwrapOrFailV(t)
+ infos := payInfos.Infos
+ require.Len(t, infos, 1)
+ require.Equal(t, tc.wantFeeBase, infos[0].FeeBaseMsat)
+
+ if tc.wantFallback {
+ wantDelta := testFinalCLTVDelta +
+ routing.BlockPadding
+ require.EqualValues(
+ t, wantDelta, infos[0].CltvExpiryDelta,
+ )
+ }
+ })
+ }
+}
+
+// TestGenerateInvoiceIssuerID verifies that GenerateInvoice signs an invoice
+// for an offer with offer_issuer_id, and refuses an offer with offer_paths and
+// no offer_issuer_id, because the invoice would carry the node identity key.
+func TestGenerateInvoiceIssuerID(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ issuerID bool
+ wantErr error
+ }{
+ // lnd never creates an offer with both fields, but another
+ // implementation can. The issuer id then binds the invoice to
+ // the node key, and the paths only route the request.
+ {
+ name: "offer paths with issuer id",
+ issuerID: true,
+ },
+ {
+ name: "offer paths without issuer id",
+ wantErr: errOfferWithoutIssuerID,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+
+ path, err := buildSingleHopBlindedPath(
+ nodeKey.PubKey(), []byte{1},
+ )
+ require.NoError(t, err)
+
+ offer.OfferPaths = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType16](
+ lnwire.BlindedPaths{
+ Paths: []lnwire.BlindedPath{
+ path,
+ },
+ },
+ ),
+ )
+ if !tc.issuerID {
+ offer.OfferIssuerID = tlv.OptionalRecordT[
+ tlv.TlvType22, *btcec.PublicKey,
+ ]{}
+ }
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ ir := testInvoiceRequest(t, offer, payerKey, 0)
+
+ result, err := GenerateInvoice(
+ testInvoiceConfig(nodeKey), ir,
+ )
+ if tc.wantErr != nil {
+ require.ErrorIs(t, err, tc.wantErr)
+ return
+ }
+ require.NoError(t, err)
+
+ require.Equal(
+ t, nodeKey.PubKey(),
+ result.Invoice.InvoiceNodeID.UnwrapOrFailV(t),
+ )
+ })
+ }
+}
### bolt12handler/helpers_test.go
@@ -0,0 +1,151 @@
+package bolt12handler
+
+import (
+ "testing"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr"
+ "github.com/btcsuite/btcd/chaincfg/v2"
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// testChainHash returns the Bitcoin mainnet genesis hash, the chain
+// the codec defaults to when offer_chains/invreq_chain is absent.
+func testChainHash() [32]byte {
+ return *chaincfg.MainNetParams.GenesisHash
+}
+
+// testNow is the time of the test clock. It is near the real time, because
+// the invoice reader checks the expiry against the real time.
+var testNow = time.Unix(time.Now().Unix(), 0)
+
+// testFinalCLTVDelta is the final CLTV delta of testInvoiceConfig. It differs
+// from every default, so a test detects a hard-coded value.
+const testFinalCLTVDelta = 42
+
+// testInvoiceConfig returns an InvoiceConfig that signs with key and has no
+// PaymentPathBuilder.
+func testInvoiceConfig(key *btcec.PrivateKey) *InvoiceConfig {
+ return &InvoiceConfig{
+ Signer: newPrivKeySigner(key),
+ Clock: clock.NewTestClock(testNow),
+ FinalCLTVDelta: testFinalCLTVDelta,
+ }
+}
+
+// testKey returns a deterministic private key for testing.
+func testKey(t *testing.T) *btcec.PrivateKey {
+ t.Helper()
+
+ var seed [32]byte
+ for i := range seed {
+ seed[i] = byte(i + 1)
+ }
+
+ privKey, _ := btcec.PrivKeyFromBytes(seed[:])
+
+ return privKey
+}
+
+// testOffer creates a codec offer from the test issuer key with a
+// description and, when amountMsat is non-zero, an amount.
+func testOffer(t *testing.T, key *btcec.PrivateKey,
+ amountMsat uint64) *bolt12.Offer {
+
+ t.Helper()
+
+ offer := &bolt12.Offer{}
+ offer.OfferIssuerID = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType22, *btcec.PublicKey]{
+ Val: key.PubKey(),
+ },
+ )
+ offer.OfferDescription = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType10, tlv.Blob]{
+ Val: []byte("test offer"),
+ },
+ )
+
+ if amountMsat > 0 {
+ offer.OfferAmount = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType8, bolt12.TUint64]{
+ Val: bolt12.TUint64(amountMsat),
+ },
+ )
+ }
+
+ return offer
+}
+
+// setQuantityMax sets offer_quantity_max on the offer.
+func setQuantityMax(offer *bolt12.Offer, quantityMax uint64) {
+ offer.OfferQuantityMax = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType20, bolt12.TUint64]{
+ Val: bolt12.TUint64(quantityMax),
+ },
+ )
+}
+
+// testInvoiceRequest creates a minimal invoice request that mirrors the given
+// offer's fields.
+func testInvoiceRequest(t *testing.T, offer *bolt12.Offer,
+ payerKey *btcec.PrivateKey,
+ invreqAmount uint64) *bolt12.InvoiceRequest {
+
+ t.Helper()
+
+ ir, err := bolt12.NewInvoiceRequestFromOffer(
+ offer, payerKey.PubKey(), []byte("test-metadata"),
+ testChainHash(),
+ )
+ require.NoError(t, err)
+
+ if invreqAmount > 0 {
+ amt := bolt12.TUint64(invreqAmount)
+ ir.InvreqAmount = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType82, bolt12.TUint64]{
+ Val: amt,
+ },
+ )
+ }
+
+ return ir
+}
+
+// privKeySigner implements NodeSigner with a raw private key for tests.
+type privKeySigner struct {
+ privKey *btcec.PrivateKey
+}
+
+// newPrivKeySigner creates a NodeSigner backed by a raw private key.
+func newPrivKeySigner(privKey *btcec.PrivateKey) *privKeySigner {
+ return &privKeySigner{privKey: privKey}
+}
+
+// NodePubKey returns the node's identity public key.
+//
+// NOTE: This is part of the NodeSigner interface.
+func (s *privKeySigner) NodePubKey() *btcec.PublicKey {
+ return s.privKey.PubKey()
+}
+
+// SignInvoiceRoot signs an invoice Merkle root with the wrapped private key.
+//
+// NOTE: This is part of the NodeSigner interface.
+func (s *privKeySigner) SignInvoiceRoot(root [32]byte) ([64]byte, error) {
+ digest := chainhash.TaggedHash(
+ []byte(bolt12.InvoiceSignatureTag), root[:],
+ )
+
+ sig, err := schnorr.Sign(s.privKey, digest[:])
+ if err != nil {
+ return [64]byte{}, err
+ }
+
+ return [64]byte(sig.Serialize()), nil
+}
### bolt12handler/keyring_signer.go
@@ -0,0 +1,52 @@
+package bolt12handler
+
+import (
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/keychain"
+)
+
+// KeyRingSigner implements NodeSigner for the daemon. It signs through the
+// Schnorr message signer of the key ring and never sees the private key, so it
+// also works in remote signing mode.
+type KeyRingSigner struct {
+ signer keychain.MessageSignerRing
+ keyLoc keychain.KeyLocator
+ identityPub *btcec.PublicKey
+}
+
+// NewKeyRingSigner creates a NodeSigner backed by the daemon's key ring.
+func NewKeyRingSigner(signer keychain.MessageSignerRing,
+ keyLoc keychain.KeyLocator,
+ identityPub *btcec.PublicKey) *KeyRingSigner {
+
+ return &KeyRingSigner{
+ signer: signer,
+ keyLoc: keyLoc,
+ identityPub: identityPub,
+ }
+}
+
+// NodePubKey returns the node's identity public key.
+//
+// NOTE: This is part of the NodeSigner interface.
+func (s *KeyRingSigner) NodePubKey() *btcec.PublicKey {
+ return s.identityPub
+}
+
+// SignInvoiceRoot signs an invoice Merkle root with the node's identity key.
+//
+// NOTE: This is part of the NodeSigner interface.
+func (s *KeyRingSigner) SignInvoiceRoot(root [32]byte) ([64]byte, error) {
+ sig, err := s.signer.SignMessageSchnorr(
+ s.keyLoc, root[:], false, nil,
+ []byte(bolt12.InvoiceSignatureTag),
+ )
+ if err != nil {
+ return [64]byte{}, fmt.Errorf("sign invoice root: %w", err)
+ }
+
+ return [64]byte(sig.Serialize()), nil
+}
### bolt12handler/keyring_signer_test.go
@@ -0,0 +1,43 @@
+package bolt12handler
+
+import (
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr"
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/keychain"
+ "github.com/lightningnetwork/lnd/lntest/mock"
+ "github.com/stretchr/testify/require"
+)
+
+// TestKeyRingSignerSignInvoiceRoot verifies that KeyRingSigner signs the
+// tagged hash of the root under the BOLT 12 invoice tag.
+func TestKeyRingSignerSignInvoiceRoot(t *testing.T) {
+ t.Parallel()
+
+ var seed [32]byte
+ seed[0] = 0x01
+ nodeKey, _ := btcec.PrivKeyFromBytes(seed[:])
+
+ signer := NewKeyRingSigner(
+ &mock.SecretKeyRing{RootKey: nodeKey},
+ keychain.KeyLocator{Family: keychain.KeyFamilyNodeKey},
+ nodeKey.PubKey(),
+ )
+
+ var root [32]byte
+ root[0] = 0xAB
+
+ sigBytes, err := signer.SignInvoiceRoot(root)
+ require.NoError(t, err)
+
+ sig, err := schnorr.ParseSignature(sigBytes[:])
+ require.NoError(t, err)
+
+ digest := chainhash.TaggedHash(
+ []byte(bolt12.InvoiceSignatureTag), root[:],
+ )
+ require.True(t, sig.Verify(digest[:], nodeKey.PubKey()))
+}
### bolt12handler/log.go
@@ -0,0 +1,31 @@
+package bolt12handler
+
+import (
+ "github.com/btcsuite/btclog/v2"
+ "github.com/lightningnetwork/lnd/build"
+)
+
+// log is a logger that is initialized with no output filters. This means the
+// package will not perform any logging by default until the caller requests it.
+var log btclog.Logger
+
+// Subsystem defines the logging sub system name of this package.
+const Subsystem = "B12H"
+
+// The default amount of logging is none.
+func init() {
+ UseLogger(build.NewSubLogger(Subsystem, nil))
+}
+
+// DisableLog disables all library log output. Logging output is disabled by
+// default until UseLogger is called.
+func DisableLog() {
+ UseLogger(btclog.Disabled)
+}
+
+// UseLogger uses a specified Logger to output package logging info. This
+// should be used in preference to SetLogWriter if the caller is also using
+// btclog.
+func UseLogger(logger btclog.Logger) {
+ log = logger
+}
### bolt12handler/signer.go
@@ -0,0 +1,17 @@
+package bolt12handler
+
+import (
+ "github.com/btcsuite/btcd/btcec/v2"
+)
+
+// NodeSigner provides the node's identity key for BOLT 12 invoice signing.
+type NodeSigner interface {
+ // NodePubKey returns the node's identity public key.
+ NodePubKey() *btcec.PublicKey
+
+ // SignInvoiceRoot returns a BIP-340 Schnorr signature by the node's
+ // identity key over the tagged hash of root, with the tag
+ // bolt12.InvoiceSignatureTag. The root comes from
+ // bolt12.InvoiceSigningRoot.
+ SignInvoiceRoot(root [32]byte) ([64]byte, error)
+}
### log.go
@@ -8,6 +8,7 @@ import (
"github.com/lightninglabs/neutrino"
sphinx "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/autopilot"
+ "github.com/lightningnetwork/lnd/bolt12handler"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/chainio"
"github.com/lightningnetwork/lnd/chainntnfs"
@@ -207,6 +208,10 @@ func SetupLoggers(root *build.SubLoggerManager, interceptor signal.Interceptor)
AddSubLogger(
root, blindedpath.Subsystem, interceptor, blindedpath.UseLogger,
)
+ AddSubLogger(
+ root, bolt12handler.Subsystem, interceptor,
+ bolt12handler.UseLogger,
+ )
AddSubLogger(root, graphdb.Subsystem, interceptor, graphdb.UseLogger)
AddSubLogger(root, chainio.Subsystem, interceptor, chainio.UseLogger)
AddSubLogger(root, msgmux.Subsystem, interceptor, msgmux.UseLogger)Why this scored 29/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.