Merge pull request #11636 from bitromortac/20261111-1e97-dispatch
What changed, and why it matters
This commit enables LND to actually receive and settle payments for BOLT 12 offers. Previously, LND could issue BOLT 12 invoices but did not store them or settle HTLCs against them. The key change is that the invoice is now reconstructed from data carried by the first incoming payment (HTLC), stored in the database, and then settled like a normal invoice. The commit also removes the old behavior of sending an 'Open' invoice event when the invoice is issued; instead, the Open event is sent when the invoice row is stored on first HTLC arrival. There are several TODOs left, including around garbage collection of canceled BOLT 12 invoices and context handling.
Reviewers and operators should treat this as a significant BOLT 12 feature completion with security-relevant state machine changes. Recommended: (1) audit the Reconstructor for any bypass of path-ID authentication or price checks, (2) ensure the canceled-invoice GC TODO does not allow unintended re-settlement of already-paid/canceled BOLT 12 invoices, (3) replace context.TODO() with proper context propagation in NotifyExitHopHtlc and reconstruction paths, (4) verify that partial/failing HTLC sets cannot be abused to create many open BOLT 12 rows (DoS/resource exhaustion), (5) run the new integration test testBolt12ReceiveSettle and the full BOLT 12 test matrix before release.
Security signals we found
New authentication boundary: BOLT 12 invoice reconstruction requires payment path ID to authenticate the invoice envelope, preventing payers from forging or modifying invoices.
Offer state re-check on later HTLCs: a disabled offer after the first shard will cause subsequent shards to fail, preventing settlement of invoices for disabled offers.
Expiry re-check on later HTLCs: invoices that expire before the MPP set completes are refused for new shards (with replay-safe handling for already-accepted shards).
Amount/price validation: reconstructed invoice amount must meet or exceed offer_amount * quantity, and currency-priced offers are rejected at reconstruction.
Removal of unindexed BOLT 12 event dispatch: previously BOLT 12 Open events had no database row/add index; now events are tied to stored rows, improving consistency and replay/backlog behavior.
TODO noted: canceled-invoice GC can delete a canceled BOLT 12 invoice, allowing later payment over the same blinded path to rebuild and potentially settle until expiry.
TODO noted: context.TODO() used in reconstruction and offer-active checks because NotifyExitHopHtlc does not yet take a context.
Evidence from the diff
The commit implements BOLT 12 invoice settlement in LND. Major changes: (1) A new bolt12handler.Reconstructor rebuilds an invoices.Invoice from the invoice envelope carried in the final-hop encrypted data of a BOLT 12 blinded path, verifying the payment path ID, payment hash, envelope expiry, offer existence/active status, and offer price. (2) The invoice registry (NotifyExitHopHtlc) now detects an unknown payment hash with an invoice envelope + path ID, calls ReconstructInvoice, stores the row via AddInvoice, emits the Open event, and registers the invoice with the expiry watcher. (3) Later HTLCs for the same BOLT 12 invoice re-check invoice expiry and offer active status via checkLaterBolt12Htlc. (4) The BOLT 12 handler no longer sends an Open event at invoice issuance and no longer depends on an InvoiceNotifier. (5) RPC invoices gain a bolt12_detail field. (6) Tests cover disabled offers, foreign path IDs, amount/price checks, expiry, MPP behavior, replay handling, and an end-to-end integration test. Several TODOs remain (context plumbing, canceled-invoice GC interaction, opt-in issued-state subscription).
Changed components
bolt12handler (handler.go, dispatcher.go, reconstruct.go, tests)invoices.InvoiceRegistry (invoiceregistry.go, update.go, interface.go)htlcswitch/hop payload/forwarding/iterator (BOLT 12 invoice envelope extraction)lnrpc (lightning.proto, swagger, invoicesrpc/utils.go)switchrpc (code move only: unmarshal.go split out)server.go (wiring of Reconstructor into registry config)Inspect captured patch +3014 / −1050
### bolt12handler/disabled_offer_test.go
@@ -0,0 +1,28 @@
+package bolt12handler
+
+import (
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/stretchr/testify/require"
+)
+
+// TestReconstruct_DisabledOffer verifies that the first HTLC for an invoice of
+// a disabled offer settles nothing.
+func TestReconstruct_DisabledOffer(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+ offer.IsDisabled = true
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: testOfferPrice,
+ })
+
+ _, err := env.reconstruct(t, r)
+ require.ErrorIs(t, err, ErrOfferDisabled)
+}
### bolt12handler/dispatcher.go
@@ -18,9 +18,8 @@ const maxInflightRequests = 8
const (
// requestRate is the number of invoice requests per second that the
- // node answers. Each answer costs a signature and puts an event into
- // the queue of every invoice subscriber, and any peer can send a
- // request. A payer needs one invoice per payment.
+ // node answers. Each answer costs a signature, and any peer can send
+ // a request. A payer needs one invoice per payment.
requestRate = 10
// requestBurst is the number of invoice requests that the node answers
### bolt12handler/dispatcher_test.go
@@ -12,8 +12,6 @@ import (
sphinx "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/bolt12"
"github.com/lightningnetwork/lnd/clock"
- "github.com/lightningnetwork/lnd/invoices"
- "github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/onionmessage"
"github.com/lightningnetwork/lnd/record"
@@ -101,15 +99,6 @@ func TestInvoiceRequest(t *testing.T) {
}
}
-// nopNotifier drops the invoice events. The handlers of the dispatch tests run
-// in parallel, and the events are not part of these tests.
-type nopNotifier struct{}
-
-// NotifyNewBolt12Invoice does nothing.
-func (nopNotifier) NotifyNewBolt12Invoice(context.Context, lntypes.Hash,
- *invoices.Invoice) {
-}
-
// sentReply holds an invoice reply and the blinded path it was sent on.
type sentReply struct {
invoice []byte
@@ -210,7 +199,7 @@ func newDispatchTest(t *testing.T, maxInflight int,
replies := make(chan sentReply)
replier := &chanReplier{replies: replies}
handler, err := NewHandler(
- store, nopNotifier{}, replier,
+ store, replier,
newPrivKeySigner(nodeKey), testPathIDKey(nodeKey), nil,
clock.NewDefaultClock(), testChainHash(), testFinalCLTVDelta,
)
@@ -497,7 +486,7 @@ func TestHandlerDispatch(t *testing.T) {
t.Parallel()
handler, err := NewHandler(
- newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newMockOfferStore(), &mockReplier{},
newPrivKeySigner(testKey(t)),
testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
@@ -518,7 +507,7 @@ func TestHandlerDispatch(t *testing.T) {
t.Parallel()
handler, err := NewHandler(
- newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newMockOfferStore(), &mockReplier{},
newPrivKeySigner(testKey(t)),
testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
@@ -543,7 +532,7 @@ func TestHandlerDispatch(t *testing.T) {
t.Parallel()
handler, err := NewHandler(
- newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newMockOfferStore(), &mockReplier{},
newPrivKeySigner(testKey(t)),
testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
@@ -578,8 +567,8 @@ func TestHandlerDispatch(t *testing.T) {
// group while Start adds to it.
for range 50 {
handler, err := NewHandler(
- newMockOfferStore(), nopNotifier{},
- &mockReplier{}, newPrivKeySigner(testKey(t)),
+ newMockOfferStore(), &mockReplier{},
+ newPrivKeySigner(testKey(t)),
testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
testFinalCLTVDelta,
### bolt12handler/handler.go
@@ -9,38 +9,22 @@ import (
"fmt"
"math"
"sync/atomic"
- "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"
"golang.org/x/time/rate"
)
-// 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
pathIDKey PathIDKey
@@ -78,23 +62,20 @@ type Handler struct {
}
// 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. It also returns an error when the path id key is the zero key.
-// The path builder can be nil. The handler then uses a single-hop blinded
-// path. The final CLTV delta must be at least routing.MinCLTVDelta. It must
-// also leave room for routing.BlockPadding in a uint16.
-func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
- replier OnionReplier, signer NodeSigner, pathIDKey PathIDKey,
+// when the offer store, the replier, the signer or the clock is nil. It also
+// returns an error when the path id key is the zero key. The path builder can
+// be nil. The handler then uses a single-hop blinded path. The final CLTV delta
+// must be at least routing.MinCLTVDelta. It must also leave room for
+// routing.BlockPadding in a uint16.
+func NewHandler(offerStore offers.Store, replier OnionReplier,
+ signer NodeSigner, pathIDKey PathIDKey,
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")
@@ -119,7 +100,6 @@ func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
return &Handler{
offerStore: offerStore,
- notifier: notifier,
replier: replier,
signer: signer,
pathIDKey: pathIDKey,
@@ -182,8 +162,8 @@ func (h *Handler) HandleInvoiceRequest(ctx context.Context, invreqBytes []byte,
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.
+ // Send the invoice before the log line, so that it does not announce
+ // an invoice that never left this node.
invoiceBytes, err := result.Invoice.EncodeSigned()
if err != nil {
return fmt.Errorf("encode reply: %w", err)
@@ -198,10 +178,13 @@ func (h *Handler) HandleInvoiceRequest(ctx context.Context, invreqBytes []byte,
"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)
+ // The handler writes no invoice row. The first HTLC makes the invoice
+ // registry rebuild the invoice from its invoice envelope, store the
+ // row and send its Open event. The expiry watcher cancels an unpaid
+ // row.
+ //
+ // TODO: send the lni1 invoice to the clients that opt in to a new
+ // issued state on SubscribeInvoices.
return nil
}
@@ -224,63 +207,6 @@ func (h *Handler) lookupOffer(ctx context.Context, ir *bolt12.InvoiceRequest) (
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 {
### bolt12handler/handler_test.go
@@ -13,8 +13,6 @@ import (
"github.com/lightningnetwork/lnd/bolt12handler/envelope"
"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"
@@ -23,22 +21,21 @@ import (
)
// TestHandleInvoiceRequest_FullFlow verifies that the handler replies with a
-// signed invoice and notifies an Open event that carries the terms of that
-// invoice.
+// signed invoice for the offer, with a blinded path whose envelope names the
+// offer.
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),
+ store, replier, newPrivKeySigner(nodeKey),
testPathIDKey(nodeKey), builder, clock.NewDefaultClock(),
testChainHash(),
testFinalCLTVDelta,
@@ -67,50 +64,17 @@ func TestHandleInvoiceRequest_FullFlow(t *testing.T) {
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)
+ require.EqualValues(t, 10000, amount)
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, features.IsSet(lnwire.MPPOptional))
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
@@ -119,15 +83,17 @@ func TestHandleInvoiceRequest_FullFlow(t *testing.T) {
testFinalCLTVDelta+routing.BlockPadding,
payInfos[0].CltvExpiryDelta,
)
- require.Equal(t, builder.gotPathID, inv.Terms.PaymentAddr[:])
+ require.Len(t, builder.gotPathID, 32)
// The envelope binds the invoice to the offer it answers.
data, err := envelope.Decode(builder.gotEnvelope)
require.NoError(t, err)
require.Equal(t, fn.Some(stored.Hash), data.OfferHash)
+ payerID := sent.InvreqPayerID.UnwrapOrFailV(t)
require.Equal(t,
- payerKey.PubKey().SerializeCompressed(), inv.InvreqPayerID,
+ payerKey.PubKey().SerializeCompressed(),
+ payerID.SerializeCompressed(),
)
}
@@ -161,19 +127,6 @@ func (m *mockOfferStore) GetOfferByHash(_ context.Context,
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
@@ -318,11 +271,9 @@ func TestHandleInvoiceRequestErrors(t *testing.T) {
t.Parallel()
store := newMockOfferStore()
- notifier := &mockNotifier{}
+ replier := &mockReplier{err: tc.replyErr}
handler, err := NewHandler(
- store, notifier,
- &mockReplier{err: tc.replyErr},
- newPrivKeySigner(nodeKey),
+ store, replier, newPrivKeySigner(nodeKey),
testPathIDKey(nodeKey), nil,
clock.NewTestClock(now), testChainHash(),
testFinalCLTVDelta,
@@ -380,9 +331,10 @@ func TestHandleInvoiceRequestErrors(t *testing.T) {
)
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)
+ // A rejected request sends no reply.
+ if tc.replyErr == nil {
+ require.Empty(t, replier.replies)
+ }
})
}
}
@@ -393,7 +345,7 @@ func TestNewHandlerZeroPathIDKey(t *testing.T) {
t.Parallel()
_, err := NewHandler(
- newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newMockOfferStore(), &mockReplier{},
newPrivKeySigner(testKey(t)), PathIDKey{}, nil,
clock.NewDefaultClock(), testChainHash(), testFinalCLTVDelta,
)
### bolt12handler/reconstruct.go
@@ -0,0 +1,280 @@
+package bolt12handler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+ "unicode/utf8"
+
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "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/tlv"
+)
+
+var (
+ // errForeignPathID is returned for a payment whose path id this node
+ // did not make for its invoice envelope.
+ errForeignPathID = errors.New("payment path id does not match the " +
+ "invoice envelope")
+
+ // errNoOfferInEnvelope is returned for a payment whose invoice
+ // envelope names no offer.
+ errNoOfferInEnvelope = errors.New("invoice envelope names no offer")
+
+ // errAmountBelowOffer is returned for an invoice envelope whose amount
+ // is below the price of the offer.
+ errAmountBelowOffer = errors.New("invoice amount below the offer " +
+ "price")
+)
+
+// Reconstructor implements invoices.Bolt12Reconstructor. It builds an
+// invoices.Invoice from an invoice envelope and the offer store. It refuses
+// an envelope that the payment path id does not authenticate.
+type Reconstructor struct {
+ // pathIDKey checks the payment path ids that this node made.
+ pathIDKey PathIDKey
+ offerStore offers.Store
+
+ // activeChain is the genesis hash of the chain of this node. The
+ // offer reader checks the stored offer against it.
+ activeChain [32]byte
+
+ // finalCLTVDelta is the final CLTV delta of the invoices, see
+ // InvoiceConfig. The invoice does not carry it, so a changed config
+ // value also applies to the invoices that are already out.
+ finalCLTVDelta uint16
+
+ // clock gives the time of the envelope expiry check. It must be the
+ // clock of the invoice registry, which checks the expiry of a later
+ // HTLC.
+ clock clock.Clock
+}
+
+// NewReconstructor creates a Reconstructor that checks payment path ids with
+// pathIDKey and reads offers from the offer store. clk must be the clock of
+// the invoice registry, so that both expiry checks agree.
+func NewReconstructor(pathIDKey PathIDKey, offerStore offers.Store,
+ activeChain [32]byte, finalCLTVDelta uint16,
+ clk clock.Clock) *Reconstructor {
+
+ return &Reconstructor{
+ pathIDKey: pathIDKey,
+ offerStore: offerStore,
+ activeChain: activeChain,
+ finalCLTVDelta: finalCLTVDelta,
+ clock: clk,
+ }
+}
+
+// ReconstructInvoice rebuilds a fully populated Invoice from the invoice
+// envelope of a payment, after it checks the payment path id.
+//
+// NOTE: This is part of the invoices.Bolt12Reconstructor interface.
+func (r *Reconstructor) ReconstructInvoice(ctx context.Context,
+ envelopeBytes []byte, pathID chainhash.Hash,
+ paymentHash lntypes.Hash) (*invoices.Invoice, error) {
+
+ // Only this node can make a path id that matches the envelope, and
+ // the same check gives the preimage. So a payer can neither build nor
+ // change an envelope.
+ preimage, ok := r.pathIDKey.checkPaymentPathID(
+ pathID[:], EnvelopeBinding(envelopeBytes),
+ )
+ if !ok {
+ return nil, errForeignPathID
+ }
+
+ if preimage.Hash() != paymentHash {
+ return nil, fmt.Errorf("preimage hash mismatch: computed %v, "+
+ "expected %v", preimage.Hash(), paymentHash)
+ }
+
+ data, err := envelope.Decode(envelopeBytes)
+ if err != nil {
+ return nil, fmt.Errorf("decode invoice envelope: %w", err)
+ }
+
+ // An invoice that answers no offer is stored when it is made, so only
+ // an envelope that names an offer can be rebuilt here.
+ offerHash, err := data.OfferHash.UnwrapOrErr(errNoOfferInEnvelope)
+ if err != nil {
+ return nil, err
+ }
+
+ // The invoice expires after its last second. The payer's codec reads
+ // invoice_relative_expiry, so a payment in that second settles.
+ relExpiry := uint64(bolt12.DefaultInvoiceRelativeExpiry / time.Second)
+ expiryTime := data.CreatedAt + relExpiry
+ now := uint64(r.clock.Now().Unix())
+ if now > expiryTime {
+ return nil, fmt.Errorf("envelope expired: created_at=%d, "+
+ "expiry=%d, now=%d",
+ data.CreatedAt, expiryTime, now)
+ }
+
+ offer, err := r.offerStore.GetOfferByHash(ctx, offerHash)
+ if err != nil {
+ return nil, fmt.Errorf("lookup offer: %w", err)
+ }
+
+ // A disabled offer takes no new payments. This check runs only for the
+ // first HTLC of an invoice. No HTLC settles before the whole set is
+ // accepted, so refusing here settles nothing for the offer.
+ if offer.IsDisabled {
+ return nil, ErrOfferDisabled
+ }
+
+ // The offer is decoded as of the creation time of the invoice. The
+ // handler checked the offer expiry at that time. An offer that expired
+ // since then must not fail the payment.
+ decoded, err := bolt12.DecodeOfferString(
+ offer.Encoded, time.Unix(int64(data.CreatedAt), 0),
+ r.activeChain,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("decode offer %x: %w", offer.Hash[:],
+ err)
+ }
+
+ if err := checkOfferPrice(decoded, data); err != nil {
+ return nil, err
+ }
+
+ invoice := &invoices.Invoice{
+ Memo: offerMemo(decoded),
+ CreationDate: time.Unix(int64(data.CreatedAt), 0).UTC(),
+ Terms: invoices.ContractTerm{
+ Expiry: bolt12.DefaultInvoiceRelativeExpiry,
+ FinalCltvDelta: int32(r.finalCLTVDelta),
+ PaymentPreimage: &preimage,
+ PaymentAddr: pathID,
+ Value: lnwire.MilliSatoshi(data.Amount),
+
+ // An issued invoice advertises basic MPP, so the
+ // rebuilt invoice has it and the features that MPP
+ // depends on. The payment path id is the payment
+ // address, so the address is required.
+ Features: lnwire.NewFeatureVector(
+ lnwire.NewRawFeatureVector(
+ lnwire.MPPOptional,
+ lnwire.PaymentAddrRequired,
+ lnwire.TLVOnionPayloadRequired,
+ ),
+ lnwire.Features,
+ ),
+ },
+ IsBolt12: true,
+ Bolt12Envelope: envelopeBytes,
+ OfferID: fn.Some(offer.ID),
+ OfferHash: offer.Hash[:],
+ InvreqPayerID: data.PayerID[:],
+ InvreqQuantity: data.Quantity,
+ InvreqPayerNote: data.PayerNote,
+ }
+
+ return invoice, nil
+}
+
+// checkOfferPrice returns an error when the envelope amount is below the
+// price of the offer. The price is offer_amount times the quantity, and no
+// quantity counts as one item.
+func checkOfferPrice(offer *bolt12.Offer, data *envelope.Data) error {
+ // The handler answers no request for an offer priced in a currency.
+ // Only a forged envelope names one, and it fails with
+ // errCurrencyConversion.
+ if offer.OfferCurrency.IsSome() {
+ return errCurrencyConversion
+ }
+
+ // An offer without a price lets the payer choose the amount, so it is
+ // not checked.
+ if offer.OfferAmount.IsNone() {
+ return nil
+ }
+
+ offerAmount := offer.OfferAmount.ValOpt().UnwrapOr(0)
+
+ quantity := data.Quantity
+ if quantity == 0 {
+ quantity = 1
+ }
+
+ price, err := expectedOfferAmount(uint64(offerAmount), quantity)
+ if err != nil {
+ return err
+ }
+
+ // A valid envelope carries an amount from a checked request, so only a
+ // forged envelope fails here.
+ if data.Amount < price {
+ return fmt.Errorf("%w: amount %d, price %d",
+ errAmountBelowOffer, data.Amount, price)
+ }
+
+ return nil
+}
+
+// offerMemo returns the offer_description of the offer, which is the memo of
+// the rebuilt invoice.
+func offerMemo(offer *bolt12.Offer) []byte {
+ var memo []byte
+ offer.OfferDescription.WhenSome(
+ func(rec tlv.RecordT[tlv.TlvType10, tlv.Blob]) {
+ memo = rec.Val
+ },
+ )
+
+ return truncateMemo(memo)
+}
+
+// truncateMemo cuts the memo to invoices.MaxMemoSize bytes, because the
+// invoice store refuses a longer memo. An onion message can carry a longer
+// offer_description. The cut does not split a UTF-8 rune.
+func truncateMemo(memo []byte) []byte {
+ if len(memo) <= invoices.MaxMemoSize {
+ return memo
+ }
+
+ cut := invoices.MaxMemoSize
+ for cut > 0 && !utf8.RuneStart(memo[cut]) {
+ cut--
+ }
+
+ return memo[:cut]
+}
+
+// CheckOfferActive returns an error when the offer with the given hash is
+// unknown or disabled.
+//
+// NOTE: This is part of the invoices.Bolt12Reconstructor interface.
+func (r *Reconstructor) CheckOfferActive(ctx context.Context,
+ offerHash []byte) error {
+
+ if len(offerHash) != 32 {
+ return fmt.Errorf("invalid offer hash length %d",
+ len(offerHash))
+ }
+
+ offer, err := r.offerStore.GetOfferByHash(ctx, [32]byte(offerHash))
+ if err != nil {
+ return fmt.Errorf("lookup offer: %w", err)
+ }
+
+ if offer.IsDisabled {
+ return ErrOfferDisabled
+ }
+
+ return nil
+}
+
+// Compile-time check that Reconstructor implements
+// invoices.Bolt12Reconstructor.
+var _ invoices.Bolt12Reconstructor = (*Reconstructor)(nil)
### bolt12handler/reconstruct_test.go
@@ -0,0 +1,529 @@
+package bolt12handler
+
+import (
+ "math"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "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/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// testOfferPrice is the offer_amount of the offer of newTestReconstructor.
+const testOfferPrice = 1000
+
+// newTestReconstructor creates a Reconstructor with the path id key of the
+// test node key and a mock offer store that holds one offer with the price
+// testOfferPrice.
+func newTestReconstructor(t *testing.T) (*Reconstructor,
+ *btcec.PrivateKey, *offers.Offer) {
+
+ t.Helper()
+
+ nodeKey := testKey(t)
+ store := newMockOfferStore()
+
+ decoded := testOffer(t, nodeKey, testOfferPrice)
+ encoded, err := bolt12.EncodeOfferString(decoded)
+ require.NoError(t, err)
+
+ offerHash, err := bolt12.OfferHash(decoded)
+ require.NoError(t, err)
+
+ offer := &offers.Offer{
+ ID: 1,
+ Hash: offerHash,
+ Encoded: encoded,
+ }
+ store.offers[offer.Hash] = offer
+
+ r := NewReconstructor(
+ testPathIDKey(nodeKey), store, testChainHash(),
+ testFinalCLTVDelta, clock.NewDefaultClock(),
+ )
+
+ return r, nodeKey, offer
+}
+
+// testEnvelope is an invoice envelope with the payment path id and the
+// payment hash that the node made for it.
+type testEnvelope struct {
+ envelope []byte
+ pathID chainhash.Hash
+ paymentHash lntypes.Hash
+ preimage lntypes.Preimage
+}
+
+// buildTestEnvelope encodes an envelope with the given fields and makes its
+// payment path id with the path id key of nodeKey.
+func buildTestEnvelope(t *testing.T, nodeKey *btcec.PrivateKey,
+ data *envelope.Data) *testEnvelope {
+
+ t.Helper()
+
+ if data.PayerID == ([33]byte{}) {
+ payerKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ data.PayerID = [33]byte(payerKey.PubKey().SerializeCompressed())
+ }
+
+ envelope, err := envelope.Encode(data)
+ require.NoError(t, err)
+
+ key := testPathIDKey(nodeKey)
+ binding := EnvelopeBinding(envelope)
+ pathID, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+
+ preimage, ok := key.checkPaymentPathID(pathID[:], binding)
+ require.True(t, ok)
+
+ return &testEnvelope{
+ envelope: envelope,
+ pathID: chainhash.Hash(pathID),
+ paymentHash: preimage.Hash(),
+ preimage: preimage,
+ }
+}
+
+// reconstruct returns the invoice that the reconstructor rebuilds from the
+// envelope, or the error that it gives for it.
+func (e *testEnvelope) reconstruct(t *testing.T,
+ r *Reconstructor) (*invoices.Invoice, error) {
+
+ return r.ReconstructInvoice(
+ t.Context(), e.envelope, e.pathID, e.paymentHash,
+ )
+}
+
+// TestReconstruct_Valid verifies that a valid envelope reconstructs a correct
+// invoice.
+func TestReconstruct_Valid(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: 50000,
+ Quantity: 3,
+ })
+
+ inv, err := env.reconstruct(t, r)
+ require.NoError(t, err)
+
+ require.True(t, inv.IsBolt12)
+ require.Equal(t, fn.Some(offer.ID), inv.OfferID)
+ require.Equal(t, offer.Hash[:], inv.OfferHash)
+ require.Equal(t, [32]byte(env.pathID), inv.Terms.PaymentAddr)
+ require.Equal(t, env.preimage, *inv.Terms.PaymentPreimage)
+ require.Equal(t, env.envelope, inv.Bolt12Envelope)
+ require.EqualValues(t, 50000, inv.Terms.Value)
+ require.EqualValues(t, 3, inv.InvreqQuantity)
+ require.EqualValues(t, testFinalCLTVDelta, inv.Terms.FinalCltvDelta)
+
+ // The rebuilt invoice keeps the basic MPP that the issued invoice
+ // advertised, with the features that it depends on.
+ require.Equal(
+ t, lnwire.NewRawFeatureVector(
+ lnwire.MPPOptional, lnwire.PaymentAddrRequired,
+ lnwire.TLVOnionPayloadRequired,
+ ),
+ inv.Terms.Features.RawFeatureVector,
+ )
+}
+
+// TestReconstruct_ForeignPathID verifies that a payment whose path id this
+// node did not make for the envelope reconstructs nothing.
+func TestReconstruct_ForeignPathID(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+
+ // Each subtest gets its own copy, because buildTestEnvelope sets the
+ // payer id.
+ data := func() *envelope.Data {
+ return &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: testOfferPrice,
+ }
+ }
+
+ t.Run("changed envelope", func(t *testing.T) {
+ t.Parallel()
+
+ env := buildTestEnvelope(t, nodeKey, data())
+ env.envelope[len(env.envelope)-1] ^= 0x01
+
+ _, err := env.reconstruct(t, r)
+ require.ErrorIs(t, err, errForeignPathID)
+ })
+
+ t.Run("path id of another node", func(t *testing.T) {
+ t.Parallel()
+
+ otherKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ env := buildTestEnvelope(t, otherKey, data())
+
+ _, err = env.reconstruct(t, r)
+ require.ErrorIs(t, err, errForeignPathID)
+ })
+}
+
+// TestReconstruct_NoOffer verifies that an envelope that names no offer is not
+// rebuilt. An invoice that answers no offer is stored when it is made.
+func TestReconstruct_NoOffer(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, _ := newTestReconstructor(t)
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: testOfferPrice,
+ })
+
+ _, err := env.reconstruct(t, r)
+ require.ErrorIs(t, err, errNoOfferInEnvelope)
+}
+
+// TestReconstruct_HashMismatch verifies that reconstruction fails when the
+// payment hash does not match the preimage of the path id.
+func TestReconstruct_HashMismatch(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: 2000,
+ })
+ env.paymentHash = lntypes.Hash{0xFF, 0xFF}
+
+ _, err := env.reconstruct(t, r)
+ require.ErrorContains(t, err, "preimage hash mismatch")
+}
+
+// TestReconstruct_Expired verifies that the reconstructor reads the expiry of
+// the envelope on its clock: a payment in the last second of the invoice
+// settles, and a payment one second later is refused.
+func TestReconstruct_Expired(t *testing.T) {
+ t.Parallel()
+
+ createdAt := time.Unix(1_700_000_000, 0)
+ expiry := createdAt.Add(bolt12.DefaultInvoiceRelativeExpiry)
+
+ tests := []struct {
+ name string
+ now time.Time
+ expired bool
+ }{
+ {
+ name: "last second",
+ now: expiry,
+ },
+ {
+ name: "first expired second",
+ now: expiry.Add(time.Second),
+ expired: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+ r.clock = clock.NewTestClock(test.now)
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(createdAt.Unix()),
+ Amount: testOfferPrice,
+ })
+
+ _, err := env.reconstruct(t, r)
+ if test.expired {
+ require.ErrorContains(
+ t, err, "envelope expired",
+ )
+
+ return
+ }
+ require.NoError(t, err)
+ })
+ }
+}
+
+// TestReconstruct_UnknownOffer verifies that reconstruction fails when the
+// offer hash in the envelope does not match any stored offer.
+func TestReconstruct_UnknownOffer(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, _ := newTestReconstructor(t)
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some([32]byte{0xFF, 0xFE, 0xFD}),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: 4000,
+ })
+
+ _, err := env.reconstruct(t, r)
+ require.ErrorContains(t, err, "lookup offer")
+}
+
+// TestReconstruct_OfferPrice verifies that an envelope amount below the offer
+// price does not settle. Only a forged envelope can carry such an amount.
+func TestReconstruct_OfferPrice(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ price uint64
+ currency string
+ amount uint64
+ quantity uint64
+ wantErr error
+ }{
+ {
+ name: "amount below the price",
+ price: testOfferPrice,
+ amount: testOfferPrice - 1,
+ wantErr: errAmountBelowOffer,
+ },
+ {
+ name: "amount equal to the price",
+ price: testOfferPrice,
+ amount: testOfferPrice,
+ },
+ {
+ name: "amount above the price",
+ price: testOfferPrice,
+ amount: testOfferPrice + 1,
+ },
+ {
+ name: "amount below the price of the quantity",
+ price: testOfferPrice,
+ amount: 2*testOfferPrice + 1,
+ quantity: 3,
+ wantErr: errAmountBelowOffer,
+ },
+ {
+ name: "offer without a price",
+ amount: 1,
+ },
+ {
+ name: "offer priced in a currency",
+ price: testOfferPrice,
+ currency: "USD",
+ amount: 1,
+ wantErr: errCurrencyConversion,
+ },
+ {
+ name: "overflowing quantity",
+ price: testOfferPrice,
+ amount: math.MaxUint64,
+ quantity: math.MaxUint64,
+ wantErr: errAmountOverflow,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+
+ decoded := testOffer(t, nodeKey, tc.price)
+ if tc.currency != "" {
+ decoded.OfferCurrency = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType6, tlv.Blob]{
+ Val: []byte(tc.currency),
+ },
+ )
+ }
+ encoded, err := bolt12.EncodeOfferString(decoded)
+ require.NoError(t, err)
+ offer.Encoded = encoded
+
+ env := buildTestEnvelope(
+ t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: tc.amount,
+ Quantity: tc.quantity,
+ },
+ )
+
+ _, err = env.reconstruct(t, r)
+ if tc.wantErr != nil {
+ require.ErrorIs(t, err, tc.wantErr)
+
+ return
+ }
+ require.NoError(t, err)
+ })
+ }
+}
+
+// TestReconstruct_Memo verifies that the reconstructed invoice carries the
+// offer_description as its memo, cut to invoices.MaxMemoSize at a UTF-8 rune
+// boundary.
+func TestReconstruct_Memo(t *testing.T) {
+ t.Parallel()
+
+ // The two-byte rune starts at the last byte that fits, so a cut at
+ // the size limit would split it.
+ short := strings.Repeat("a", invoices.MaxMemoSize-1)
+ long := short + "é" + "tail"
+
+ tests := []struct {
+ name string
+ description string
+ wantMemo string
+ }{
+ {
+ name: "description",
+ description: "coffee",
+ wantMemo: "coffee",
+ },
+ {
+ name: "description above the size limit",
+ description: long,
+ wantMemo: short,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+
+ decoded := testOffer(t, nodeKey, 1000)
+ decoded.OfferDescription = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType10, tlv.Blob]{
+ Val: []byte(tc.description),
+ },
+ )
+
+ encoded, err := bolt12.EncodeOfferString(decoded)
+ require.NoError(t, err)
+ offer.Encoded = encoded
+
+ env := buildTestEnvelope(
+ t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: uint64(time.Now().Unix()),
+ Amount: testOfferPrice,
+ },
+ )
+
+ inv, err := env.reconstruct(t, r)
+ require.NoError(t, err)
+ require.Equal(t, tc.wantMemo, string(inv.Memo))
+ require.NoError(
+ t, invoices.ValidateInvoice(
+ inv, env.paymentHash,
+ ),
+ )
+ })
+ }
+}
+
+// TestReconstruct_OfferExpiredLater verifies that an offer that expired after
+// the invoice was issued does not fail the payment of that invoice.
+func TestReconstruct_OfferExpiredLater(t *testing.T) {
+ t.Parallel()
+
+ r, nodeKey, offer := newTestReconstructor(t)
+ createdAt := uint64(time.Now().Unix()) - 100
+
+ decoded := testOffer(t, nodeKey, testOfferPrice)
+ decoded.OfferAbsoluteExpiry = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType14, bolt12.TUint64]{
+ Val: bolt12.TUint64(createdAt + 1),
+ },
+ )
+ encoded, err := bolt12.EncodeOfferString(decoded)
+ require.NoError(t, err)
+ offer.Encoded = encoded
+
+ env := buildTestEnvelope(t, nodeKey, &envelope.Data{
+ OfferHash: fn.Some(offer.Hash),
+ CreatedAt: createdAt,
+ Amount: testOfferPrice,
+ })
+
+ _, err = env.reconstruct(t, r)
+ require.NoError(t, err)
+}
+
+// TestCheckOfferActive verifies that CheckOfferActive refuses an offer hash
+// that is malformed, unknown or disabled, and accepts an active offer.
+func TestCheckOfferActive(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ hash []byte
+ disabled bool
+ wantErr string
+ }{
+ {
+ name: "active offer",
+ },
+ {
+ name: "disabled offer",
+ disabled: true,
+ wantErr: ErrOfferDisabled.Error(),
+ },
+ {
+ name: "unknown offer",
+ hash: make([]byte, 32),
+ wantErr: offers.ErrOfferNotFound.Error(),
+ },
+ {
+ name: "short offer hash",
+ hash: make([]byte, 31),
+ wantErr: "invalid offer hash length",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ r, _, offer := newTestReconstructor(t)
+ offer.IsDisabled = tc.disabled
+
+ hash := tc.hash
+ if hash == nil {
+ hash = offer.Hash[:]
+ }
+
+ err := r.CheckOfferActive(t.Context(), hash)
+ if tc.wantErr == "" {
+ require.NoError(t, err)
+
+ return
+ }
+ require.ErrorContains(t, err, tc.wantErr)
+ })
+ }
+}
### docs/release-notes/unreleased/11636.md
@@ -0,0 +1,27 @@
+# Technical and Architectural Updates
+
+## BOLT 12 (Offers)
+
+* [Settle BOLT 12
+ invoices](https://github.com/lightningnetwork/lnd/pull/11636): a node now
+ settles payments to its BOLT 12 offers. The first HTLC of an invoice carries
+ the invoice envelope, and the node checks it against the payment path id,
+ rebuilds the invoice, stores it and settles it. An envelope amount below the
+ offer price does not settle. The invoice RPCs show the new `bolt12_detail`
+ field for BOLT 12 invoices.
+
+ `SubscribeInvoices` sends the Open event of a BOLT 12 invoice when the node
+ stores it, at its first HTLC, not when the node issues the invoice. An
+ invoice that no HTLC set pays is canceled at its expiry, two hours after the
+ node issued it.
+
+ A payer who sends only partial or failing HTLCs can leave one canceled
+ invoice per invoice request. It stays until the canceled-invoice garbage
+ collection deletes it. A later change writes a BOLT 12 invoice only when its
+ HTLC set completes.
+
+ `CancelInvoice` cancels only a stored BOLT 12 invoice. If the node then
+ deletes the canceled invoice, for example with
+ `gc-canceled-invoices-on-the-fly`, a later payment over the same blinded path
+ rebuilds the invoice and can settle it until the invoice expires, two hours
+ after the node issued it.
### htlcswitch/hop/forwarding_info.go
@@ -38,6 +38,11 @@ type ForwardingInfo struct {
// sets for itself to ensure that the blinded path has been used in the
// correct context.
PathID *chainhash.Hash
+
+ // InvoiceEnvelope is the invoice envelope from the final-hop
+ // encrypted data of a BOLT 12 blinded path. The payment path id
+ // authenticates it. It is nil for BOLT 11 blinded paths.
+ InvoiceEnvelope []byte
}
// NewChannelNextHop returns a next-hop value that identifies the outgoing
### htlcswitch/hop/iterator.go
@@ -271,8 +271,12 @@ func deriveBlindedRouteFinalHopForwardingInfo(
}
}
+ // The registry rebuilds a BOLT 12 invoice from the optional envelope.
+ invoiceEnvelope := routeData.InvoiceEnvelope.ValOpt().UnwrapOr(nil)
+
payload.FwdInfo = ForwardingInfo{
- PathID: pathID,
+ PathID: pathID,
+ InvoiceEnvelope: invoiceEnvelope,
}
return payload, routeRole, nil
### htlcswitch/hop/iterator_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/binary"
"errors"
+ "reflect"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
@@ -98,7 +99,7 @@ func TestSphinxHopIteratorForwardingInstructions(t *testing.T) {
}
fwdInfo := pld.ForwardingInfo()
- if fwdInfo != testCase.expectedFwdInfo {
+ if !reflect.DeepEqual(fwdInfo, testCase.expectedFwdInfo) {
t.Fatalf("#%v: wrong fwding info: expected %v, got %v",
i, spew.Sdump(testCase.expectedFwdInfo),
spew.Sdump(fwdInfo))
@@ -844,3 +845,47 @@ func TestBlindedRouteDummyHopPeeledLocally(t *testing.T) {
require.NotNil(t, fwdInfo.PathID)
require.Equal(t, secret, fwdInfo.PathID[:])
}
+
+// TestFinalHopInvoiceEnvelope verifies that the payload of a blinded final hop
+// gives the invoice envelope of its encrypted data, from which the registry
+// rebuilds a BOLT 12 invoice.
+func TestFinalHopInvoiceEnvelope(t *testing.T) {
+ t.Parallel()
+
+ envelope := []byte{0xde, 0xad, 0xbe, 0xef}
+ data, err := record.EncodeBlindedRouteData(
+ record.NewFinalHopBlindedRouteData(
+ &record.PaymentConstraints{
+ MaxCltvExpiry: 1000,
+ HtlcMinimumMsat: 1,
+ }, make([]byte, 32), envelope,
+ ),
+ )
+ require.NoError(t, err)
+
+ nodeKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ iterator := &sphinxHopIterator{
+ blindingKit: BlindingKit{
+ Processor: &mockProcessor{},
+ IncomingAmount: 10000,
+ IncomingCltv: 500,
+ UpdateAddBlinding: tlv.SomeRecordT(
+ //nolint:ll
+ tlv.NewPrimitiveRecord[lnwire.BlindingPointTlvType](nodeKey.PubKey()),
+ ),
+ },
+ router: sphinx.NewRouter(
+ &sphinx.PrivKeyECDH{PrivKey: nodeKey},
+ sphinx.NewMemoryReplayLog(),
+ ),
+ }
+
+ payload, _, err := parseAndValidateRecipientData(
+ iterator, &Payload{encryptedData: data}, true,
+ RouteRoleCleartext,
+ )
+ require.NoError(t, err)
+ require.Equal(t, envelope, payload.InvoiceEnvelope())
+}
### htlcswitch/hop/payload.go
@@ -425,6 +425,13 @@ func (h *Payload) Metadata() []byte {
return h.metadata
}
+// InvoiceEnvelope returns the invoice envelope from the final-hop encrypted
+// data of a BOLT 12 blinded path. Returns nil for BOLT 11 blinded paths or
+// when no envelope is present.
+func (h *Payload) InvoiceEnvelope() []byte {
+ return h.FwdInfo.InvoiceEnvelope
+}
+
// TotalAmtMsat returns the total amount sent to the final hop, as set by the
// payee.
func (h *Payload) TotalAmtMsat() lnwire.MilliSatoshi {
### invoices/bolt12_registry_test.go
@@ -0,0 +1,646 @@
+//go:build test_db_postgres || test_db_sqlite || test_native_sql
+
+package invoices_test
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ invpkg "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/lightningnetwork/lnd/sqldb"
+ "github.com/lightningnetwork/lnd/sqldb/sqlc"
+ "github.com/stretchr/testify/require"
+)
+
+// bolt12Features are the features of a rebuilt BOLT 12 invoice.
+var bolt12Features = lnwire.NewFeatureVector(
+ lnwire.NewRawFeatureVector(
+ lnwire.MPPOptional, lnwire.PaymentAddrRequired,
+ lnwire.TLVOnionPayloadRequired,
+ ),
+ lnwire.Features,
+)
+
+// errTestOfferDisabled stands in for the handler's disabled-offer error.
+var errTestOfferDisabled = errors.New("offer is disabled")
+
+// fakeReconstructor rebuilds a fixed BOLT 12 invoice, as the handler's
+// reconstructor does from a valid envelope, and reports whether its offer is
+// disabled.
+type fakeReconstructor struct {
+ invoice *invpkg.Invoice
+ disabled atomic.Bool
+}
+
+// ReconstructInvoice returns a copy of the fixed invoice, or refuses it when
+// the offer is disabled.
+func (f *fakeReconstructor) ReconstructInvoice(context.Context, []byte,
+ chainhash.Hash, lntypes.Hash) (*invpkg.Invoice, error) {
+
+ if f.disabled.Load() {
+ return nil, errTestOfferDisabled
+ }
+
+ invoice := *f.invoice
+
+ return &invoice, nil
+}
+
+// CheckOfferActive refuses the offer once it is disabled.
+func (f *fakeReconstructor) CheckOfferActive(context.Context, []byte) error {
+ if f.disabled.Load() {
+ return errTestOfferDisabled
+ }
+
+ return nil
+}
+
+// newBolt12RegistryContext creates a registry over a BOLT 12 enabled SQLite
+// store with one offer, and a reconstructor for an invoice of that offer. The
+// options change the registry config.
+func newBolt12RegistryContext(t *testing.T,
+ opts ...func(*invpkg.RegistryConfig)) (*testContext, *fakeReconstructor,
+ lntypes.Preimage, chainhash.Hash) {
+
+ t.Helper()
+
+ db := sqldb.NewTestSqliteDB(t).BaseDB
+ testClock := clock.NewTestClock(testTime)
+
+ offerHash := [32]byte{0xaa}
+ offerID, err := db.Queries.InsertOffer(
+ t.Context(), sqlc.InsertOfferParams{
+ Hash: offerHash[:],
+ Encoded: "lno1test",
+ CreatedAt: testTime,
+ },
+ )
+ require.NoError(t, err)
+
+ preimage := lntypes.Preimage{0x01, 0x02}
+ pathID := chainhash.Hash{0x03}
+ payerID := make([]byte, 33)
+ payerID[0] = 0x02
+
+ data := testRegistryEnvelope(payerID)
+ data.OfferHash = fn.Some(offerHash)
+ encoded, err := envelope.Encode(data)
+ require.NoError(t, err)
+
+ reconstructor := &fakeReconstructor{
+ invoice: &invpkg.Invoice{
+ CreationDate: testTime,
+ Terms: invpkg.ContractTerm{
+ Expiry: time.Hour,
+ PaymentPreimage: &preimage,
+ PaymentAddr: pathID,
+ Value: testInvoiceAmount,
+ Features: bolt12Features,
+ },
+ IsBolt12: true,
+ Bolt12Envelope: encoded,
+ OfferID: fn.Some(offerID),
+ OfferHash: offerHash[:],
+ InvreqPayerID: payerID,
+ },
+ }
+
+ cfg := defaultRegistryConfig()
+ cfg.Bolt12Reconstructor = reconstructor
+ for _, opt := range opts {
+ opt(&cfg)
+ }
+
+ makeDB := func(*testing.T) (invpkg.InvoiceDB, *clock.TestClock) {
+ executor := sqldb.NewTransactionExecutor(
+ db, func(tx *sql.Tx) invpkg.SQLInvoiceQueries {
+ return db.WithTx(tx)
+ },
+ )
+
+ store := invpkg.NewSQLStore(
+ executor, testClock, invpkg.WithBolt12(),
+ )
+
+ return store, testClock
+ }
+
+ return newTestContext(t, &cfg, makeDB), reconstructor, preimage,
+ pathID
+}
+
+// testRegistryEnvelope returns the envelope data of the test invoice, without
+// an offer hash.
+func testRegistryEnvelope(payerID []byte) *envelope.Data {
+ return &envelope.Data{
+ PayerID: [33]byte(payerID),
+ CreatedAt: uint64(testTime.Unix()),
+ Amount: uint64(testInvoiceAmount),
+ }
+}
+
+// notifyBolt12Shard sends one MPP shard of half the invoice amount to the
+// registry.
+func notifyBolt12Shard(t *testing.T, ctx *testContext,
+ preimage lntypes.Preimage, pathID chainhash.Hash,
+ htlcID uint64) (invpkg.HtlcResolution, chan interface{}) {
+
+ t.Helper()
+
+ return notifyBolt12Payload(
+ t, ctx, preimage, bolt12Payload(pathID, testInvoiceAmount),
+ htlcID,
+ )
+}
+
+// bolt12Payload returns the payload of a shard that pays through the BOLT 12
+// blinded path, for an MPP set of the given total.
+func bolt12Payload(pathID chainhash.Hash,
+ total lnwire.MilliSatoshi) *mockPayload {
+
+ return &mockPayload{
+ mpp: record.NewMPP(total, pathID),
+ pathID: &pathID,
+ envelope: []byte{0x01},
+ totalAmtMsat: total,
+ }
+}
+
+// notifyBolt12Payload sends one HTLC of half the invoice amount with the given
+// payload to the registry.
+func notifyBolt12Payload(t *testing.T, ctx *testContext,
+ preimage lntypes.Preimage, payload *mockPayload,
+ htlcID uint64) (invpkg.HtlcResolution, chan interface{}) {
+
+ t.Helper()
+
+ hodlChan := make(chan interface{}, 1)
+ resolution, err := ctx.registry.NotifyExitHopHtlc(
+ preimage.Hash(), testInvoiceAmount/2, testHtlcExpiry,
+ testCurrentHeight, getCircuitKey(htlcID), hodlChan, nil,
+ payload,
+ )
+ require.NoError(t, err)
+
+ return resolution, hodlChan
+}
+
+// requireNoInvoice checks that the registry has no invoice for the hash.
+func requireNoInvoice(t *testing.T, ctx *testContext, hash lntypes.Hash) {
+ t.Helper()
+
+ _, err := ctx.registry.LookupInvoice(t.Context(), hash)
+ require.ErrorIs(t, err, invpkg.ErrInvoiceNotFound)
+}
+
+// TestBolt12SettlesWhileOfferActive verifies that the reconstructed invoice
+// settles when both shards of an MPP payment arrive while the offer is
+// active.
+func TestBolt12SettlesWhileOfferActive(t *testing.T) {
+ t.Parallel()
+
+ ctx, _, preimage, pathID := newBolt12RegistryContext(t)
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 2)
+ checkSettleResolution(t, resolution, preimage)
+}
+
+// TestBolt12RefusesShardAfterOfferDisabled verifies that a later shard is
+// refused when the offer is disabled after the first shard arrived. No shard
+// settles, so the payment of the disabled offer never completes.
+func TestBolt12RefusesShardAfterOfferDisabled(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID := newBolt12RegistryContext(t)
+
+ resolution, hodlChan := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ reconstructor.disabled.Store(true)
+
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 2)
+ checkFailResolution(t, resolution, invpkg.ResultInvoiceNotOpen)
+
+ // The first shard is still held, not settled.
+ select {
+ case <-hodlChan:
+ t.Fatal("first shard was resolved")
+
+ default:
+ }
+
+ invoice, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, invoice.State)
+}
+
+// TestBolt12RefusesFirstShardOfDisabledOffer verifies that no invoice is
+// created when the first shard arrives for a disabled offer.
+func TestBolt12RefusesFirstShardOfDisabledOffer(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID := newBolt12RegistryContext(t)
+ reconstructor.disabled.Store(true)
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ checkFailResolution(t, resolution, invpkg.ResultInvoiceNotFound)
+
+ _, err := ctx.registry.LookupInvoice(t.Context(), preimage.Hash())
+ require.ErrorIs(t, err, invpkg.ErrInvoiceNotFound)
+}
+
+// TestBolt12SettlesInvoiceWithoutOffer verifies that the disabled-offer check
+// skips an invoice that answers an invoice request without an offer. Such an
+// invoice is stored when it is created, so it never goes through the
+// reconstructor, and it has no offer to disable.
+func TestBolt12SettlesInvoiceWithoutOffer(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID := newBolt12RegistryContext(t)
+
+ // The reconstructor reports every offer as disabled, so a settled
+ // payment proves that the check did not run.
+ reconstructor.disabled.Store(true)
+
+ encoded, err := envelope.Encode(
+ testRegistryEnvelope(reconstructor.invoice.InvreqPayerID),
+ )
+ require.NoError(t, err)
+
+ invoice := *reconstructor.invoice
+ invoice.OfferID = fn.None[int64]()
+ invoice.OfferHash = nil
+ invoice.Bolt12Envelope = encoded
+ _, err = ctx.registry.AddInvoice(t.Context(), &invoice, preimage.Hash())
+ require.NoError(t, err)
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 2)
+ checkSettleResolution(t, resolution, preimage)
+}
+
+// TestBolt12RebuildNeedsEnvelopeAndPathID verifies that an HTLC for an unknown
+// hash rebuilds no invoice unless it carries both the invoice envelope and the
+// payment path id. A BOLT 11 blinded path has a path id and no envelope.
+func TestBolt12RebuildNeedsEnvelopeAndPathID(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ noEnvelope bool
+ noPathID bool
+ }{
+ {
+ name: "no envelope",
+ noEnvelope: true,
+ },
+ {
+ name: "no path id",
+ noPathID: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ ctx, _, preimage, pathID := newBolt12RegistryContext(t)
+
+ payload := bolt12Payload(pathID, testInvoiceAmount)
+ if test.noEnvelope {
+ payload.envelope = nil
+ }
+ if test.noPathID {
+ payload.pathID = nil
+ }
+
+ resolution, _ := notifyBolt12Payload(
+ t, ctx, preimage, payload, 1,
+ )
+ checkFailResolution(
+ t, resolution, invpkg.ResultInvoiceNotFound,
+ )
+
+ requireNoInvoice(t, ctx, preimage.Hash())
+ })
+ }
+}
+
+// TestBolt12SendsOneOpenEvent verifies that an all-invoice subscriber gets one
+// Open event for a rebuilt BOLT 12 invoice, with the add index of the stored
+// row and no HTLC, and then the Settled event. A BOLT 11 invoice that is added
+// after it gets the next add index.
+func TestBolt12SendsOneOpenEvent(t *testing.T) {
+ t.Parallel()
+
+ ctx, _, preimage, pathID := newBolt12RegistryContext(t)
+
+ subscription, err := ctx.registry.SubscribeNotifications(
+ t.Context(), 0, 0,
+ )
+ require.NoError(t, err)
+ defer subscription.Cancel()
+
+ receive := func(events chan *invpkg.Invoice) *invpkg.Invoice {
+ t.Helper()
+
+ select {
+ case invoice := <-events:
+ return invoice
+
+ case <-time.After(testTimeout):
+ t.Fatal("no invoice event")
+
+ return nil
+ }
+ }
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ stored, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+ require.NoError(t, err)
+
+ opened := receive(subscription.NewInvoices)
+ require.True(t, opened.IsBolt12)
+ require.Equal(t, invpkg.ContractOpen, opened.State)
+ require.Equal(t, stored.AddIndex, opened.AddIndex)
+ require.Empty(t, opened.Htlcs)
+
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 2)
+ checkSettleResolution(t, resolution, preimage)
+
+ // The settle moves the invoice to PendingSettle, which sends no
+ // event. The Settled event comes when both shards have their final
+ // outcome.
+ ref := invpkg.InvoiceRefByHash(preimage.Hash())
+ ctx.finalizeHtlc(ref, getCircuitKey(1), true)
+ ctx.finalizeHtlc(ref, getCircuitKey(2), true)
+
+ settled := receive(subscription.SettledInvoices)
+ require.True(t, settled.IsBolt12)
+ require.Equal(t, stored.AddIndex, settled.AddIndex)
+
+ _, err = ctx.registry.AddInvoice(
+ t.Context(), newInvoice(t, false, false),
+ testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+
+ // The rebuilt invoice sent one Open event, so the next one is the
+ // BOLT 11 invoice, with the next add index.
+ bolt11 := receive(subscription.NewInvoices)
+ require.False(t, bolt11.IsBolt12)
+ require.Equal(t, stored.AddIndex+1, bolt11.AddIndex)
+}
+
+// receiveOpen returns the next Open event of the all-invoice subscription.
+func receiveOpen(t *testing.T,
+ subscription *invpkg.InvoiceSubscription) *invpkg.Invoice {
+
+ t.Helper()
+
+ select {
+ case invoice := <-subscription.NewInvoices:
+ return invoice
+
+ case <-time.After(testTimeout):
+ t.Fatal("no Open event")
+
+ return nil
+ }
+}
+
+// requireOneOpenEvent checks that the subscription got exactly one Open event
+// for the rebuilt invoice: the next Open event is the one of a BOLT 11 invoice
+// that the test adds now.
+func requireOneOpenEvent(t *testing.T, ctx *testContext,
+ subscription *invpkg.InvoiceSubscription) {
+
+ t.Helper()
+
+ _, err := ctx.registry.AddInvoice(
+ t.Context(), newInvoice(t, false, false),
+ testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+ require.False(t, receiveOpen(t, subscription).IsBolt12)
+}
+
+// TestBolt12FailedFirstShardKeepsRow verifies that a first HTLC that fails a
+// check leaves the rebuilt row open. The row sent one Open event, and the
+// expiry watcher cancels it at its expiry.
+func TestBolt12FailedFirstShardKeepsRow(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID := newBolt12RegistryContext(t)
+
+ subscription, err := ctx.registry.SubscribeNotifications(
+ t.Context(), 0, 0,
+ )
+ require.NoError(t, err)
+ defer subscription.Cancel()
+
+ // The MPP total is below the invoice amount, so the update refuses
+ // the shard after the registry stored the rebuilt row.
+ payload := bolt12Payload(pathID, testInvoiceAmount/2)
+ resolution, _ := notifyBolt12Payload(t, ctx, preimage, payload, 1)
+ checkFailResolution(t, resolution, invpkg.ResultHtlcSetTotalTooLow)
+
+ opened := receiveOpen(t, subscription)
+ require.True(t, opened.IsBolt12)
+
+ invoice, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, invoice.State)
+ require.Equal(t, opened.AddIndex, invoice.AddIndex)
+
+ // The expiry watcher cancels the row after its last second.
+ expiry := testTime.Add(reconstructor.invoice.Terms.Expiry)
+ ctx.clock.SetTime(expiry.Add(time.Second))
+ require.Eventually(t, func() bool {
+ invoice, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+
+ return err == nil && invoice.State == invpkg.ContractCanceled
+ }, testTimeout, 10*time.Millisecond)
+
+ requireOneOpenEvent(t, ctx, subscription)
+}
+
+// TestBolt12MppTimeoutKeepsRow verifies that a partial MPP set that times out
+// leaves the rebuilt row open with one Open event, and that a replay of the
+// timed-out shard finds the row and gets the replay result, as on master.
+func TestBolt12MppTimeoutKeepsRow(t *testing.T) {
+ t.Parallel()
+
+ ctx, _, preimage, pathID := newBolt12RegistryContext(t)
+
+ subscription, err := ctx.registry.SubscribeNotifications(
+ t.Context(), 0, 0,
+ )
+ require.NoError(t, err)
+ defer subscription.Cancel()
+
+ resolution, hodlChan := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+ require.True(t, receiveOpen(t, subscription).IsBolt12)
+
+ ctx.clock.SetTime(testTime.Add(30 * time.Second))
+ select {
+ case res := <-hodlChan:
+ checkFailResolution(
+ t, res.(invpkg.HtlcResolution),
+ invpkg.ResultMppTimeout,
+ )
+
+ case <-time.After(testTimeout):
+ t.Fatal("no MPP timeout")
+ }
+
+ invoice, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, invoice.State)
+ require.Equal(
+ t, invpkg.HtlcStateCanceled,
+ invoice.Htlcs[getCircuitKey(1)].State,
+ )
+
+ // A replay of the timed-out shard, for example after a restart
+ // before its fail was committed, gets the replay result.
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ checkFailResolution(t, resolution, invpkg.ResultReplayToCanceled)
+
+ requireOneOpenEvent(t, ctx, subscription)
+}
+
+// TestBolt12LaterShardExpiry verifies that a later shard settles up to the last
+// second of the stored invoice and is refused after it. The rebuild checks the
+// expiry only for the first shard.
+func TestBolt12LaterShardExpiry(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ elapsed time.Duration
+ settles bool
+ }{
+ {
+ name: "last second",
+ elapsed: 10 * time.Second,
+ settles: true,
+ },
+ {
+ name: "after expiry",
+ elapsed: 11 * time.Second,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID :=
+ newBolt12RegistryContext(t)
+
+ // The invoice expires before the MPP timeout, so the
+ // first shard is still held when the second arrives.
+ reconstructor.invoice.Terms.Expiry = 10 * time.Second
+
+ resolution, _ := notifyBolt12Shard(
+ t, ctx, preimage, pathID, 1,
+ )
+ require.Nil(t, resolution)
+
+ ctx.clock.SetTime(testTime.Add(test.elapsed))
+ resolution, _ = notifyBolt12Shard(
+ t, ctx, preimage, pathID, 2,
+ )
+ if test.settles {
+ checkSettleResolution(t, resolution, preimage)
+
+ return
+ }
+ checkFailResolution(
+ t, resolution, invpkg.ResultInvoiceNotOpen,
+ )
+ })
+ }
+}
+
+// TestBolt12ReplayAfterExpiry verifies that a replay of an accepted shard after
+// the invoice expiry gets its replay result. The expiry check of later HTLCs
+// must not fail an HTLC that the invoice already counts as accepted.
+func TestBolt12ReplayAfterExpiry(t *testing.T) {
+ t.Parallel()
+
+ ctx, reconstructor, preimage, pathID := newBolt12RegistryContext(t)
+
+ // The invoice expires before the MPP timeout, so the shard is still
+ // held at the replay.
+ reconstructor.invoice.Terms.Expiry = 10 * time.Second
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ // A replay, for example after a restart, comes after the expiry. The
+ // expiry watcher can cancel the invoice before the replay, and the
+ // replay then gets the replay result of the canceled HTLC.
+ ctx.clock.SetTime(testTime.Add(11 * time.Second))
+ resolution, _ = notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ if resolution != nil {
+ checkFailResolution(
+ t, resolution, invpkg.ResultReplayToCanceled,
+ )
+ }
+}
+
+// TestBolt12RefusesHtlcWithoutPathID verifies that a BOLT 12 invoice refuses a
+// plain HTLC that does not pay through its blinded path, even when the HTLC
+// pays the whole amount.
+func TestBolt12RefusesHtlcWithoutPathID(t *testing.T) {
+ t.Parallel()
+
+ ctx, _, preimage, pathID := newBolt12RegistryContext(t)
+
+ resolution, _ := notifyBolt12Shard(t, ctx, preimage, pathID, 1)
+ require.Nil(t, resolution)
+
+ resolution, err := ctx.registry.NotifyExitHopHtlc(
+ preimage.Hash(), testInvoiceAmount, testHtlcExpiry,
+ testCurrentHeight, getCircuitKey(2), nil, nil, &mockPayload{},
+ )
+ require.NoError(t, err)
+ checkFailResolution(t, resolution, invpkg.ResultAddressMismatch)
+
+ invoice, err := ctx.registry.LookupInvoice(
+ t.Context(), preimage.Hash(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, invoice.State)
+}
### invoices/interface.go
@@ -124,6 +124,11 @@ type Payload interface {
// TotalAmtMsat returns the total amount sent to the final hop, as set
// by the payee.
TotalAmtMsat() lnwire.MilliSatoshi
+
+ // InvoiceEnvelope returns the invoice envelope from the final-hop
+ // encrypted data of a BOLT 12 blinded path. Returns nil for BOLT 11
+ // blinded paths.
+ InvoiceEnvelope() []byte
}
// InvoiceQuery represents a query to the invoice database. The query allows a
@@ -269,6 +274,24 @@ type HtlcModifyResponse struct {
// intercepted by the invoice interceptor.
type HtlcModifyCallback func(HtlcModifyRequest) (*HtlcModifyResponse, error)
+// Bolt12Reconstructor rebuilds a BOLT 12 invoice from the invoice envelope of
+// its first HTLC. The node stores no BOLT 12 invoice of an offer before that
+// HTLC arrives.
+type Bolt12Reconstructor interface {
+ // ReconstructInvoice rebuilds a fully populated Invoice from an
+ // invoice envelope and the offer that backs it, after it checks that
+ // the payment path id authenticates the envelope.
+ ReconstructInvoice(ctx context.Context, envelope []byte,
+ pathID chainhash.Hash,
+ paymentHash lntypes.Hash) (*Invoice, error)
+
+ // CheckOfferActive returns an error when the offer with the given
+ // hash is unknown or disabled. An offer can be disabled after the first
+ // HTLC of a set arrives, so the check must run for each later HTLC of
+ // an open BOLT 12 invoice.
+ CheckOfferActive(ctx context.Context, offerHash []byte) error
+}
+
// HtlcModifier is an interface that allows an intercept client to register
// itself as a modifier of HTLCs that are settling an invoice. The client can
// then modify the HTLCs based on the invoice and the HTLC that is settling it.
### invoices/invoiceregistry.go
@@ -88,6 +88,11 @@ type RegistryConfig struct {
// SettleReconcileInterval retries pending outcome discovery. Zero
// uses DefaultSettleReconcileInterval, and idle passes skip scans.
SettleReconcileInterval time.Duration
+
+ // Bolt12Reconstructor rebuilds BOLT 12 invoices from the invoice
+ // envelopes of their first HTLCs. When nil, the registry rebuilds no
+ // invoice.
+ Bolt12Reconstructor Bolt12Reconstructor
}
// htlcReleaseEvent describes an htlc auto-release event. It is used to release
@@ -415,11 +420,6 @@ 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 {
// We won't deliver any events until the backlog has been
@@ -440,8 +440,6 @@ 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 &&
@@ -491,8 +489,6 @@ 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
@@ -1066,6 +1062,7 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
metadata: payload.Metadata(),
pathID: payload.PathID(),
totalAmtMsat: payload.TotalAmtMsat(),
+ invoiceEnvelope: payload.InvoiceEnvelope(),
}
// Only spontaneous AMP and keysend processing needs replay detection
@@ -1124,6 +1121,12 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
&ctx, hodlChan,
)
i.Unlock()
+
+ // A rebuilt row stays even when the rest of the update fails, so the
+ // expiry watcher must get it before the error return.
+ if ctx.rebuiltExpiry != nil {
+ i.expiryWatcher.AddInvoices(ctx.rebuiltExpiry)
+ }
if err != nil {
return nil, err
}
@@ -1179,10 +1182,79 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
// Look up the current invoice state to detect replays and provide
// existing HTLCs to the interceptor.
+ //
+ // reconstructedBolt12 records that this HTLC rebuilt the BOLT 12
+ // invoice. The rebuild already checked the expiry and the offer.
+ var reconstructedBolt12 bool
existingInvoice, err := i.idb.LookupInvoice(
context.Background(), invoiceRef,
)
switch {
+ case (errors.Is(err, ErrInvoiceNotFound) ||
+ errors.Is(err, ErrNoInvoicesCreated) ||
+ errors.Is(err, ErrInvRefEquivocation)) &&
+ ctx.invoiceEnvelope != nil &&
+ ctx.pathID != nil &&
+ i.cfg.Bolt12Reconstructor != nil:
+
+ // The rebuild runs when the store has no row for the HTLC,
+ // the HTLC carries an invoice envelope and a payment path id,
+ // and the registry has a Bolt12Reconstructor. This runs under
+ // i.Lock(), so only the first shard of a payment rebuilds and
+ // stores the invoice. Later shards find the stored row.
+ //
+ // TODO: the canceled-invoice GC can delete a canceled BOLT 12
+ // invoice, and this case then rebuilds it before its expiry.
+ log.Debugf("Attempting BOLT 12 invoice reconstruction "+
+ "for hash=%v", ctx.hash)
+
+ // TODO: take the context from NotifyExitHopHtlc when it
+ // gets one.
+ reconstructed, rErr := i.cfg.Bolt12Reconstructor.
+ ReconstructInvoice(
+ context.TODO(), ctx.invoiceEnvelope,
+ *ctx.pathID, ctx.hash,
+ )
+ if rErr != nil {
+ log.Debugf("BOLT 12 reconstruction failed: %v",
+ rErr)
+
+ return NewFailResolution(
+ ctx.circuitKey, ctx.currentHeight,
+ ResultInvoiceNotFound,
+ ), nil, nil
+ }
+
+ // The first shard stores the reconstructed invoice, and the
+ // store sets the add index of the new row.
+ //
+ // TODO: take the context from NotifyExitHopHtlc when it
+ // gets one.
+ _, addErr := i.idb.AddInvoice(
+ context.TODO(), reconstructed, ctx.hash,
+ )
+ if addErr != nil {
+ log.Errorf("Failed to insert reconstructed "+
+ "invoice: %v", addErr)
+
+ return NewFailResolution(
+ ctx.circuitKey, ctx.currentHeight,
+ ResultInvoiceNotFound,
+ ), nil, nil
+ }
+
+ // The stored row is a new invoice, so it gets its Open event
+ // at once, with its add index, before any event of its HTLCs.
+ // The row stays whatever happens to this HTLC, so the expiry
+ // watcher gets it too and cancels it at its expiry if no HTLC
+ // set completes.
+ stored := *reconstructed
+ i.notifyClients(ctx.hash, &stored, nil)
+ ctx.rebuiltExpiry = makeInvoiceExpiry(ctx.hash, &stored)
+
+ existingInvoice = *reconstructed
+ reconstructedBolt12 = true
+
case errors.Is(err, ErrInvoiceNotFound) ||
errors.Is(err, ErrNoInvoicesCreated) ||
errors.Is(err, ErrInvRefEquivocation):
@@ -1211,6 +1283,15 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
return nil, nil, err
}
+ if !isReplayed && !reconstructedBolt12 && existingInvoice.IsBolt12 &&
+ existingInvoice.State == ContractOpen {
+
+ res := i.checkLaterBolt12Htlc(ctx, &existingInvoice)
+ if res != nil {
+ return res, nil, nil
+ }
+ }
+
resolution := replayResolution
invoice := &existingInvoice
var updateSubscribers bool
@@ -1514,6 +1595,44 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
return resolution, invoiceToExpire, nil
}
+// checkLaterBolt12Htlc checks a later HTLC of an open BOLT 12 invoice that an
+// earlier HTLC stored. It returns a fail resolution when the HTLC must be
+// refused, or nil when the HTLC can go on. The rebuild checked the invoice
+// expiry and the offer for the first HTLC, so a later HTLC must pass the same
+// checks. The invoice can expire, and the offer can be disabled, after the
+// first HTLC. No HTLC of the set has settled. A refused HTLC lets the set time
+// out, and the expiry watcher cancels the invoice at its expiry.
+func (i *InvoiceRegistry) checkLaterBolt12Htlc(ctx *invoiceUpdateCtx,
+ invoice *Invoice) HtlcResolution {
+
+ // The invoice expires after its last second, as the rebuild reads it.
+ expiry := invoice.CreationDate.Add(invoice.Terms.Expiry)
+ if i.cfg.Clock.Now().Unix() > expiry.Unix() {
+ log.Debugf("Refusing HTLC for expired BOLT 12 invoice "+
+ "hash=%v", ctx.hash)
+
+ return ctx.failRes(ResultInvoiceNotOpen)
+ }
+
+ // An invoice without an offer has nothing to disable.
+ if len(invoice.OfferHash) == 0 || i.cfg.Bolt12Reconstructor == nil {
+ return nil
+ }
+
+ // TODO: take the context from NotifyExitHopHtlc when it gets one.
+ err := i.cfg.Bolt12Reconstructor.CheckOfferActive(
+ context.TODO(), invoice.OfferHash,
+ )
+ if err != nil {
+ log.Debugf("Refusing HTLC for BOLT 12 invoice hash=%v: %v",
+ ctx.hash, err)
+
+ return ctx.failRes(ResultInvoiceNotOpen)
+ }
+
+ return nil
+}
+
// SettleHodlInvoice sets the preimage of a hodl invoice.
func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
preimage lntypes.Preimage) error {
@@ -1734,25 +1853,6 @@ 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
@@ -1,40 +0,0 @@
-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
@@ -610,14 +610,6 @@ func TestInvoiceRegistry(t *testing.T) {
name: "ProcessingErrors",
test: testInvoiceRegistryProcessingErrors,
},
- {
- name: "Bolt12InvoiceNotification",
- test: testBolt12InvoiceNotification,
- },
- {
- name: "Bolt12InvoiceNoBacklog",
- test: testBolt12InvoiceNoBacklog,
- },
{
name: "LookupAMPHtlcPreimage",
test: testLookupAMPHtlcPreimage,
@@ -821,149 +813,6 @@ func testSubscribeBacklogNoDuplicate(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):
- }
-}
-
// testLookupAMPHtlcPreimage asserts that the child preimage of an AMP HTLC
// can be looked up by its set ID and hash once, and only once, the HTLC is
// settled.
### invoices/test_utils_test.go
@@ -33,6 +33,7 @@ type mockPayload struct {
metadata []byte
pathID *chainhash.Hash
totalAmtMsat lnwire.MilliSatoshi
+ envelope []byte
}
func (p *mockPayload) MultiPath() *record.MPP {
@@ -65,6 +66,11 @@ func (p *mockPayload) Metadata() []byte {
return p.metadata
}
+// InvoiceEnvelope returns the invoice envelope that the test payload carries.
+func (p *mockPayload) InvoiceEnvelope() []byte {
+ return p.envelope
+}
+
type mockChainNotifier struct {
chainntnfs.ChainNotifier
### invoices/update.go
@@ -30,11 +30,17 @@ type invoiceUpdateCtx struct {
// HTLC onion payload.
customRecords record.CustomSet
- mpp *record.MPP
- amp *record.AMP
- metadata []byte
- pathID *chainhash.Hash
- totalAmtMsat lnwire.MilliSatoshi
+ mpp *record.MPP
+ amp *record.AMP
+ metadata []byte
+ pathID *chainhash.Hash
+ totalAmtMsat lnwire.MilliSatoshi
+ invoiceEnvelope []byte
+
+ // rebuiltExpiry is the expiry of a BOLT 12 invoice that this HTLC
+ // rebuilt and stored. The caller gives it to the expiry watcher
+ // outside of the registry lock.
+ rebuiltExpiry invoiceExpiry
}
// invoiceRef returns an identifier that can be used to lookup or update the
### itest/list_on_test.go
@@ -619,6 +619,10 @@ var allTestCases = []*lntest.TestCase{
Name: "bolt12 invoice request",
TestFunc: testBolt12InvoiceRequest,
},
+ {
+ Name: "bolt12 receive and settle",
+ TestFunc: testBolt12ReceiveSettle,
+ },
{
Name: "sign verify message with addr",
TestFunc: testSignVerifyMessageWithAddr,
### itest/lnd_bolt12_test.go
@@ -3,7 +3,9 @@ package itest
import (
"bytes"
"context"
+ "crypto/sha256"
"encoding/hex"
+ "errors"
"time"
"github.com/btcsuite/btcd/btcec/v2"
@@ -13,6 +15,7 @@ import (
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/devrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
"github.com/lightningnetwork/lnd/lnwire"
@@ -120,16 +123,234 @@ func testBolt12InvoiceRequest(ht *lntest.HarnessTest) {
require.NoError(ht, err, "CreateOffer")
ht.Logf("Alice offer: %s", offerResp.Offer)
- offer, err := bolt12.DecodeOfferString(
- offerResp.Offer, time.Now(), *harnessNetParams.GenesisHash,
+ // Step 2: Bob subscribes to onion messages for the reply.
+ bobMessages := subscribeOnionMessages(ht, bob)
+
+ // Step 3: Build a signed invoice request.
+ ir, signedIRBytes, _ := buildInvoiceRequest(
+ ht, offerResp.Offer, 50000,
)
+
+ // Step 4: Send the invoice request to Alice twice, and expect each
+ // invoice on Bob's subscription. The first reply path starts at Bob.
+ // The second one starts at Alice, as the reply path of a payer whose
+ // only peer is Alice does, so Alice processes her own reply first.
+ alicePubKey, err := btcec.ParsePubKey(alice.PubKey[:])
require.NoError(ht, err)
- // Step 2: Bob subscribes to onion messages for the reply.
- msgClient, msgCancel := bob.RPC.SubscribeOnionMessages()
- defer msgCancel()
+ bobPubKey, err := btcec.ParsePubKey(bob.PubKey[:])
+ require.NoError(ht, err)
+
+ bobHop := &sphinx.HopInfo{
+ NodePub: bobPubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, &record.BlindedRouteData{},
+ ),
+ }
+ aliceToBobHop := &sphinx.HopInfo{
+ NodePub: alicePubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, record.NewNonFinalBlindedRouteDataOnionMessage(
+ fn.NewLeft[*btcec.PublicKey,
+ lnwire.ShortChannelID](bobPubKey),
+ nil, nil,
+ ),
+ ),
+ }
+
+ sendInvoiceRequest(
+ ht, alice, bob, signedIRBytes, []*sphinx.HopInfo{bobHop},
+ )
+ expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+
+ sendInvoiceRequest(
+ ht, alice, bob, signedIRBytes,
+ []*sphinx.HopInfo{aliceToBobHop, bobHop},
+ )
+ expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+}
+
+// testBolt12ReceiveSettle checks the receiver side of a BOLT 12 payment. The
+// invoice uses a single-hop blinded payment path, and the payee keeps no
+// invoice until the payment arrives. The invoice RPCs then report the
+// settled BOLT 12 invoice.
+func testBolt12ReceiveSettle(ht *lntest.HarnessTest) {
+ alice := ht.NewNode("Alice", bolt12NodeArgs(ht))
+ bob := ht.NewNode("Bob", bolt12NodeArgs(ht))
+
+ ht.EnsureConnected(alice, bob)
+
+ // Bob pays Alice, so he opens the channel and holds its balance.
+ ht.FundCoins(btcutil.SatoshiPerBitcoin, bob)
+ chanPoint := ht.OpenChannel(
+ bob, alice, lntest.OpenChannelParams{Amt: 500_000},
+ )
+ defer ht.CloseChannel(bob, chanPoint)
+
+ const amtMsat = 50_000
+
+ offerResp := alice.RPC.CreateOffer(&devrpc.CreateOfferRequest{
+ Description: "settle test",
+ AmountMsat: amtMsat,
+ })
- bobMessages := make(chan *lnrpc.OnionMessageUpdate, 1)
+ // Subscribe early, because the stream sends no backlog without an
+ // add index.
+ aliceInvoices := alice.RPC.SubscribeInvoices(
+ &lnrpc.InvoiceSubscription{},
+ )
+
+ bobMessages := subscribeOnionMessages(ht, bob)
+ ir, signedIRBytes, payerKey := buildInvoiceRequest(
+ ht, offerResp.Offer, amtMsat,
+ )
+
+ bobPubKey, err := btcec.ParsePubKey(bob.PubKey[:])
+ require.NoError(ht, err)
+ alicePubKey, err := btcec.ParsePubKey(alice.PubKey[:])
+ require.NoError(ht, err)
+
+ bobHop := &sphinx.HopInfo{
+ NodePub: bobPubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, &record.BlindedRouteData{},
+ ),
+ }
+
+ sendInvoiceRequest(
+ ht, alice, bob, signedIRBytes, []*sphinx.HopInfo{bobHop},
+ )
+ invoice := expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+ require.NotNil(ht, invoice)
+
+ // Alice keeps no invoice until the payment arrives.
+ invoices := alice.RPC.ListInvoices(&lnrpc.ListInvoiceRequest{})
+ require.Empty(ht, invoices.Invoices)
+
+ paths := invoice.InvoicePaths.ValOpt().UnwrapOr(
+ lnwire.BlindedPaths{},
+ ).Paths
+ payInfos := invoice.InvoiceBlindedPay.ValOpt().UnwrapOr(
+ bolt12.BlindedPayInfos{},
+ ).Infos
+ require.Len(ht, paths, 1, "invoice paths")
+ require.Len(ht, payInfos, 1, "invoice blinded pay infos")
+
+ // The path has a single hop, so Alice is its introduction node.
+ path, payInfo := paths[0], payInfos[0]
+ require.Equal(ht, alice.PubKey[:], path.IntroductionNode.Bytes())
+
+ hops := make([]*lnrpc.BlindedHop, len(path.Hops))
+ for i, hop := range path.Hops {
+ hops[i] = &lnrpc.BlindedHop{
+ BlindedNode: hop.BlindedNodeID.SerializeCompressed(),
+ EncryptedData: hop.EncryptedData,
+ }
+ }
+
+ blindingPoint := path.BlindingPoint.SerializeCompressed()
+ blindedPath := &lnrpc.BlindedPaymentPath{
+ BlindedPath: &lnrpc.BlindedPath{
+ IntroductionNode: path.IntroductionNode.Bytes(),
+ BlindingPoint: blindingPoint,
+ BlindedHops: hops,
+ },
+ BaseFeeMsat: uint64(payInfo.FeeBaseMsat),
+ ProportionalFeeRate: payInfo.FeeProportionalMillionths,
+ TotalCltvDelta: uint32(payInfo.CltvExpiryDelta),
+ HtlcMinMsat: payInfo.HtlcMinimumMsat,
+ HtlcMaxMsat: payInfo.HtlcMaximumMsat,
+ }
+
+ routes := bob.RPC.QueryRoutes(&lnrpc.QueryRoutesRequest{
+ AmtMsat: amtMsat,
+ BlindedPaymentPaths: []*lnrpc.BlindedPaymentPath{blindedPath},
+ })
+ require.NotEmpty(ht, routes.Routes, "no route to the blinded path")
+
+ hash, err := invoice.InvoicePaymentHash.UnwrapOrErrV(
+ errors.New("invoice has no payment hash"),
+ )
+ require.NoError(ht, err)
+
+ attempt := bob.RPC.SendToRouteV2(&routerrpc.SendToRouteRequest{
+ PaymentHash: hash[:],
+ Route: routes.Routes[0],
+ })
+ require.Nil(ht, attempt.Failure)
+ require.Equal(ht, lnrpc.HTLCAttempt_SUCCEEDED, attempt.Status)
+ require.Equal(ht, hash, sha256.Sum256(attempt.Preimage))
+
+ // Alice stored the invoice with its BOLT 12 detail when the HTLC
+ // arrived. The invoice goes through PENDING_SETTLE, and the payer can
+ // finish before Alice locks in the settle, so wait for the settled
+ // state first.
+ inv := alice.RPC.LookupInvoice(hash[:])
+ ht.AssertInvoiceSettled(alice, inv.PaymentAddr)
+ inv = alice.RPC.LookupInvoice(hash[:])
+ require.Equal(ht, lnrpc.Invoice_SETTLED, inv.State)
+ require.EqualValues(ht, amtMsat, inv.AmtPaidMsat)
+ require.Empty(ht, inv.PaymentRequest)
+ require.NotNil(ht, inv.Bolt12Detail)
+ require.Equal(ht, offerResp.OfferHash, inv.Bolt12Detail.OfferHash)
+ require.Equal(
+ ht, payerKey.PubKey().SerializeCompressed(),
+ inv.Bolt12Detail.InvreqPayerId,
+ )
+
+ invoices = alice.RPC.ListInvoices(&lnrpc.ListInvoiceRequest{})
+ require.Len(ht, invoices.Invoices, 1)
+ require.Equal(ht, hash[:], invoices.Invoices[0].RHash)
+ require.NotNil(ht, invoices.Invoices[0].Bolt12Detail)
+
+ // The subscriber gets the Open event when Alice keeps the HTLC, and
+ // then the Settled event.
+ opened := ht.ReceiveInvoiceUpdate(aliceInvoices)
+ require.Equal(ht, hash[:], opened.RHash)
+ require.Equal(ht, lnrpc.Invoice_OPEN, opened.State)
+ require.NotNil(ht, opened.Bolt12Detail)
+
+ settled := ht.ReceiveInvoiceUpdate(aliceInvoices)
+ require.Equal(ht, hash[:], settled.RHash)
+ require.Equal(ht, lnrpc.Invoice_SETTLED, settled.State)
+
+ // A second payment over the same path carries the same envelope and
+ // payment hash. Bob's own payment store refuses to pay the hash again,
+ // so Carol replays it. Alice must refuse it, because the invoice is
+ // settled.
+ carol := ht.NewNode("Carol", bolt12NodeArgs(ht))
+ ht.EnsureConnected(carol, alice)
+ ht.FundCoins(btcutil.SatoshiPerBitcoin, carol)
+ carolChan := ht.OpenChannel(
+ carol, alice, lntest.OpenChannelParams{Amt: 500_000},
+ )
+ defer ht.CloseChannel(carol, carolChan)
+
+ routes = carol.RPC.QueryRoutes(&lnrpc.QueryRoutesRequest{
+ AmtMsat: amtMsat,
+ BlindedPaymentPaths: []*lnrpc.BlindedPaymentPath{blindedPath},
+ })
+ require.NotEmpty(ht, routes.Routes, "no route to the blinded path")
+
+ attempt = carol.RPC.SendToRouteV2(&routerrpc.SendToRouteRequest{
+ PaymentHash: hash[:],
+ Route: routes.Routes[0],
+ })
+ require.Equal(ht, lnrpc.HTLCAttempt_FAILED, attempt.Status)
+
+ inv = alice.RPC.LookupInvoice(hash[:])
+ require.EqualValues(ht, amtMsat, inv.AmtPaidMsat)
+}
+
+// subscribeOnionMessages subscribes hn to onion messages for the test. The
+// subscription is cancelled when the test ends.
+func subscribeOnionMessages(ht *lntest.HarnessTest,
+ hn *node.HarnessNode) <-chan *lnrpc.OnionMessageUpdate {
+
+ msgClient, msgCancel := hn.RPC.SubscribeOnionMessages()
+ ht.Cleanup(msgCancel)
+
+ messages := make(chan *lnrpc.OnionMessageUpdate, 1)
go func() {
for {
msg, recvErr := msgClient.Recv()
@@ -138,14 +359,26 @@ func testBolt12InvoiceRequest(ht *lntest.HarnessTest) {
}
select {
- case bobMessages <- msg:
+ case messages <- msg:
case <-ht.Context().Done():
return
}
}
}()
- // Step 3: Build a signed invoice request.
+ return messages
+}
+
+// buildInvoiceRequest builds and signs an invoice request for the offer with
+// a fresh payer key.
+func buildInvoiceRequest(ht *lntest.HarnessTest, offerStr string,
+ amtMsat uint64) (*bolt12.InvoiceRequest, []byte, *btcec.PrivateKey) {
+
+ offer, err := bolt12.DecodeOfferString(
+ offerStr, time.Now(), *harnessNetParams.GenesisHash,
+ )
+ require.NoError(ht, err)
+
payerKey, err := btcec.NewPrivateKey()
require.NoError(ht, err)
@@ -157,10 +390,9 @@ func testBolt12InvoiceRequest(ht *lntest.HarnessTest) {
)
require.NoError(ht, err)
- amt := bolt12.TUint64(50000)
ir.InvreqAmount = tlv.SomeRecordT(
tlv.RecordT[tlv.TlvType82, bolt12.TUint64]{
- Val: amt,
+ Val: bolt12.TUint64(amtMsat),
},
)
@@ -176,43 +408,7 @@ func testBolt12InvoiceRequest(ht *lntest.HarnessTest) {
require.NoError(ht, err)
ht.Logf("Signed invreq: %d bytes", len(signedIRBytes))
- // Step 4: Send the invoice request to Alice twice, and expect each
- // invoice on Bob's subscription. The first reply path starts at Bob.
- // The second one starts at Alice, as the reply path of a payer whose
- // only peer is Alice does, so Alice processes her own reply first.
- alicePubKey, err := btcec.ParsePubKey(alice.PubKey[:])
- require.NoError(ht, err)
-
- bobPubKey, err := btcec.ParsePubKey(bob.PubKey[:])
- require.NoError(ht, err)
-
- bobHop := &sphinx.HopInfo{
- NodePub: bobPubKey,
- PlainText: onionmessage.EncodeBlindedRouteData(
- ht.T, &record.BlindedRouteData{},
- ),
- }
- aliceToBobHop := &sphinx.HopInfo{
- NodePub: alicePubKey,
- PlainText: onionmessage.EncodeBlindedRouteData(
- ht.T, record.NewNonFinalBlindedRouteDataOnionMessage(
- fn.NewLeft[*btcec.PublicKey,
- lnwire.ShortChannelID](bobPubKey),
- nil, nil,
- ),
- ),
- }
-
- sendInvoiceRequest(
- ht, alice, bob, signedIRBytes, []*sphinx.HopInfo{bobHop},
- )
- expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
-
- sendInvoiceRequest(
- ht, alice, bob, signedIRBytes,
- []*sphinx.HopInfo{aliceToBobHop, bobHop},
- )
- expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+ return ir, signedIRBytes, payerKey
}
// sendInvoiceRequest sends the signed invoice request from the payer to the
@@ -280,7 +476,8 @@ func sendInvoiceRequest(ht *lntest.HarnessTest, receiver,
// against the receiver, whose offer carries its node ID as offer_issuer_id.
func expectInvoiceReply(ht *lntest.HarnessTest,
messages <-chan *lnrpc.OnionMessageUpdate,
- ir *bolt12.InvoiceRequest, receiverPubKey *btcec.PublicKey) {
+ ir *bolt12.InvoiceRequest,
+ receiverPubKey *btcec.PublicKey) *bolt12.Invoice {
select {
case msg := <-messages:
@@ -305,9 +502,13 @@ func expectInvoiceReply(ht *lntest.HarnessTest,
)
require.NoError(ht, err, "validate invoice")
+ return invoice
+
case <-time.After(lntest.DefaultTimeout):
ht.Fatal("payer did not receive the invoice reply")
}
+
+ return nil
}
// bolt12NodeArgs returns the node arguments that enable BOLT 12 offers. It
### lnrpc/invoicesrpc/invoices.swagger.json
@@ -744,6 +744,10 @@
"preimage_released": {
"type": "boolean",
"description": "Whether lnd committed to releasing the preimage for this ordinary invoice,\nincluding when collection later failed. This is derived from the invoice\nand HTLC states, not from whether lnd knows the preimage. It does not prove\nthe payer received the preimage, and false does not guarantee the secret\nis unknown elsewhere. Clients must not infer preimage privacy from\nCANCELED alone when refunding a counterpart payment or reusing a hash.\nThis field is not supported for AMP invoices and is false for them.\nNote: Output only, don't specify for creating an invoice."
+ },
+ "bolt12_detail": {
+ "$ref": "#/definitions/lnrpcOfferInvoiceDetail",
+ "description": "BOLT 12-specific invoice context, set only for an invoice that the\nnode made with the BOLT 12 offer protocol. A client checks that it is\nset to find a BOLT 12 invoice. Contains offer identity, payer identity,\nand negotiation parameters that have no BOLT 11 equivalent. Old callers\ncan safely ignore this field.\n\nThe node stores a received BOLT 12 invoice when its first HTLC arrives,\nand it does not keep the signed lni1... invoice. So payment_request is\nempty, and no RPC returns the lni1... invoice. SubscribeInvoices sends\nthe Open event when the node stores the invoice. If no HTLC set pays\nthe invoice, the node cancels it at its expiry.\nNote: Output only, don't specify for creating an invoice."
}
}
},
@@ -826,6 +830,30 @@
"default": "ACCEPTED",
"description": " - SETTLED: An ordinary HTLC settled irrevocably. AMP retains its existing\npreimage-release settlement semantics.\n - PENDING_SETTLE: An ordinary HTLC released its preimage but its outcome is not final yet.\nIt becomes SETTLED on final success or FAILED if the payer reclaims it.\n - FAILED: An ordinary HTLC whose preimage was released but was not collected. This\ndiffers from CANCELED, which failed before preimage release."
},
+ "lnrpcOfferInvoiceDetail": {
+ "type": "object",
+ "properties": {
+ "offer_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The 32-byte hash of the offer this invoice answers."
+ },
+ "invreq_payer_id": {
+ "type": "string",
+ "format": "byte",
+ "description": "The 33-byte compressed ephemeral payer pubkey from the invoice\nrequest (invreq_payer_id, TLV type 88)."
+ },
+ "quantity": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The number of items requested (invreq_quantity, TLV type 86). Zero\nif the offer does not support a quantity."
+ },
+ "payer_note": {
+ "type": "string",
+ "description": "The note of the payer from the invoice request (invreq_payer_note,\nTLV type 89), cut to at most 64 bytes. Bytes that are not valid\nUTF-8 are replaced with U+FFFD."
+ }
+ }
+ },
"lnrpcRouteHint": {
"type": "object",
"properties": {
### lnrpc/invoicesrpc/utils.go
@@ -5,6 +5,7 @@ import (
"encoding/hex"
"fmt"
"slices"
+ "strings"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chaincfg/v2"
@@ -227,6 +228,11 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
IsAmp: isAMP,
IsBlinded: invoice.IsBlinded(),
}
+
+ if invoice.IsBolt12 {
+ rpcInvoice.Bolt12Detail = marshalBolt12Detail(invoice)
+ }
+
rpcInvoice.PreimageReleased = preimageReleased
rpcInvoice.AmpInvoiceState = make(map[string]*lnrpc.AMPInvoiceState)
@@ -268,6 +274,23 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
return rpcInvoice, nil
}
+// marshalBolt12Detail maps the offer hash, payer id and quantity of a BOLT 12
+// invoice to its RPC detail.
+func marshalBolt12Detail(invoice *invoices.Invoice) *lnrpc.OfferInvoiceDetail {
+ // A proto string must be valid UTF-8, and the codec does not check
+ // the payer note.
+ payerNote := strings.ToValidUTF8(
+ string(invoice.InvreqPayerNote), "\uFFFD",
+ )
+
+ return &lnrpc.OfferInvoiceDetail{
+ OfferHash: invoice.OfferHash,
+ InvreqPayerId: invoice.InvreqPayerID,
+ Quantity: invoice.InvreqQuantity,
+ PayerNote: payerNote,
+ }
+}
+
// CreateRPCFeatures maps a feature vector into a list of lnrpc.Features.
func CreateRPCFeatures(fv *lnwire.FeatureVector) map[uint32]*lnrpc.Feature {
if fv == nil {
### lnrpc/invoicesrpc/utils_test.go
@@ -1,16 +1,156 @@
package invoicesrpc
import (
+ "bytes"
"testing"
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/zpay32"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
)
+// testPreimage is a deterministic preimage used across tests.
+var testPreimage = lntypes.Preimage{
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+ 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
+}
+
+// TestCreateRPCInvoiceNoPayReq verifies that an invoice without a BOLT 11
+// payment request takes its payment hash from the preimage, and has none
+// without a preimage.
+func TestCreateRPCInvoiceNoPayReq(t *testing.T) {
+ t.Parallel()
+
+ preimage := testPreimage
+ hash := preimage.Hash()
+
+ tests := []struct {
+ name string
+ bolt12 bool
+ preimage *lntypes.Preimage
+ wantHash []byte
+ }{
+ {
+ name: "keysend",
+ preimage: &preimage,
+ wantHash: hash[:],
+ },
+ {
+ name: "bolt12 without preimage",
+ bolt12: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ features := lnwire.EmptyFeatureVector()
+ inv := &invoices.Invoice{
+ IsBolt12: test.bolt12,
+ Terms: invoices.ContractTerm{
+ PaymentPreimage: test.preimage,
+ Features: features,
+ },
+ }
+
+ rpcInv, err := CreateRPCInvoice(
+ inv, &chaincfg.MainNetParams,
+ )
+ require.NoError(t, err)
+ require.Equal(t, test.wantHash, rpcInv.RHash)
+ })
+ }
+}
+
+// TestCreateRPCInvoiceBolt12Detail verifies that a BOLT 12 invoice shows its
+// offer hash, payer id and quantity, and that a BOLT 11 invoice shows none.
+func TestCreateRPCInvoiceBolt12Detail(t *testing.T) {
+ t.Parallel()
+
+ offerHash := bytes.Repeat([]byte{0xab}, 32)
+ payerID := []byte{0x03, 0x02}
+
+ tests := []struct {
+ name string
+ bolt12 bool
+ payerNote []byte
+ wantDetail *lnrpc.OfferInvoiceDetail
+ }{
+ {
+ name: "bolt12",
+ bolt12: true,
+ payerNote: []byte("tip"),
+ wantDetail: &lnrpc.OfferInvoiceDetail{
+ OfferHash: offerHash,
+ InvreqPayerId: payerID,
+ Quantity: 3,
+ PayerNote: "tip",
+ },
+ },
+ {
+ // A proto string must be valid UTF-8, and the codec
+ // does not check the note.
+ name: "payer note not UTF-8",
+ bolt12: true,
+ payerNote: []byte{'a', 0xff},
+ wantDetail: &lnrpc.OfferInvoiceDetail{
+ OfferHash: offerHash,
+ InvreqPayerId: payerID,
+ Quantity: 3,
+ PayerNote: "a\uFFFD",
+ },
+ },
+ {
+ name: "bolt11",
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ preimage := testPreimage
+ features := lnwire.EmptyFeatureVector()
+ inv := &invoices.Invoice{
+ IsBolt12: test.bolt12,
+ OfferHash: offerHash,
+ InvreqPayerID: payerID,
+ InvreqQuantity: 3,
+ InvreqPayerNote: test.payerNote,
+ Terms: invoices.ContractTerm{
+ PaymentPreimage: &preimage,
+ Features: features,
+ },
+ }
+
+ rpcInv, err := CreateRPCInvoice(
+ inv, &chaincfg.MainNetParams,
+ )
+ require.NoError(t, err)
+
+ if test.wantDetail == nil {
+ require.Nil(t, rpcInv.Bolt12Detail)
+
+ return
+ }
+ require.True(t, proto.Equal(
+ test.wantDetail, rpcInv.Bolt12Detail,
+ ))
+
+ _, err = proto.Marshal(rpcInv)
+ require.NoError(t, err)
+ })
+ }
+}
+
// 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.
### lnrpc/lightning.pb.go
[binary or diff unavailable]
### lnrpc/lightning.proto
@@ -4109,6 +4109,40 @@ message Invoice {
Note: Output only, don't specify for creating an invoice.
*/
bool preimage_released = 31;
+
+ /*
+ BOLT 12-specific invoice context, set only for an invoice that the
+ node made with the BOLT 12 offer protocol. A client checks that it is
+ set to find a BOLT 12 invoice. Contains offer identity, payer identity,
+ and negotiation parameters that have no BOLT 11 equivalent. Old callers
+ can safely ignore this field.
+
+ The node stores a received BOLT 12 invoice when its first HTLC arrives,
+ and it does not keep the signed lni1... invoice. So payment_request is
+ empty, and no RPC returns the lni1... invoice. SubscribeInvoices sends
+ the Open event when the node stores the invoice. If no HTLC set pays
+ the invoice, the node cancels it at its expiry.
+ Note: Output only, don't specify for creating an invoice.
+ */
+ OfferInvoiceDetail bolt12_detail = 32;
+}
+
+message OfferInvoiceDetail {
+ // The 32-byte hash of the offer this invoice answers.
+ bytes offer_hash = 1;
+
+ // The 33-byte compressed ephemeral payer pubkey from the invoice
+ // request (invreq_payer_id, TLV type 88).
+ bytes invreq_payer_id = 2;
+
+ // The number of items requested (invreq_quantity, TLV type 86). Zero
+ // if the offer does not support a quantity.
+ uint64 quantity = 3;
+
+ // The note of the payer from the invoice request (invreq_payer_note,
+ // TLV type 89), cut to at most 64 bytes. Bytes that are not valid
+ // UTF-8 are replaced with U+FFFD.
+ string payer_note = 4;
}
message BlindedPathConfig {
### lnrpc/lightning.swagger.json
@@ -5945,6 +5945,10 @@
"preimage_released": {
"type": "boolean",
"description": "Whether lnd committed to releasing the preimage for this ordinary invoice,\nincluding when collection later failed. This is derived from the invoice\nand HTLC states, not from whether lnd knows the preimage. It does not prove\nthe payer received the preimage, and false does not guarantee the secret\nis unknown elsewhere. Clients must not infer preimage privacy from\nCANCELED alone when refunding a counterpart payment or reusing a hash.\nThis field is not supported for AMP invoices and is false for them.\nNote: Output only, don't specify for creating an invoice."
+ },
+ "bolt12_detail": {
+ "$ref": "#/definitions/lnrpcOfferInvoiceDetail",
+ "description": "BOLT 12-specific invoice context, set only for an invoice that the\nnode made with the BOLT 12 offer protocol. A client checks that it is\nset to find a BOLT 12 invoice. Contains offer identity, payer identity,\nand negotiation parameters that have no BOLT 11 equivalent. Old callers\ncan safely ignore this field.\n\nThe node stores a received BOLT 12 invoice when its first HTLC arrives,\nand it does not keep the signed lni1... invoice. So payment_request is\nempty, and no RPC returns the lni1... invoice. SubscribeInvoices sends\nthe Open event when the node stores the invoice. If no HTLC set pays\nthe invoice, the node cancels it at its expiry.\nNote: Output only, don't specify for creating an invoice."
}
}
},
@@ -6509,6 +6513,30 @@
}
}
},
+ "lnrpcOfferInvoiceDetail": {
+ "type": "object",
+ "properties": {
+ "offer_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The 32-byte hash of the offer this invoice answers."
+ },
+ "invreq_payer_id": {
+ "type": "string",
+ "format": "byte",
+ "description": "The 33-byte compressed ephemeral payer pubkey from the invoice\nrequest (invreq_payer_id, TLV type 88)."
+ },
+ "quantity": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The number of items requested (invreq_quantity, TLV type 86). Zero\nif the offer does not support a quantity."
+ },
+ "payer_note": {
+ "type": "string",
+ "description": "The note of the payer from the invoice request (invreq_payer_note,\nTLV type 89), cut to at most 64 bytes. Bytes that are not valid\nUTF-8 are replaced with U+FFFD."
+ }
+ }
+ },
"lnrpcOnionMessageUpdate": {
"type": "object",
"properties": {
### lnrpc/switchrpc/switch_server.go
@@ -1183,45 +1183,3 @@ func UnmarshallFailureDetails(details *FailureDetails,
return nil, fmt.Errorf("unknown or empty failure reason in "+
"response: %v", details.ErrorMessage)
}
-
-// UnmarshallForwardingError converts a protobuf ForwardingFailure message into
-// an htlcswitch.ForwardingError.
-func UnmarshallForwardingError(f *ForwardingFailure) (
- *htlcswitch.ForwardingError, error) {
-
- if f == nil {
- return nil, fmt.Errorf("cannot parse nil ForwardingFailure")
- }
-
- wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
- if err != nil {
- return nil, fmt.Errorf("failed to decode wire message: %w", err)
- }
-
- return htlcswitch.NewForwardingError(
- wireMsg, int(f.FailureSourceIndex),
- ), nil
-}
-
-// UnmarshallLinkError converts a protobuf LocalFailure message into an
-// htlcswitch.LinkError.
-func UnmarshallLinkError(f *LocalFailure) (*htlcswitch.LinkError, error) {
- if f == nil {
- return nil, fmt.Errorf("cannot parse nil LocalFailure")
- }
-
- wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
- if err != nil {
- return nil, fmt.Errorf("failed to decode wire message: %w", err)
- }
-
- return htlcswitch.NewLinkError(wireMsg), nil
-}
-
-// UnmarshallFailureMessage decodes a raw wire message byte slice into a rich
-// lnwire.FailureMessage object.
-func UnmarshallFailureMessage(wireMsg []byte) (lnwire.FailureMessage, error) {
- r := bytes.NewReader(wireMsg)
-
- return lnwire.DecodeFailure(r, 0)
-}
### lnrpc/switchrpc/unmarshal.go
@@ -0,0 +1,51 @@
+package switchrpc
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnwire"
+)
+
+// UnmarshallForwardingError converts a protobuf ForwardingFailure message into
+// an htlcswitch.ForwardingError.
+func UnmarshallForwardingError(f *ForwardingFailure) (
+ *htlcswitch.ForwardingError, error) {
+
+ if f == nil {
+ return nil, fmt.Errorf("cannot parse nil ForwardingFailure")
+ }
+
+ wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode wire message: %w", err)
+ }
+
+ return htlcswitch.NewForwardingError(
+ wireMsg, int(f.FailureSourceIndex),
+ ), nil
+}
+
+// UnmarshallLinkError converts a protobuf LocalFailure message into an
+// htlcswitch.LinkError.
+func UnmarshallLinkError(f *LocalFailure) (*htlcswitch.LinkError, error) {
+ if f == nil {
+ return nil, fmt.Errorf("cannot parse nil LocalFailure")
+ }
+
+ wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode wire message: %w", err)
+ }
+
+ return htlcswitch.NewLinkError(wireMsg), nil
+}
+
+// UnmarshallFailureMessage decodes a raw wire message byte slice into a rich
+// lnwire.FailureMessage object.
+func UnmarshallFailureMessage(wireMsg []byte) (lnwire.FailureMessage, error) {
+ r := bytes.NewReader(wireMsg)
+
+ return lnwire.DecodeFailure(r, 0)
+}
### server.go
@@ -980,7 +980,7 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
// Use the final CLTV delta of BOLT 11 invoices.
s.bolt12Handler, err = bolt12handler.NewHandler(
- s.offerStore, s.invoices, replier, signer, pathIDKey,
+ s.offerStore, replier, signer, pathIDKey,
nil,
clock.NewDefaultClock(),
*s.cfg.ActiveNetParams.GenesisHash,
@@ -989,6 +989,16 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
if err != nil {
return nil, err
}
+
+ // The registry rebuilds a BOLT 12 invoice from the invoice
+ // envelope of its first HTLC.
+ registryConfig.Bolt12Reconstructor =
+ bolt12handler.NewReconstructor(
+ pathIDKey, s.offerStore,
+ *s.cfg.ActiveNetParams.GenesisHash,
+ uint16(cfg.Bitcoin.TimeLockDelta),
+ registryConfig.Clock,
+ )
}
thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)Why this scored 60/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.