Merge pull request #11340 from bitromortac/20261012-b57b-dispatch
What changed, and why it matters
This commit adds a new, experimental BOLT 12 invoice-request handler to LND. It is gated behind a build flag and a protocol option, requires native SQL, and is described in release notes as not yet routing real invoice requests to the handler. The change is a feature addition with defensive validation and tests, not a fix for an active vulnerability.
Treat this as a routine feature merge rather than an urgent security patch. Reviewers should focus on the validation logic in bolt12handler/validate.go and handler.go, ensure the CLTV-delta bounds are correct, and confirm the experimental gating prevents accidental production activation. Continue monitoring for follow-up commits that wire real invoice-request routing and database persistence.
Security signals we found
New experimental feature behind build and protocol flags
Adds input validation for BOLT 12 invoice requests (reply path, offer lookup, expiry, disabled, currency)
Adds CLTV delta bounds checks to avoid uint16 overflow when building blinded payment paths
Adds startup config validation requiring native SQL, onion messages, route blinding, and development migrations
No database row is written for generated BOLT 12 invoices yet; only an in-memory notification is sent
No vendor disclosure of a security issue or CVE
Evidence from the diff
The merge introduces the bolt12handler package, which decodes incoming BOLT 12 invoice requests, validates them against stored offers, generates signed invoices, and replies over onion messages. It wires the handler into config validation, database setup, and invoice-registry notifications. The feature is behind ExperimentalProtocol.Bolt12Offers and only enabled in builds with dev/test_native_sql tags. The code includes input validation (reply path, offer existence/expiry/disabled state, currency conversion), CLTV-delta bounds checks, and unit tests for happy path and error cases. No existing security bug is patched; this is new, guarded functionality.
Changed components
bolt12/validate.gobolt12handler/handler.gobolt12handler/replier.gobolt12handler/validate.goconfig.goconfig_builder.goinvoices/invoiceregistry.goinvoices/invoices.golncfg/protocol_experimental_off.golncfg/protocol_experimental_on.golnrpc/invoicesrpc/utils.goInspect captured patch +1509 / −5
### bolt12/validate.go
@@ -1577,9 +1577,9 @@ func validateInvoiceWrite(inv *Invoice) error {
return nil
}
-// defaultInvoiceRelativeExpiry is the spec-defined fallback when an invoice
+// DefaultInvoiceRelativeExpiry is the spec-defined fallback when an invoice
// omits invoice_relative_expiry: two hours from creation.
-const defaultInvoiceRelativeExpiry uint32 = 7200
+const DefaultInvoiceRelativeExpiry = 7200 * time.Second
// validateInvoiceExpiry rejects an invoice whose effective expiry is strictly
// before now. The effective expiry is invoice_created_at +
@@ -1600,7 +1600,7 @@ func validateInvoiceExpiry(inv *Invoice, now time.Time) error {
}
relExpiry := inv.InvoiceRelativeExp.ValOpt().UnwrapOr(
- TUint32(defaultInvoiceRelativeExpiry),
+ TUint32(DefaultInvoiceRelativeExpiry / time.Second),
)
// invoice_created_at + the relative expiry can overflow uint64 for an
### bolt12handler/handler.go
@@ -0,0 +1,262 @@
+// Package bolt12handler implements the BOLT 12 receiver side: handling incoming
+// invoice requests, generating signed invoices, and replying via onion
+// messages.
+package bolt12handler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math"
+ "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/fn/v2"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/offers"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/tlv"
+)
+
+// InvoiceNotifier sends an Open event for each new BOLT 12 invoice to the
+// connected invoice subscribers. No database row backs the event, so a
+// subscriber that connects later does not get it.
+type InvoiceNotifier interface {
+ // NotifyNewBolt12Invoice notifies connected subscribers about a newly
+ // generated BOLT 12 invoice. No database write occurs. It returns
+ // without the event when ctx ends.
+ NotifyNewBolt12Invoice(ctx context.Context, hash lntypes.Hash,
+ invoice *invoices.Invoice)
+}
+
+// Handler processes incoming BOLT 12 invoice requests and generates signed
+// invoices in response.
+type Handler struct {
+ offerStore offers.Store
+ notifier InvoiceNotifier
+ replier OnionReplier
+ signer NodeSigner
+ paymentPathBuilder PaymentPathBuilder
+ clock clock.Clock
+
+ // activeChain is the genesis hash of the chain this handler serves.
+ // It gates the spec invreq_chain reader rule.
+ activeChain [32]byte
+
+ // finalCLTVDelta is the final CLTV delta that this node requires for a
+ // BOLT 12 invoice payment.
+ finalCLTVDelta uint16
+}
+
+// NewHandler creates a new BOLT 12 invoice request handler. It returns an error
+// when the offer store, the notifier, the replier, the signer or the clock is
+// nil. The path builder can be nil, and the handler then uses a single-hop
+// blinded path. The final CLTV delta must be at least routing.MinCLTVDelta,
+// and it must leave room for routing.BlockPadding in a uint16.
+func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
+ replier OnionReplier, signer NodeSigner,
+ paymentPathBuilder PaymentPathBuilder, clk clock.Clock,
+ activeChain [32]byte, finalCLTVDelta uint16) (*Handler, error) {
+
+ switch {
+ case offerStore == nil:
+ return nil, errors.New("handler has no offer store")
+
+ case notifier == nil:
+ return nil, errors.New("handler has no notifier")
+
+ case replier == nil:
+ return nil, errors.New("handler has no replier")
+
+ case signer == nil:
+ return nil, errors.New("handler has no signer")
+
+ case clk == nil:
+ return nil, errors.New("handler has no clock")
+ }
+
+ // The payment paths add routing.BlockPadding to the delta in a
+ // uint16, so a larger delta overflows there.
+ maxDelta := uint16(math.MaxUint16) - routing.BlockPadding
+ if finalCLTVDelta < routing.MinCLTVDelta || finalCLTVDelta > maxDelta {
+ return nil, fmt.Errorf("final CLTV delta %d is outside the "+
+ "range [%d, %d]", finalCLTVDelta, routing.MinCLTVDelta,
+ maxDelta)
+ }
+
+ return &Handler{
+ offerStore: offerStore,
+ notifier: notifier,
+ replier: replier,
+ signer: signer,
+ paymentPathBuilder: paymentPathBuilder,
+ clock: clk,
+ activeChain: activeChain,
+ finalCLTVDelta: finalCLTVDelta,
+ }, nil
+}
+
+// errNoReplyPath is returned for an invoice request that arrived without a
+// reply path, because the invoice then has no way back to the payer.
+var errNoReplyPath = errors.New("invoice request has no reply path")
+
+// HandleInvoiceRequest is the top-level entry point called when an onion
+// message with TLV type 64 (invoice request) arrives.
+func (h *Handler) HandleInvoiceRequest(ctx context.Context, invreqBytes []byte,
+ replyPath *sphinx.BlindedPath) error {
+
+ // Check the reply path first, so that a request without one costs no
+ // decode and no signature.
+ if replyPath == nil {
+ return errNoReplyPath
+ }
+
+ ir, err := bolt12.DecodeInvoiceRequest(invreqBytes)
+ if err != nil {
+ return fmt.Errorf("decode invoice request: %w", err)
+ }
+
+ if err := bolt12.ValidateInvoiceRequestRead(
+ ir, h.activeChain, bolt12.Bolt12Features,
+ ); err != nil {
+ return fmt.Errorf("validate invoice request: %w", err)
+ }
+
+ offer, err := h.lookupOffer(ctx, ir)
+ if err != nil {
+ return fmt.Errorf("lookup offer: %w", err)
+ }
+
+ now := uint64(h.clock.Now().Unix())
+ if err := validateInvoiceRequestForOffer(
+ ir, offer, now,
+ ); err != nil {
+ return fmt.Errorf("validate against offer: %w", err)
+ }
+
+ result, err := GenerateInvoice(&InvoiceConfig{
+ Signer: h.signer,
+ PathBuilder: h.paymentPathBuilder,
+ Clock: h.clock,
+ FinalCLTVDelta: h.finalCLTVDelta,
+ }, ir)
+ if err != nil {
+ return fmt.Errorf("generate invoice: %w", err)
+ }
+
+ // Send the invoice before the event and the log line, so that neither
+ // announces an invoice that never left this node.
+ invoiceBytes, err := result.Invoice.EncodeSigned()
+ if err != nil {
+ return fmt.Errorf("encode reply: %w", err)
+ }
+
+ err = h.replier.SendInvoiceReply(ctx, invoiceBytes, replyPath)
+ if err != nil {
+ return fmt.Errorf("send reply: %w", err)
+ }
+
+ log.Debugf("Issued BOLT 12 invoice for offer %d: payment_hash=%v, "+
+ "amount=%v", offer.ID, result.PaymentHash,
+ lnwire.MilliSatoshi(getInvoiceAmount(result.Invoice)))
+
+ // The handler writes no invoice row and keeps the preimage nowhere, so
+ // the event is the only record of the invoice. A later change adds the
+ // state that a payment needs to settle the invoice.
+ h.notifyInvoice(ctx, result, offer)
+
+ return nil
+}
+
+// lookupOffer finds the stored offer that matches the invoice request's offer
+// fields. It computes the offer hash from the offer fields in the request and
+// looks it up in the store.
+func (h *Handler) lookupOffer(ctx context.Context, ir *bolt12.InvoiceRequest) (
+ *offers.Offer, error) {
+
+ // The codec hashes the request's offer-range records, so an unknown TLV
+ // the payer mirrored also moves the id. A hit therefore proves the
+ // offer fields match the stored offer exactly, which is the check the
+ // reader requirements ask for.
+ offerHash, err := bolt12.OfferHash(ir)
+ if err != nil {
+ return nil, fmt.Errorf("offer hash: %w", err)
+ }
+
+ return h.offerStore.GetOfferByHash(ctx, offerHash)
+}
+
+// notifyInvoice sends the Open event of a new BOLT 12 invoice to the connected
+// invoice subscribers.
+func (h *Handler) notifyInvoice(ctx context.Context, result *InvoiceResult,
+ offer *offers.Offer) {
+
+ // Extract invreq_payer_id as the serialised compressed point, for the
+ // invoices.Invoice struct which stores it as []byte.
+ var payerIDBytes []byte
+ result.Invoice.InvreqPayerID.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType88, *btcec.PublicKey]) {
+ payerIDBytes = r.Val.SerializeCompressed()
+ },
+ )
+
+ // The event carries the creation time and the features of the signed
+ // invoice, so that a subscriber sees the terms the payer received.
+ createdAt := result.Invoice.InvoiceCreatedAt.ValOpt().UnwrapOr(0)
+ features := lnwire.EmptyFeatureVector()
+ result.Invoice.InvoiceFeatures.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType174, lnwire.RawFeatureVector]) {
+ features = lnwire.NewFeatureVector(
+ &r.Val, lnwire.Features,
+ )
+ },
+ )
+
+ // An offer without an amount can omit offer_description, and the memo
+ // is then empty.
+ var memo []byte
+ result.Invoice.OfferDescription.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType10, tlv.Blob]) {
+ memo = r.Val
+ },
+ )
+
+ invoice := &invoices.Invoice{
+ Memo: memo,
+ CreationDate: time.Unix(int64(createdAt), 0).UTC(),
+ Terms: invoices.ContractTerm{
+ Expiry: bolt12.DefaultInvoiceRelativeExpiry,
+ FinalCltvDelta: int32(h.finalCLTVDelta),
+ PaymentPreimage: &result.Preimage,
+ PaymentAddr: result.PathID,
+ Value: lnwire.MilliSatoshi(
+ getInvoiceAmount(result.Invoice),
+ ),
+ Features: features,
+ },
+ PaymentRequest: []byte(result.Encoded),
+ IsBolt12: true,
+ OfferID: fn.Some(offer.ID),
+ InvreqPayerID: payerIDBytes,
+ }
+
+ h.notifier.NotifyNewBolt12Invoice(ctx, result.PaymentHash, invoice)
+}
+
+// getInvoiceAmount returns the invoice_amount in msat, or zero if the invoice
+// has none.
+func getInvoiceAmount(inv *bolt12.Invoice) uint64 {
+ var amt uint64
+ inv.InvoiceAmount.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType170, bolt12.TUint64]) {
+ amt = uint64(r.Val)
+ },
+ )
+
+ return amt
+}
### bolt12handler/handler_test.go
@@ -0,0 +1,379 @@
+package bolt12handler
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "testing"
+ "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/fn/v2"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/offers"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestHandleInvoiceRequest_FullFlow verifies that the handler replies with a
+// signed invoice and notifies an Open event that carries the terms of that
+// invoice.
+func TestHandleInvoiceRequest_FullFlow(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ store := newMockOfferStore()
+ notifier := &mockNotifier{}
+ replier := &mockReplier{}
+
+ // The builder records the path id and fails, so the handler uses the
+ // single-hop path.
+ builder := &fakePathBuilder{err: errors.New("no paths")}
+
+ handler, err := NewHandler(
+ store, notifier, replier, newPrivKeySigner(nodeKey),
+ builder, clock.NewDefaultClock(), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ // Create and store an offer.
+ offer, stored := addOffer(t, store, nodeKey, 10000)
+
+ // Build a signed invoice request.
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ invreqBytes := buildSignedInvreqBytes(
+ t, offer, payerKey, 10000,
+ )
+
+ // Create a dummy reply path.
+ replyPath := &sphinx.BlindedPath{
+ IntroductionPoint: nodeKey.PubKey(),
+ }
+
+ // Handle the request.
+ ctx := t.Context()
+ err = handler.HandleInvoiceRequest(ctx, invreqBytes, replyPath)
+ require.NoError(t, err)
+
+ // Verify invoice notification was sent (no DB write).
+ require.Len(t, notifier.invoices, 1)
+ inv := notifier.invoices[0]
+ require.True(t, inv.IsBolt12)
+ require.Equal(t, fn.Some(stored.ID), inv.OfferID)
+ require.Equal(t, []byte("test offer"), inv.Memo)
+ require.Equal(t,
+ lnwire.MilliSatoshi(10000), inv.Terms.Value,
+ )
+
+ // Verify the preimage is set and hashes to the registered payment hash.
+ require.NotNil(t, inv.Terms.PaymentPreimage)
+ expectedHash := inv.Terms.PaymentPreimage.Hash()
+ require.Equal(t, expectedHash, notifier.hashes[0])
+
+ // The reply carries the signed invoice, and the event must match its
+ // terms.
+ require.Len(t, replier.replies, 1)
+ sent, err := bolt12.DecodeInvoice(replier.replies[0])
+ require.NoError(t, err)
+
+ createdAt := sent.InvoiceCreatedAt.UnwrapOrFailV(t)
+ require.Equal(t, int64(createdAt), inv.CreationDate.Unix())
+
+ paymentHash := sent.InvoicePaymentHash.UnwrapOrFailV(t)
+ require.Equal(t, lntypes.Hash(paymentHash), notifier.hashes[0])
+
+ amount := sent.InvoiceAmount.UnwrapOrFailV(t)
+ require.EqualValues(t, amount, inv.Terms.Value)
+
+ features := sent.InvoiceFeatures.UnwrapOrFailV(t)
+ require.Equal(t,
+ lnwire.NewFeatureVector(&features, lnwire.Features),
+ inv.Terms.Features,
+ )
+ require.True(t, inv.Terms.Features.HasFeature(lnwire.MPPOptional))
+
+ encoded, err := bolt12.EncodeInvoiceString(sent)
+ require.NoError(t, err)
+ require.Equal(t, encoded, string(inv.PaymentRequest))
+
+ require.True(t, sent.InvoiceRelativeExp.IsNone())
+ require.Equal(t, bolt12.DefaultInvoiceRelativeExpiry, inv.Terms.Expiry)
+ require.EqualValues(t, testFinalCLTVDelta, inv.Terms.FinalCltvDelta)
+
+ // The single-hop path asks the payer for the delta plus the padding.
+ payInfos := sent.InvoiceBlindedPay.UnwrapOrFailV(t).Infos
+ require.Len(t, payInfos, 1)
+ require.Equal(t,
+ testFinalCLTVDelta+routing.BlockPadding,
+ payInfos[0].CltvExpiryDelta,
+ )
+ require.Equal(t, builder.gotPathID, inv.Terms.PaymentAddr[:])
+ require.Equal(t,
+ payerKey.PubKey().SerializeCompressed(), inv.InvreqPayerID,
+ )
+}
+
+// mockOfferStore implements offers.Store for testing.
+type mockOfferStore struct {
+ offers map[[32]byte]*offers.Offer
+}
+
+func newMockOfferStore() *mockOfferStore {
+ return &mockOfferStore{
+ offers: make(map[[32]byte]*offers.Offer),
+ }
+}
+
+func (m *mockOfferStore) InsertOffer(_ context.Context, offer *offers.Offer) (
+ int64, error) {
+
+ m.offers[offer.Hash] = offer
+ offer.ID = int64(len(m.offers))
+
+ return offer.ID, nil
+}
+
+func (m *mockOfferStore) GetOfferByHash(_ context.Context,
+ offerHash [32]byte) (*offers.Offer, error) {
+
+ if o, ok := m.offers[offerHash]; ok {
+ return o, nil
+ }
+
+ return nil, offers.ErrOfferNotFound
+}
+
+// mockNotifier captures BOLT 12 invoice notifications during the handler flow.
+type mockNotifier struct {
+ invoices []*invoices.Invoice
+ hashes []lntypes.Hash
+}
+
+func (m *mockNotifier) NotifyNewBolt12Invoice(_ context.Context,
+ hash lntypes.Hash, invoice *invoices.Invoice) {
+
+ m.invoices = append(m.invoices, invoice)
+ m.hashes = append(m.hashes, hash)
+}
+
+// mockReplier captures reply invocations and returns err.
+type mockReplier struct {
+ replies [][]byte
+ err error
+}
+
+func (m *mockReplier) SendInvoiceReply(_ context.Context, invoiceBytes []byte,
+ _ *sphinx.BlindedPath) error {
+
+ m.replies = append(m.replies, invoiceBytes)
+
+ return m.err
+}
+
+// addOffer creates a bolt12 offer and stores it in the mock store. It returns
+// the codec offer and the stored record.
+func addOffer(t *testing.T, store *mockOfferStore, nodeKey *btcec.PrivateKey,
+ amountMsat uint64) (*bolt12.Offer, *offers.Offer) {
+
+ t.Helper()
+
+ b12Offer := testOffer(t, nodeKey, amountMsat)
+
+ return b12Offer, storeOffer(t, store, b12Offer)
+}
+
+// storeOffer stores the codec offer in the mock store and returns the stored
+// record.
+func storeOffer(t *testing.T, store *mockOfferStore,
+ b12Offer *bolt12.Offer) *offers.Offer {
+
+ t.Helper()
+
+ encoded, err := bolt12.EncodeOfferString(b12Offer)
+ require.NoError(t, err)
+
+ offerHash, err := bolt12.OfferHash(b12Offer)
+ require.NoError(t, err)
+
+ offer := &offers.Offer{
+ Hash: offerHash,
+ Encoded: encoded,
+ }
+
+ _, err = store.InsertOffer(t.Context(), offer)
+ require.NoError(t, err)
+
+ return offer
+}
+
+// buildSignedInvreqBytes constructs a signed invoice request and returns the
+// raw TLV bytes.
+func buildSignedInvreqBytes(t *testing.T, offer *bolt12.Offer,
+ payerKey *btcec.PrivateKey, invreqAmount uint64) []byte {
+
+ t.Helper()
+
+ ir := testInvoiceRequest(t, offer, payerKey, invreqAmount)
+
+ sig, err := bolt12.SignInvoiceRequest(ir, payerKey)
+ require.NoError(t, err)
+
+ ir.Signature = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType240, [64]byte]{
+ Val: sig,
+ },
+ )
+
+ finalBytes, err := ir.EncodeSigned()
+ require.NoError(t, err)
+
+ return finalBytes
+}
+
+// TestHandleInvoiceRequestErrors verifies that the handler returns the error
+// of each step that refuses a request. The reader checks the quantity and the
+// amount, so one reader rule shows that the handler runs the reader.
+func TestHandleInvoiceRequestErrors(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ errReply := errors.New("reply failed")
+
+ now := time.Unix(4102444800, 0)
+
+ tests := []struct {
+ name string
+ invreqAmount uint64
+ noReplyPath bool
+ unsigned bool
+ unstored bool
+ disabled bool
+ expired bool
+ replyErr error
+ wantErr error
+ }{
+ {
+ name: "no reply path",
+ invreqAmount: 10000,
+ noReplyPath: true,
+ wantErr: errNoReplyPath,
+ },
+ {
+ name: "reader rule",
+ invreqAmount: 5000,
+ unsigned: true,
+ wantErr: bolt12.ErrAmountBelowExpected,
+ },
+ {
+ name: "offer not found",
+ invreqAmount: 10000,
+ unstored: true,
+ wantErr: offers.ErrOfferNotFound,
+ },
+ {
+ name: "offer disabled",
+ invreqAmount: 10000,
+ disabled: true,
+ wantErr: ErrOfferDisabled,
+ },
+ {
+ name: "offer expired",
+ invreqAmount: 10000,
+ expired: true,
+ wantErr: bolt12.ErrOfferExpired,
+ },
+ {
+ name: "reply fails",
+ invreqAmount: 10000,
+ replyErr: errReply,
+ wantErr: errReply,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ store := newMockOfferStore()
+ notifier := &mockNotifier{}
+ handler, err := NewHandler(
+ store, notifier,
+ &mockReplier{err: tc.replyErr},
+ newPrivKeySigner(nodeKey), nil,
+ clock.NewTestClock(now), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ offer := testOffer(t, nodeKey, 10000)
+ if tc.expired {
+ expiry := bolt12.TUint64(now.Unix() - 1)
+ offer.OfferAbsoluteExpiry = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType14](
+ expiry,
+ ),
+ )
+ }
+ if !tc.unstored {
+ stored := storeOffer(t, store, offer)
+ stored.IsDisabled = tc.disabled
+ }
+
+ ir := testInvoiceRequest(
+ t, offer, payerKey, tc.invreqAmount,
+ )
+
+ // The codec refuses to sign a request that breaks a
+ // reader rule, so encode the records directly. The
+ // reader checks the signature after the amount, so a
+ // placeholder signature reaches the amount rule.
+ var sig [64]byte
+ if !tc.unsigned {
+ var err error
+ sig, err = bolt12.SignInvoiceRequest(
+ ir, payerKey,
+ )
+ require.NoError(t, err)
+ }
+ ir.Signature = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType240, [64]byte]{
+ Val: sig,
+ },
+ )
+
+ var buf bytes.Buffer
+ err = lnwire.EncodePureTLVMessage(ir, &buf)
+ require.NoError(t, err)
+
+ replyPath := &sphinx.BlindedPath{
+ IntroductionPoint: nodeKey.PubKey(),
+ }
+ if tc.noReplyPath {
+ replyPath = nil
+ }
+ err = handler.HandleInvoiceRequest(
+ t.Context(), buf.Bytes(), replyPath,
+ )
+ require.ErrorIs(t, err, tc.wantErr)
+
+ // A rejected request, or an invoice that could not be
+ // sent, must not reach the subscribers.
+ require.Empty(t, notifier.invoices)
+ })
+ }
+}
### bolt12handler/replier.go
@@ -0,0 +1,120 @@
+package bolt12handler
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/routing/route"
+)
+
+// OnionMessageSender sends an onion message to a peer.
+type OnionMessageSender interface {
+ // SendOnionMessage sends the onion to the peer with the path key that
+ // the peer needs to decrypt its layer.
+ SendOnionMessage(ctx context.Context, peerPub [33]byte,
+ pathKey *btcec.PublicKey, onion []byte) error
+}
+
+// OnionReplier sends an onion message containing an invoice back to the payer
+// via the provided reply path.
+type OnionReplier interface {
+ // SendInvoiceReply sends the encoded invoice bytes as a type-66 TLV
+ // payload via the reply path.
+ SendInvoiceReply(ctx context.Context, invoiceBytes []byte,
+ replyPath *sphinx.BlindedPath) error
+}
+
+// A compile-time check that ServerOnionReplier implements OnionReplier.
+var _ OnionReplier = (*ServerOnionReplier)(nil)
+
+// ServerOnionReplier implements OnionReplier by constructing an onion message
+// from the reply path and sending it via the daemon's SendOnionMessage method.
+// The reply path's introduction node must be a direct peer for now.
+type ServerOnionReplier struct {
+ sender OnionMessageSender
+}
+
+// NewServerOnionReplier creates a new OnionReplier backed by the daemon's onion
+// message sender.
+func NewServerOnionReplier(
+ sender OnionMessageSender) *ServerOnionReplier {
+
+ return &ServerOnionReplier{
+ sender: sender,
+ }
+}
+
+// SendInvoiceReply sends the encoded invoice bytes as a type-66 TLV payload via
+// the reply path.
+//
+// NOTE: This is part of the OnionReplier interface.
+func (r *ServerOnionReplier) SendInvoiceReply(ctx context.Context,
+ invoiceBytes []byte, replyPath *sphinx.BlindedPath) error {
+
+ if replyPath == nil {
+ return fmt.Errorf("no reply path provided")
+ }
+
+ if len(replyPath.BlindedHops) == 0 {
+ return fmt.Errorf("reply path has no hops")
+ }
+
+ if replyPath.IntroductionPoint == nil {
+ return fmt.Errorf("reply path has no introduction node key")
+ }
+
+ finalHopTLVs := []*lnwire.FinalHopTLV{
+ {
+ TLVType: lnwire.InvoiceNamespaceType,
+ Value: invoiceBytes,
+ },
+ }
+
+ // TODO: Find a route to an introduction node that is not a peer, and
+ // send the reply through the nodes on that route. Until then, a payer
+ // whose reply path starts at a non-peer gets no invoice.
+ return r.sendDirect(ctx, replyPath, finalHopTLVs)
+}
+
+// sendDirect sends the reply onion directly to the reply path's intro node.
+func (r *ServerOnionReplier) sendDirect(ctx context.Context,
+ replyPath *sphinx.BlindedPath,
+ finalHopTLVs []*lnwire.FinalHopTLV) error {
+
+ sphinxPath, err := route.OnionMessageBlindedPathToSphinxPath(
+ replyPath, nil, finalHopTLVs,
+ )
+ if err != nil {
+ return fmt.Errorf("build sphinx path: %w", err)
+ }
+
+ sessionKey, err := btcec.NewPrivateKey()
+ if err != nil {
+ return fmt.Errorf("generate session key: %w", err)
+ }
+
+ onionPkt, err := sphinx.NewOnionPacket(
+ sphinxPath, sessionKey, nil,
+ sphinx.DeterministicPacketFiller,
+ sphinx.WithMaxPayloadSize(sphinx.MaxOnionMessagePayloadSize),
+ )
+ if err != nil {
+ return fmt.Errorf("build onion packet: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := onionPkt.Encode(&buf); err != nil {
+ return fmt.Errorf("encode onion packet: %w", err)
+ }
+
+ var peerPub [33]byte
+ copy(peerPub[:], replyPath.IntroductionPoint.SerializeCompressed())
+
+ return r.sender.SendOnionMessage(
+ ctx, peerPub, replyPath.BlindingPoint, buf.Bytes(),
+ )
+}
### bolt12handler/replier_test.go
@@ -0,0 +1,115 @@
+package bolt12handler
+
+import (
+ "context"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/onionmessage"
+ "github.com/stretchr/testify/require"
+)
+
+// TestServerOnionReplierPathChecks verifies that the replier refuses a reply
+// path that it cannot send to. Otherwise it sends the invoice as a type-66
+// payload to the introduction node.
+func TestServerOnionReplierPathChecks(t *testing.T) {
+ t.Parallel()
+
+ introKey := testKey(t)
+ hopKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ pathKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ newPath := func() *sphinx.BlindedPath {
+ return &sphinx.BlindedPath{
+ IntroductionPoint: introKey.PubKey(),
+ BlindingPoint: pathKey.PubKey(),
+ BlindedHops: []*sphinx.BlindedHopInfo{{
+ BlindedNodePub: hopKey.PubKey(),
+ CipherText: []byte{1, 2, 3},
+ }},
+ }
+ }
+
+ noHops := newPath()
+ noHops.BlindedHops = nil
+
+ noIntroKey := newPath()
+ noIntroKey.IntroductionPoint = nil
+
+ invoiceBytes := []byte{0x01, 0x02}
+
+ tests := []struct {
+ name string
+ path *sphinx.BlindedPath
+ wantErr string
+ }{
+ {name: "nil path", wantErr: "no reply path"},
+ {name: "no hops", path: noHops, wantErr: "no hops"},
+ {
+ name: "no introduction node key",
+ path: noIntroKey,
+ wantErr: "no introduction node key",
+ },
+ {name: "valid path", path: newPath()},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ sender := &mockOnionSender{}
+ replier := NewServerOnionReplier(sender)
+
+ err := replier.SendInvoiceReply(
+ t.Context(), invoiceBytes, tc.path,
+ )
+ if tc.wantErr != "" {
+ require.ErrorContains(t, err, tc.wantErr)
+ require.Empty(t, sender.peers)
+
+ return
+ }
+
+ require.NoError(t, err)
+ require.Len(t, sender.peers, 1)
+
+ var want [33]byte
+ copy(want[:], introKey.PubKey().SerializeCompressed())
+ require.Equal(t, want, sender.peers[0])
+
+ // The path has no real blinding, so the hop key alone
+ // peels the onion.
+ msg := &lnwire.OnionMessage{
+ OnionBlob: sender.onions[0],
+ }
+ hops := onionmessage.PeelOnionLayers(
+ t, []*btcec.PrivateKey{hopKey}, msg,
+ )
+ require.Len(t, hops, 1)
+ require.Equal(t, []*lnwire.FinalHopTLV{{
+ TLVType: lnwire.InvoiceNamespaceType,
+ Value: invoiceBytes,
+ }}, hops[0].Payload.FinalHopTLVs)
+ })
+ }
+}
+
+// mockOnionSender records the peer and the onion of each onion message it
+// sends.
+type mockOnionSender struct {
+ peers [][33]byte
+ onions [][]byte
+}
+
+func (m *mockOnionSender) SendOnionMessage(_ context.Context,
+ peerPub [33]byte, _ *btcec.PublicKey, onion []byte) error {
+
+ m.peers = append(m.peers, peerPub)
+ m.onions = append(m.onions, onion)
+
+ return nil
+}
### bolt12handler/validate.go
@@ -0,0 +1,47 @@
+package bolt12handler
+
+import (
+ "errors"
+
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/offers"
+)
+
+// ErrOfferDisabled is returned when the offer has been administratively
+// disabled.
+var ErrOfferDisabled = errors.New("offer is disabled")
+
+// validateInvoiceRequestForOffer performs the offer-specific validation of an
+// invoice request that ValidateInvoiceRequestRead does not cover. It checks
+// that the offer is not expired or disabled, and that the offer is priced in
+// msat.
+//
+// The caller must look up the offer by the offer hash of the request. That hit
+// proves the offer fields in the request match the stored offer, so the terms
+// are read from the request. The caller must also run
+// bolt12.ValidateInvoiceRequestRead first, because only the reader checks the
+// quantity and the amount.
+func validateInvoiceRequestForOffer(ir *bolt12.InvoiceRequest,
+ offer *offers.Offer, now uint64) error {
+
+ if offer.IsDisabled {
+ return ErrOfferDisabled
+ }
+
+ // Offer must not be expired. The offer expires after its last second,
+ // as the payer's codec reads offer_absolute_expiry, so a request that
+ // the payer could still send in that second is answered.
+ if ir.OfferAbsoluteExpiry.IsSome() &&
+ now > uint64(ir.OfferAbsoluteExpiry.ValOpt().UnwrapOr(0)) {
+
+ return bolt12.ErrOfferExpired
+ }
+
+ // The reader cannot check invreq_amount against an offer_amount in
+ // offer_currency units, and the handler has no exchange rate to do it.
+ if ir.OfferCurrency.IsSome() {
+ return errCurrencyConversion
+ }
+
+ return nil
+}
### bolt12handler/validate_test.go
@@ -0,0 +1,88 @@
+package bolt12handler
+
+import (
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/offers"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestValidateInvoiceRequestForOffer verifies the offer-specific checks. A
+// request that arrives in the offer_absolute_expiry second passes, as the
+// payer's codec still accepts the offer then. A request for an offer priced in
+// a currency fails, because its invreq_amount in msat cannot be compared with
+// offer_amount.
+func TestValidateInvoiceRequestForOffer(t *testing.T) {
+ t.Parallel()
+
+ const expiry = 1735689600
+
+ var payerSeed [32]byte
+ payerSeed[0] = 0xFF
+ payerKey, _ := btcec.PrivKeyFromBytes(payerSeed[:])
+
+ tests := []struct {
+ name string
+ expiry uint64
+ currency bool
+ disabled bool
+ now uint64
+ wantErr error
+ }{
+ {name: "valid", now: expiry},
+ {
+ name: "disabled",
+ disabled: true,
+ now: expiry,
+ wantErr: ErrOfferDisabled,
+ },
+ {name: "expiry second", expiry: expiry, now: expiry},
+ {
+ name: "expired",
+ expiry: expiry,
+ now: expiry + 1,
+ wantErr: bolt12.ErrOfferExpired,
+ },
+ {
+ name: "currency",
+ currency: true,
+ now: expiry,
+ wantErr: errCurrencyConversion,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ offer := testOffer(t, testKey(t), 1000)
+ if tc.expiry > 0 {
+ expiry := bolt12.TUint64(tc.expiry)
+ offer.OfferAbsoluteExpiry = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType14](
+ expiry,
+ ),
+ )
+ }
+
+ if tc.currency {
+ offer.OfferCurrency = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType6, tlv.Blob]{
+ Val: []byte("USD"),
+ },
+ )
+ }
+
+ ir := testInvoiceRequest(t, offer, payerKey, 1000)
+
+ err := validateInvoiceRequestForOffer(
+ ir, &offers.Offer{IsDisabled: tc.disabled},
+ tc.now,
+ )
+ require.ErrorIs(t, err, tc.wantErr)
+ })
+ }
+}
### config.go
@@ -46,6 +46,7 @@ import (
"github.com/lightningnetwork/lnd/onionmessage"
"github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/signal"
+ "github.com/lightningnetwork/lnd/sqldb"
"github.com/lightningnetwork/lnd/tor"
)
@@ -1220,6 +1221,12 @@ func ValidateConfig(cfg Config, interceptor signal.Interceptor, fileParser,
return nil, mkErr("%s", err)
}
+ if cfg.ProtocolOptions.Bolt12OffersEnabled() {
+ if err := validateBolt12Offers(&cfg); err != nil {
+ return nil, mkErr("%s", err)
+ }
+ }
+
// Ensure that --maxchansize is properly handled when set by user.
// For non-Wumbo channels this limit remains 16777215 satoshis by default
// as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
@@ -2621,3 +2628,63 @@ func logWarningsForDeprecation(cfg Config) {
ltndLog.Warnf("Config '%s' is deprecated, please remove it", k)
}
}
+
+// bolt12Migrations names the development migrations that BOLT 12 offers need.
+// A release build does not apply them, so BOLT 12 tables exist only in a build
+// with the development migrations.
+var bolt12Migrations = []string{
+ "000016_offers",
+}
+
+// validateBolt12Offers makes sure that the node can run BOLT 12 offers. The
+// offer store lives in native SQL, and its migration must be part of this
+// build. Checking at startup keeps a node from failing later, on the first
+// offer or the first payment.
+func validateBolt12Offers(cfg *Config) error {
+ if cfg.ProtocolOptions.NoOnionMessages() {
+ return errors.New("protocol.bolt12-offers needs onion messages")
+ }
+
+ if cfg.ProtocolOptions.NoRouteBlinding() {
+ return errors.New("protocol.bolt12-offers needs route blinding")
+ }
+
+ if cfg.DB == nil || !cfg.DB.UseNativeSQL {
+ return errors.New("protocol.bolt12-offers needs " +
+ "db.use-native-sql")
+ }
+
+ // The payment paths add routing.BlockPadding to the final CLTV delta
+ // in a uint16, so the BOLT 12 handler refuses a larger delta. The
+ // general config check sets only the lower bound.
+ maxDelta := uint32(math.MaxUint16 - routing.BlockPadding)
+ if cfg.Bitcoin.TimeLockDelta > maxDelta {
+ return fmt.Errorf("protocol.bolt12-offers needs "+
+ "bitcoin.timelockdelta of at most %d", maxDelta)
+ }
+
+ if name, ok := missingMigration(bolt12Migrations); ok {
+ return fmt.Errorf("protocol.bolt12-offers needs the BOLT 12 "+
+ "development migrations, but %s is not part of this "+
+ "build, which needs the test_native_sql tag", name)
+ }
+
+ return nil
+}
+
+// missingMigration returns the first of the named migrations that this build
+// does not apply, and false if the build applies all of them.
+func missingMigration(names []string) (string, bool) {
+ known := make(map[string]struct{})
+ for _, migration := range sqldb.GetMigrations() {
+ known[migration.Name] = struct{}{}
+ }
+
+ for _, name := range names {
+ if _, ok := known[name]; !ok {
+ return name, true
+ }
+ }
+
+ return "", false
+}
### config_builder.go
@@ -52,6 +52,7 @@ import (
"github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
"github.com/lightningnetwork/lnd/macaroons"
"github.com/lightningnetwork/lnd/msgmux"
+ "github.com/lightningnetwork/lnd/offers"
paymentsdb "github.com/lightningnetwork/lnd/payments/db"
paymentsmig1 "github.com/lightningnetwork/lnd/payments/db/migration1"
paymentsmig1sqlc "github.com/lightningnetwork/lnd/payments/db/migration1/sqlc"
@@ -1028,6 +1029,9 @@ type DatabaseInstances struct {
// be used for native SQL queries for tables that already support it.
// This may be nil if the use-native-sql flag was not set.
NativeSQLStore sqldb.DB
+
+ // OfferDB is the database that stores BOLT 12 offers.
+ OfferDB offers.Store
}
// DefaultDatabaseBuilder is a type that builds the default database backends
@@ -1360,6 +1364,23 @@ func (d *DefaultDatabaseBuilder) BuildDatabase(
dbs.InvoiceDB = sqlInvoiceDB
+ // The offer table comes from a development migration, so only
+ // a node with BOLT 12 offers enabled touches it. The startup
+ // check makes sure that the migration exists then. Without an
+ // offer store the server answers no invoice requests.
+ if d.cfg.ProtocolOptions.Bolt12OffersEnabled() {
+ offerExecutor := sqldb.NewTransactionExecutor(
+ baseDB,
+ func(tx *sql.Tx) offers.SQLOfferQueries {
+ return baseDB.WithTx(tx)
+ },
+ )
+
+ dbs.OfferDB = offers.NewSQLStore(
+ offerExecutor, clock.NewDefaultClock(),
+ )
+ }
+
// Create the graph store.
graphExecutor := sqldb.NewTransactionExecutor(
baseDB, func(tx *sql.Tx) graphdb.SQLQueries {
### config_test.go
@@ -347,3 +347,98 @@ func TestValidateChannelPolicyTimeLockDelta(t *testing.T) {
)
require.ErrorContains(t, err, "exceeds max-cltv-expiry")
}
+
+// TestValidateBolt12Offers verifies that the startup check refuses BOLT 12
+// offers on a node that cannot hold their tables or deliver their messages,
+// and accepts them only in a build with the development migrations.
+func TestValidateBolt12Offers(t *testing.T) {
+ t.Parallel()
+
+ // A release build has no BOLT 12 migrations and must refuse the
+ // flag. A build with the development migrations accepts it.
+ buildErr := ""
+ if _, missing := missingMigration(bolt12Migrations); missing {
+ buildErr = "not part of this build"
+ }
+
+ tests := []struct {
+ name string
+ modify func(cfg *Config)
+ wantErr string
+ }{
+ {
+ name: "no onion messages",
+ modify: func(cfg *Config) {
+ cfg.ProtocolOptions.NoOnionMessagesOption = true
+ },
+ wantErr: "onion messages",
+ },
+ {
+ name: "no route blinding",
+ modify: func(cfg *Config) {
+ cfg.ProtocolOptions.NoRouteBlindingOption = true
+ },
+ wantErr: "route blinding",
+ },
+ {
+ name: "no native sql",
+ modify: func(cfg *Config) {
+ cfg.DB.UseNativeSQL = false
+ },
+ wantErr: "db.use-native-sql",
+ },
+ {
+ name: "time lock delta above the path limit",
+ modify: func(cfg *Config) {
+ cfg.Bitcoin.TimeLockDelta = math.MaxUint16 -
+ uint32(routing.BlockPadding) + 1
+ },
+ wantErr: "bitcoin.timelockdelta",
+ },
+ {
+ name: "build migrations",
+ modify: func(*Config) {},
+ wantErr: buildErr,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ cfg := &Config{
+ ProtocolOptions: &lncfg.ProtocolOptions{},
+ DB: &lncfg.DB{UseNativeSQL: true},
+ Bitcoin: &lncfg.Chain{
+ TimeLockDelta: chainreg.
+ DefaultBitcoinTimeLockDelta,
+ },
+ }
+ tc.modify(cfg)
+
+ err := validateBolt12Offers(cfg)
+ if tc.wantErr == "" {
+ require.NoError(t, err)
+
+ return
+ }
+
+ require.ErrorContains(t, err, tc.wantErr)
+ })
+ }
+}
+
+// TestMissingMigration verifies that the migration lookup finds a migration
+// that every build applies and reports one that no build has.
+func TestMissingMigration(t *testing.T) {
+ t.Parallel()
+
+ _, missing := missingMigration([]string{"000001_invoices"})
+ require.False(t, missing)
+
+ name, missing := missingMigration(
+ []string{"000001_invoices", "999999_unknown"},
+ )
+ require.True(t, missing)
+ require.Equal(t, "999999_unknown", name)
+}
### docs/release-notes/release-notes-0.22.0.md
@@ -196,6 +196,13 @@
migration for now, so a normal build does not change the database
schema.
+* [BOLT 12 invoice request
+ handler](https://github.com/lightningnetwork/lnd/pull/11340): add the
+ experimental `protocol.bolt12-offers` flag, which needs a build with the `dev`
+ and `test_native_sql` tags and native SQL. Add a handler that answers an
+ invoice request for a stored offer with a signed invoice and notifies invoice
+ subscribers. The node does not route invoice requests to the handler yet.
+
## Testing
* [BOLT 12 spec test vectors](https://github.com/lightningnetwork/lnd/pull/11001):
### invoices/invoiceregistry.go
@@ -389,6 +389,11 @@ func (i *InvoiceRegistry) dispatchToSingleClients(event *invoiceEvent) {
func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) {
invoice := event.invoice
+ // A BOLT 12 invoice has no database row and so no add index. Its
+ // event skips the add index checks and must not move the add index of
+ // a client back to zero, which would replay later events.
+ unindexedBolt12 := invoice.IsBolt12 && invoice.AddIndex == 0
+
clients := i.copyClients()
for clientID, client := range clients {
// Before we dispatch this event, we'll check
@@ -399,6 +404,8 @@ func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) {
// TODO(joostjager): Refactor switches.
state := event.invoice.State
switch {
+ case unindexedBolt12:
+
// If we've already sent this settle event to
// the client, then we can skip this.
case state == ContractSettled &&
@@ -456,6 +463,8 @@ func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) {
// event is added while we're catching up a new client.
invState := event.invoice.State
switch {
+ case unindexedBolt12:
+
case invState == ContractSettled:
client.settleIndex = invoice.SettleIndex
@@ -1567,6 +1576,25 @@ func (i *InvoiceRegistry) notifyClients(hash lntypes.Hash,
}
}
+// NotifyNewBolt12Invoice sends an Open event for a new BOLT 12 invoice to the
+// connected subscribers. The invoice has no database row, so a subscriber that
+// connects later does not get the event. It returns without the event when ctx
+// ends, so that a caller can stop before the registry.
+func (i *InvoiceRegistry) NotifyNewBolt12Invoice(ctx context.Context,
+ hash lntypes.Hash, invoice *Invoice) {
+
+ event := &invoiceEvent{
+ invoice: invoice,
+ hash: hash,
+ }
+
+ select {
+ case i.invoiceEvents <- event:
+ case <-i.quit:
+ case <-ctx.Done():
+ }
+}
+
// invoiceSubscriptionKit defines that are common to both all invoice
// subscribers and single invoice subscribers.
type invoiceSubscriptionKit struct {
### invoices/invoiceregistry_bolt12_test.go
@@ -0,0 +1,40 @@
+package invoices
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/stretchr/testify/require"
+)
+
+// TestNotifyNewBolt12InvoiceContext checks that a BOLT 12 notification
+// returns when its context ends, even while the registry takes no events.
+func TestNotifyNewBolt12InvoiceContext(t *testing.T) {
+ t.Parallel()
+
+ // No event loop reads this channel, so a send blocks.
+ registry := &InvoiceRegistry{
+ invoiceEvents: make(chan *invoiceEvent),
+ quit: make(chan struct{}),
+ }
+
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+
+ registry.NotifyNewBolt12Invoice(
+ ctx, lntypes.Hash{1}, &Invoice{IsBolt12: true},
+ )
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ require.FailNow(t, "notification ignored its context")
+ }
+}
### invoices/invoiceregistry_test.go
@@ -544,6 +544,14 @@ func TestInvoiceRegistry(t *testing.T) {
name: "ProcessingErrors",
test: testInvoiceRegistryProcessingErrors,
},
+ {
+ name: "Bolt12InvoiceNotification",
+ test: testBolt12InvoiceNotification,
+ },
+ {
+ name: "Bolt12InvoiceNoBacklog",
+ test: testBolt12InvoiceNoBacklog,
+ },
}
makeKeyValueDB := func(t *testing.T) (invpkg.InvoiceDB,
@@ -614,6 +622,149 @@ func TestInvoiceRegistry(t *testing.T) {
}
}
+// testBolt12InvoiceNotification verifies that an all-invoice subscriber gets
+// the Open event of a BOLT 12 invoice, which has no add index, and that the
+// event does not change the add index the registry records for the client.
+func testBolt12InvoiceNotification(t *testing.T,
+ makeDB func(t *testing.T) (invpkg.InvoiceDB, *clock.TestClock)) {
+
+ t.Parallel()
+
+ ctx := newTestContext(t, nil, makeDB)
+
+ // The client reports add index 1 as seen, so the registry must not
+ // send the stored invoice with that index.
+ ctxb := t.Context()
+ allSubscriptions, err := ctx.registry.SubscribeNotifications(ctxb, 1, 0)
+ require.NoError(t, err)
+ defer allSubscriptions.Cancel()
+
+ expectNew := func(isBolt12 bool, addIndex uint64) {
+ t.Helper()
+
+ select {
+ case inv := <-allSubscriptions.NewInvoices:
+ require.Equal(t, invpkg.ContractOpen, inv.State)
+ require.Equal(t, isBolt12, inv.IsBolt12)
+ require.Equal(t, addIndex, inv.AddIndex)
+
+ case <-time.After(testTimeout):
+ t.Fatal("no new invoice event received")
+ }
+ }
+
+ var preimage lntypes.Preimage
+ preimage[0] = 0x12
+
+ ctx.registry.NotifyNewBolt12Invoice(
+ t.Context(), preimage.Hash(), &invpkg.Invoice{
+ IsBolt12: true,
+ Terms: invpkg.ContractTerm{
+ PaymentPreimage: &preimage,
+ Value: testInvoiceAmount,
+ },
+ },
+ )
+ expectNew(true, 0)
+
+ _, err = ctx.registry.AddInvoice(
+ ctxb, newInvoice(t, false, false), testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+
+ second := newInvoiceExpiryTestInvoice(
+ t, lntypes.Preimage{2}, testTime, 0,
+ )
+ _, err = ctx.registry.AddInvoice(
+ ctxb, second, second.Terms.PaymentPreimage.Hash(),
+ )
+ require.NoError(t, err)
+ expectNew(false, 2)
+
+ select {
+ case inv := <-allSubscriptions.NewInvoices:
+ t.Fatalf("unexpected event: %v", inv)
+
+ case <-time.After(100 * time.Millisecond):
+ }
+}
+
+// testBolt12InvoiceNoBacklog verifies that a subscriber that connects after
+// the events gets the stored BOLT 11 invoice from the backlog, but not the
+// BOLT 12 invoice, because no database row backs a BOLT 12 event.
+func testBolt12InvoiceNoBacklog(t *testing.T,
+ makeDB func(t *testing.T) (invpkg.InvoiceDB, *clock.TestClock)) {
+
+ t.Parallel()
+
+ ctx := newTestContext(t, nil, makeDB)
+ ctxb := t.Context()
+
+ // The registry dispatches events in the background. A subscriber that
+ // sees every event shows that the dispatch is done before the late
+ // subscriber connects.
+ early, err := ctx.registry.SubscribeNotifications(ctxb, 0, 0)
+ require.NoError(t, err)
+ defer early.Cancel()
+
+ _, err = ctx.registry.AddInvoice(
+ ctxb, newInvoice(t, false, false), testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+
+ var preimage lntypes.Preimage
+ preimage[0] = 0x12
+
+ ctx.registry.NotifyNewBolt12Invoice(
+ t.Context(), preimage.Hash(), &invpkg.Invoice{
+ IsBolt12: true,
+ Terms: invpkg.ContractTerm{
+ PaymentPreimage: &preimage,
+ Value: testInvoiceAmount,
+ },
+ },
+ )
+
+ second := newInvoiceExpiryTestInvoice(
+ t, lntypes.Preimage{2}, testTime, 0,
+ )
+ _, err = ctx.registry.AddInvoice(
+ ctxb, second, second.Terms.PaymentPreimage.Hash(),
+ )
+ require.NoError(t, err)
+
+ for range 3 {
+ select {
+ case <-early.NewInvoices:
+ case <-time.After(testTimeout):
+ t.Fatal("no event received")
+ }
+ }
+
+ // The backlog holds the invoices with an add index above the one the
+ // client reports, so add index 1 asks for everything after the first
+ // invoice. Add index 0 would ask for no backlog at all.
+ late, err := ctx.registry.SubscribeNotifications(ctxb, 1, 0)
+ require.NoError(t, err)
+ defer late.Cancel()
+
+ select {
+ case inv := <-late.NewInvoices:
+ require.False(t, inv.IsBolt12)
+ require.EqualValues(t, 2, inv.AddIndex)
+
+ case <-time.After(testTimeout):
+ t.Fatal("no backlog event received")
+ }
+
+ select {
+ case inv := <-late.NewInvoices:
+ t.Fatalf("unexpected event: %v", inv)
+
+ case <-time.After(100 * time.Millisecond):
+ }
+}
+
// testSettleInvoice tests settling of an invoice and related notifications.
func testSettleInvoice(t *testing.T,
makeDB func(t *testing.T) (invpkg.InvoiceDB, *clock.TestClock)) {
### invoices/invoices.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/lightningnetwork/lnd/feature"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
@@ -430,6 +431,20 @@ type Invoice struct {
// HodlInvoice indicates whether the invoice should be held in the
// Accepted state or be settled right away.
HodlInvoice bool
+
+ // IsBolt12 indicates whether this invoice was created via the
+ // BOLT 12 offer/invoice-request protocol.
+ IsBolt12 bool
+
+ // OfferID is the database primary key of the offer that spawned
+ // this invoice. It is None for BOLT 11 invoices and BOLT 12 invoices
+ // not tied to an offer.
+ OfferID fn.Option[int64]
+
+ // InvreqPayerID is the 33-byte compressed pubkey from the
+ // invreq_payer_id TLV (type 88) in the invoice request. Nil
+ // for BOLT 11.
+ InvreqPayerID []byte
}
// HTLCSet returns the set of HTLCs belonging to setID and in the provided
### lncfg/protocol_experimental_off.go
@@ -7,3 +7,9 @@ package lncfg
// features that also require a build-tag to activate.
type ExperimentalProtocol struct {
}
+
+// Bolt12OffersEnabled returns false, because a release build has no BOLT 12
+// offers.
+func (p ExperimentalProtocol) Bolt12OffersEnabled() bool {
+ return false
+}
### lncfg/protocol_experimental_on.go
@@ -5,5 +5,16 @@ package lncfg
// ExperimentalProtocol is a sub-config that houses any experimental protocol
// features that also require a build-tag to activate.
+//
+//nolint:ll
type ExperimentalProtocol struct {
+ // Bolt12Offers turns on BOLT 12 offers. The node opens the offer store,
+ // which needs native SQL and the BOLT 12 development migrations. Only
+ // a build with the test_native_sql tag contains those migrations.
+ Bolt12Offers bool `long:"bolt12-offers" description:"enable BOLT 12 offers (experimental), which needs db.use-native-sql and a build with the dev and test_native_sql tags"`
+}
+
+// Bolt12OffersEnabled returns true if BOLT 12 offers are enabled.
+func (p ExperimentalProtocol) Bolt12OffersEnabled() bool {
+ return p.Bolt12Offers
}
### lnrpc/invoicesrpc/utils.go
@@ -17,12 +17,13 @@ import (
// decodePayReq decodes the invoice payment request if present. This is needed,
// because not all information is stored in dedicated invoice fields. If there
// is no payment request present, a dummy request will be returned. This can
-// happen with just-in-time inserted keysend invoices.
+// happen with just-in-time inserted keysend invoices. A BOLT 12 invoice also
+// gets the dummy request, because zpay32 cannot decode its lni1 string.
func decodePayReq(invoice *invoices.Invoice,
activeNetParams *chaincfg.Params) (*zpay32.Invoice, error) {
paymentRequest := string(invoice.PaymentRequest)
- if paymentRequest == "" {
+ if paymentRequest == "" || invoice.IsBolt12 {
preimage := invoice.Terms.PaymentPreimage
if preimage == nil {
return &zpay32.Invoice{}, nil
### lnrpc/invoicesrpc/utils_test.go
@@ -0,0 +1,51 @@
+package invoicesrpc
+
+import (
+ "testing"
+
+ "github.com/btcsuite/btcd/chaincfg/v2"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/zpay32"
+ "github.com/stretchr/testify/require"
+)
+
+// TestCreateRPCInvoiceBolt12 verifies that a BOLT 12 invoice converts to an
+// RPC invoice. Its lni1 payment request is not a BOLT 11 string, so the
+// conversion must take the payment hash from the preimage.
+func TestCreateRPCInvoiceBolt12(t *testing.T) {
+ t.Parallel()
+
+ const payReq = "lni1qqgsqvgnwgcg35z6ee2h3yczraddm72xrfua9uve2rlrm9" +
+ "deu7xyfzr"
+
+ // The conversion would fail if it decoded the string as BOLT 11.
+ _, err := zpay32.Decode(payReq, &chaincfg.MainNetParams)
+ require.Error(t, err)
+
+ var preimage lntypes.Preimage
+ preimage[0] = 0x12
+
+ invoice := &invoices.Invoice{
+ PaymentRequest: []byte(payReq),
+ IsBolt12: true,
+ Terms: invoices.ContractTerm{
+ PaymentPreimage: &preimage,
+ Value: lnwire.MilliSatoshi(10000),
+ Features: lnwire.NewFeatureVector(
+ lnwire.NewRawFeatureVector(
+ lnwire.MPPOptional,
+ ), lnwire.Features,
+ ),
+ },
+ }
+
+ rpcInvoice, err := CreateRPCInvoice(invoice, &chaincfg.MainNetParams)
+ require.NoError(t, err)
+
+ hash := preimage.Hash()
+ require.Equal(t, hash[:], rpcInvoice.RHash)
+ require.Equal(t, payReq, rpcInvoice.PaymentRequest)
+ require.EqualValues(t, 10000, rpcInvoice.ValueMsat)
+}Why this scored 25/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.