Merge pull request #11532 from bitromortac/20261104-2742-dispatch
What changed, and why it matters
This commit adds a new BOLT 12 feature to the LND Lightning node. It lets the node embed a small encrypted 'invoice envelope' inside the final hop of a blinded payment path, and derives the payment preimage from a new 'path id' key instead of storing it immediately. This is a design change toward stateless BOLT 12 invoice settlement. The commit also adds a development-only SQL side table for BOLT 12 invoices and changes how offer/invoice hashes are computed so that blinded paths are not included in the signed hash. The release notes explicitly note that callers with the signer:generate permission can now derive every BOLT 12 preimage the node issues, which is a deliberate permission-scope change, not a hidden bug.
Reviewers should verify the HMAC-based preimage derivation is sound and that the path id cannot be verified under the zero key. Confirm that the signer:generate permission scope change is acceptable to the project and documented. Ensure the new SQL side table is only created/queried when BOLT 12 development migrations are enabled, and that the invoice envelope validation on AddInvoice cannot be bypassed. Because settlement logic is noted as coming in a later change, this commit should not be treated as a complete security fix but as an incremental feature that introduces new key material and trust assumptions.
Security signals we found
New cryptographic key derivation (PathIDKey) from ECDH with a fixed public point and tagged HMAC for path ids/preimages.
Payment preimage is no longer randomly generated but deterministically derived from path id and envelope binding; any flaw in the derivation would let an attacker compute preimages.
Invoice envelope is carried in encrypted_recipient_data as a custom TLV (65538) and bound to the path id; tampering with envelope bytes changes the binding and invalidates the path id/preimage check.
Release notes explicitly disclose that signer:generate permission now allows derivation of all BOLT 12 preimages, widening that permission's scope.
BOLT 12 side table is gated behind a development migration and a store option; without it, BOLT 12 invoices are rejected.
Validation prevents BOLT 12 + AMP invoices and requires a decodable envelope on add.
Payer note is truncated to 64 bytes in the envelope to limit onion size; the full note is still mirrored in the signed invoice sent to the payer.
Evidence from the diff
The PR implements BOLT 12 ‘invoice envelope in payment paths’ (PR #11532). Key changes: (1) new bolt12handler/envelope package encodes offer hash, payer id, created_at, amount, quantity and a capped payer note into a TLV envelope; (2) record.NewFinalHopBlindedRouteData now accepts an optional invoiceEnvelope carried as custom TLV 65538 in encrypted_recipient_data; (3) GenerateInvoice builds the envelope, computes EnvelopeBinding as a tagged hash of the raw envelope bytes, and uses a new PathIDKey to derive both the 32-byte payment path id (shown as payment address) and the payment preimage via HMAC, removing the previous random preimage/path_id generation; (4) OfferHashWithoutPaths and InvoiceRequestHash are added so that offer/invoice-request hashes exclude the blinded paths that are bound to them; (5) the SQL invoice store gains a bolt12_invoices side table (development migration 000018) and WithBolt12 option, with validation that BOLT 12 invoices must have a decodable envelope and cannot be AMP; (6) server.go derives the PathIDKey from an ECDH with a fixed public node-secret point. The release notes state this makes signer:generate permission holders able to derive all BOLT 12 preimages.
Changed components
bolt12/offer_hash.gobolt12handler/envelopebolt12handler/generate.gobolt12handler/handler.gobolt12handler/path_id.gobolt12handler/node_secret.goinvoices/sql_store.gorecord/blinded_data.gorouting/blindedpath/blinded_path.goserver.gosqldb/sqlc migrations and queries for bolt12_invoicesInspect captured patch +2905 / −72
### bolt12/offer_hash.go
@@ -23,9 +23,37 @@ import (
// used here. LDK and eclair derive their offer id from that root instead, so
// those values differ for the same offer.
func OfferHash(m lnwire.PureTLVMessage) ([32]byte, error) {
+ return hashRecords(m, offerAllowedRange)
+}
+
+// OfferHashWithoutPaths returns the offer hash of a message with offer_paths
+// left out. A node binds the blinded paths of an offer to this hash because
+// the hash exists before the paths do. An invoice_request over such a path
+// mirrors the fields that the hash covers.
+func OfferHashWithoutPaths(m lnwire.PureTLVMessage) ([32]byte, error) {
+ return hashRecords(m, func(typ tlv.Type) bool {
+ return offerAllowedRange(typ) && typ != offerPathsType
+ })
+}
+
+// InvoiceRequestHash returns the SHA-256 of the records of a message in the
+// invoice_request TLV ranges, with invreq_paths left out. An invoice mirrors
+// these ranges of the request it answers, so a request and its invoice hash to
+// the same value. The signature is outside these ranges.
+func InvoiceRequestHash(m lnwire.PureTLVMessage) ([32]byte, error) {
+ return hashRecords(m, func(typ tlv.Type) bool {
+ return invreqAllowedRange(typ) && typ != invreqPathsType
+ })
+}
+
+// hashRecords returns the SHA-256 of the encoding of the records of a message
+// whose type keep accepts.
+func hashRecords(m lnwire.PureTLVMessage, keep func(tlv.Type) bool) ([32]byte,
+ error) {
+
var records []tlv.Record
for _, r := range m.AllRecords() {
- if offerAllowedRange(r.Type()) {
+ if keep(r.Type()) {
records = append(records, r)
}
}
### bolt12/offer_hash_test.go
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"testing"
+ "github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
@@ -130,3 +131,110 @@ func TestOfferHashMatchesCoreLightning(t *testing.T) {
require.Equal(t, clnOfferHash, hex.EncodeToString(id[:]))
}
+
+// testPaths returns one blinded path with one hop, for the offer_paths and
+// invreq_paths records of a test message.
+func testPaths() lnwire.BlindedPaths {
+ _, intro := aliceKey()
+ _, blinding := bobKey()
+
+ return lnwire.BlindedPaths{
+ Paths: []lnwire.BlindedPath{{
+ IntroductionNode: lnwire.PubkeyIntro{Pubkey: intro},
+ BlindingPoint: blinding,
+ Hops: []lnwire.BlindedHop{{
+ BlindedNodeID: intro,
+ EncryptedData: []byte{1, 2, 3},
+ }},
+ }},
+ }
+}
+
+// TestOfferHashWithoutPaths verifies that the hash ignores offer_paths. This
+// lets a node bind the paths of an offer to a value that exists before them.
+// It also verifies that a request over such a path gives the same value.
+func TestOfferHashWithoutPaths(t *testing.T) {
+ t.Parallel()
+
+ _, issuer := bobKey()
+ _, payer := aliceKey()
+
+ offer := &Offer{}
+ offer.OfferDescription = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType10, []byte]([]byte("coffee")),
+ )
+ offer.OfferIssuerID = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType22](issuer),
+ )
+
+ before, err := OfferHashWithoutPaths(offer)
+ require.NoError(t, err)
+
+ offer.OfferPaths = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType16](testPaths()),
+ )
+
+ after, err := OfferHashWithoutPaths(offer)
+ require.NoError(t, err)
+ require.Equal(t, before, after)
+
+ full, err := OfferHash(offer)
+ require.NoError(t, err)
+ require.NotEqual(t, full, after)
+
+ ir, err := NewInvoiceRequestFromOffer(
+ offer, payer, []byte("meta"), bitcoinMainnetGenesisHash,
+ )
+ require.NoError(t, err)
+
+ fromRequest, err := OfferHashWithoutPaths(ir)
+ require.NoError(t, err)
+ require.Equal(t, after, fromRequest)
+}
+
+// TestInvoiceRequestHash verifies that an invoice hashes to the hash of the
+// request it answers, that invreq_paths do not count, and that a field in the
+// request range does.
+func TestInvoiceRequestHash(t *testing.T) {
+ t.Parallel()
+
+ _, issuer := bobKey()
+ _, payer := aliceKey()
+
+ offer := &Offer{}
+ offer.OfferDescription = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType10, []byte]([]byte("coffee")),
+ )
+ offer.OfferIssuerID = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType22](issuer),
+ )
+
+ newRequest := func(metadata string) *InvoiceRequest {
+ ir, err := NewInvoiceRequestFromOffer(
+ offer, payer, []byte(metadata),
+ bitcoinMainnetGenesisHash,
+ )
+ require.NoError(t, err)
+
+ return ir
+ }
+
+ ir := newRequest("meta")
+ reqHash, err := InvoiceRequestHash(ir)
+ require.NoError(t, err)
+
+ invHash, err := InvoiceRequestHash(NewInvoiceFromRequest(ir))
+ require.NoError(t, err)
+ require.Equal(t, reqHash, invHash)
+
+ ir.InvreqPaths = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType90](testPaths()),
+ )
+ withPaths, err := InvoiceRequestHash(ir)
+ require.NoError(t, err)
+ require.Equal(t, reqHash, withPaths)
+
+ other, err := InvoiceRequestHash(newRequest("other"))
+ require.NoError(t, err)
+ require.NotEqual(t, reqHash, other)
+}
### bolt12handler/dispatcher_test.go
@@ -211,8 +211,8 @@ func newDispatchTest(t *testing.T, maxInflight int,
replier := &chanReplier{replies: replies}
handler, err := NewHandler(
store, nopNotifier{}, replier,
- newPrivKeySigner(nodeKey), nil, clock.NewDefaultClock(),
- testChainHash(), testFinalCLTVDelta,
+ newPrivKeySigner(nodeKey), testPathIDKey(nodeKey), nil,
+ clock.NewDefaultClock(), testChainHash(), testFinalCLTVDelta,
)
require.NoError(t, err)
handler.maxInflight = maxInflight
@@ -498,7 +498,8 @@ func TestHandlerDispatch(t *testing.T) {
handler, err := NewHandler(
newMockOfferStore(), nopNotifier{}, &mockReplier{},
- newPrivKeySigner(testKey(t)), nil,
+ newPrivKeySigner(testKey(t)),
+ testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
testFinalCLTVDelta,
)
@@ -518,7 +519,8 @@ func TestHandlerDispatch(t *testing.T) {
handler, err := NewHandler(
newMockOfferStore(), nopNotifier{}, &mockReplier{},
- newPrivKeySigner(testKey(t)), nil,
+ newPrivKeySigner(testKey(t)),
+ testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
testFinalCLTVDelta,
)
@@ -542,7 +544,8 @@ func TestHandlerDispatch(t *testing.T) {
handler, err := NewHandler(
newMockOfferStore(), nopNotifier{}, &mockReplier{},
- newPrivKeySigner(testKey(t)), nil,
+ newPrivKeySigner(testKey(t)),
+ testPathIDKey(testKey(t)), nil,
clock.NewDefaultClock(), testChainHash(),
testFinalCLTVDelta,
)
@@ -577,7 +580,8 @@ func TestHandlerDispatch(t *testing.T) {
handler, err := NewHandler(
newMockOfferStore(), nopNotifier{},
&mockReplier{}, newPrivKeySigner(testKey(t)),
- nil, clock.NewDefaultClock(), testChainHash(),
+ testPathIDKey(testKey(t)), nil,
+ clock.NewDefaultClock(), testChainHash(),
testFinalCLTVDelta,
)
require.NoError(t, err)
### bolt12handler/envelope.go
@@ -0,0 +1,17 @@
+package bolt12handler
+
+import (
+ "github.com/btcsuite/btcd/chainhash/v2"
+)
+
+// envelopeBindingTag tags the hash of an encoded invoice envelope that the
+// payment path id covers.
+const envelopeBindingTag = "bolt12/invoice-envelope"
+
+// EnvelopeBinding returns the hash of an encoded invoice envelope that the
+// payment path id covers. A change of any envelope byte changes it. It hashes
+// the bytes as the onion carries them and not a re-encoding of the decoded
+// data, because the decoder skips unknown records.
+func EnvelopeBinding(envelope []byte) [32]byte {
+ return *chainhash.TaggedHash([]byte(envelopeBindingTag), envelope)
+}
### bolt12handler/envelope/envelope.go
@@ -0,0 +1,201 @@
+// Package envelope encodes the invoice envelope that the final hop of each
+// BOLT 12 blinded payment path carries. The invoice store decodes it too, so
+// the package imports neither bolt12handler nor invoices.
+package envelope
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/tlv"
+)
+
+const (
+ // MaxPayerNoteLen is the longest invreq_payer_note in bytes that an
+ // envelope carries.
+ MaxPayerNoteLen = 64
+
+ // typeOfferHash is the TLV type for the 32-byte hash of the offer.
+ typeOfferHash tlv.Type = 0
+
+ // typePayerID is the TLV type for the 33-byte compressed public key of
+ // the payer (invreq_payer_id).
+ typePayerID tlv.Type = 2
+
+ // typeCreatedAt is the TLV type for the invoice creation timestamp in
+ // seconds since epoch.
+ typeCreatedAt tlv.Type = 4
+
+ // typeAmount is the TLV type for the invoice amount in millisatoshis.
+ typeAmount tlv.Type = 6
+
+ // typeQuantity is the TLV type for the optional number of items
+ // requested (invreq_quantity).
+ typeQuantity tlv.Type = 8
+
+ // typePayerNote is the TLV type for the optional invreq_payer_note.
+ typePayerNote tlv.Type = 10
+)
+
+// ErrPayerNoteTooLong is returned for a payer note longer than
+// MaxPayerNoteLen.
+var ErrPayerNoteTooLong = errors.New("payer note too long")
+
+// Data contains the fields needed to reconstruct a BOLT 12 invoice at HTLC
+// settlement time. The same node writes and reads it, so the BOLT even/odd
+// interop convention does not apply. It has no version field, because a new
+// field gets a new TLV type.
+//
+// Keep the encoding minimal. Padding gives every blinded hop the size of the
+// largest hop. The final hop carries the envelope. Each envelope byte
+// therefore costs the payer one onion byte per blinded hop, and the payer note
+// costs its length once per blinded hop.
+type Data struct {
+ // OfferHash is the hash of the offer that the invoice answers. It is
+ // None for an invoice that answers no offer.
+ OfferHash fn.Option[[32]byte]
+
+ // PayerID is the compressed public key from invreq_payer_id.
+ PayerID [33]byte
+
+ // CreatedAt is the invoice creation timestamp (seconds since epoch).
+ CreatedAt uint64
+
+ // Amount is the invoice amount in millisatoshis.
+ Amount uint64
+
+ // Quantity is the invreq_quantity of the request. Zero means the
+ // request carried no quantity, and the field is then not encoded.
+ Quantity uint64
+
+ // PayerNote is the invreq_payer_note of the request, at most
+ // MaxPayerNoteLen bytes. An empty note is not encoded.
+ PayerNote []byte
+}
+
+// tu64 returns a record of a truncated uint64, which keeps the envelope small
+// on every blinded hop.
+func tu64(typ tlv.Type, val *uint64) tlv.Record {
+ return tlv.MakeDynamicRecord(
+ typ, val, func() uint64 {
+ return tlv.SizeTUint64(*val)
+ }, tlv.ETUint64, tlv.DTUint64,
+ )
+}
+
+// Encode serializes the envelope into canonical TLV bytes. It returns
+// ErrPayerNoteTooLong for a payer note longer than MaxPayerNoteLen.
+func Encode(data *Data) ([]byte, error) {
+ if len(data.PayerNote) > MaxPayerNoteLen {
+ return nil, fmt.Errorf("%w: %d bytes", ErrPayerNoteTooLong,
+ len(data.PayerNote))
+ }
+
+ var (
+ records []tlv.Record
+ offerHash []byte
+ payerID = data.PayerID[:]
+ payerNote = data.PayerNote
+ )
+ data.OfferHash.WhenSome(func(hash [32]byte) {
+ offerHash = hash[:]
+ records = append(records, tlv.MakePrimitiveRecord(
+ typeOfferHash, &offerHash,
+ ))
+ })
+ records = append(
+ records,
+ tlv.MakePrimitiveRecord(typePayerID, &payerID),
+ tu64(typeCreatedAt, &data.CreatedAt),
+ tu64(typeAmount, &data.Amount),
+ )
+ if data.Quantity > 0 {
+ records = append(records, tu64(typeQuantity, &data.Quantity))
+ }
+ if len(payerNote) > 0 {
+ records = append(records, tlv.MakePrimitiveRecord(
+ typePayerNote, &payerNote,
+ ))
+ }
+
+ tlvStream, err := tlv.NewStream(records...)
+ if err != nil {
+ return nil, fmt.Errorf("create tlv stream: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := tlvStream.Encode(&buf); err != nil {
+ return nil, fmt.Errorf("encode tlv: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// Decode deserializes TLV bytes into an envelope. Unknown TLV types are
+// silently ignored for forward compatibility.
+func Decode(b []byte) (*Data, error) {
+ var (
+ data Data
+ offerHash []byte
+ payerID []byte
+ payerNote []byte
+ )
+
+ tlvStream, err := tlv.NewStream(
+ tlv.MakePrimitiveRecord(typeOfferHash, &offerHash),
+ tlv.MakePrimitiveRecord(typePayerID, &payerID),
+ tu64(typeCreatedAt, &data.CreatedAt),
+ tu64(typeAmount, &data.Amount),
+ tu64(typeQuantity, &data.Quantity),
+ tlv.MakePrimitiveRecord(typePayerNote, &payerNote),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("create tlv stream: %w", err)
+ }
+
+ parsedTypes, err := tlvStream.DecodeWithParsedTypes(bytes.NewReader(b))
+ if err != nil {
+ return nil, fmt.Errorf("decode tlv: %w", err)
+ }
+
+ required := []struct {
+ typ tlv.Type
+ name string
+ }{
+ {typePayerID, "payer_id"},
+ {typeCreatedAt, "created_at"},
+ {typeAmount, "amount"},
+ }
+ for _, r := range required {
+ if _, ok := parsedTypes[r.typ]; !ok {
+ return nil, fmt.Errorf("missing %s (type %d)", r.name,
+ r.typ)
+ }
+ }
+
+ if _, ok := parsedTypes[typeOfferHash]; ok {
+ if len(offerHash) != 32 {
+ return nil, fmt.Errorf("invalid offer_hash length: %d",
+ len(offerHash))
+ }
+ data.OfferHash = fn.Some([32]byte(offerHash))
+ }
+
+ if len(payerID) != len(data.PayerID) {
+ return nil, fmt.Errorf("invalid payer_id length: %d",
+ len(payerID))
+ }
+ copy(data.PayerID[:], payerID)
+
+ if len(payerNote) > MaxPayerNoteLen {
+ return nil, fmt.Errorf("%w: %d bytes", ErrPayerNoteTooLong,
+ len(payerNote))
+ }
+ if len(payerNote) > 0 {
+ data.PayerNote = payerNote
+ }
+
+ return &data, nil
+}
### bolt12handler/envelope/envelope_test.go
@@ -0,0 +1,232 @@
+package envelope
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+ "pgregory.net/rapid"
+)
+
+// TestRoundTrip verifies that decoding an encoded envelope returns the same
+// data for any field values, with and without the optional records.
+func TestRoundTrip(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(t *rapid.T) {
+ data := &Data{
+ PayerID: [33]byte(rapid.SliceOfN(
+ rapid.Byte(), 33, 33,
+ ).Draw(t, "payerID")),
+ CreatedAt: rapid.Uint64().Draw(t, "createdAt"),
+ Amount: rapid.Uint64().Draw(t, "amount"),
+ Quantity: rapid.OneOf(
+ rapid.Just(uint64(0)), rapid.Uint64(),
+ ).Draw(t, "quantity"),
+ }
+ if rapid.Bool().Draw(t, "withOfferHash") {
+ data.OfferHash = fn.Some([32]byte(rapid.SliceOfN(
+ rapid.Byte(), 32, 32,
+ ).Draw(t, "offerHash")))
+ }
+ note := rapid.SliceOfN(
+ rapid.Byte(), 0, MaxPayerNoteLen,
+ ).Draw(t, "payerNote")
+ if len(note) > 0 {
+ data.PayerNote = note
+ }
+
+ encoded, err := Encode(data)
+ require.NoError(t, err)
+
+ decoded, err := Decode(encoded)
+ require.NoError(t, err)
+ require.Equal(t, data, decoded)
+ })
+}
+
+// TestOptionalRecords verifies that a zero quantity, an empty payer note and a
+// missing offer hash are left out of the encoding.
+func TestOptionalRecords(t *testing.T) {
+ t.Parallel()
+
+ data := &Data{CreatedAt: 1, Amount: 2}
+ bare, err := Encode(data)
+ require.NoError(t, err)
+
+ // The payer id, created_at and amount records only.
+ require.Len(t, bare, 2+33+2+1+2+1)
+
+ data.Quantity = 1
+ data.PayerNote = []byte("hi")
+ data.OfferHash = fn.Some([32]byte{1})
+ full, err := Encode(data)
+ require.NoError(t, err)
+ require.Len(t, full, len(bare)+(2+32)+(2+1)+(2+2))
+
+ decoded, err := Decode(bare)
+ require.NoError(t, err)
+ require.True(t, decoded.OfferHash.IsNone())
+ require.Nil(t, decoded.PayerNote)
+ require.Zero(t, decoded.Quantity)
+}
+
+// TestPayerNoteCap verifies that Encode refuses a payer note over the cap, so
+// no caller can make an envelope over the onion budget.
+func TestPayerNoteCap(t *testing.T) {
+ t.Parallel()
+
+ data := &Data{
+ CreatedAt: 1,
+ Amount: 2,
+ PayerNote: bytes.Repeat([]byte{'a'}, MaxPayerNoteLen),
+ }
+ _, err := Encode(data)
+ require.NoError(t, err)
+
+ data.PayerNote = append(data.PayerNote, 'a')
+ _, err = Encode(data)
+ require.ErrorIs(t, err, ErrPayerNoteTooLong)
+}
+
+// TestSize pins the size of an invoice envelope with large field values,
+// because padding repeats it on every blinded hop.
+func TestSize(t *testing.T) {
+ t.Parallel()
+
+ // An amount just below 2^40 msat is about 11 BTC.
+ encoded, err := Encode(&Data{
+ OfferHash: fn.Some([32]byte{}),
+ CreatedAt: 1_800_000_000,
+ Amount: 1<<40 - 1,
+ Quantity: 100,
+ PayerNote: bytes.Repeat([]byte{'a'}, MaxPayerNoteLen),
+ })
+ require.NoError(t, err)
+ require.LessOrEqual(t, len(encoded), 151)
+}
+
+// encodeRecords builds raw envelope bytes from the given records. It can build
+// envelopes that Encode cannot produce, such as ones with a missing or short
+// field.
+func encodeRecords(t *testing.T, records ...tlv.Record) []byte {
+ t.Helper()
+
+ stream, err := tlv.NewStream(records...)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ require.NoError(t, stream.Encode(&buf))
+
+ return buf.Bytes()
+}
+
+// TestDecodeErrors verifies that decoding refuses data with a missing required
+// field, a field of the wrong length or a broken stream.
+func TestDecodeErrors(t *testing.T) {
+ t.Parallel()
+
+ var (
+ offerHash = make([]byte, 32)
+ payerID = make([]byte, 33)
+ short = make([]byte, 31)
+ longNote = make([]byte, MaxPayerNoteLen+1)
+ createdAt = uint64(1)
+ amount = uint64(1)
+ )
+ record := tlv.MakePrimitiveRecord
+ tu64 := func(typ tlv.Type, val *uint64) tlv.Record {
+ return tlv.MakeDynamicRecord(
+ typ, val, func() uint64 {
+ return tlv.SizeTUint64(*val)
+ }, tlv.ETUint64, tlv.DTUint64,
+ )
+ }
+
+ tests := []struct {
+ name string
+ data []byte
+ wantErr string
+ }{
+ {
+ name: "empty",
+ wantErr: "missing payer_id",
+ },
+ {
+ name: "missing payer id",
+ data: encodeRecords(
+ t,
+ record(typeOfferHash, &offerHash),
+ tu64(typeCreatedAt, &createdAt),
+ tu64(typeAmount, &amount),
+ ),
+ wantErr: "missing payer_id",
+ },
+ {
+ name: "missing created at",
+ data: encodeRecords(
+ t,
+ record(typePayerID, &payerID),
+ tu64(typeAmount, &amount),
+ ),
+ wantErr: "missing created_at",
+ },
+ {
+ name: "missing amount",
+ data: encodeRecords(
+ t,
+ record(typePayerID, &payerID),
+ tu64(typeCreatedAt, &createdAt),
+ ),
+ wantErr: "missing amount",
+ },
+ {
+ name: "short offer hash",
+ data: encodeRecords(
+ t,
+ record(typeOfferHash, &short),
+ record(typePayerID, &payerID),
+ tu64(typeCreatedAt, &createdAt),
+ tu64(typeAmount, &amount),
+ ),
+ wantErr: "invalid offer_hash length",
+ },
+ {
+ name: "short payer id",
+ data: encodeRecords(
+ t,
+ record(typePayerID, &short),
+ tu64(typeCreatedAt, &createdAt),
+ tu64(typeAmount, &amount),
+ ),
+ wantErr: "invalid payer_id length",
+ },
+ {
+ name: "long payer note",
+ data: encodeRecords(
+ t,
+ record(typePayerID, &payerID),
+ tu64(typeCreatedAt, &createdAt),
+ tu64(typeAmount, &amount),
+ record(typePayerNote, &longNote),
+ ),
+ wantErr: "payer note too long",
+ },
+ {
+ name: "truncated stream",
+ data: []byte{0x02, 0x21, 0x01},
+ wantErr: "decode tlv",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ _, err := Decode(tc.data)
+ require.ErrorContains(t, err, tc.wantErr)
+ })
+ }
+}
### bolt12handler/envelope_test.go
@@ -0,0 +1,27 @@
+package bolt12handler
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "github.com/stretchr/testify/require"
+)
+
+// TestEnvelopeBinding verifies that a change of any envelope byte changes the
+// binding.
+func TestEnvelopeBinding(t *testing.T) {
+ t.Parallel()
+
+ encoded, err := envelope.Encode(&envelope.Data{
+ CreatedAt: 1, Amount: 2, Quantity: 3,
+ })
+ require.NoError(t, err)
+
+ binding := EnvelopeBinding(encoded)
+ for i := range encoded {
+ changed := bytes.Clone(encoded)
+ changed[i] ^= 1
+ require.NotEqual(t, binding, EnvelopeBinding(changed))
+ }
+}
### bolt12handler/generate.go
@@ -1,16 +1,18 @@
package bolt12handler
import (
- "crypto/rand"
"errors"
"fmt"
"math/bits"
"time"
+ "unicode/utf8"
"github.com/btcsuite/btcd/btcec/v2"
sphinx "github.com/lightningnetwork/lightning-onion"
"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/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
@@ -30,6 +32,11 @@ var (
errOfferWithoutIssuerID = errors.New("offer without " +
"offer_issuer_id is not supported")
+ // errMissingPayerID is returned for an invoice request without
+ // invreq_payer_id. The invoice envelope must carry the payer id.
+ errMissingPayerID = errors.New("invoice request has no " +
+ "invreq_payer_id")
+
// errCurrencyConversion is returned when the invoice amount needs a
// conversion from offer_currency to msat. The handler has no exchange
// rate.
@@ -46,6 +53,10 @@ type InvoiceConfig struct {
// invoice uses a single-hop blinded path to this node.
PathBuilder PaymentPathBuilder
+ // PathIDKey computes the payment path id and the preimage of the
+ // invoice.
+ PathIDKey PathIDKey
+
// Clock provides the invoice creation time.
Clock clock.Clock
@@ -64,6 +75,9 @@ func (c *InvoiceConfig) Validate() error {
case c.Clock == nil:
return errors.New("invoice config has no clock")
+
+ case c.PathIDKey == PathIDKey{}:
+ return errors.New("invoice config has no path id key")
}
return nil
@@ -80,13 +94,13 @@ type PaymentPathResult struct {
}
// PaymentPathBuilder constructs blinded payment paths for a BOLT 12 invoice.
-// The builder receives the invoice amount and a path_id to embed in the final
-// hop's encrypted data.
+// The builder receives the invoice amount, a path_id, and an optional invoice
+// envelope to embed in the final hop's encrypted data.
type PaymentPathBuilder interface {
// BuildPaymentPaths returns blinded payment paths suitable for
// embedding in a BOLT 12 invoice.
- BuildPaymentPaths(amountMsat uint64,
- pathID []byte) (*PaymentPathResult, error)
+ BuildPaymentPaths(amountMsat uint64, pathID []byte,
+ invoiceEnvelope []byte) (*PaymentPathResult, error)
}
// InvoiceResult contains the output of invoice generation.
@@ -110,10 +124,11 @@ type InvoiceResult struct {
// GenerateInvoice creates a BOLT 12 invoice in response to a validated invoice
// request. The invoice mirrors the request, and the node identity key signs
-// it. If cfg.PathBuilder is nil or fails, a single-hop blinded path is used as
-// fallback.
-func GenerateInvoice(cfg *InvoiceConfig,
- ir *bolt12.InvoiceRequest) (*InvoiceResult, error) {
+// it. The invoice envelope records offerHash, the hash of the offer that the
+// request answers. If cfg.PathBuilder is nil or fails, a single-hop blinded
+// path is used as fallback.
+func GenerateInvoice(cfg *InvoiceConfig, ir *bolt12.InvoiceRequest,
+ offerHash [32]byte) (*InvoiceResult, error) {
if err := cfg.Validate(); err != nil {
return nil, err
@@ -129,26 +144,60 @@ func GenerateInvoice(cfg *InvoiceConfig,
return nil, errOfferWithoutIssuerID
}
- var preimage lntypes.Preimage
- if _, err := rand.Read(preimage[:]); err != nil {
- return nil, fmt.Errorf("generate preimage: %w", err)
+ payerID, err := ir.InvreqPayerID.ValOpt().UnwrapOrErr(
+ errMissingPayerID,
+ )
+ if err != nil {
+ return nil, err
}
- paymentHash := preimage.Hash()
- var pathID [32]byte
- if _, err := rand.Read(pathID[:]); err != nil {
- return nil, fmt.Errorf("generate path_id: %w", err)
- }
+ // The envelope carries our copy of the payer note on every blinded
+ // hop, so it keeps only a capped prefix. The invoice that the payer
+ // gets mirrors the full note, but the node rebuilds its invoice from
+ // the envelope, so the rest of a longer note is lost at settlement.
+ //
+ // TODO: Add a policy that answers a note over the cap with an
+ // invoice_error once the handler sends invoice errors.
+ payerNote := truncatePayerNote(
+ ir.InvreqPayerNote.ValOpt().UnwrapOr(nil),
+ )
+ // The envelope carries the invoice state for stateless BOLT 12
+ // settlement. The envelope and the invoice share the creation time.
invoiceAmount, err := computeInvoiceAmount(ir)
if err != nil {
return nil, err
}
+ now := cfg.Clock.Now()
+ invoiceEnvelope, err := envelope.Encode(&envelope.Data{
+ OfferHash: fn.Some(offerHash),
+ PayerID: [33]byte(payerID.SerializeCompressed()),
+ CreatedAt: uint64(now.Unix()),
+ Amount: invoiceAmount,
+ Quantity: uint64(ir.InvreqQuantity.ValOpt().UnwrapOr(0)),
+ PayerNote: payerNote,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("encode envelope: %w", err)
+ }
+
+ // The path id authenticates the envelope and gives the preimage, so
+ // the node stores nothing until the payment arrives.
+ binding := EnvelopeBinding(invoiceEnvelope)
+ pathID, err := cfg.PathIDKey.newPaymentPathID(binding)
+ if err != nil {
+ return nil, err
+ }
+ preimage, ok := cfg.PathIDKey.checkPaymentPathID(pathID[:], binding)
+ if !ok {
+ return nil, errors.New("new payment path id does not verify")
+ }
+ paymentHash := preimage.Hash()
var pathResult *PaymentPathResult
if cfg.PathBuilder != nil {
pathResult, err = cfg.PathBuilder.BuildPaymentPaths(
- invoiceAmount, pathID[:],
+ invoiceAmount, pathID[:], invoiceEnvelope,
)
switch {
case err != nil:
@@ -175,7 +224,7 @@ func GenerateInvoice(cfg *InvoiceConfig,
// instead of using the single-hop path.
if pathResult == nil {
path, pathErr := buildSingleHopBlindedPath(
- cfg.Signer.NodePubKey(), pathID[:],
+ cfg.Signer.NodePubKey(), pathID[:], invoiceEnvelope,
)
if pathErr != nil {
return nil, fmt.Errorf("build single-hop path: %w",
@@ -207,7 +256,7 @@ func GenerateInvoice(cfg *InvoiceConfig,
inv := buildInvoiceFromRequest(
ir, cfg.Signer.NodePubKey(), paymentHash, pathResult,
- invoiceAmount, cfg.Clock.Now(),
+ invoiceAmount, now,
)
signedInv, encoded, err := signAndEncode(inv, cfg.Signer)
@@ -337,18 +386,23 @@ func expectedOfferAmount(offerAmount, quantity uint64) (uint64, error) {
// buildSingleHopBlindedPath creates a single-hop blinded payment path for the
// direct-peer case. The introduction node is the receiver itself, and the
-// single hop's encrypted data carries the path_id for invoice lookup.
+// single hop's encrypted data carries the path_id for invoice lookup and the
+// invoice envelope for settlement.
func buildSingleHopBlindedPath(nodePubKey *btcec.PublicKey,
- pathID []byte) (lnwire.BlindedPath, error) {
+ pathID []byte,
+ invoiceEnvelope []byte) (lnwire.BlindedPath, error) {
sessionKey, err := btcec.NewPrivateKey()
if err != nil {
return lnwire.BlindedPath{}, fmt.Errorf("generate session "+
"key: %w", err)
}
- // The path_id lets the receiver match the incoming HTLC to the invoice.
- routeData := record.NewFinalHopBlindedRouteData(nil, pathID)
+ // The path_id lets the receiver match the incoming HTLC, and the
+ // optional envelope lets it reconstruct the invoice.
+ routeData := record.NewFinalHopBlindedRouteData(
+ nil, pathID, invoiceEnvelope,
+ )
plainText, err := record.EncodeBlindedRouteData(routeData)
if err != nil {
return lnwire.BlindedPath{}, fmt.Errorf("encode route data: %w",
@@ -418,3 +472,19 @@ func signAndEncode(inv *bolt12.Invoice, signer NodeSigner) (*bolt12.Invoice,
return inv, encoded, nil
}
+
+// truncatePayerNote cuts the payer note to envelope.MaxPayerNoteLen bytes.
+func truncatePayerNote(note []byte) []byte {
+ if len(note) <= envelope.MaxPayerNoteLen {
+ return note
+ }
+
+ // The note is a UTF-8 string, so the cut moves back to the start of a
+ // rune and never splits one.
+ cut := envelope.MaxPayerNoteLen
+ for cut > 0 && !utf8.RuneStart(note[cut]) {
+ cut--
+ }
+
+ return note[:cut]
+}
### bolt12handler/generate_test.go
@@ -1,15 +1,22 @@
package bolt12handler
import (
+ "bytes"
"errors"
+ "strings"
"testing"
"time"
+ "unicode/utf8"
"github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
"github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/record"
"github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
@@ -29,7 +36,9 @@ func TestGenerateInvoice_HappyPath(t *testing.T) {
ir := testInvoiceRequest(t, offer, payerKey, 10000)
- result, err := GenerateInvoice(testInvoiceConfig(nodeKey), ir)
+ result, err := GenerateInvoice(
+ testInvoiceConfig(nodeKey), ir, [32]byte{},
+ )
require.NoError(t, err)
require.NotEmpty(t, result.Encoded)
@@ -174,7 +183,7 @@ func TestGenerateInvoiceAmount(t *testing.T) {
})
result, err := GenerateInvoice(
- testInvoiceConfig(nodeKey), ir,
+ testInvoiceConfig(nodeKey), ir, [32]byte{},
)
if tc.wantErr != nil {
require.ErrorIs(t, err, tc.wantErr)
@@ -209,7 +218,9 @@ func TestGenerateInvoice_BlindedPath(t *testing.T) {
ir := testInvoiceRequest(t, offer, payerKey, 10000)
- result, err := GenerateInvoice(testInvoiceConfig(nodeKey), ir)
+ result, err := GenerateInvoice(
+ testInvoiceConfig(nodeKey), ir, [32]byte{},
+ )
require.NoError(t, err)
decoded, err := bolt12.DecodeInvoiceString(
@@ -234,16 +245,18 @@ type fakePathBuilder struct {
result *PaymentPathResult
err error
- gotAmount uint64
- gotPathID []byte
+ gotAmount uint64
+ gotPathID []byte
+ gotEnvelope []byte
}
// BuildPaymentPaths returns the fixed result and error.
-func (f *fakePathBuilder) BuildPaymentPaths(amountMsat uint64,
- pathID []byte) (*PaymentPathResult, error) {
+func (f *fakePathBuilder) BuildPaymentPaths(amountMsat uint64, pathID []byte,
+ invoiceEnvelope []byte) (*PaymentPathResult, error) {
f.gotAmount = amountMsat
f.gotPathID = pathID
+ f.gotEnvelope = invoiceEnvelope
return f.result, f.err
}
@@ -301,7 +314,7 @@ func TestGenerateInvoicePathBuilder(t *testing.T) {
ir := testInvoiceRequest(t, offer, payerKey, 0)
path, err := buildSingleHopBlindedPath(
- nodeKey.PubKey(), []byte{1},
+ nodeKey.PubKey(), []byte{1}, nil,
)
require.NoError(t, err)
@@ -322,7 +335,7 @@ func TestGenerateInvoicePathBuilder(t *testing.T) {
cfg := testInvoiceConfig(nodeKey)
cfg.PathBuilder = builder
- result, err := GenerateInvoice(cfg, ir)
+ result, err := GenerateInvoice(cfg, ir, [32]byte{})
require.NoError(t, err)
require.EqualValues(t, 10000, builder.gotAmount)
@@ -381,7 +394,7 @@ func TestGenerateInvoiceIssuerID(t *testing.T) {
offer := testOffer(t, nodeKey, 10000)
path, err := buildSingleHopBlindedPath(
- nodeKey.PubKey(), []byte{1},
+ nodeKey.PubKey(), []byte{1}, nil,
)
require.NoError(t, err)
@@ -407,7 +420,7 @@ func TestGenerateInvoiceIssuerID(t *testing.T) {
ir := testInvoiceRequest(t, offer, payerKey, 0)
result, err := GenerateInvoice(
- testInvoiceConfig(nodeKey), ir,
+ testInvoiceConfig(nodeKey), ir, [32]byte{},
)
if tc.wantErr != nil {
require.ErrorIs(t, err, tc.wantErr)
@@ -422,3 +435,200 @@ func TestGenerateInvoiceIssuerID(t *testing.T) {
})
}
}
+
+// TestGenerateInvoiceMissingPayerID verifies that an invoice request without
+// invreq_payer_id gets no invoice, so no envelope carries an empty payer id.
+func TestGenerateInvoiceMissingPayerID(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+ ir.InvreqPayerID = tlv.OptionalRecordT[
+ tlv.TlvType88, *btcec.PublicKey,
+ ]{}
+
+ _, err := GenerateInvoice(testInvoiceConfig(nodeKey), ir, [32]byte{})
+ require.ErrorIs(t, err, errMissingPayerID)
+}
+
+// TestGenerateInvoiceEnvelope verifies that the path builder gets an envelope
+// with the invoice state.
+func TestGenerateInvoiceEnvelope(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+ setQuantityMax(offer, 10)
+
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ ir := testInvoiceRequest(t, offer, payerKey, 30000)
+ ir.InvreqQuantity = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType86, bolt12.TUint64]{Val: 3},
+ )
+
+ builder := &fakePathBuilder{err: errors.New("no route")}
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathBuilder = builder
+ offerHash := [32]byte{0x09}
+
+ result, err := GenerateInvoice(cfg, ir, offerHash)
+ require.NoError(t, err)
+
+ data, err := envelope.Decode(builder.gotEnvelope)
+ require.NoError(t, err)
+
+ createdAt := result.Invoice.InvoiceCreatedAt.UnwrapOrFailV(t)
+ require.Equal(t, &envelope.Data{
+ OfferHash: fn.Some(offerHash),
+ PayerID: [33]byte(payerKey.PubKey().SerializeCompressed()),
+ CreatedAt: uint64(createdAt),
+ Amount: 30000,
+ Quantity: 3,
+ }, data)
+}
+
+// TestGenerateInvoicePathID verifies that the path id of the invoice
+// authenticates its envelope and gives the preimage of the invoice.
+func TestGenerateInvoicePathID(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+
+ builder := &fakePathBuilder{err: errors.New("no route")}
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathBuilder = builder
+
+ result, err := GenerateInvoice(cfg, ir, [32]byte{})
+ require.NoError(t, err)
+ require.Equal(t, result.PathID[:], builder.gotPathID)
+
+ preimage, ok := cfg.PathIDKey.checkPaymentPathID(
+ builder.gotPathID, EnvelopeBinding(builder.gotEnvelope),
+ )
+ require.True(t, ok)
+ require.Equal(t, result.Preimage, preimage)
+ require.Equal(t, preimage.Hash(), result.PaymentHash)
+}
+
+// TestGenerateInvoiceFallbackEnvelope verifies that the final hop of the
+// single-hop fallback path carries the envelope.
+func TestGenerateInvoiceFallbackEnvelope(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+
+ builder := &fakePathBuilder{err: errors.New("no route")}
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathBuilder = builder
+
+ result, err := GenerateInvoice(cfg, ir, [32]byte{})
+ require.NoError(t, err)
+
+ path := result.Invoice.InvoicePaths.UnwrapOrFailV(t).Paths[0]
+ router := sphinx.NewRouter(
+ &keychain.PrivKeyECDH{PrivKey: nodeKey}, nil,
+ )
+ plainText, err := router.DecryptBlindedHopData(
+ path.BlindingPoint, path.Hops[0].EncryptedData,
+ )
+ require.NoError(t, err)
+
+ routeData, err := record.DecodeBlindedRouteData(
+ bytes.NewReader(plainText),
+ )
+ require.NoError(t, err)
+ require.Equal(
+ t, builder.gotEnvelope,
+ routeData.InvoiceEnvelope.UnwrapOrFailV(t),
+ )
+}
+
+// TestGenerateInvoiceZeroPathIDKey verifies that GenerateInvoice refuses a
+// config without a path id key.
+func TestGenerateInvoiceZeroPathIDKey(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathIDKey = PathIDKey{}
+
+ _, err := GenerateInvoice(cfg, ir, [32]byte{})
+ require.ErrorContains(t, err, "no path id key")
+}
+
+// TestGenerateInvoicePayerNote verifies that the envelope carries the payer
+// note cut to the cap, and that the invoice mirrors the full note.
+func TestGenerateInvoicePayerNote(t *testing.T) {
+ t.Parallel()
+
+ nodeKey := testKey(t)
+ offer := testOffer(t, nodeKey, 10000)
+ payerKey, _ := btcec.PrivKeyFromBytes([]byte{0xFF})
+ atCap := strings.Repeat("a", envelope.MaxPayerNoteLen)
+
+ tests := []struct {
+ name string
+ note string
+ wantEnvelope string
+ }{
+ {
+ name: "note at the cap",
+ note: atCap,
+ wantEnvelope: atCap,
+ },
+ {
+ name: "note over the cap",
+ note: atCap + "b",
+ wantEnvelope: atCap,
+ },
+ {
+ // The two-byte rune would end at byte 65, so the cut
+ // leaves it out.
+ name: "rune across the cap",
+ note: atCap[1:] + "\u00e9",
+ wantEnvelope: atCap[1:],
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ ir := testInvoiceRequest(t, offer, payerKey, 10000)
+ ir.InvreqPayerNote = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType89](
+ []byte(tc.note),
+ ),
+ )
+
+ builder := &fakePathBuilder{err: errors.New("no route")}
+ cfg := testInvoiceConfig(nodeKey)
+ cfg.PathBuilder = builder
+
+ result, err := GenerateInvoice(cfg, ir, [32]byte{})
+ require.NoError(t, err)
+
+ data, err := envelope.Decode(builder.gotEnvelope)
+ require.NoError(t, err)
+ envNote := string(data.PayerNote)
+ require.Equal(t, tc.wantEnvelope, envNote)
+ require.True(t, utf8.ValidString(envNote))
+
+ invNote := result.Invoice.InvreqPayerNote.UnwrapOrFailV
+ require.Equal(t, tc.note, string(invNote(t)))
+ })
+ }
+}
### bolt12handler/handler.go
@@ -43,6 +43,7 @@ type Handler struct {
notifier InvoiceNotifier
replier OnionReplier
signer NodeSigner
+ pathIDKey PathIDKey
paymentPathBuilder PaymentPathBuilder
clock clock.Clock
@@ -78,11 +79,12 @@ 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. The path builder can be nil, and the handler then uses a single-hop
-// blinded path. The final CLTV delta must be at least routing.MinCLTVDelta,
-// and it must leave room for routing.BlockPadding in a uint16.
+// 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,
+ replier OnionReplier, signer NodeSigner, pathIDKey PathIDKey,
paymentPathBuilder PaymentPathBuilder, clk clock.Clock,
activeChain [32]byte, finalCLTVDelta uint16) (*Handler, error) {
@@ -99,6 +101,9 @@ func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
case signer == nil:
return nil, errors.New("handler has no signer")
+ case pathIDKey == PathIDKey{}:
+ return nil, errors.New("handler has no path id key")
+
case clk == nil:
return nil, errors.New("handler has no clock")
}
@@ -117,6 +122,7 @@ func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
notifier: notifier,
replier: replier,
signer: signer,
+ pathIDKey: pathIDKey,
paymentPathBuilder: paymentPathBuilder,
clock: clk,
activeChain: activeChain,
@@ -167,10 +173,11 @@ func (h *Handler) HandleInvoiceRequest(ctx context.Context, invreqBytes []byte,
result, err := GenerateInvoice(&InvoiceConfig{
Signer: h.signer,
+ PathIDKey: h.pathIDKey,
PathBuilder: h.paymentPathBuilder,
Clock: h.clock,
FinalCLTVDelta: h.finalCLTVDelta,
- }, ir)
+ }, ir, offer.Hash)
if err != nil {
return fmt.Errorf("generate invoice: %w", err)
}
### bolt12handler/handler_test.go
@@ -10,6 +10,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
sphinx "github.com/lightningnetwork/lightning-onion"
"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"
@@ -38,7 +39,8 @@ func TestHandleInvoiceRequest_FullFlow(t *testing.T) {
handler, err := NewHandler(
store, notifier, replier, newPrivKeySigner(nodeKey),
- builder, clock.NewDefaultClock(), testChainHash(),
+ testPathIDKey(nodeKey), builder, clock.NewDefaultClock(),
+ testChainHash(),
testFinalCLTVDelta,
)
require.NoError(t, err)
@@ -118,6 +120,12 @@ func TestHandleInvoiceRequest_FullFlow(t *testing.T) {
payInfos[0].CltvExpiryDelta,
)
require.Equal(t, builder.gotPathID, inv.Terms.PaymentAddr[:])
+
+ // 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)
+
require.Equal(t,
payerKey.PubKey().SerializeCompressed(), inv.InvreqPayerID,
)
@@ -314,7 +322,8 @@ func TestHandleInvoiceRequestErrors(t *testing.T) {
handler, err := NewHandler(
store, notifier,
&mockReplier{err: tc.replyErr},
- newPrivKeySigner(nodeKey), nil,
+ newPrivKeySigner(nodeKey),
+ testPathIDKey(nodeKey), nil,
clock.NewTestClock(now), testChainHash(),
testFinalCLTVDelta,
)
@@ -377,3 +386,16 @@ func TestHandleInvoiceRequestErrors(t *testing.T) {
})
}
}
+
+// TestNewHandlerZeroPathIDKey verifies that a handler refuses the zero path id
+// key, because anybody can compute path ids under it.
+func TestNewHandlerZeroPathIDKey(t *testing.T) {
+ t.Parallel()
+
+ _, err := NewHandler(
+ newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newPrivKeySigner(testKey(t)), PathIDKey{}, nil,
+ clock.NewDefaultClock(), testChainHash(), testFinalCLTVDelta,
+ )
+ require.ErrorContains(t, err, "no path id key")
+}
### bolt12handler/helpers_test.go
@@ -10,6 +10,7 @@ import (
"github.com/btcsuite/btcd/chainhash/v2"
"github.com/lightningnetwork/lnd/bolt12"
"github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
@@ -33,11 +34,23 @@ const testFinalCLTVDelta = 42
func testInvoiceConfig(key *btcec.PrivateKey) *InvoiceConfig {
return &InvoiceConfig{
Signer: newPrivKeySigner(key),
+ PathIDKey: testPathIDKey(key),
Clock: clock.NewTestClock(testNow),
FinalCLTVDelta: testFinalCLTVDelta,
}
}
+// testPathIDKey returns the path id key of the node with the given key. It
+// panics when the derivation fails.
+func testPathIDKey(key *btcec.PrivateKey) PathIDKey {
+ pathIDKey, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: key})
+ if err != nil {
+ panic(err)
+ }
+
+ return pathIDKey
+}
+
// testKey returns a deterministic private key for testing.
func testKey(t *testing.T) *btcec.PrivateKey {
t.Helper()
### bolt12handler/node_secret.go
@@ -0,0 +1,45 @@
+package bolt12handler
+
+import (
+ "encoding/binary"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr"
+ "github.com/btcsuite/btcd/chainhash/v2"
+)
+
+// nodeSecretPointTag tags the hashes that the node secret point is derived
+// from. It is a public domain separator, not a credential.
+//
+//nolint:gosec
+const nodeSecretPointTag = "bolt12/node-secret-point"
+
+// nodeSecretPoint is a fixed point with no known private key. Its ECDH with the
+// node key is a secret that only the node can compute. The secrets of this
+// package are tagged hashes of it.
+var nodeSecretPoint = deriveNodeSecretPoint()
+
+// deriveNodeSecretPoint returns the first point whose x coordinate is the
+// tagged hash of a counter. Nobody knows the private key of a point that a
+// hash selects.
+func deriveNodeSecretPoint() *btcec.PublicKey {
+ var counter [4]byte
+ for i := uint32(0); ; i++ {
+ binary.BigEndian.PutUint32(counter[:], i)
+ x := chainhash.TaggedHash(
+ []byte(nodeSecretPointTag), counter[:],
+ )
+
+ point, err := schnorr.ParsePubKey(x[:])
+ if err == nil {
+ return point
+ }
+ }
+}
+
+// ECDHer computes the ECDH of the node key and a public key. It returns the
+// SHA256 of the shared point, as keychain.SingleKeyECDH does, so the node key
+// can stay in a remote signer.
+type ECDHer interface {
+ ECDH(pub *btcec.PublicKey) ([32]byte, error)
+}
### bolt12handler/path_id.go
@@ -0,0 +1,186 @@
+package bolt12handler
+
+import (
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/lntypes"
+)
+
+const (
+ // pathIDKeyTag tags the hash of the node secret that path ids are
+ // computed with.
+ pathIDKeyTag = "bolt12/path-id"
+
+ // pathIDHalfLen is the byte length of each half of a path id.
+ pathIDHalfLen = 16
+
+ // pathIDLen is the byte length of a path id that this node creates.
+ pathIDLen = 2 * pathIDHalfLen
+)
+
+// PathIDContext names the kind of blinded path that a path id belongs to. A
+// path id of one kind never verifies as a path id of another kind.
+type PathIDContext string
+
+const (
+ // PathIDOffer marks the offer_paths of an offer. The binding is the
+ // offer hash without offer_paths.
+ PathIDOffer PathIDContext = "offer"
+
+ // PathIDReply marks the reply path of an invoice_request. The binding
+ // is the invoice request hash.
+ PathIDReply PathIDContext = "reply"
+
+ // pathIDPayment marks the payment paths of an invoice. The binding is
+ // the hash of the invoice envelope. Only the payment path id methods
+ // use it.
+ pathIDPayment PathIDContext = "payment"
+)
+
+// PathIDKey computes and checks the path ids that this node puts into the
+// final hop of the blinded paths that lead to it. A path id is a nonce and a
+// tag. The nonce comes from the message that the path belongs to. The tag
+// comes from the nonce. The tag alone shows that this node made the path. The
+// nonce shows which message the path belongs to. The node stores nothing for
+// either check. A payment path id has a random nonce instead. See
+// newPaymentPathID.
+//
+// The zero key is public, so it is unusable. No check accepts a path id under
+// it, and newPaymentPathID returns an error for it. Only DerivePathIDKey gives
+// a real key.
+type PathIDKey struct {
+ key [32]byte
+}
+
+// isZero reports whether k is the zero key, under which anybody can compute
+// path ids.
+func (k PathIDKey) isZero() bool {
+ return k.key == [32]byte{}
+}
+
+// DerivePathIDKey derives the path id key from the node key. The node key
+// stays behind ecdh, so this works with a remote signer.
+func DerivePathIDKey(ecdh ECDHer) (PathIDKey, error) {
+ // signrpc.DeriveSharedKey returns the same value for this point, so a
+ // caller with signer:generate can derive the key and with it every
+ // BOLT 12 preimage that this node issues.
+ shared, err := ecdh.ECDH(nodeSecretPoint)
+ if err != nil {
+ return PathIDKey{}, fmt.Errorf("path id key ECDH: %w", err)
+ }
+
+ return PathIDKey{
+ key: *chainhash.TaggedHash([]byte(pathIDKeyTag), shared[:]),
+ }, nil
+}
+
+// New returns the path id for a path of kind ctx that belongs to the message
+// with the given binding.
+func (k PathIDKey) New(ctx PathIDContext, binding [32]byte) [pathIDLen]byte {
+ var id [pathIDLen]byte
+ copy(id[:pathIDHalfLen], k.mac('n', ctx, binding[:]))
+ copy(id[pathIDHalfLen:], k.mac('t', ctx, id[:pathIDHalfLen]))
+
+ return id
+}
+
+// isOurs reports whether id is a path id of kind ctx that this node made. It
+// needs no binding, so it answers for any path of that kind.
+func (k PathIDKey) isOurs(ctx PathIDContext, id []byte) bool {
+ if k.isZero() || len(id) != pathIDLen {
+ return false
+ }
+
+ tag := k.mac('t', ctx, id[:pathIDHalfLen])
+
+ return hmac.Equal(tag, id[pathIDHalfLen:])
+}
+
+// matches reports whether id is the path id of kind ctx that this node made
+// for the message with the given binding.
+func (k PathIDKey) matches(ctx PathIDContext, id []byte,
+ binding [32]byte) bool {
+
+ if k.isZero() {
+ return false
+ }
+
+ want := k.New(ctx, binding)
+
+ return hmac.Equal(want[:], id)
+}
+
+// newPaymentPathID returns a new path id for a blinded payment path. The final
+// hop of the path carries the invoice envelope with the given binding. It
+// returns an error for the zero key.
+//
+// The tag covers the random nonce and the binding. The nonce feeds the
+// preimage, and the path id is shown as the payment address. The nonce is
+// random, so two equal invoice requests get two different preimages. Offer and
+// reply paths derive their nonce from their message instead.
+func (k PathIDKey) newPaymentPathID(binding [32]byte) ([pathIDLen]byte,
+ error) {
+
+ var id [pathIDLen]byte
+ if k.isZero() {
+ return id, errors.New("zero path id key")
+ }
+
+ if _, err := rand.Read(id[:pathIDHalfLen]); err != nil {
+ return id, fmt.Errorf("payment path id nonce: %w", err)
+ }
+
+ tag := k.mac('t', pathIDPayment, paymentInput(id[:], binding))
+ copy(id[pathIDHalfLen:], tag)
+
+ return id, nil
+}
+
+// checkPaymentPathID reports whether id is a payment path id that this node
+// made for the given binding. Only then does it return the preimage of the
+// payment.
+func (k PathIDKey) checkPaymentPathID(id []byte,
+ binding [32]byte) (lntypes.Preimage, bool) {
+
+ if k.isZero() || len(id) != pathIDLen {
+ return lntypes.Preimage{}, false
+ }
+
+ input := paymentInput(id, binding)
+ tag := k.mac('t', pathIDPayment, input)
+ if !hmac.Equal(tag, id[pathIDHalfLen:]) {
+ return lntypes.Preimage{}, false
+ }
+
+ return lntypes.Preimage(k.sum('p', pathIDPayment, input)), true
+}
+
+// paymentInput returns the nonce of the payment path id followed by the
+// binding.
+func paymentInput(id []byte, binding [32]byte) []byte {
+ input := make([]byte, 0, pathIDHalfLen+len(binding))
+ input = append(input, id[:pathIDHalfLen]...)
+
+ return append(input, binding[:]...)
+}
+
+// mac returns the first half of the HMAC of the label, the context and data.
+func (k PathIDKey) mac(label byte, ctx PathIDContext, data []byte) []byte {
+ return k.sum(label, ctx, data)[:pathIDHalfLen]
+}
+
+// sum returns the HMAC of the label, the context and data. The context
+// carries its length, so two contexts never give the same input.
+func (k PathIDKey) sum(label byte, ctx PathIDContext, data []byte) []byte {
+ h := hmac.New(sha256.New, k.key[:])
+ h.Write([]byte{label, byte(len(ctx))})
+ h.Write([]byte(ctx))
+ h.Write(data)
+
+ return h.Sum(nil)
+}
### bolt12handler/path_id_test.go
@@ -0,0 +1,280 @@
+package bolt12handler
+
+import (
+ "encoding/hex"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/keychain"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/stretchr/testify/require"
+ "pgregory.net/rapid"
+)
+
+// TestPathIDVectors pins the path ids and the preimage of one node key. Offers
+// and invoices outlive a node restart and an upgrade, so a change in the key
+// derivation or the HMAC input breaks the paths and payments in flight.
+func TestPathIDVectors(t *testing.T) {
+ t.Parallel()
+
+ const (
+ offerID = "a154a15c8c4f5cf901d0b9e03622fb97" +
+ "758ed94a1fba1f42dcb1ffdb1a28503f"
+ replyID = "b559429c22ae07cdfe0a902b53406f39" +
+ "862128a729cb6ba19d072c87db58b0f8"
+ paymentID = "02000000000000000000000000000000" +
+ "7253c83b388302b9f9683d465c294cba"
+ preimage = "aeeaa2d57ab8850e3b60c84a0b8c9dff" +
+ "81d97c76fd847b6eb0853fcb319dbab3"
+ )
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ binding := [32]byte{1}
+
+ gotOffer := key.New(PathIDOffer, binding)
+ require.Equal(t, offerID, hex.EncodeToString(gotOffer[:]))
+
+ gotReply := key.New(PathIDReply, binding)
+ require.Equal(t, replyID, hex.EncodeToString(gotReply[:]))
+
+ id, err := hex.DecodeString(paymentID)
+ require.NoError(t, err)
+ gotPreimage, ok := key.checkPaymentPathID(id, binding)
+ require.True(t, ok)
+ require.Equal(t, preimage, hex.EncodeToString(gotPreimage[:]))
+}
+
+// TestPathIDContexts verifies that a path id of one kind never verifies as a
+// path id of another kind, for any binding.
+func TestPathIDContexts(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ contexts := []PathIDContext{PathIDOffer, PathIDReply}
+
+ rapid.Check(t, func(t *rapid.T) {
+ binding := [32]byte(rapid.SliceOfN(
+ rapid.Byte(), 32, 32,
+ ).Draw(t, "binding"))
+
+ for _, ctx := range contexts {
+ id := key.New(ctx, binding)
+ require.True(t, key.isOurs(ctx, id[:]))
+
+ requireOtherContextsReject(
+ t, key, contexts, ctx, id[:], binding,
+ )
+
+ _, ok := key.checkPaymentPathID(id[:], binding)
+ require.False(t, ok)
+ }
+
+ paymentID, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+ for _, ctx := range contexts {
+ require.False(t, key.isOurs(ctx, paymentID[:]))
+ require.False(
+ t, key.matches(ctx, paymentID[:], binding),
+ )
+ }
+ })
+}
+
+// requireOtherContextsReject asserts that every context in contexts except ctx
+// rejects the path id.
+func requireOtherContextsReject(t require.TestingT, key PathIDKey,
+ contexts []PathIDContext, ctx PathIDContext, id []byte,
+ binding [32]byte) {
+
+ for _, other := range contexts {
+ if other == ctx {
+ continue
+ }
+ require.False(t, key.isOurs(other, id))
+ require.False(t, key.matches(other, id, binding))
+ }
+}
+
+// TestPathIDIsOurs verifies that isOurs accepts every path id that this node
+// made for the kind, whatever its message, and nothing else.
+func TestPathIDIsOurs(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ id := key.New(PathIDOffer, [32]byte{1})
+ otherMessage := key.New(PathIDOffer, [32]byte{2})
+
+ otherNode, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ otherKey, err := DerivePathIDKey(
+ &keychain.PrivKeyECDH{PrivKey: otherNode},
+ )
+ require.NoError(t, err)
+ foreign := otherKey.New(PathIDOffer, [32]byte{1})
+
+ changed := id
+ changed[pathIDLen-1] ^= 1
+
+ tests := []struct {
+ name string
+ id []byte
+ want bool
+ }{
+ {name: "ours", id: id[:], want: true},
+ {name: "other message", id: otherMessage[:], want: true},
+ {name: "other node", id: foreign[:]},
+ {name: "changed tag", id: changed[:]},
+ {name: "short", id: id[:pathIDLen-1]},
+ {name: "none"},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ got := key.isOurs(PathIDOffer, tc.id)
+ require.Equal(t, tc.want, got)
+ })
+ }
+}
+
+// TestPathIDMatches verifies that a path id matches only the message it was
+// made for.
+func TestPathIDMatches(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ id := key.New(PathIDOffer, [32]byte{1})
+
+ require.True(t, key.matches(PathIDOffer, id[:], [32]byte{1}))
+ require.False(t, key.matches(PathIDOffer, id[:], [32]byte{2}))
+}
+
+// TestPaymentPathID verifies that a payment path id gives its preimage, and
+// that the path id does not show the preimage to the payer.
+func TestPaymentPathID(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ binding := [32]byte{1}
+
+ id, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+
+ preimage, ok := key.checkPaymentPathID(id[:], binding)
+ require.True(t, ok)
+ require.NotEqual(t, lntypes.Preimage{}, preimage)
+ require.NotContains(
+ t, hex.EncodeToString(preimage[:]),
+ hex.EncodeToString(id[pathIDHalfLen:]),
+ )
+}
+
+// TestCheckPaymentPathIDRejects verifies that a payment path id gives no
+// preimage when its nonce, its tag or the envelope binding changed.
+func TestCheckPaymentPathIDRejects(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ binding := [32]byte{1}
+
+ id, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+
+ changedBinding := binding
+ changedBinding[31] ^= 1
+ changedNonce := id
+ changedNonce[0] ^= 1
+ changedTag := id
+ changedTag[pathIDLen-1] ^= 1
+
+ tests := []struct {
+ name string
+ id []byte
+ binding [32]byte
+ }{
+ {name: "changed binding", id: id[:], binding: changedBinding},
+ {name: "changed nonce", id: changedNonce[:], binding: binding},
+ {name: "changed tag", id: changedTag[:], binding: binding},
+ {name: "short", id: id[:pathIDLen-1], binding: binding},
+ {name: "none", binding: binding},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ _, ok := key.checkPaymentPathID(tc.id, tc.binding)
+ require.False(t, ok)
+ })
+ }
+}
+
+// TestPaymentPathIDUnique verifies that two invoices with one binding get two
+// path ids and two preimages.
+func TestPaymentPathIDUnique(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+ binding := [32]byte{1}
+
+ id, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+ otherID, err := key.newPaymentPathID(binding)
+ require.NoError(t, err)
+ require.NotEqual(t, id, otherID)
+
+ preimage, ok := key.checkPaymentPathID(id[:], binding)
+ require.True(t, ok)
+ otherPreimage, ok := key.checkPaymentPathID(otherID[:], binding)
+ require.True(t, ok)
+ require.NotEqual(t, preimage, otherPreimage)
+}
+
+// TestZeroPathIDKey verifies that the zero key is unusable. Anybody can compute
+// path ids under it, so no check may accept one.
+func TestZeroPathIDKey(t *testing.T) {
+ t.Parallel()
+
+ var zero PathIDKey
+ binding := [32]byte{1}
+
+ for _, ctx := range []PathIDContext{PathIDOffer, PathIDReply} {
+ id := zero.New(ctx, binding)
+ require.False(t, zero.isOurs(ctx, id[:]))
+ require.False(t, zero.matches(ctx, id[:], binding))
+ }
+
+ // A forger computes a payment path id under the zero key.
+ var forged [pathIDLen]byte
+ copy(
+ forged[pathIDHalfLen:],
+ zero.mac('t', pathIDPayment, paymentInput(forged[:], binding)),
+ )
+ _, ok := zero.checkPaymentPathID(forged[:], binding)
+ require.False(t, ok)
+
+ _, err := zero.newPaymentPathID(binding)
+ require.ErrorContains(t, err, "zero path id key")
+}
+
+// TestPathIDContextLengthPrefix verifies that the context length prefix keeps
+// inputs apart when the context and data split the same bytes differently.
+func TestPathIDContextLengthPrefix(t *testing.T) {
+ t.Parallel()
+
+ key, err := DerivePathIDKey(&keychain.PrivKeyECDH{PrivKey: testKey(t)})
+ require.NoError(t, err)
+
+ require.NotEqual(
+ t, key.sum('t', "ab", []byte("c")),
+ key.sum('t', "a", []byte("bc")),
+ )
+}
### config.go
@@ -2632,6 +2632,7 @@ func logWarningsForDeprecation(cfg Config) {
// with the development migrations.
var bolt12Migrations = []string{
"000017_offers",
+ "000018_bolt12_invoices",
}
// validateBolt12Offers makes sure that the node can run BOLT 12 offers. The
### config_builder.go
@@ -1360,6 +1360,7 @@ func (d *DefaultDatabaseBuilder) BuildDatabase(
sqlInvoiceDB := invoices.NewSQLStore(
invoiceExecutor, clock.NewDefaultClock(),
+ sqlInvoiceStoreOptions(d.cfg.ProtocolOptions)...,
)
dbs.InvoiceDB = sqlInvoiceDB
@@ -1523,6 +1524,18 @@ func (d *DefaultDatabaseBuilder) BuildDatabase(
return dbs, cleanUp, nil
}
+// sqlInvoiceStoreOptions enables the BOLT 12 side table only when BOLT 12
+// offers are enabled, because the table comes from a development migration.
+func sqlInvoiceStoreOptions(
+ protocol *lncfg.ProtocolOptions) []invoices.SQLStoreOption {
+
+ if !protocol.Bolt12OffersEnabled() {
+ return nil
+ }
+
+ return []invoices.SQLStoreOption{invoices.WithBolt12()}
+}
+
// waitForWalletPassword blocks until a password is provided by the user to
// this RPC server.
func waitForWalletPassword(cfg *Config,
### config_builder_bolt12_test.go
@@ -0,0 +1,78 @@
+//go:build dev && test_db_sqlite
+
+package lnd
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lncfg"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/sqldb"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSQLInvoiceStoreWithBolt12 verifies that the SQL invoice store of a node
+// with BOLT 12 offers enabled stores and reads a BOLT 12 invoice.
+func TestSQLInvoiceStoreWithBolt12(t *testing.T) {
+ t.Parallel()
+
+ ctx := t.Context()
+ db := sqldb.NewTestSqliteDB(t).BaseDB
+ executor := sqldb.NewTransactionExecutor(
+ db, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
+ return db.WithTx(tx)
+ },
+ )
+
+ protocol := &lncfg.ProtocolOptions{}
+ protocol.Bolt12Offers = true
+ store := invoices.NewSQLStore(
+ executor, clock.NewTestClock(time.Unix(1, 0)),
+ sqlInvoiceStoreOptions(protocol)...,
+ )
+
+ var (
+ preimage lntypes.Preimage
+ payAddr [32]byte
+ )
+ _, err := rand.Read(preimage[:])
+ require.NoError(t, err)
+ _, err = rand.Read(payAddr[:])
+ require.NoError(t, err)
+
+ envelopeBytes, err := envelope.Encode(&envelope.Data{
+ CreatedAt: 1,
+ Amount: 5000,
+ })
+ require.NoError(t, err)
+
+ invoice := &invoices.Invoice{
+ CreationDate: time.Unix(1, 0),
+ Terms: invoices.ContractTerm{
+ Expiry: time.Hour,
+ PaymentPreimage: &preimage,
+ PaymentAddr: payAddr,
+ Value: lnwire.MilliSatoshi(5000),
+ Features: lnwire.NewFeatureVector(
+ nil, lnwire.Features,
+ ),
+ },
+ IsBolt12: true,
+ Bolt12Envelope: envelopeBytes,
+ }
+ payHash := preimage.Hash()
+
+ _, err = store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ got, err := store.LookupInvoice(ctx, invoices.InvoiceRefByHash(payHash))
+ require.NoError(t, err)
+ require.True(t, got.IsBolt12)
+}
### config_builder_test.go
@@ -0,0 +1,72 @@
+package lnd
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lncfg"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/sqldb"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSQLInvoiceStoreWithoutBolt12 verifies that the SQL invoice store of a
+// node without BOLT 12 offers reads a BOLT 11 invoice. A release build has no
+// BOLT 12 side table, so the store must not query it.
+func TestSQLInvoiceStoreWithoutBolt12(t *testing.T) {
+ t.Parallel()
+
+ ctx := t.Context()
+ db := sqldb.NewTestSqliteDB(t).BaseDB
+ executor := sqldb.NewTransactionExecutor(
+ db, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
+ return db.WithTx(tx)
+ },
+ )
+
+ store := invoices.NewSQLStore(
+ executor, clock.NewTestClock(time.Unix(1, 0)),
+ sqlInvoiceStoreOptions(&lncfg.ProtocolOptions{})...,
+ )
+
+ var (
+ preimage lntypes.Preimage
+ payAddr [32]byte
+ )
+ _, err := rand.Read(preimage[:])
+ require.NoError(t, err)
+ _, err = rand.Read(payAddr[:])
+ require.NoError(t, err)
+
+ invoice := &invoices.Invoice{
+ CreationDate: time.Unix(1, 0),
+ PaymentRequest: []byte("lnbc1test"),
+ Terms: invoices.ContractTerm{
+ Expiry: time.Hour,
+ PaymentPreimage: &preimage,
+ PaymentAddr: payAddr,
+ Value: lnwire.MilliSatoshi(5000),
+ Features: lnwire.NewFeatureVector(
+ nil, lnwire.Features,
+ ),
+ },
+ }
+ payHash := preimage.Hash()
+
+ _, err = store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ got, err := store.LookupInvoice(ctx, invoices.InvoiceRefByHash(payHash))
+ require.NoError(t, err)
+ require.False(t, got.IsBolt12)
+
+ _, err = store.QueryInvoices(ctx, invoices.InvoiceQuery{
+ NumMaxInvoices: 10,
+ })
+ require.NoError(t, err)
+}
### docs/release-notes/unreleased/11532.md
@@ -0,0 +1,18 @@
+# Technical and Architectural Updates
+
+## BOLT 12 (Offers)
+
+* [BOLT 12 invoice envelope in payment
+ paths](https://github.com/lightningnetwork/lnd/pull/11532): the final hop of
+ each blinded payment path of a BOLT 12 invoice now carries an invoice
+ envelope with the invoice data, and a path id that authenticates it. The node
+ derives the preimage from the path id, so it stores nothing when it answers
+ an invoice request. A development table `bolt12_invoices` holds the
+ envelope of a BOLT 12 invoice. Settlement of these invoices comes in a later
+ change.
+
+ The key of the payment path ids comes from an ECDH with the node key, which
+ `signrpc.DeriveSharedKey` also gives. A caller with the `signer:generate`
+ permission can therefore derive every BOLT 12 preimage that the node issues.
+ Before, that permission could sign with the node key but could not learn
+ preimages.
### invoices/bolt12_invoice_test.go
@@ -0,0 +1,551 @@
+//go:build test_db_postgres || test_db_sqlite || test_native_sql
+
+package invoices_test
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/graph/db/models"
+ invpkg "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/sqldb"
+ "github.com/lightningnetwork/lnd/sqldb/sqlc"
+ "github.com/stretchr/testify/require"
+)
+
+// bolt12TestDB bundles an invoice store with the raw queries the tests use to
+// set up offers and to look into the BOLT 12 side table.
+type bolt12TestDB struct {
+ store invpkg.InvoiceDB
+ queries *sqlc.Queries
+}
+
+// bolt12DBMaker creates an invoice store with the given options on one SQL
+// backend.
+type bolt12DBMaker func(t *testing.T,
+ opts ...invpkg.SQLStoreOption) *bolt12TestDB
+
+// newBolt12TestDB creates an invoice store on the given database. The build
+// constraint of this file matches the development migrations, so the BOLT 12
+// side table exists whatever the options are.
+func newBolt12TestDB(db *sqldb.BaseDB,
+ opts ...invpkg.SQLStoreOption) *bolt12TestDB {
+
+ executor := sqldb.NewTransactionExecutor(
+ db,
+ func(tx *sql.Tx) invpkg.SQLInvoiceQueries {
+ return db.WithTx(tx)
+ },
+ )
+
+ testClock := clock.NewTestClock(time.Unix(1, 0))
+
+ return &bolt12TestDB{
+ store: invpkg.NewSQLStore(executor, testClock, opts...),
+ queries: db.Queries,
+ }
+}
+
+// TestBolt12SQLStore runs the BOLT 12 store tests on SQLite and on Postgres.
+func TestBolt12SQLStore(t *testing.T) {
+ backends := []struct {
+ name string
+ setup func(t *testing.T) bolt12DBMaker
+ }{
+ {
+ name: "SQLite",
+ setup: func(*testing.T) bolt12DBMaker {
+ return sqliteBolt12DB
+ },
+ },
+ {
+ name: "Postgres",
+ setup: postgresBolt12DBMaker,
+ },
+ }
+
+ tests := []struct {
+ name string
+ test func(t *testing.T, newDB bolt12DBMaker)
+ }{
+ {"RoundTrip", testBolt12InvoiceRoundTrip},
+ {"Bolt11Invoice", testBolt11InvoiceWithBolt12Store},
+ {"StoreDisabled", testBolt12InvoiceStoreDisabled},
+ {"DeleteCascades", testBolt12InvoiceDeleteCascades},
+ {"RejectsAMP", testBolt12InvoiceRejectsAMP},
+ {"EnvelopeChecks", testBolt12InvoiceEnvelopeChecks},
+ {"ListPaths", testBolt12InvoiceListPaths},
+ {
+ "DeleteCanceledCascades",
+ testBolt12InvoiceDeleteCanceledCascades,
+ },
+ }
+
+ for _, backend := range backends {
+ t.Run(backend.name, func(t *testing.T) {
+ newDB := backend.setup(t)
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.test(t, newDB)
+ })
+ }
+ })
+ }
+}
+
+// sqliteBolt12DB creates an invoice store on a new SQLite database.
+func sqliteBolt12DB(t *testing.T,
+ opts ...invpkg.SQLStoreOption) *bolt12TestDB {
+
+ return newBolt12TestDB(sqldb.NewTestSqliteDB(t).BaseDB, opts...)
+}
+
+// postgresBolt12DBMaker starts one Postgres instance for all tests of the
+// calling test, so no test spawns its own docker container. The instance stops
+// when the calling test ends.
+func postgresBolt12DBMaker(t *testing.T) bolt12DBMaker {
+ fixture := sqldb.NewTestPgFixture(
+ t, sqldb.DefaultPostgresFixtureLifetime,
+ )
+ t.Cleanup(func() {
+ fixture.TearDown(t)
+ })
+
+ return func(t *testing.T,
+ opts ...invpkg.SQLStoreOption) *bolt12TestDB {
+
+ db := sqldb.NewTestPostgresDB(t, fixture)
+
+ return newBolt12TestDB(db.BaseDB, opts...)
+ }
+}
+
+// insertTestOffer stores an offer and returns its database ID and hash.
+func insertTestOffer(t *testing.T, db *bolt12TestDB) (int64, [32]byte) {
+ t.Helper()
+
+ var hash [32]byte
+ _, err := rand.Read(hash[:])
+ require.NoError(t, err)
+
+ id, err := db.queries.InsertOffer(t.Context(), sqlc.InsertOfferParams{
+ Hash: hash[:],
+ Encoded: "lno1test",
+ CreatedAt: time.Unix(1, 0),
+ })
+ require.NoError(t, err)
+
+ return id, hash
+}
+
+// testEnvelope returns the envelope data of a BOLT 12 invoice for the offer
+// with the given hash, or for no offer when the hash is None.
+func testEnvelope(offerHash fn.Option[[32]byte]) *envelope.Data {
+ var payerID [33]byte
+ payerID[0] = 0x03
+ for i := 1; i < 33; i++ {
+ payerID[i] = byte(i + 50)
+ }
+
+ return &envelope.Data{
+ OfferHash: offerHash,
+ PayerID: payerID,
+ CreatedAt: 1,
+ Amount: 10000,
+ Quantity: 3,
+ PayerNote: []byte("tip"),
+ }
+}
+
+// newBolt12Invoice returns a BOLT 12 invoice for the offer with the given ID
+// that carries the given envelope, in the form that HTLC settlement rebuilds.
+// It has no payment request.
+func newBolt12Invoice(t *testing.T, offerID fn.Option[int64],
+ data *envelope.Data) (*invpkg.Invoice, lntypes.Hash) {
+
+ t.Helper()
+
+ var (
+ preimage lntypes.Preimage
+ payAddr [32]byte
+ )
+ _, err := rand.Read(preimage[:])
+ require.NoError(t, err)
+ _, err = rand.Read(payAddr[:])
+ require.NoError(t, err)
+
+ encoded, err := envelope.Encode(data)
+ require.NoError(t, err)
+
+ invoice := &invpkg.Invoice{
+ CreationDate: time.Unix(1, 0),
+ Terms: invpkg.ContractTerm{
+ Expiry: 7200 * time.Second,
+ PaymentPreimage: &preimage,
+ PaymentAddr: payAddr,
+ Value: lnwire.MilliSatoshi(10000),
+ Features: emptyFeatures,
+ },
+ IsBolt12: true,
+ OfferID: offerID,
+ Bolt12Envelope: encoded,
+ }
+
+ return invoice, preimage.Hash()
+}
+
+// requireEnvelopeFields asserts that the invoice carries the typed fields of
+// the envelope data.
+func requireEnvelopeFields(t *testing.T, invoice invpkg.Invoice,
+ data *envelope.Data) {
+
+ t.Helper()
+
+ require.True(t, invoice.IsBolt12)
+ require.NotEmpty(t, invoice.Bolt12Envelope)
+ require.Equal(t, data.PayerID[:], invoice.InvreqPayerID)
+ require.Equal(t, data.Quantity, invoice.InvreqQuantity)
+ require.Equal(t, data.PayerNote, invoice.InvreqPayerNote)
+
+ var offerHash []byte
+ data.OfferHash.WhenSome(func(hash [32]byte) {
+ offerHash = hash[:]
+ })
+ require.Equal(t, offerHash, invoice.OfferHash)
+}
+
+// testBolt12InvoiceRoundTrip verifies that the store writes the envelope and
+// fills the typed BOLT 12 fields from it on read. An envelope without an offer
+// hash gives an empty offer hash. A request without a quantity or a payer note
+// gives a zero quantity and no note.
+func testBolt12InvoiceRoundTrip(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ withOffer bool
+ modify func(data *envelope.Data)
+ }{
+ {
+ name: "with offer",
+ withOffer: true,
+ modify: func(*envelope.Data) {},
+ },
+ {
+ name: "without offer",
+ modify: func(*envelope.Data) {},
+ },
+ {
+ name: "without quantity and payer note",
+ withOffer: true,
+ modify: func(data *envelope.Data) {
+ data.Quantity = 0
+ data.PayerNote = nil
+ },
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ offerID := fn.None[int64]()
+ offerHash := fn.None[[32]byte]()
+ if tc.withOffer {
+ id, hash := insertTestOffer(t, db)
+ offerID, offerHash = fn.Some(id), fn.Some(hash)
+ }
+ data := testEnvelope(offerHash)
+ tc.modify(data)
+ invoice, payHash := newBolt12Invoice(t, offerID, data)
+
+ _, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ ref := invpkg.InvoiceRefByHash(payHash)
+ got, err := db.store.LookupInvoice(ctx, ref)
+ require.NoError(t, err)
+
+ require.Equal(t, offerID, got.OfferID)
+ require.Equal(
+ t, invoice.Bolt12Envelope, got.Bolt12Envelope,
+ )
+ requireEnvelopeFields(t, got, data)
+ })
+ }
+}
+
+// testBolt11InvoiceWithBolt12Store verifies that a BOLT 11 invoice has no side
+// table row and reads back without BOLT 12 data.
+func testBolt11InvoiceWithBolt12Store(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ invoice, err := randInvoice(lnwire.MilliSatoshi(5000))
+ require.NoError(t, err)
+
+ payHash := invoice.Terms.PaymentPreimage.Hash()
+
+ addIndex, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ ref := invpkg.InvoiceRefByHash(payHash)
+ got, err := db.store.LookupInvoice(ctx, ref)
+ require.NoError(t, err)
+
+ require.False(t, got.IsBolt12)
+ require.Zero(t, got.InvreqQuantity)
+ require.True(t, got.OfferID.IsNone())
+ require.Nil(t, got.OfferHash)
+ require.Nil(t, got.InvreqPayerID)
+ require.Nil(t, got.InvreqPayerNote)
+ require.Nil(t, got.Bolt12Envelope)
+
+ _, err = db.queries.FetchBolt12Invoice(ctx, int64(addIndex))
+ require.ErrorIs(t, err, sql.ErrNoRows)
+}
+
+// testBolt12InvoiceStoreDisabled verifies that a store without BOLT 12 refuses
+// a BOLT 12 invoice and stores nothing.
+func testBolt12InvoiceStoreDisabled(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ ctx := t.Context()
+
+ db := newDB(t)
+ offerID, offerHash := insertTestOffer(t, db)
+ invoice, payHash := newBolt12Invoice(
+ t, fn.Some(offerID), testEnvelope(fn.Some(offerHash)),
+ )
+
+ _, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.ErrorIs(t, err, invpkg.ErrBolt12Disabled)
+
+ _, err = db.store.LookupInvoice(ctx, invpkg.InvoiceRefByHash(payHash))
+ require.ErrorIs(t, err, invpkg.ErrInvoiceNotFound)
+}
+
+// testBolt12InvoiceDeleteCascades verifies that deleting a BOLT 12 invoice also
+// deletes its side table row. The registry does this for an open BOLT 12
+// invoice whose HTLCs all failed.
+func testBolt12InvoiceDeleteCascades(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ offerID, offerHash := insertTestOffer(t, db)
+ invoice, payHash := newBolt12Invoice(
+ t, fn.Some(offerID), testEnvelope(fn.Some(offerHash)),
+ )
+
+ addIndex, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ _, err = db.queries.FetchBolt12Invoice(ctx, int64(addIndex))
+ require.NoError(t, err)
+
+ payAddr := invoice.Terms.PaymentAddr
+ err = db.store.DeleteInvoice(ctx, []invpkg.InvoiceDeleteRef{{
+ PayHash: payHash,
+ PayAddr: &payAddr,
+ AddIndex: addIndex,
+ }})
+ require.NoError(t, err)
+
+ _, err = db.queries.FetchBolt12Invoice(ctx, int64(addIndex))
+ require.ErrorIs(t, err, sql.ErrNoRows)
+}
+
+// testBolt12InvoiceRejectsAMP verifies that the store refuses an invoice that
+// is both a BOLT 12 and an AMP invoice, because the read path does not load
+// the BOLT 12 data of an AMP invoice.
+func testBolt12InvoiceRejectsAMP(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ invoice, payHash := newBolt12Invoice(
+ t, fn.None[int64](), testEnvelope(fn.None[[32]byte]()),
+ )
+ invoice.Terms.Features = ampFeatures
+ invoice.Terms.PaymentPreimage = nil
+
+ _, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.ErrorIs(t, err, invpkg.ErrBolt12AMP)
+}
+
+// testBolt12InvoiceEnvelopeChecks verifies that the store refuses a BOLT 12
+// invoice without an envelope or with one that does not decode, so that every
+// later read of the invoice can decode its envelope.
+func testBolt12InvoiceEnvelopeChecks(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ envelope []byte
+ wantErr error
+ }{
+ {
+ name: "no envelope",
+ wantErr: invpkg.ErrBolt12NoEnvelope,
+ },
+ {
+ name: "envelope that does not decode",
+ envelope: []byte{0x02, 0x21, 0x01},
+ wantErr: invpkg.ErrBolt12BadEnvelope,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ invoice, payHash := newBolt12Invoice(
+ t, fn.None[int64](),
+ testEnvelope(fn.None[[32]byte]()),
+ )
+ invoice.Bolt12Envelope = tc.envelope
+
+ _, err := db.store.AddInvoice(
+ t.Context(), invoice, payHash,
+ )
+ require.ErrorIs(t, err, tc.wantErr)
+ })
+ }
+}
+
+// testBolt12InvoiceListPaths verifies that every list call returns the BOLT 12
+// data of a BOLT 12 invoice.
+func testBolt12InvoiceListPaths(t *testing.T, newDB bolt12DBMaker) {
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ // The calls with an index return the invoices after it, so a BOLT 11
+ // invoice takes the first add and settle index.
+ bolt11, err := randInvoice(lnwire.MilliSatoshi(5000))
+ require.NoError(t, err)
+ bolt11Hash := bolt11.Terms.PaymentPreimage.Hash()
+ _, err = db.store.AddInvoice(ctx, bolt11, bolt11Hash)
+ require.NoError(t, err)
+ _, err = settleInvoice(
+ db.store, invpkg.InvoiceRefByHash(bolt11Hash), 0,
+ bolt11.Terms.Value,
+ )
+ require.NoError(t, err)
+
+ offerID, offerHash := insertTestOffer(t, db)
+ data := testEnvelope(fn.Some(offerHash))
+ invoice, payHash := newBolt12Invoice(t, fn.Some(offerID), data)
+
+ _, err = db.store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ requireFields := func(invoice invpkg.Invoice) {
+ t.Helper()
+
+ require.Equal(t, fn.Some(offerID), invoice.OfferID)
+ requireEnvelopeFields(t, invoice, data)
+ }
+
+ pending, err := db.store.FetchPendingInvoices(ctx)
+ require.NoError(t, err)
+ require.Contains(t, pending, payHash)
+ requireFields(pending[payHash])
+
+ added, err := db.store.InvoicesAddedSince(ctx, 1)
+ require.NoError(t, err)
+ require.Len(t, added, 1)
+ requireFields(added[0])
+
+ resp, err := db.store.QueryInvoices(ctx, invpkg.InvoiceQuery{
+ NumMaxInvoices: 10,
+ })
+ require.NoError(t, err)
+ require.Len(t, resp.Invoices, 2)
+ requireFields(resp.Invoices[1])
+
+ // The release of the preimage leaves the HTLC pending settlement
+ // until its final outcome is recorded.
+ ref := invpkg.InvoiceRefByHash(payHash)
+ pendingSettle, err := db.store.UpdateInvoice(
+ ctx, ref, nil, getUpdateInvoice(1, invoice.Terms.Value),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractPendingSettle, pendingSettle.State)
+ requireFields(*pendingSettle)
+
+ pendingSettles, err := db.store.FetchPendingSettleInvoices(ctx)
+ require.NoError(t, err)
+ require.Contains(t, pendingSettles, payHash)
+ requireFields(pendingSettles[payHash])
+
+ settled, err := db.store.UpdateInvoice(
+ ctx, ref, nil,
+ getFinalizeHtlcs(true, models.CircuitKey{HtlcID: 1}),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractSettled, settled.State)
+ requireFields(*settled)
+
+ settledSince, err := db.store.InvoicesSettledSince(ctx, 1)
+ require.NoError(t, err)
+ require.Len(t, settledSince, 1)
+ requireFields(settledSince[0])
+}
+
+// testBolt12InvoiceDeleteCanceledCascades verifies that deleting the canceled
+// invoices also deletes their side table rows.
+func testBolt12InvoiceDeleteCanceledCascades(t *testing.T,
+ newDB bolt12DBMaker) {
+
+ t.Parallel()
+
+ db := newDB(t, invpkg.WithBolt12())
+ ctx := t.Context()
+
+ offerID, offerHash := insertTestOffer(t, db)
+ invoice, payHash := newBolt12Invoice(
+ t, fn.Some(offerID), testEnvelope(fn.Some(offerHash)),
+ )
+
+ addIndex, err := db.store.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+
+ cancel := func(*invpkg.Invoice) (*invpkg.InvoiceUpdateDesc, error) {
+ return &invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.CancelInvoiceUpdate,
+ State: &invpkg.InvoiceStateUpdateDesc{
+ NewState: invpkg.ContractCanceled,
+ },
+ }, nil
+ }
+ _, err = db.store.UpdateInvoice(
+ ctx, invpkg.InvoiceRefByHash(payHash), nil, cancel,
+ )
+ require.NoError(t, err)
+
+ _, err = db.queries.FetchBolt12Invoice(ctx, int64(addIndex))
+ require.NoError(t, err)
+
+ require.NoError(t, db.store.DeleteCanceledInvoices(ctx))
+
+ _, err = db.queries.FetchBolt12Invoice(ctx, int64(addIndex))
+ require.ErrorIs(t, err, sql.ErrNoRows)
+}
### invoices/errors.go
@@ -94,6 +94,25 @@ var (
"invoice with payment hash already exists",
)
+ // ErrBolt12Disabled is returned when a BOLT 12 invoice is added to a
+ // store that does not have BOLT 12 enabled.
+ ErrBolt12Disabled = errors.New("BOLT 12 is not enabled in the " +
+ "invoice store")
+
+ // ErrBolt12NoEnvelope is returned when a BOLT 12 invoice without an
+ // invoice envelope is added.
+ ErrBolt12NoEnvelope = errors.New("BOLT 12 invoice has no envelope")
+
+ // ErrBolt12BadEnvelope is returned when the invoice envelope of a
+ // BOLT 12 invoice does not decode.
+ ErrBolt12BadEnvelope = errors.New("BOLT 12 invoice envelope does " +
+ "not decode")
+
+ // ErrBolt12AMP is returned when an invoice is both a BOLT 12 and an
+ // AMP invoice.
+ ErrBolt12AMP = errors.New("a BOLT 12 invoice cannot be an AMP " +
+ "invoice")
+
// ErrDuplicatePayAddr is returned when an invoice with the target
// payment addr already exists.
ErrDuplicatePayAddr = errors.New(
### invoices/invoices.go
@@ -1,6 +1,7 @@
package invoices
import (
+ "bytes"
"errors"
"fmt"
"math"
@@ -459,13 +460,38 @@ type Invoice struct {
// OfferID is the database primary key of the offer that spawned
// this invoice. It is None for BOLT 11 invoices and BOLT 12 invoices
- // not tied to an offer.
+ // not tied to an offer. The caller sets it from the offer that the
+ // offer hash in Bolt12Envelope names. The store does not check this.
OfferID fn.Option[int64]
+ // Bolt12Envelope is the invoice envelope that the payment of a BOLT 12
+ // invoice carried. It is the authoritative source of the BOLT 12
+ // order data. The store writes it and refuses a BOLT 12 invoice
+ // without it. It is nil for BOLT 11.
+ Bolt12Envelope []byte
+
+ // OfferHash is the 32-byte SHA256 hash of the TLV-encoded offer. It
+ // is the external identifier in RPC responses. The store decodes it
+ // from Bolt12Envelope on read. It is nil for an invoice that answers
+ // no offer.
+ OfferHash []byte
+
// InvreqPayerID is the 33-byte compressed pubkey from the
- // invreq_payer_id TLV (type 88) in the invoice request. Nil
- // for BOLT 11.
+ // invreq_payer_id TLV (type 88) in the invoice request. The store
+ // decodes it from Bolt12Envelope on read. Nil for BOLT 11.
InvreqPayerID []byte
+
+ // InvreqQuantity is the number of items requested by the payer
+ // (invreq_quantity, TLV type 86). The store decodes it from
+ // Bolt12Envelope on read. Zero when the request has no
+ // invreq_quantity, and for BOLT 11.
+ InvreqQuantity uint64
+
+ // InvreqPayerNote is the invreq_payer_note of the invoice request
+ // (TLV type 89), cut to its first 64 bytes. The store decodes it from
+ // Bolt12Envelope on read. Nil when the request has no note, and for
+ // BOLT 11.
+ InvreqPayerNote []byte
}
// HTLCSet returns the set of HTLCs belonging to setID and in the provided
@@ -522,7 +548,13 @@ func (i *Invoice) HTLCSetCompliment(setID *[32]byte,
func (i *Invoice) IsKeysend() bool {
// TODO(positiveblue): look for a more reliable way to tests if
// an invoice is keysend.
- return len(i.PaymentRequest) == 0 && !i.IsAMP()
+ //
+ // A settled BOLT 12 invoice also has no payment request, because the
+ // signed lni1... string is not kept after it is sent to the payer.
+ // A store without BOLT 12 enabled does not read the side table, so
+ // IsBolt12 is false and such an invoice reads back as keysend. The
+ // stored is_keysend column stays false.
+ return len(i.PaymentRequest) == 0 && !i.IsAMP() && !i.IsBolt12
}
// IsAMP returns true if the invoice is an AMP invoice.
@@ -948,6 +980,14 @@ func CopyInvoice(src *Invoice) (*Invoice, error) {
),
AMPState: make(map[SetID]InvoiceStateAMP),
HodlInvoice: src.HodlInvoice,
+
+ IsBolt12: src.IsBolt12,
+ OfferID: src.OfferID,
+ Bolt12Envelope: bytes.Clone(src.Bolt12Envelope),
+ OfferHash: bytes.Clone(src.OfferHash),
+ InvreqPayerID: bytes.Clone(src.InvreqPayerID),
+ InvreqQuantity: src.InvreqQuantity,
+ InvreqPayerNote: bytes.Clone(src.InvreqPayerNote),
}
dest.Terms.Features = src.Terms.Features.Clone()
### invoices/invoices_test.go
@@ -13,6 +13,7 @@ import (
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/clock"
"github.com/lightningnetwork/lnd/feature"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/graph/db/models"
invpkg "github.com/lightningnetwork/lnd/invoices"
"github.com/lightningnetwork/lnd/lntypes"
@@ -2255,6 +2256,52 @@ func TestHTLCSet(t *testing.T) {
}
}
+// TestInvoiceIsKeysend verifies that only an invoice without a payment request
+// that is neither AMP nor BOLT 12 counts as a keysend invoice.
+func TestInvoiceIsKeysend(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ invoice invpkg.Invoice
+ want bool
+ }{
+ {
+ name: "no payment request",
+ want: true,
+ },
+ {
+ name: "payment request",
+ invoice: invpkg.Invoice{
+ PaymentRequest: []byte("lnbc1test"),
+ },
+ },
+ {
+ name: "AMP",
+ invoice: invpkg.Invoice{
+ Terms: invpkg.ContractTerm{
+ Features: ampFeatures,
+ },
+ },
+ },
+ {
+ name: "BOLT 12",
+ invoice: invpkg.Invoice{IsBolt12: true},
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ if tc.invoice.Terms.Features == nil {
+ tc.invoice.Terms.Features = emptyFeatures
+ }
+ require.Equal(t, tc.want, tc.invoice.IsKeysend())
+ })
+ }
+}
+
// testAddInvoiceWithHTLCs asserts that you can't insert an invoice that already
// has HTLCs.
func testAddInvoiceWithHTLCs(t *testing.T,
@@ -3052,3 +3099,49 @@ func testFinalizeHtlcs(t *testing.T,
require.NoError(t, err)
require.NotContains(t, pendingSettle, payHash)
}
+
+// TestCopyInvoiceBolt12 verifies that CopyInvoice keeps the BOLT 12 fields,
+// so an update callback does not see a BOLT 12 invoice as a keysend invoice,
+// and that the copy shares no slice with the source.
+func TestCopyInvoiceBolt12(t *testing.T) {
+ t.Parallel()
+
+ src := &invpkg.Invoice{
+ Terms: invpkg.ContractTerm{Features: emptyFeatures},
+ IsBolt12: true,
+ OfferID: fn.Some(int64(7)),
+ Bolt12Envelope: []byte{1, 2, 3},
+ OfferHash: []byte{4, 5},
+ InvreqPayerID: []byte{6, 7},
+ InvreqQuantity: 3,
+ InvreqPayerNote: []byte("tip"),
+ }
+
+ dest, err := invpkg.CopyInvoice(src)
+ require.NoError(t, err)
+ require.True(t, dest.IsBolt12)
+ require.False(t, dest.IsKeysend())
+ require.Equal(t, src.OfferID, dest.OfferID)
+ require.Equal(t, src.Bolt12Envelope, dest.Bolt12Envelope)
+ require.Equal(t, src.OfferHash, dest.OfferHash)
+ require.Equal(t, src.InvreqPayerID, dest.InvreqPayerID)
+ require.Equal(t, src.InvreqQuantity, dest.InvreqQuantity)
+ require.Equal(t, src.InvreqPayerNote, dest.InvreqPayerNote)
+
+ dest.Bolt12Envelope[0] = 9
+ dest.OfferHash[0] = 9
+ dest.InvreqPayerID[0] = 9
+ dest.InvreqPayerNote[0] = 'x'
+ require.Equal(t, []byte{1, 2, 3}, src.Bolt12Envelope)
+ require.Equal(t, []byte{4, 5}, src.OfferHash)
+ require.Equal(t, []byte{6, 7}, src.InvreqPayerID)
+ require.Equal(t, []byte("tip"), src.InvreqPayerNote)
+
+ // A BOLT 11 invoice keeps nil BOLT 12 fields in its copy.
+ bolt11, err := invpkg.CopyInvoice(&invpkg.Invoice{
+ Terms: invpkg.ContractTerm{Features: emptyFeatures},
+ })
+ require.NoError(t, err)
+ require.Nil(t, bolt11.Bolt12Envelope)
+ require.Nil(t, bolt11.InvreqPayerNote)
+}
### invoices/sql_migration.go
@@ -623,7 +623,7 @@ func migrateInvoices(ctx context.Context, tx *sqlc.Queries,
}
migratedInvoice, err := fetchInvoice(
- ctx, tx, InvoiceRefByHash(paymentHash),
+ ctx, tx, InvoiceRefByHash(paymentHash), false,
)
if err != nil {
return fmt.Errorf("unable to fetch migrated "+
### invoices/sql_store.go
@@ -11,7 +11,9 @@ import (
"strconv"
"time"
+ "github.com/lightningnetwork/lnd/bolt12handler/envelope"
"github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
@@ -54,6 +56,16 @@ type SQLInvoiceQueries interface { //nolint:interfacebloat
InsertInvoice(ctx context.Context, arg sqlc.InsertInvoiceParams) (int64,
error)
+ // InsertBolt12Invoice stores the BOLT 12 data of an invoice in its
+ // side table. Only a store with BOLT 12 enabled calls it.
+ InsertBolt12Invoice(ctx context.Context,
+ arg sqlc.InsertBolt12InvoiceParams) error
+
+ // FetchBolt12Invoice returns the BOLT 12 data of an invoice, or
+ // sql.ErrNoRows for an invoice that is not a BOLT 12 invoice.
+ FetchBolt12Invoice(ctx context.Context,
+ invoiceID int64) (sqlc.FetchBolt12InvoiceRow, error)
+
// TODO(bhandras): remove this once migrations have been separated out.
InsertMigratedInvoice(ctx context.Context,
arg sqlc.InsertMigratedInvoiceParams) (int64, error)
@@ -223,6 +235,11 @@ type SQLStore struct {
// SQLStoreOptions holds the options for the SQL store.
type SQLStoreOptions struct {
paginationLimit int
+
+ // bolt12 enables the BOLT 12 side table. Its migration is only
+ // applied in builds with the development migrations, so a store
+ // without this option never queries it.
+ bolt12 bool
}
// defaultSQLStoreOptions returns the default options for the SQL store.
@@ -244,6 +261,15 @@ func WithPaginationLimit(limit int) SQLStoreOption {
}
}
+// WithBolt12 lets the store read and write the BOLT 12 side table. The
+// caller sets it only when BOLT 12 is enabled, which also guarantees that the
+// table exists.
+func WithBolt12() SQLStoreOption {
+ return func(o *SQLStoreOptions) {
+ o.bolt12 = true
+ }
+}
+
// NewSQLStore creates a new SQLStore instance given a open
// BatchedSQLInvoiceQueries storage backend.
func NewSQLStore(db BatchedSQLInvoiceQueries,
@@ -336,6 +362,30 @@ func (i *SQLStore) AddInvoice(ctx context.Context,
return 0, err
}
+ if newInvoice.IsBolt12 && !i.opts.bolt12 {
+ return 0, ErrBolt12Disabled
+ }
+
+ // The read path does not load the BOLT 12 data of an AMP invoice, so
+ // the store refuses such an invoice.
+ if newInvoice.IsBolt12 && newInvoice.IsAMP() {
+ return 0, ErrBolt12AMP
+ }
+
+ // Every read of a BOLT 12 invoice decodes its envelope, so the store
+ // only takes an envelope that decodes.
+ if newInvoice.IsBolt12 {
+ if len(newInvoice.Bolt12Envelope) == 0 {
+ return 0, ErrBolt12NoEnvelope
+ }
+
+ _, err := envelope.Decode(newInvoice.Bolt12Envelope)
+ if err != nil {
+ return 0, fmt.Errorf("%w: %w", ErrBolt12BadEnvelope,
+ err)
+ }
+ }
+
var (
writeTxOpts = sqldb.WriteTxOpt()
invoiceID int64
@@ -355,6 +405,11 @@ func (i *SQLStore) AddInvoice(ctx context.Context,
return fmt.Errorf("unable to insert invoice: %w", err)
}
+ err = insertBolt12Invoice(ctx, db, invoiceID, newInvoice)
+ if err != nil {
+ return err
+ }
+
// TODO(positiveblue): if invocies do not have custom features
// maybe just store the "invoice type" and populate the features
// based on that.
@@ -394,6 +449,36 @@ func (i *SQLStore) AddInvoice(ctx context.Context,
return newInvoice.AddIndex, nil
}
+// insertBolt12Invoice stores the BOLT 12 data of the invoice with the given ID
+// in its side table.
+func insertBolt12Invoice(ctx context.Context, db SQLInvoiceQueries,
+ invoiceID int64, invoice *Invoice) error {
+
+ // A BOLT 11 invoice has no side table row.
+ if !invoice.IsBolt12 {
+ return nil
+ }
+
+ params := sqlc.InsertBolt12InvoiceParams{
+ InvoiceID: invoiceID,
+ Envelope: invoice.Bolt12Envelope,
+ }
+
+ // An invoice that answers an invoice request without an offer has no
+ // offer link.
+ invoice.OfferID.WhenSome(func(id int64) {
+ params.OfferID = sqldb.SQLInt64(id)
+ })
+
+ err := db.InsertBolt12Invoice(ctx, params)
+ if err != nil {
+ return fmt.Errorf("unable to insert BOLT 12 data of "+
+ "invoice(id=%d): %w", invoiceID, err)
+ }
+
+ return nil
+}
+
// getInvoiceByRef fetches the invoice with the given reference. The reference
// may be a payment hash, a payment address, or a set ID for an AMP sub invoice.
func getInvoiceByRef(ctx context.Context,
@@ -477,9 +562,10 @@ func getInvoiceByRef(ctx context.Context,
}
// fetchInvoice fetches the common invoice data and the AMP state for the
-// invoice with the given reference.
-func fetchInvoice(ctx context.Context, db SQLInvoiceQueries, ref InvoiceRef) (
- *Invoice, error) {
+// invoice with the given reference. If bolt12 is true, it also reads the
+// BOLT 12 side table.
+func fetchInvoice(ctx context.Context, db SQLInvoiceQueries, ref InvoiceRef,
+ bolt12 bool) (*Invoice, error) {
// Fetch the invoice from the database.
sqlInvoice, err := getInvoiceByRef(ctx, db, ref)
@@ -523,7 +609,7 @@ func fetchInvoice(ctx context.Context, db SQLInvoiceQueries, ref InvoiceRef) (
// Fetch the rest of the invoice data and fill the invoice struct.
_, invoice, err := fetchInvoiceData(
- ctx, db, sqlInvoice, setID, fetchAmpHtlcs,
+ ctx, db, sqlInvoice, setID, fetchAmpHtlcs, bolt12,
)
if err != nil {
return nil, err
@@ -756,7 +842,7 @@ func (i *SQLStore) LookupInvoice(ctx context.Context,
readTxOpt := sqldb.ReadTxOpt()
txErr := i.db.ExecTx(ctx, readTxOpt, func(db SQLInvoiceQueries) error {
- invoice, err = fetchInvoice(ctx, db, ref)
+ invoice, err = fetchInvoice(ctx, db, ref, i.opts.bolt12)
return err
}, sqldb.NoOpReset)
@@ -794,6 +880,7 @@ func (i *SQLStore) FetchPendingInvoices(ctx context.Context) (
for _, row := range rows {
hash, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
+ i.opts.bolt12,
)
if err != nil {
return err
@@ -844,6 +931,7 @@ func (i *SQLStore) FetchPendingSettleInvoices(ctx context.Context) (
for _, row := range rows {
hash, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
+ i.opts.bolt12,
)
if err != nil {
return err
@@ -911,6 +999,7 @@ func (i *SQLStore) InvoicesSettledSince(ctx context.Context, idx uint64) (
for _, row := range rows {
_, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
+ i.opts.bolt12,
)
if err != nil {
return fmt.Errorf("unable to fetch "+
@@ -977,6 +1066,7 @@ func (i *SQLStore) InvoicesSettledSince(ctx context.Context, idx uint64) (
_, invoice, err := fetchInvoiceData(
ctx, db, sqlInvoice,
(*[32]byte)(ampInvoice.SetID), true,
+ i.opts.bolt12,
)
if err != nil {
return fmt.Errorf("unable to fetch "+
@@ -1061,6 +1151,7 @@ func (i *SQLStore) InvoicesAddedSince(ctx context.Context, idx uint64) (
for _, row := range rows {
_, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
+ i.opts.bolt12,
)
if err != nil {
return err
@@ -1194,6 +1285,7 @@ func (i *SQLStore) QueryInvoices(ctx context.Context,
for _, row := range rows {
_, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
+ i.opts.bolt12,
)
if err != nil {
return err
@@ -1618,7 +1710,7 @@ func (i *SQLStore) UpdateInvoice(ctx context.Context, ref InvoiceRef,
ref.refModifier = HtlcSetOnlyModifier
}
- invoice, err := fetchInvoice(ctx, db, ref)
+ invoice, err := fetchInvoice(ctx, db, ref, i.opts.bolt12)
if err != nil {
return err
}
@@ -1733,10 +1825,12 @@ func (i *SQLStore) DeleteCanceledInvoices(ctx context.Context) error {
// fetchInvoiceData fetches additional data for the given invoice. If the
// invoice is AMP and the setID is not nil, then it will also fetch the AMP
// state and HTLCs for the given setID, otherwise for all AMP sub invoices of
-// the invoice. If fetchAmpHtlcs is true, it will also fetch the AMP HTLCs.
+// the invoice. If fetchAmpHtlcs is true, it will also fetch the AMP HTLCs. If
+// bolt12 is true and the invoice is not AMP, it also fills the BOLT 12 fields
+// from the side table.
func fetchInvoiceData(ctx context.Context, db SQLInvoiceQueries,
- row sqlc.Invoice, setID *[32]byte, fetchAmpHtlcs bool) (*lntypes.Hash,
- *Invoice, error) {
+ row sqlc.Invoice, setID *[32]byte, fetchAmpHtlcs bool,
+ bolt12 bool) (*lntypes.Hash, *Invoice, error) {
// Unmarshal the common data.
hash, invoice, err := unmarshalInvoice(row)
@@ -1753,6 +1847,13 @@ func fetchInvoiceData(ctx context.Context, db SQLInvoiceQueries,
invoice.Terms.Features = features
+ if bolt12 && !invoice.IsAMP() {
+ err := fetchBolt12Invoice(ctx, db, row.ID, invoice)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+
// If this is an AMP invoice, we'll need fetch the AMP state along
// with the HTLCs (if requested).
if invoice.IsAMP() {
@@ -1783,6 +1884,47 @@ func fetchInvoiceData(ctx context.Context, db SQLInvoiceQueries,
return hash, invoice, nil
}
+// fetchBolt12Invoice fills the BOLT 12 fields of the invoice with the given ID
+// from the envelope in its side table. An invoice without a row is not a BOLT
+// 12 invoice and stays unchanged.
+//
+// List calls run this query once per invoice. That keeps the shared invoice
+// queries free of the development table, at the cost of one extra query per
+// row while BOLT 12 is enabled.
+func fetchBolt12Invoice(ctx context.Context, db SQLInvoiceQueries,
+ invoiceID int64, invoice *Invoice) error {
+
+ row, err := db.FetchBolt12Invoice(ctx, invoiceID)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return nil
+
+ case err != nil:
+ return fmt.Errorf("unable to fetch BOLT 12 data of "+
+ "invoice(id=%d): %w", invoiceID, err)
+ }
+
+ data, err := envelope.Decode(row.Envelope)
+ if err != nil {
+ return fmt.Errorf("unable to decode BOLT 12 envelope of "+
+ "invoice(id=%d): %w", invoiceID, err)
+ }
+
+ invoice.IsBolt12 = true
+ if row.OfferID.Valid {
+ invoice.OfferID = fn.Some(row.OfferID.Int64)
+ }
+ invoice.Bolt12Envelope = row.Envelope
+ data.OfferHash.WhenSome(func(hash [32]byte) {
+ invoice.OfferHash = hash[:]
+ })
+ invoice.InvreqPayerID = data.PayerID[:]
+ invoice.InvreqQuantity = data.Quantity
+ invoice.InvreqPayerNote = data.PayerNote
+
+ return nil
+}
+
// getInvoiceFeatures fetches the invoice features for the given invoice id.
func getInvoiceFeatures(ctx context.Context, db SQLInvoiceQueries,
invoiceID int64) (*lnwire.FeatureVector, error) {
### itest/lnd_route_blinding_test.go
@@ -1590,6 +1590,7 @@ func (b *blindedForwardTest) buildBlindedPathWithNextNodeID(
pub: davePub,
data: record.NewFinalHopBlindedRouteData(
constraints, bytes.Repeat([]byte{1}, 32),
+ nil,
),
},
}
### record/blinded_data.go
@@ -56,6 +56,13 @@ type BlindedRouteData struct {
// Features is the set of features the payment requires.
Features tlv.OptionalRecordT[tlv.TlvType14, lnwire.FeatureVector]
+
+ // InvoiceEnvelope is an optional envelope carrying the data needed
+ // to reconstruct a BOLT 12 invoice at HTLC settlement time.
+ // It uses the custom TLV range (65536 or higher), so it cannot collide
+ // with future spec-assigned types in encrypted_recipient_data. Only
+ // BOLT 12 invoices set it.
+ InvoiceEnvelope tlv.OptionalRecordT[tlv.TlvType65538, []byte]
}
// NewNonFinalBlindedRouteData creates the data that's provided for hops within
@@ -135,9 +142,10 @@ func NewNonFinalBlindedRouteDataOnionMessage(
}
// NewFinalHopBlindedRouteData creates the data that's provided for the final
-// hop in a blinded route.
+// hop in a blinded route. The optional invoiceEnvelope carries BOLT 12 invoice
+// data for stateless settlement. Pass nil for BOLT 11 blinded paths.
func NewFinalHopBlindedRouteData(constraints *PaymentConstraints,
- pathID []byte) *BlindedRouteData {
+ pathID []byte, invoiceEnvelope []byte) *BlindedRouteData {
var data BlindedRouteData
if pathID != nil {
@@ -151,6 +159,14 @@ func NewFinalHopBlindedRouteData(constraints *PaymentConstraints,
tlv.NewRecordT[tlv.TlvType12](*constraints))
}
+ if invoiceEnvelope != nil {
+ data.InvoiceEnvelope = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType65538](
+ invoiceEnvelope,
+ ),
+ )
+ }
+
return &data
}
@@ -187,6 +203,7 @@ func DecodeBlindedRouteData(r io.Reader) (*BlindedRouteData, error) {
relayInfo = d.RelayInfo.Zero()
constraints = d.Constraints.Zero()
features = d.Features.Zero()
+ invoiceEnvelope = d.InvoiceEnvelope.Zero()
)
var tlvRecords lnwire.ExtraOpaqueData
@@ -196,7 +213,7 @@ func DecodeBlindedRouteData(r io.Reader) (*BlindedRouteData, error) {
typeMap, err := tlvRecords.ExtractRecords(
&padding, &scid, &nextNodeID, &pathID, &blindingOverride,
- &relayInfo, &constraints, &features,
+ &relayInfo, &constraints, &features, &invoiceEnvelope,
)
if err != nil {
return nil, err
@@ -236,6 +253,11 @@ func DecodeBlindedRouteData(r io.Reader) (*BlindedRouteData, error) {
d.Features = tlv.SomeRecordT(features)
}
+ val, ok = typeMap[d.InvoiceEnvelope.TlvType()]
+ if ok && val == nil {
+ d.InvoiceEnvelope = tlv.SomeRecordT(invoiceEnvelope)
+ }
+
return &d, nil
}
@@ -290,6 +312,12 @@ func EncodeBlindedRouteData(data *BlindedRouteData) ([]byte, error) {
recordProducers = append(recordProducers, &f)
})
+ data.InvoiceEnvelope.WhenSome(
+ func(env tlv.RecordT[tlv.TlvType65538, []byte]) {
+ recordProducers = append(recordProducers, &env)
+ },
+ )
+
if err := e.PackRecords(recordProducers...); err != nil {
return nil, err
}
### record/blinded_data_test.go
@@ -125,6 +125,7 @@ func TestBlindedDataFinalHopEncoding(t *testing.T) {
name string
pathID []byte
constraints bool
+ envelope []byte
}{
{
name: "with path ID",
@@ -139,6 +140,11 @@ func TestBlindedDataFinalHopEncoding(t *testing.T) {
pathID: []byte{1, 2, 3, 4, 5, 6},
constraints: true,
},
+ {
+ name: "with path ID and invoice envelope",
+ pathID: []byte{1, 2, 3, 4, 5, 6},
+ envelope: []byte{7, 8, 9},
+ },
}
for _, test := range tests {
@@ -154,7 +160,7 @@ func TestBlindedDataFinalHopEncoding(t *testing.T) {
}
encodedData := NewFinalHopBlindedRouteData(
- constraints, test.pathID,
+ constraints, test.pathID, test.envelope,
)
encoded, err := EncodeBlindedRouteData(encodedData)
@@ -165,6 +171,9 @@ func TestBlindedDataFinalHopEncoding(t *testing.T) {
require.NoError(t, err)
require.Equal(t, encodedData, decodedData)
+
+ envelope := decodedData.InvoiceEnvelope.ValOpt()
+ require.Equal(t, test.envelope, envelope.UnwrapOr(nil))
})
}
}
### routing/blindedpath/blinded_path.go
@@ -23,6 +23,11 @@ import (
const (
// oneMillion is a constant used frequently in fee rate calculations.
oneMillion = uint32(1_000_000)
+
+ // payerOnionReserve is the part of the payer's onion that a blinded
+ // path with an invoice envelope leaves free. It holds five clear hops
+ // of the payer to the introduction node, at 59 bytes each.
+ payerOnionReserve = 295
)
// errInvalidBlindedPath indicates that the chosen real path is not usable as
@@ -69,6 +74,11 @@ type BuildBlindedPathCfg struct {
// that the path is being used in the correct context.
PathID []byte
+ // InvoiceEnvelope is an optional envelope for stateless BOLT 12
+ // invoice settlement. When set, it is embedded alongside PathID in the
+ // final hop's encrypted data.
+ InvoiceEnvelope []byte
+
// ValueMsat is the payment amount in milli-satoshis that must be
// routed. This will be used for selecting appropriate routes to use for
// the blinded path.
@@ -226,10 +236,9 @@ func buildBlindedPaymentPath(cfg *BuildBlindedPathCfg, path *candidatePath) (
finalHopPubKey = path.hops[len(path.hops)-1].pubKey
}
- // For the final hop, we only send it the path ID and payment
- // constraints.
info, err := buildFinalHopRouteData(
- finalHopPubKey, cfg.PathID, constraints,
+ finalHopPubKey, cfg.PathID, cfg.InvoiceEnvelope,
+ constraints,
)
if err != nil {
return nil, err
@@ -299,6 +308,23 @@ func buildBlindedPaymentPath(cfg *BuildBlindedPathCfg, path *candidatePath) (
"hop")
}
+ // The padding gives every hop the size of the final hop, so an
+ // invoice envelope grows each hop. The payer cannot use a path that
+ // leaves no room in its onion for its own hops.
+ if len(cfg.InvoiceEnvelope) > 0 {
+ size := blindedPathOnionSize(
+ blindedPath, cfg.ValueMsat, cltvExpiry,
+ )
+ maxSize := uint64(
+ sphinx.MaxRoutingPayloadSize - payerOnionReserve,
+ )
+ if size > maxSize {
+ return nil, fmt.Errorf("%w: blinded hops use %d bytes "+
+ "of the onion, maximum is %d",
+ errInvalidBlindedPath, size, maxSize)
+ }
+ }
+
// Overwrite the introduction point's blinded pub key with the real
// pub key since then we can use this more compact format in the
// invoice without needing to encode the un-used blinded node pub key of
@@ -319,6 +345,32 @@ func buildBlindedPaymentPath(cfg *BuildBlindedPathCfg, path *candidatePath) (
}, nil
}
+// blindedPathOnionSize returns the number of onion bytes that the payer
+// spends on the hops of the blinded path. The final hop amount and CLTV are
+// upper bounds, so the result does not underestimate the size.
+func blindedPathOnionSize(path *sphinx.BlindedPath, amt lnwire.MilliSatoshi,
+ cltvExpiry uint32) uint64 {
+
+ var size uint64
+ for i, blindedHop := range path.BlindedHops {
+ hop := route.Hop{
+ EncryptedData: blindedHop.CipherText,
+ }
+ if i == 0 {
+ hop.BlindingPoint = path.BlindingPoint
+ }
+ if i == len(path.BlindedHops)-1 {
+ hop.AmtToForward = amt
+ hop.TotalAmtMsat = amt
+ hop.OutgoingTimeLock = cltvExpiry
+ }
+
+ size += hop.PayloadSize(0)
+ }
+
+ return size
+}
+
// hopRelayInfo packages together the relay info to send to hop on a blinded
// path along with the pub key of that hop and the SCID that the hop should
// forward the payment on to.
@@ -626,10 +678,11 @@ func buildHopRouteData(node route.Vertex, scid lnwire.ShortChannelID,
// final hop and packages it with the real node ID of the node it is intended
// for.
func buildFinalHopRouteData(node route.Vertex, pathID []byte,
+ invoiceEnvelope []byte,
constraints *record.PaymentConstraints) (*hopData, error) {
blindedRouteHopData := record.NewFinalHopBlindedRouteData(
- constraints, pathID,
+ constraints, pathID, invoiceEnvelope,
)
nodeID, err := btcec.ParsePubKey(node[:])
if err != nil {
### routing/blindedpath/blinded_path_test.go
@@ -12,6 +12,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/chanstate"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lnwire"
@@ -1266,3 +1267,164 @@ func decryptAndDecodeHopData(t *testing.T, priv *btcec.PrivateKey,
return routeData, nextEphem
}
+
+// TestBuildBlindedPathInvoiceEnvelope verifies that only the final hop of a
+// blinded path carries the invoice envelope.
+func TestBuildBlindedPathInvoiceEnvelope(t *testing.T) {
+ t.Parallel()
+
+ privKey, _ := btcec.PrivKeyFromBytes([]byte{1})
+ envelope := []byte{4, 5, 6}
+
+ paths, err := BuildBlindedPaymentPaths(envelopePathCfg(2, envelope))
+ require.NoError(t, err)
+ require.Len(t, paths, 1)
+
+ hops := paths[0].Hops
+ ephem := paths[0].FirstEphemeralBlindingPoint
+ for i, hop := range hops {
+ var data *record.BlindedRouteData
+ data, ephem = decryptAndDecodeHopData(
+ t, privKey, ephem, hop.CipherText,
+ )
+
+ if i < len(hops)-1 {
+ require.True(t, data.InvoiceEnvelope.IsNone())
+ continue
+ }
+ require.Equal(
+ t, envelope, data.InvoiceEnvelope.UnwrapOrFailV(t),
+ )
+ }
+}
+
+// envelopePathCfg returns a config for paths of the local node padded to
+// numHops+1 hops, with the given invoice envelope in the final hop.
+func envelopePathCfg(numHops uint8, envelope []byte) *BuildBlindedPathCfg {
+ _, pubKey := btcec.PrivKeyFromBytes([]byte{1})
+ self := route.NewVertex(pubKey)
+
+ return &BuildBlindedPathCfg{
+ FindRoutes: func(_ lnwire.MilliSatoshi) ([]*route.Route,
+ error) {
+
+ return []*route.Route{{SourcePubKey: self}}, nil
+ },
+ FetchOurOpenChannels: func() ([]*chanstate.OpenChannel,
+ error) {
+
+ return []*chanstate.OpenChannel{{
+ Capacity: 1_000_000,
+ }}, nil
+ },
+ BestHeight: func() (uint32, error) {
+ return 1000, nil
+ },
+ AddPolicyBuffer: func(p *BlindedHopPolicy) (
+ *BlindedHopPolicy, error) {
+
+ return p, nil
+ },
+ PathID: []byte{1, 2, 3},
+ InvoiceEnvelope: envelope,
+ ValueMsat: 1000,
+ MinFinalCLTVExpiryDelta: 12,
+ BlocksUntilExpiry: 200,
+ MinNumHops: numHops,
+ DefaultDummyHopPolicy: &BlindedHopPolicy{
+ CLTVExpiryDelta: 50,
+ FeeRate: 100,
+ BaseFee: 100,
+ MinHTLCMsat: 1000,
+ MaxHTLCMsat: lnwire.MaxMilliSatoshi,
+ },
+ }
+}
+
+// TestBuildBlindedPathEnvelopeOnionBudget verifies that a path with an
+// invoice envelope is dropped when its blinded hops leave less than the
+// reserve of the payer's onion. A path without an envelope is not checked.
+func TestBuildBlindedPathEnvelopeOnionBudget(t *testing.T) {
+ t.Parallel()
+
+ maxSize := uint64(sphinx.MaxRoutingPayloadSize - payerOnionReserve)
+
+ // A single hop spends 123 onion bytes besides its envelope, so an
+ // envelope of 882 bytes fills the budget exactly. An invoice envelope
+ // has 151 bytes with the field sizes that TestSize pins.
+ tests := []struct {
+ name string
+ numHops uint8
+ envelopeLen int
+ wantHops int
+ atBudget bool
+ }{
+ {
+ name: "three hops with an invoice envelope",
+ numHops: 2,
+ envelopeLen: 151,
+ wantHops: 3,
+ },
+ {
+ name: "envelope at the budget",
+ envelopeLen: 882,
+ wantHops: 1,
+ atBudget: true,
+ },
+ {
+ name: "envelope one byte over the budget",
+ envelopeLen: 883,
+ },
+ {
+ name: "no envelope over the budget",
+ numHops: 10,
+ wantHops: 11,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ var envelope []byte
+ if tc.envelopeLen > 0 {
+ envelope = bytes.Repeat(
+ []byte{1}, tc.envelopeLen,
+ )
+ }
+
+ paths, err := BuildBlindedPaymentPaths(
+ envelopePathCfg(tc.numHops, envelope),
+ )
+ if tc.wantHops == 0 {
+ require.ErrorContains(
+ t, err, "could not build any blinded "+
+ "paths",
+ )
+
+ return
+ }
+ require.NoError(t, err)
+ require.Len(t, paths, 1)
+ require.Len(t, paths[0].Hops, tc.wantHops)
+
+ if envelope == nil {
+ return
+ }
+
+ path := paths[0]
+ blindedPath := &sphinx.BlindedPath{
+ BlindingPoint: path.FirstEphemeralBlindingPoint,
+ BlindedHops: path.Hops,
+ }
+ size := blindedPathOnionSize(
+ blindedPath, 1000, 1000+200+12,
+ )
+ if tc.atBudget {
+ require.Equal(t, maxSize, size)
+ } else {
+ require.Less(t, size, maxSize)
+ }
+ })
+ }
+}
### server.go
@@ -972,9 +972,16 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
)
replier := bolt12handler.NewServerOnionReplier(s)
+ var pathIDKey bolt12handler.PathIDKey
+ pathIDKey, err = bolt12handler.DerivePathIDKey(nodeKeyECDH)
+ if err != nil {
+ return nil, err
+ }
+
// Use the final CLTV delta of BOLT 11 invoices.
s.bolt12Handler, err = bolt12handler.NewHandler(
- s.offerStore, s.invoices, replier, signer, nil,
+ s.offerStore, s.invoices, replier, signer, pathIDKey,
+ nil,
clock.NewDefaultClock(),
*s.cfg.ActiveNetParams.GenesisHash,
uint16(cfg.Bitcoin.TimeLockDelta),
### sqldb/migrations_dev.go
@@ -14,4 +14,9 @@ var migrationAdditions = []MigrationConfig{
Version: 20,
SchemaVersion: 17,
},
+ {
+ Name: "000018_bolt12_invoices",
+ Version: 21,
+ SchemaVersion: 18,
+ },
}
### sqldb/sqlc/bolt12.sql.go
@@ -0,0 +1,48 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: bolt12.sql
+
+package sqlc
+
+import (
+ "context"
+ "database/sql"
+)
+
+const fetchBolt12Invoice = `-- name: FetchBolt12Invoice :one
+SELECT offer_id, envelope
+FROM bolt12_invoices
+WHERE invoice_id = $1
+`
+
+type FetchBolt12InvoiceRow struct {
+ OfferID sql.NullInt64
+ Envelope []byte
+}
+
+func (q *Queries) FetchBolt12Invoice(ctx context.Context, invoiceID int64) (FetchBolt12InvoiceRow, error) {
+ row := q.db.QueryRowContext(ctx, fetchBolt12Invoice, invoiceID)
+ var i FetchBolt12InvoiceRow
+ err := row.Scan(&i.OfferID, &i.Envelope)
+ return i, err
+}
+
+const insertBolt12Invoice = `-- name: InsertBolt12Invoice :exec
+INSERT INTO bolt12_invoices (
+ invoice_id, offer_id, envelope
+) VALUES (
+ $1, $2, $3
+)
+`
+
+type InsertBolt12InvoiceParams struct {
+ InvoiceID int64
+ OfferID sql.NullInt64
+ Envelope []byte
+}
+
+func (q *Queries) InsertBolt12Invoice(ctx context.Context, arg InsertBolt12InvoiceParams) error {
+ _, err := q.db.ExecContext(ctx, insertBolt12Invoice, arg.InvoiceID, arg.OfferID, arg.Envelope)
+ return err
+}
### sqldb/sqlc/migrations/000018_bolt12_invoices.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS bolt12_invoices_offer_id_idx;
+DROP TABLE IF EXISTS bolt12_invoices;
### sqldb/sqlc/migrations/000018_bolt12_invoices.up.sql
@@ -0,0 +1,22 @@
+-- bolt12_invoices holds the BOLT 12 data of a received invoice. The shared
+-- invoices table stays protocol agnostic, so only BOLT 12 queries touch this
+-- table. The receiver keeps no signed invoice string after stateless
+-- settlement, so this row holds every BOLT 12 fact it needs later. A row also
+-- marks its invoice as a BOLT 12 invoice.
+CREATE TABLE IF NOT EXISTS bolt12_invoices (
+ -- The invoice this data belongs to. The row is deleted with it.
+ invoice_id BIGINT PRIMARY KEY REFERENCES invoices(id) ON DELETE CASCADE,
+
+ -- The offer that created the invoice. NULL for an invoice that answers
+ -- no offer. The foreign key has no ON DELETE on purpose: an offer that
+ -- an invoice links to cannot be deleted, so an invoice never loses its
+ -- offer.
+ offer_id BIGINT REFERENCES offers(id),
+
+ -- The invoice envelope that the payment carried. It is the
+ -- authoritative source of the BOLT 12 order data of the invoice.
+ envelope BLOB NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS bolt12_invoices_offer_id_idx
+ON bolt12_invoices(offer_id);
### sqldb/sqlc/models.go
@@ -28,6 +28,12 @@ type AmpSubInvoiceHtlc struct {
Preimage []byte
}
+type Bolt12Invoice struct {
+ InvoiceID int64
+ OfferID sql.NullInt64
+ Envelope []byte
+}
+
type ChainParam struct {
SingleRow bool
Network string
### sqldb/sqlc/querier.go
@@ -40,6 +40,7 @@ type Querier interface {
FailPayment(ctx context.Context, arg FailPaymentParams) (sql.Result, error)
FetchAMPSubInvoiceHTLCs(ctx context.Context, arg FetchAMPSubInvoiceHTLCsParams) ([]FetchAMPSubInvoiceHTLCsRow, error)
FetchAMPSubInvoices(ctx context.Context, arg FetchAMPSubInvoicesParams) ([]AmpSubInvoice, error)
+ FetchBolt12Invoice(ctx context.Context, invoiceID int64) (FetchBolt12InvoiceRow, error)
FetchHopLevelCustomRecords(ctx context.Context, hopIds []int64) ([]PaymentHopCustomRecord, error)
FetchHopsForAttempts(ctx context.Context, htlcAttemptIndices []int64) ([]FetchHopsForAttemptsRow, error)
// Batch query to fetch only HTLC resolution status for multiple payments.
@@ -185,6 +186,7 @@ type Querier interface {
HighestSCID(ctx context.Context, version int16) ([]byte, error)
InsertAMPSubInvoice(ctx context.Context, arg InsertAMPSubInvoiceParams) error
InsertAMPSubInvoiceHTLC(ctx context.Context, arg InsertAMPSubInvoiceHTLCParams) error
+ InsertBolt12Invoice(ctx context.Context, arg InsertBolt12InvoiceParams) error
InsertChainNetwork(ctx context.Context, network string) error
InsertChannelFeature(ctx context.Context, arg InsertChannelFeatureParams) error
// NOTE: This query is only meant to be used by the graph SQL migration since
### sqldb/sqlc/queries/bolt12.sql
@@ -0,0 +1,11 @@
+-- name: InsertBolt12Invoice :exec
+INSERT INTO bolt12_invoices (
+ invoice_id, offer_id, envelope
+) VALUES (
+ $1, $2, $3
+);
+
+-- name: FetchBolt12Invoice :one
+SELECT offer_id, envelope
+FROM bolt12_invoices
+WHERE invoice_id = $1;Why this scored 34/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.