Merge pull request #11374 from bitromortac/20261016-c7e5-dispatch
What changed, and why it matters
This commit adds the first end-to-end BOLT 12 'Offers' flow to LND: a new dev-only RPC and CLI command to create offers, plus a dispatcher that listens for incoming onion-message invoice requests and replies with signed BOLT 12 invoices. It also adds rate/inflight limits and reply-path handling to avoid obvious DoS, but the feature is gated behind dev/native-SQL builds and explicitly marked as not yet returning invoice_error replies for failed requests.
Treat this as an early-stage feature merge rather than an active vulnerability. Reviewers should monitor for: completeness of invoice_error replies, robust validation of invoice-request signatures/amounts/quantities, correct handling of malformed reply paths, and whether the rate/concurrency limits adequately protect against CPU/queue exhaustion. Because it is dev-only and opt-in, no immediate production action is required.
Security signals we found
New network-facing dispatcher answers invoice requests from any peer; rate and concurrency limits are applied
Blinded-path PathID check prevents reply linking to self-created paths, but TODO notes the check should move once offers can have offer_paths
CreateOffer RPC is restricted to dev builds and requires offchain:write macaroon permission
BOLT 12 handler is only instantiated when offerStore (native SQL/dev migrations) is present
Release notes explicitly state 'A failed request gets no invoice_error reply yet', indicating incomplete error handling
HopPeeler decrypts own-hop recipient data to advance reply path; malformed data is logged and dropped
Evidence from the diff
The patch introduces bolt12handler.Handler dispatching via onion-message subscription, a GraphIntroResolver for sciddir introduction nodes, a HopPeeler to strip own-node hops from reply paths, and CreateOffer in devrpc/lncli. It wires the offer store, invoice registry, and server onion-message plumbing. Security-relevant design choices include: maxInflightRequests=8, requestRate=10/s with burst 20, dropping requests without reply paths, skipping requests arriving on blinded paths with PathID, and macaroon permission offchain:write for CreateOffer. The code is dev-only and requires –protocol.bolt12-offers plus native SQL.
Changed components
bolt12handlerlnrpc/devrpccmd/commandsonionmessagelnwireserver.gorpcserver.gosubrpcserver_config.goInspect captured patch +3113 / −78
### bolt12handler/dispatcher.go
@@ -0,0 +1,248 @@
+package bolt12handler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/onionmessage"
+ "github.com/lightningnetwork/lnd/subscribe"
+)
+
+// maxInflightRequests is the number of invoice requests that the node
+// handles at the same time. A reply can wait for a slow peer, so the limit
+// keeps one peer from stalling the other requests.
+const maxInflightRequests = 8
+
+const (
+ // requestRate is the number of invoice requests per second that the
+ // node answers. Each answer costs a signature and puts an event into
+ // the queue of every invoice subscriber, and any peer can send a
+ // request. A payer needs one invoice per payment.
+ requestRate = 10
+
+ // requestBurst is the number of invoice requests that the node answers
+ // at once before requestRate applies.
+ requestBurst = 20
+)
+
+// OnionMessageSubscriber gives a stream of incoming onion message updates.
+type OnionMessageSubscriber interface {
+ // SubscribeOnionMessages returns a client that receives an
+ // OnionMessageUpdate for each incoming onion message.
+ SubscribeOnionMessages() (*subscribe.Client, error)
+}
+
+// errHandlerStopped is returned by Start after Stop.
+var errHandlerStopped = errors.New("handler is stopped")
+
+// HopPeeler removes the hops of this node at the start of a reply
+// path, so that the reply goes to a peer.
+type HopPeeler interface {
+ // PeelOwnHops returns path without the hops of this node at its
+ // start, or path as it is when another node is its introduction node.
+ PeelOwnHops(ctx context.Context,
+ path *sphinx.BlindedPath) (*sphinx.BlindedPath, error)
+}
+
+// Start subscribes to onion messages and answers the invoice requests in
+// them until Stop or until ctx ends. The subscriber must already run. The
+// resolver finds the introduction node of a reply path in the sciddir form,
+// and the peeler removes the hops of this node at its start. Start after
+// Stop returns an error.
+func (h *Handler) Start(ctx context.Context,
+ subscriber OnionMessageSubscriber, resolver IntroNodeResolver,
+ peeler HopPeeler) error {
+
+ select {
+ case <-h.gm.Done():
+ return errHandlerStopped
+
+ default:
+ }
+
+ if !h.started.CompareAndSwap(false, true) {
+ return nil
+ }
+
+ client, err := subscriber.SubscribeOnionMessages()
+ if err != nil {
+ return fmt.Errorf("subscribe to onion messages: %w", err)
+ }
+ h.introResolver = resolver
+ h.hopPeeler = peeler
+
+ started := h.gm.Go(ctx, func(ctx context.Context) {
+ h.dispatch(ctx, client)
+ })
+ if !started {
+ client.Cancel()
+
+ // Go also refuses a goroutine when ctx has already ended.
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ return errHandlerStopped
+ }
+
+ return nil
+}
+
+// Stop cancels the running requests and waits until they return.
+func (h *Handler) Stop() {
+ h.gm.Stop()
+}
+
+// dispatch answers each invoice request from client until Stop, the end of
+// ctx, or the end of the subscription. It drops a request above the request
+// rate, or when maxInflight requests already run, so that the subscriber
+// queue does not grow. The context of a running request ends when the dispatch
+// ends.
+func (h *Handler) dispatch(ctx context.Context, client *subscribe.Client) {
+ defer client.Cancel()
+
+ slots := make(chan struct{}, h.maxInflight)
+
+ for {
+ select {
+ case update, ok := <-client.Updates():
+ if !ok {
+ return
+ }
+
+ invreqBytes, replyPath, ok := invoiceRequest(update)
+ if !ok {
+ continue
+ }
+
+ if !h.requestLimiter.Allow() {
+ log.Debugf("Dropping invoice request: rate " +
+ "limit reached")
+
+ continue
+ }
+
+ if !acquireSlot(slots) {
+ log.Debugf("Dropping invoice request: too " +
+ "many requests in flight")
+
+ continue
+ }
+
+ started := h.gm.Go(ctx, func(ctx context.Context) {
+ defer func() { <-slots }()
+
+ h.answerInvoiceRequest(
+ ctx, invreqBytes, replyPath,
+ )
+ })
+ if !started {
+ <-slots
+
+ return
+ }
+
+ // The subscribe server ends a subscription with Quit, and it
+ // does not close the updates.
+ case <-client.Quit():
+ return
+
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+// invoiceRequest returns the invoice request and the reply path of an onion
+// message update. It returns false when this node must not answer the
+// update, for example when the node only forwards the message.
+func invoiceRequest(update any) ([]byte, *lnwire.BlindedPath, bool) {
+ msg, ok := update.(*onionmessage.OnionMessageUpdate)
+ if !ok || !msg.Delivered {
+ return nil, nil, false
+ }
+
+ // BOLT 12 says to ignore a request for an offer without offer_paths
+ // when it arrives on a blinded path, so that an answer does not link
+ // such a path to this node. Every offer of this node has no
+ // offer_paths, and a path that this node made carries a path_id.
+ //
+ // TODO: Move this check into HandleInvoiceRequest, where the offer is
+ // known, when offers can have offer_paths.
+ if len(msg.PathID) > 0 {
+ log.Debugf("Skipping invoice request that arrived on a " +
+ "blinded path")
+
+ return nil, nil, false
+ }
+
+ invreq, ok := msg.CustomRecords[uint64(
+ lnwire.InvoiceRequestNamespaceType,
+ )]
+ if !ok {
+ return nil, nil, false
+ }
+
+ // The handler answers only through the reply path. A request without
+ // one is the sender's choice and not a fault of this node, so it gets
+ // no warning.
+ if msg.ReplyPath == nil {
+ log.Debugf("Skipping invoice request without a reply path")
+
+ return nil, nil, false
+ }
+
+ return invreq, msg.ReplyPath, true
+}
+
+// acquireSlot takes a slot from slots without blocking. It returns false
+// when every slot is taken.
+func acquireSlot(slots chan struct{}) bool {
+ select {
+ case slots <- struct{}{}:
+ return true
+
+ default:
+ return false
+ }
+}
+
+// answerInvoiceRequest answers one invoice request over its reply path.
+func (h *Handler) answerInvoiceRequest(ctx context.Context,
+ invreqBytes []byte, replyPath *lnwire.BlindedPath) {
+
+ // A payer can name the introduction node by a channel to keep the
+ // reply path short.
+ replyPath, err := resolveIntroNode(ctx, replyPath, h.introResolver)
+ if err != nil {
+ log.Debugf("Failed to resolve reply path: %v", err)
+
+ return
+ }
+
+ sphinxReplyPath, err := replyPath.ToSphinx()
+ if err != nil {
+ log.Debugf("Failed to convert reply path: %v", err)
+
+ return
+ }
+
+ // A payer whose only peer is this node names this node as the
+ // introduction node, to hide its own node id.
+ sphinxReplyPath, err = h.hopPeeler.PeelOwnHops(
+ ctx, sphinxReplyPath,
+ )
+ if err != nil {
+ log.Debugf("Failed to peel own hops off reply path: %v", err)
+
+ return
+ }
+
+ err = h.HandleInvoiceRequest(ctx, invreqBytes, sphinxReplyPath)
+ if err != nil {
+ log.Debugf("Failed to handle invoice request: %v", err)
+ }
+}
### bolt12handler/dispatcher_test.go
@@ -0,0 +1,601 @@
+package bolt12handler
+
+import (
+ "context"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/clock"
+ "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/onionmessage"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/lightningnetwork/lnd/subscribe"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/time/rate"
+)
+
+// TestInvoiceRequest checks that invoiceRequest accepts only invoice requests
+// that are delivered to this node and carry a reply path.
+func TestInvoiceRequest(t *testing.T) {
+ t.Parallel()
+
+ invreq := []byte{1, 2, 3}
+ replyPath := &lnwire.BlindedPath{}
+ records := record.CustomSet{
+ uint64(lnwire.InvoiceRequestNamespaceType): invreq,
+ }
+
+ tests := []struct {
+ name string
+ update any
+ ok bool
+ }{
+ {
+ name: "delivered request",
+ update: &onionmessage.OnionMessageUpdate{
+ CustomRecords: records,
+ ReplyPath: replyPath,
+ Delivered: true,
+ },
+ ok: true,
+ },
+ {
+ name: "forwarded request",
+ update: &onionmessage.OnionMessageUpdate{
+ CustomRecords: records,
+ ReplyPath: replyPath,
+ },
+ },
+ {
+ name: "arrived on a blinded path",
+ update: &onionmessage.OnionMessageUpdate{
+ CustomRecords: records,
+ ReplyPath: replyPath,
+ PathID: []byte{1},
+ Delivered: true,
+ },
+ },
+ {
+ name: "no reply path",
+ update: &onionmessage.OnionMessageUpdate{
+ CustomRecords: records,
+ Delivered: true,
+ },
+ },
+ {
+ name: "no invoice request",
+ update: &onionmessage.OnionMessageUpdate{
+ ReplyPath: replyPath,
+ Delivered: true,
+ },
+ },
+ {
+ name: "other update type",
+ update: "not an onion message update",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ gotInvreq, gotPath, ok := invoiceRequest(
+ tc.update,
+ )
+ require.Equal(t, tc.ok, ok)
+ if !tc.ok {
+ return
+ }
+
+ require.Equal(t, invreq, gotInvreq)
+ require.Same(t, replyPath, gotPath)
+ })
+ }
+}
+
+// nopNotifier drops the invoice events. The handlers of the dispatch tests run
+// in parallel, and the events are not part of these tests.
+type nopNotifier struct{}
+
+// NotifyNewBolt12Invoice does nothing.
+func (nopNotifier) NotifyNewBolt12Invoice(context.Context, lntypes.Hash,
+ *invoices.Invoice) {
+}
+
+// sentReply holds an invoice reply and the blinded path it was sent on.
+type sentReply struct {
+ invoice []byte
+ path *sphinx.BlindedPath
+}
+
+// chanReplier gives each reply to the test. The send blocks until the test
+// takes the reply, so a handler keeps its slot until then.
+type chanReplier struct {
+ replies chan sentReply
+
+ // canceled counts the sends that returned because ctx ended.
+ canceled atomic.Int32
+}
+
+// SendInvoiceReply sends the reply on the channel, or returns when ctx ends.
+// A canceled send returns one second later in bubble time. A caller that does
+// not wait for it sees that the send has not returned yet.
+func (r *chanReplier) SendInvoiceReply(ctx context.Context,
+ invoiceBytes []byte, replyPath *sphinx.BlindedPath) error {
+
+ select {
+ case r.replies <- sentReply{invoice: invoiceBytes, path: replyPath}:
+ return nil
+
+ case <-ctx.Done():
+ time.Sleep(time.Second)
+ r.canceled.Add(1)
+
+ return ctx.Err()
+ }
+}
+
+// subscriberFunc adapts a function to OnionMessageSubscriber.
+type subscriberFunc func() (*subscribe.Client, error)
+
+func (f subscriberFunc) SubscribeOnionMessages() (*subscribe.Client, error) {
+ return f()
+}
+
+// stubPeeler returns a reply path as it is, or fails with err.
+type stubPeeler struct {
+ err error
+}
+
+func (s *stubPeeler) PeelOwnHops(_ context.Context,
+ path *sphinx.BlindedPath) (*sphinx.BlindedPath, error) {
+
+ if s.err != nil {
+ return nil, s.err
+ }
+
+ return path, nil
+}
+
+// dispatchTest runs a started Handler on a subscribe.Server. It must be created
+// inside a synctest bubble.
+type dispatchTest struct {
+ t *testing.T
+ server *subscribe.Server
+ handler *Handler
+ replier *chanReplier
+ replies chan sentReply
+
+ // peeler is the hop peeler that the handler started with.
+ peeler *stubPeeler
+
+ // cancel ends the context that the handler started with.
+ cancel context.CancelFunc
+
+ nodeKey *btcec.PrivateKey
+ payerKey *btcec.PrivateKey
+
+ // request is a valid invoice request that is delivered to this node.
+ request *onionmessage.OnionMessageUpdate
+}
+
+// newDispatchTest starts a handler that answers maxInflight requests at the
+// same time.
+func newDispatchTest(t *testing.T, maxInflight int,
+ opts ...func(*Handler)) *dispatchTest {
+
+ t.Helper()
+
+ nodeKey := testKey(t)
+ payerKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ store := newMockOfferStore()
+ offer, _ := addOffer(t, store, nodeKey, 10000)
+
+ intro, err := lnwire.NewPubkeyIntro(nodeKey.PubKey())
+ require.NoError(t, err)
+
+ invreq := buildSignedInvreqBytes(t, offer, payerKey, 10000)
+ invreqType := uint64(lnwire.InvoiceRequestNamespaceType)
+
+ replies := make(chan sentReply)
+ replier := &chanReplier{replies: replies}
+ handler, err := NewHandler(
+ store, nopNotifier{}, replier,
+ newPrivKeySigner(nodeKey), nil, clock.NewDefaultClock(),
+ testChainHash(), testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+ handler.maxInflight = maxInflight
+ for _, opt := range opts {
+ opt(handler)
+ }
+
+ server := subscribe.NewServer()
+ require.NoError(t, server.Start())
+ // The test context ends with the test, which would hide a dispatch
+ // that ends too late. Only the test cancels this context.
+ ctx, cancel := context.WithCancel(context.WithoutCancel(t.Context()))
+ peeler := &stubPeeler{}
+ require.NoError(t, handler.Start(
+ ctx, subscriberFunc(server.Subscribe),
+ testIntroResolver(t, nodeKey), peeler,
+ ))
+
+ return &dispatchTest{
+ t: t,
+ server: server,
+ handler: handler,
+ replier: replier,
+ replies: replies,
+ peeler: peeler,
+ cancel: cancel,
+ nodeKey: nodeKey,
+ payerKey: payerKey,
+ request: &onionmessage.OnionMessageUpdate{
+ CustomRecords: record.CustomSet{invreqType: invreq},
+ ReplyPath: &lnwire.BlindedPath{
+ IntroductionNode: intro,
+ BlindingPoint: nodeKey.PubKey(),
+ },
+ Delivered: true,
+ },
+ }
+}
+
+// send gives the server an update and returns when every goroutine in the
+// bubble blocks. The handler has then handled the update.
+func (d *dispatchTest) send(update *onionmessage.OnionMessageUpdate) {
+ require.NoError(d.t, d.server.SendUpdate(update))
+ synctest.Wait()
+}
+
+// requireNoReply fails the test if a handler waits to send a reply.
+func (d *dispatchTest) requireNoReply() {
+ synctest.Wait()
+
+ select {
+ case <-d.replies:
+ require.FailNow(d.t, "unexpected reply")
+
+ default:
+ }
+}
+
+// stop stops the handler and then the server.
+func (d *dispatchTest) stop() {
+ d.handler.Stop()
+ require.NoError(d.t, d.server.Stop())
+}
+
+// TestHandlerDispatch checks that a started Handler answers the invoice
+// requests in onion messages, limits them, and stops.
+func TestHandlerDispatch(t *testing.T) {
+ t.Parallel()
+
+ t.Run("answers a request", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ d.send(d.request)
+ reply := <-d.replies
+ d.stop()
+
+ invoice, err := bolt12.DecodeInvoice(reply.invoice)
+ require.NoError(t, err)
+ require.True(t, d.payerKey.PubKey().IsEqual(
+ invoice.InvreqPayerID.UnwrapOrFailV(t),
+ ))
+ require.True(t, d.nodeKey.PubKey().IsEqual(
+ reply.path.IntroductionPoint,
+ ))
+ })
+ })
+
+ t.Run("answers a sciddir reply path", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ sciddir, err := lnwire.NewSciddirIntro(1, testSCID)
+ require.NoError(t, err)
+
+ request := *d.request
+ replyPath := *request.ReplyPath
+ replyPath.IntroductionNode = sciddir
+ request.ReplyPath = &replyPath
+
+ d.send(&request)
+ reply := <-d.replies
+ d.stop()
+
+ require.True(t, d.nodeKey.PubKey().IsEqual(
+ reply.path.IntroductionPoint,
+ ))
+ })
+ })
+
+ t.Run("skips an unknown sciddir", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ sciddir, err := lnwire.NewSciddirIntro(
+ 1, [8]byte{9, 9, 9},
+ )
+ require.NoError(t, err)
+
+ request := *d.request
+ replyPath := *request.ReplyPath
+ replyPath.IntroductionNode = sciddir
+ request.ReplyPath = &replyPath
+
+ d.send(&request)
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("skips a reply path that ends here", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ // The handler gets no peer to send the reply to, so
+ // it drops the request.
+ d.peeler.err = onionmessage.ErrPathEndsAtSelf
+ d.send(d.request)
+
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("skips a forwarded request", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ forwarded := *d.request
+ forwarded.Delivered = false
+ d.send(&forwarded)
+
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("drops when full", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ const maxInflight = 2
+
+ d := newDispatchTest(t, maxInflight)
+
+ // Each handler holds its slot until the test takes its
+ // reply, so the last two requests find no slot.
+ for range maxInflight + 2 {
+ d.send(d.request)
+ }
+ for range maxInflight {
+ <-d.replies
+ }
+
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("drops above the rate", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ const burst = 2
+
+ // The bucket never refills, so only the burst gets an
+ // answer although slots are free.
+ d := newDispatchTest(t, burst+2, func(h *Handler) {
+ h.requestLimiter = rate.NewLimiter(0, burst)
+ })
+
+ for range burst + 2 {
+ d.send(d.request)
+ }
+ for range burst {
+ <-d.replies
+ }
+
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("frees a slot", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ // The handler frees its slot when it returns after the
+ // reply. The bubble reports a deadlock if the second
+ // request finds the slot still taken.
+ for range 2 {
+ d.send(d.request)
+ <-d.replies
+ synctest.Wait()
+ }
+
+ d.stop()
+ })
+ })
+
+ t.Run("cancels on stop", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ // The handler waits to send its reply. The bubble
+ // reports a deadlock if Stop does not cancel it.
+ d.send(d.request)
+ d.handler.Stop()
+
+ require.EqualValues(t, 1, d.replier.canceled.Load(),
+ "Stop returned before the request")
+ require.NoError(t, d.server.Stop())
+ })
+ })
+
+ t.Run("ends with the context", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ // The end of the context cancels the waiting handler
+ // and ends the dispatch, so the next request gets no
+ // answer.
+ d.send(d.request)
+ d.cancel()
+ d.send(d.request)
+
+ d.requireNoReply()
+ d.stop()
+ })
+ })
+
+ t.Run("ends with the subscription", func(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ d := newDispatchTest(t, 1)
+
+ // Stopping the server ends the subscription with
+ // Quit. The bubble reports a deadlock at its
+ // end if the dispatch still runs.
+ require.NoError(t, d.server.Stop())
+ })
+ })
+
+ t.Run("subscribe fails", func(t *testing.T) {
+ t.Parallel()
+
+ handler, err := NewHandler(
+ newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newPrivKeySigner(testKey(t)), nil,
+ clock.NewDefaultClock(), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ err = handler.Start(t.Context(), subscriberFunc(func() (
+ *subscribe.Client, error) {
+
+ return nil, errors.New("no subscription")
+ }), nil, nil)
+ require.ErrorContains(t, err, "no subscription")
+ handler.Stop()
+ })
+
+ t.Run("start after stop", func(t *testing.T) {
+ t.Parallel()
+
+ handler, err := NewHandler(
+ newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newPrivKeySigner(testKey(t)), nil,
+ clock.NewDefaultClock(), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ // A Stop that runs first must keep Start from adding to the
+ // wait group that Stop already waited on.
+ handler.Stop()
+ err = handler.Start(t.Context(), subscriberFunc(func() (
+ *subscribe.Client, error) {
+
+ require.FailNow(t, "Start subscribed after Stop")
+
+ return nil, nil
+ }), nil, nil)
+ require.ErrorIs(t, err, errHandlerStopped)
+ })
+
+ t.Run("start with an ended context", func(t *testing.T) {
+ t.Parallel()
+
+ handler, err := NewHandler(
+ newMockOfferStore(), nopNotifier{}, &mockReplier{},
+ newPrivKeySigner(testKey(t)), nil,
+ clock.NewDefaultClock(), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ server := subscribe.NewServer()
+ require.NoError(t, server.Start())
+ defer func() { require.NoError(t, server.Stop()) }()
+
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ // The context error tells the caller why nothing started. The
+ // handler did not stop.
+ err = handler.Start(
+ ctx, subscriberFunc(server.Subscribe), nil, nil,
+ )
+ require.ErrorIs(t, err, context.Canceled)
+ handler.Stop()
+ })
+
+ t.Run("stop during start", func(t *testing.T) {
+ t.Parallel()
+
+ server := subscribe.NewServer()
+ require.NoError(t, server.Start())
+ defer func() { require.NoError(t, server.Stop()) }()
+
+ // The race detector reports a Stop that waits on the wait
+ // group while Start adds to it.
+ for range 50 {
+ handler, err := NewHandler(
+ newMockOfferStore(), nopNotifier{},
+ &mockReplier{}, newPrivKeySigner(testKey(t)),
+ nil, clock.NewDefaultClock(), testChainHash(),
+ testFinalCLTVDelta,
+ )
+ require.NoError(t, err)
+
+ done := make(chan error, 1)
+ go func() {
+ done <- handler.Start(
+ t.Context(),
+ subscriberFunc(server.Subscribe), nil,
+ nil,
+ )
+ }()
+ handler.Stop()
+
+ err = <-done
+ if err != nil {
+ require.ErrorIs(t, err, errHandlerStopped)
+ }
+ }
+ })
+}
### bolt12handler/handler.go
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"math"
+ "sync/atomic"
"time"
"github.com/btcsuite/btcd/btcec/v2"
@@ -21,6 +22,7 @@ import (
"github.com/lightningnetwork/lnd/offers"
"github.com/lightningnetwork/lnd/routing"
"github.com/lightningnetwork/lnd/tlv"
+ "golang.org/x/time/rate"
)
// InvoiceNotifier sends an Open event for each new BOLT 12 invoice to the
@@ -51,6 +53,27 @@ type Handler struct {
// finalCLTVDelta is the final CLTV delta that this node requires for a
// BOLT 12 invoice payment.
finalCLTVDelta uint16
+
+ // maxInflight is the number of invoice requests that the handler
+ // answers at the same time.
+ maxInflight int
+
+ // requestLimiter limits the rate of the answered invoice requests.
+ requestLimiter *rate.Limiter
+
+ // introResolver resolves a sciddir introduction node of a reply path.
+ // Start sets it before the dispatch starts.
+ introResolver IntroNodeResolver
+
+ // hopPeeler removes the hops of this node at the start of a reply
+ // path. Start sets it before the dispatch starts.
+ hopPeeler HopPeeler
+
+ started atomic.Bool
+
+ // gm runs the dispatch and the invoice requests. Its Stop cancels them
+ // and waits for them.
+ gm *fn.GoroutineManager
}
// NewHandler creates a new BOLT 12 invoice request handler. It returns an error
@@ -98,6 +121,9 @@ func NewHandler(offerStore offers.Store, notifier InvoiceNotifier,
clock: clk,
activeChain: activeChain,
finalCLTVDelta: finalCLTVDelta,
+ maxInflight: maxInflightRequests,
+ requestLimiter: rate.NewLimiter(requestRate, requestBurst),
+ gm: fn.NewGoroutineManager(),
}, nil
}
### bolt12handler/intro_resolver.go
@@ -0,0 +1,90 @@
+package bolt12handler
+
+import (
+ "context"
+ "encoding/binary"
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/graph/db/models"
+ "github.com/lightningnetwork/lnd/lnwire"
+)
+
+// IntroNodeResolver finds the node of a sciddir introduction node.
+type IntroNodeResolver interface {
+ // ResolveSciddir returns the key of the node that intro names.
+ ResolveSciddir(ctx context.Context,
+ intro lnwire.SciddirIntro) (*btcec.PublicKey, error)
+}
+
+// ChannelEdgeFetcher looks up a channel in the channel graph.
+type ChannelEdgeFetcher interface {
+ // FetchChannelEdgesByID returns the channel with the given short
+ // channel ID and its two policies.
+ FetchChannelEdgesByID(ctx context.Context, chanID uint64) (
+ *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
+ *models.ChannelEdgePolicy, error)
+}
+
+// GraphIntroResolver resolves a sciddir introduction node through the channel
+// graph. It knows only the channels in the graph of this node.
+type GraphIntroResolver struct {
+ graph ChannelEdgeFetcher
+}
+
+// NewGraphIntroResolver creates a GraphIntroResolver that reads graph.
+func NewGraphIntroResolver(graph ChannelEdgeFetcher) *GraphIntroResolver {
+ return &GraphIntroResolver{graph: graph}
+}
+
+// ResolveSciddir returns the key of the node at the side of the channel that
+// intro names. Direction 0 names node_1, which has the lesser key, and
+// direction 1 names node_2.
+//
+// NOTE: This is part of the IntroNodeResolver interface.
+func (r *GraphIntroResolver) ResolveSciddir(ctx context.Context,
+ intro lnwire.SciddirIntro) (*btcec.PublicKey, error) {
+
+ scid := binary.BigEndian.Uint64(intro.SCID[:])
+
+ edge, _, _, err := r.graph.FetchChannelEdgesByID(ctx, scid)
+ if err != nil {
+ return nil, fmt.Errorf("fetch channel %v: %w",
+ lnwire.NewShortChanIDFromInt(scid), err)
+ }
+
+ nodeKey := edge.NodeKey1Bytes
+ if intro.Direction == 1 {
+ nodeKey = edge.NodeKey2Bytes
+ }
+
+ return btcec.ParsePubKey(nodeKey[:])
+}
+
+// resolveIntroNode returns path with a pubkey introduction node. It resolves
+// a sciddir introduction node with resolver and returns any other path as it
+// is.
+func resolveIntroNode(ctx context.Context, path *lnwire.BlindedPath,
+ resolver IntroNodeResolver) (*lnwire.BlindedPath, error) {
+
+ sciddir, ok := path.IntroductionNode.(lnwire.SciddirIntro)
+ if !ok {
+ return path, nil
+ }
+
+ pubkey, err := resolver.ResolveSciddir(ctx, sciddir)
+ if err != nil {
+ return nil, fmt.Errorf("resolve sciddir introduction node: %w",
+ err)
+ }
+
+ intro, err := lnwire.NewPubkeyIntro(pubkey)
+ if err != nil {
+ return nil, err
+ }
+
+ resolved := *path
+ resolved.IntroductionNode = intro
+
+ return &resolved, nil
+}
### bolt12handler/intro_resolver_test.go
@@ -0,0 +1,161 @@
+package bolt12handler
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/graph/db/models"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/routing/route"
+ "github.com/stretchr/testify/require"
+)
+
+// testSCID is the channel that testIntroResolver knows.
+var testSCID = [8]byte{0, 0, 1, 0, 0, 2, 0, 3}
+
+// errUnknownChannel is returned by fakeEdgeFetcher for an unknown channel.
+var errUnknownChannel = errors.New("unknown channel")
+
+// fakeEdgeFetcher is a channel graph that holds one channel.
+type fakeEdgeFetcher struct {
+ scid uint64
+ edge *models.ChannelEdgeInfo
+}
+
+func (f *fakeEdgeFetcher) FetchChannelEdgesByID(_ context.Context,
+ chanID uint64) (*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
+ *models.ChannelEdgePolicy, error) {
+
+ if chanID != f.scid {
+ return nil, nil, nil, errUnknownChannel
+ }
+
+ return f.edge, nil, nil, nil
+}
+
+// newFakeEdgeFetcher returns a graph with the channel testSCID between
+// node1 and node2.
+func newFakeEdgeFetcher(node1, node2 *btcec.PublicKey) *fakeEdgeFetcher {
+ return &fakeEdgeFetcher{
+ scid: lnwire.NewShortChanIDFromInt(
+ 0x0000010000020003,
+ ).ToUint64(),
+ edge: &models.ChannelEdgeInfo{
+ NodeKey1Bytes: route.NewVertex(node1),
+ NodeKey2Bytes: route.NewVertex(node2),
+ },
+ }
+}
+
+// testIntroResolver returns a resolver that resolves direction 1 of testSCID
+// to node.
+func testIntroResolver(t *testing.T,
+ node *btcec.PrivateKey) *GraphIntroResolver {
+
+ t.Helper()
+
+ other, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ return NewGraphIntroResolver(
+ newFakeEdgeFetcher(other.PubKey(), node.PubKey()),
+ )
+}
+
+// TestGraphIntroResolver checks that the direction of a sciddir introduction
+// node selects the node of the channel.
+func TestGraphIntroResolver(t *testing.T) {
+ t.Parallel()
+
+ key1, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ key2, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ resolver := NewGraphIntroResolver(
+ newFakeEdgeFetcher(key1.PubKey(), key2.PubKey()),
+ )
+
+ tests := []struct {
+ name string
+ direction byte
+ scid [8]byte
+ want *btcec.PublicKey
+ err error
+ }{
+ {
+ name: "direction 0 is node 1",
+ direction: 0,
+ scid: testSCID,
+ want: key1.PubKey(),
+ },
+ {
+ name: "direction 1 is node 2",
+ direction: 1,
+ scid: testSCID,
+ want: key2.PubKey(),
+ },
+ {
+ name: "unknown channel",
+ direction: 0,
+ scid: [8]byte{1},
+ err: errUnknownChannel,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ intro, err := lnwire.NewSciddirIntro(
+ tc.direction, tc.scid,
+ )
+ require.NoError(t, err)
+
+ got, err := resolver.ResolveSciddir(t.Context(), intro)
+ if tc.err != nil {
+ require.ErrorIs(t, err, tc.err)
+
+ return
+ }
+
+ require.NoError(t, err)
+ require.True(t, tc.want.IsEqual(got))
+ })
+ }
+}
+
+// TestResolveIntroNode checks that resolveIntroNode replaces only a sciddir
+// introduction node and keeps the caller's path.
+func TestResolveIntroNode(t *testing.T) {
+ t.Parallel()
+
+ node := testKey(t)
+ resolver := testIntroResolver(t, node)
+
+ pubIntro, err := lnwire.NewPubkeyIntro(node.PubKey())
+ require.NoError(t, err)
+ sciddir, err := lnwire.NewSciddirIntro(1, testSCID)
+ require.NoError(t, err)
+
+ t.Run("pubkey intro", func(t *testing.T) {
+ t.Parallel()
+
+ path := &lnwire.BlindedPath{IntroductionNode: pubIntro}
+ got, err := resolveIntroNode(t.Context(), path, resolver)
+ require.NoError(t, err)
+ require.Same(t, path, got)
+ })
+
+ t.Run("sciddir intro", func(t *testing.T) {
+ t.Parallel()
+
+ path := &lnwire.BlindedPath{IntroductionNode: sciddir}
+ got, err := resolveIntroNode(t.Context(), path, resolver)
+ require.NoError(t, err)
+ require.Equal(t, pubIntro, got.IntroductionNode)
+ require.Equal(t, sciddir, path.IntroductionNode)
+ })
+}
### cmd/commands/cmd_offer.go
@@ -0,0 +1,114 @@
+//go:build dev
+// +build dev
+
+package commands
+
+import (
+ "errors"
+ "time"
+
+ "github.com/lightningnetwork/lnd/lnrpc/devrpc"
+ "github.com/urfave/cli"
+)
+
+// CreateOfferCommand defines the lncli createoffer command.
+var CreateOfferCommand = cli.Command{
+ Name: "createoffer",
+ Category: "Offers",
+ Usage: "Create a new BOLT 12 offer.",
+ Description: `
+ Create a new BOLT 12 offer and persist it in the offer store.
+ The encoded offer string (lno1...) is returned for sharing
+ with payers. The node must run with --protocol.bolt12-offers.
+
+ Offers without an amount can be created by omitting the
+ --amt_msat flag. These offers allow the payer to specify the
+ amount they wish to pay.
+
+ The expiry can be set as a duration from now with --expiry, for
+ example 1h or 168h, or as a timestamp with --absolute_expiry.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "description",
+ Usage: "a description of the payment purpose " +
+ "to include in the offer " +
+ "(required when amount is set)",
+ },
+ cli.Uint64Flag{
+ Name: "amt_msat",
+ Usage: "the amount in millisatoshis per item " +
+ "(0 or omit for any-amount offers)",
+ },
+ cli.DurationFlag{
+ Name: "expiry",
+ Usage: "the duration from now after which the " +
+ "offer expires, for example 1h " +
+ "(cannot be used with --absolute_expiry)",
+ },
+ cli.Uint64Flag{
+ Name: "absolute_expiry",
+ Usage: "seconds since epoch after which the " +
+ "offer expires (0 or omit for no " +
+ "expiry)",
+ },
+ cli.Uint64Flag{
+ Name: "quantity_max",
+ Usage: "maximum number of items per invoice " +
+ "(0 = unlimited, omit to disable " +
+ "quantity selection)",
+ },
+ },
+ Action: actionDecorator(createOffer),
+}
+
+func createOffer(ctx *cli.Context) error {
+ ctxc := getContext()
+ client, cleanUp := getDevClient(ctx)
+ defer cleanUp()
+
+ absoluteExpiry, err := offerExpiry(ctx, time.Now())
+ if err != nil {
+ return err
+ }
+
+ req := &devrpc.CreateOfferRequest{
+ Description: ctx.String("description"),
+ AmountMsat: ctx.Uint64("amt_msat"),
+ AbsoluteExpiry: absoluteExpiry,
+ }
+
+ if ctx.IsSet("quantity_max") {
+ qty := ctx.Uint64("quantity_max")
+ req.QuantityMax = &qty
+ }
+
+ resp, err := client.CreateOffer(ctxc, req)
+ if err != nil {
+ return err
+ }
+
+ printRespJSON(resp)
+
+ return nil
+}
+
+// offerExpiry returns the absolute expiry of the offer in seconds since
+// epoch, from either --expiry relative to now or --absolute_expiry. Zero
+// means no expiry.
+func offerExpiry(ctx *cli.Context, now time.Time) (uint64, error) {
+ if !ctx.IsSet("expiry") {
+ return ctx.Uint64("absolute_expiry"), nil
+ }
+
+ if ctx.IsSet("absolute_expiry") {
+ return 0, errors.New("use either --expiry or " +
+ "--absolute_expiry, not both")
+ }
+
+ expiry := ctx.Duration("expiry")
+ if expiry <= 0 {
+ return 0, errors.New("--expiry must be positive")
+ }
+
+ return uint64(now.Add(expiry).Unix()), nil
+}
### cmd/commands/cmd_offer_test.go
@@ -0,0 +1,91 @@
+//go:build dev
+// +build dev
+
+package commands
+
+import (
+ "flag"
+ "io"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "github.com/urfave/cli"
+)
+
+// TestOfferExpiry checks how createoffer turns its expiry flags into an
+// absolute expiry.
+func TestOfferExpiry(t *testing.T) {
+ t.Parallel()
+
+ now := time.Unix(1_700_000_000, 0)
+
+ tests := []struct {
+ name string
+ args []string
+ expiry uint64
+ err string
+ }{
+ {
+ name: "no expiry",
+ },
+ {
+ name: "absolute expiry",
+ args: []string{"--absolute_expiry", "1800000000"},
+ expiry: 1_800_000_000,
+ },
+ {
+ name: "duration",
+ args: []string{"--expiry", "1h30m"},
+ expiry: 1_700_005_400,
+ },
+ {
+ name: "both",
+ args: []string{
+ "--expiry", "1h", "--absolute_expiry", "1",
+ },
+ err: "not both",
+ },
+ {
+ name: "zero duration",
+ args: []string{"--expiry", "0s"},
+ err: "must be positive",
+ },
+ {
+ name: "negative duration",
+ args: []string{"--expiry", "-1h"},
+ err: "must be positive",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ ctx := newOfferContext(t, tc.args)
+ expiry, err := offerExpiry(ctx, now)
+ if tc.err != "" {
+ require.ErrorContains(t, err, tc.err)
+
+ return
+ }
+
+ require.NoError(t, err)
+ require.Equal(t, tc.expiry, expiry)
+ })
+ }
+}
+
+// newOfferContext parses args with the flags of the createoffer command.
+func newOfferContext(t *testing.T, args []string) *cli.Context {
+ t.Helper()
+
+ flagSet := flag.NewFlagSet("createoffer", flag.ContinueOnError)
+ flagSet.SetOutput(io.Discard)
+ for _, f := range CreateOfferCommand.Flags {
+ f.Apply(flagSet)
+ }
+ require.NoError(t, flagSet.Parse(args))
+
+ return cli.NewContext(cli.NewApp(), flagSet, nil)
+}
### cmd/commands/devrpc_active.go
@@ -24,6 +24,7 @@ func devCommands() []cli.Command {
ArgsUsage: "graph-json-file",
Action: actionDecorator(importGraph),
},
+ CreateOfferCommand,
}
}
### docs/release-notes/unreleased/11374.md
@@ -0,0 +1,12 @@
+# Technical and Architectural Updates
+
+## BOLT 12 (Offers)
+
+* [BOLT 12 offer creation and invoice request
+ dispatch](https://github.com/lightningnetwork/lnd/pull/11374): add the
+ `CreateOffer` RPC to the `devrpc` sub-server, with the
+ `POST /v2/dev/createoffer` REST route and the `lncli createoffer` command,
+ which create and store an offer. Like the rest of `devrpc`, they exist only
+ in a `dev` build. The node now sends each invoice request that it receives
+ to the BOLT 12 handler and sends the invoice over the reply path of the
+ request. A failed request gets no `invoice_error` reply yet.
### itest/bolt12_build_native_test.go
@@ -0,0 +1,8 @@
+//go:build test_db_postgres || test_db_sqlite || test_native_sql
+
+package itest
+
+// bolt12DevMigrations is true because the SQL test tags add the development
+// migrations that hold the BOLT 12 tables. The build constraint matches the
+// one of sqldb/migrations_dev.go.
+const bolt12DevMigrations = true
### itest/bolt12_build_test.go
@@ -0,0 +1,8 @@
+//go:build !test_db_postgres && !test_db_sqlite && !test_native_sql
+
+package itest
+
+// bolt12DevMigrations is false because without a SQL test tag the build has
+// no development migrations, so it has no BOLT 12 tables. The build
+// constraint matches the one of sqldb/migrations_prod.go.
+const bolt12DevMigrations = false
### itest/list_on_test.go
@@ -603,6 +603,14 @@ var allTestCases = []*lntest.TestCase{
Name: "onion message forwarding",
TestFunc: testOnionMessageForwarding,
},
+ {
+ Name: "create offer",
+ TestFunc: testCreateOffer,
+ },
+ {
+ Name: "bolt12 invoice request",
+ TestFunc: testBolt12InvoiceRequest,
+ },
{
Name: "sign verify message with addr",
TestFunc: testSignVerifyMessageWithAddr,
### itest/lnd_bolt12_test.go
@@ -0,0 +1,329 @@
+package itest
+
+import (
+ "bytes"
+ "context"
+ "encoding/hex"
+ "time"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcutil/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/bolt12"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/devrpc"
+ "github.com/lightningnetwork/lnd/lntest"
+ "github.com/lightningnetwork/lnd/lntest/node"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/onionmessage"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/lightningnetwork/lnd/routing/route"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// testCreateOffer checks that CreateOffer returns a decodable offer issued
+// by the node, with an offer hash that matches the offer.
+func testCreateOffer(ht *lntest.HarnessTest) {
+ alice := ht.NewNode("Alice", bolt12NodeArgs(ht))
+
+ ctxt, cancel := context.WithTimeout(
+ ht.Context(), lntest.DefaultTimeout,
+ )
+ defer cancel()
+
+ resp, err := alice.RPC.Dev.CreateOffer(
+ ctxt, &devrpc.CreateOfferRequest{
+ Description: "integration test coffee",
+ AmountMsat: 10000,
+ },
+ )
+ require.NoError(ht, err, "CreateOffer")
+
+ require.NotEmpty(ht, resp.Offer)
+
+ decoded, err := bolt12.DecodeOfferString(
+ resp.Offer, time.Now(), *harnessNetParams.GenesisHash,
+ )
+ require.NoError(ht, err, "decode offer string")
+
+ issuerPub := decoded.OfferIssuerID.UnwrapOrFailV(ht.T)
+ require.Equal(
+ ht, alice.PubKey[:],
+ issuerPub.SerializeCompressed(),
+ )
+
+ require.Len(ht, resp.OfferHash, 32)
+
+ expectedID, err := bolt12.OfferHash(decoded)
+ require.NoError(ht, err)
+ require.Equal(ht, expectedID[:], resp.OfferHash)
+
+ ht.Logf(
+ "Created offer: %s (id=%s)", resp.Offer,
+ hex.EncodeToString(resp.OfferHash),
+ )
+
+ // Second offer without amount.
+ resp2 := alice.RPC.CreateOffer(
+ &devrpc.CreateOfferRequest{
+ Description: "tips welcome",
+ },
+ )
+ require.NotEqual(ht, resp.OfferHash, resp2.OfferHash)
+
+ decoded2, err := bolt12.DecodeOfferString(
+ resp2.Offer, time.Now(), *harnessNetParams.GenesisHash,
+ )
+ require.NoError(ht, err)
+
+ hasAmount := false
+ decoded2.OfferAmount.WhenSome(
+ func(_ tlv.RecordT[tlv.TlvType8, bolt12.TUint64]) {
+ hasAmount = true
+ },
+ )
+ require.False(ht, hasAmount)
+}
+
+// testBolt12InvoiceRequest tests that a node answers an invoice request for
+// its offer with a signed BOLT 12 invoice.
+func testBolt12InvoiceRequest(ht *lntest.HarnessTest) {
+ alice := ht.NewNode("Alice", bolt12NodeArgs(ht))
+ bob := ht.NewNode("Bob", bolt12NodeArgs(ht))
+
+ ht.EnsureConnected(alice, bob)
+
+ // Onion message ingress needs a fully open channel between the sender
+ // and the receiver. This gate is the Sybil-resistance layer on top of
+ // the byte-granular rate limiter. Open a channel before exchanging
+ // invoice requests and invoice messages.
+ ht.FundCoins(btcutil.SatoshiPerBitcoin, bob)
+ chanPoint := ht.OpenChannel(
+ bob, alice, lntest.OpenChannelParams{Amt: 500_000},
+ )
+ defer ht.CloseChannel(bob, chanPoint)
+
+ // Step 1: Alice creates an offer.
+ ctxt, cancel := context.WithTimeout(
+ ht.Context(), lntest.DefaultTimeout,
+ )
+ defer cancel()
+
+ offerResp, err := alice.RPC.Dev.CreateOffer(
+ ctxt, &devrpc.CreateOfferRequest{
+ Description: "e2e test coffee",
+ AmountMsat: 50000,
+ },
+ )
+ require.NoError(ht, err, "CreateOffer")
+ ht.Logf("Alice offer: %s", offerResp.Offer)
+
+ offer, err := bolt12.DecodeOfferString(
+ offerResp.Offer, time.Now(), *harnessNetParams.GenesisHash,
+ )
+ require.NoError(ht, err)
+
+ // Step 2: Bob subscribes to onion messages for the reply.
+ msgClient, msgCancel := bob.RPC.SubscribeOnionMessages()
+ defer msgCancel()
+
+ bobMessages := make(chan *lnrpc.OnionMessageUpdate, 1)
+ go func() {
+ for {
+ msg, recvErr := msgClient.Recv()
+ if recvErr != nil {
+ return
+ }
+
+ select {
+ case bobMessages <- msg:
+ case <-ht.Context().Done():
+ return
+ }
+ }
+ }()
+
+ // Step 3: Build a signed invoice request.
+ payerKey, err := btcec.NewPrivateKey()
+ require.NoError(ht, err)
+
+ // The request copies the offer fields and sets invreq_chain, because
+ // an absent invreq_chain means mainnet and the node runs on regtest.
+ ir, err := bolt12.NewInvoiceRequestFromOffer(
+ offer, payerKey.PubKey(), []byte("itest-payer-metadata"),
+ *harnessNetParams.GenesisHash,
+ )
+ require.NoError(ht, err)
+
+ amt := bolt12.TUint64(50000)
+ ir.InvreqAmount = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType82, bolt12.TUint64]{
+ Val: amt,
+ },
+ )
+
+ // SignInvoiceRequest validates the writer rules before it signs.
+ sig, err := bolt12.SignInvoiceRequest(ir, payerKey)
+ require.NoError(ht, err)
+
+ ir.Signature = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType240, [64]byte](sig),
+ )
+
+ signedIRBytes, err := ir.EncodeSigned()
+ require.NoError(ht, err)
+ ht.Logf("Signed invreq: %d bytes", len(signedIRBytes))
+
+ // Step 4: Send the invoice request to Alice twice, and expect each
+ // invoice on Bob's subscription. The first reply path starts at Bob.
+ // The second one starts at Alice, as the reply path of a payer whose
+ // only peer is Alice does, so Alice processes her own reply first.
+ alicePubKey, err := btcec.ParsePubKey(alice.PubKey[:])
+ require.NoError(ht, err)
+
+ bobPubKey, err := btcec.ParsePubKey(bob.PubKey[:])
+ require.NoError(ht, err)
+
+ bobHop := &sphinx.HopInfo{
+ NodePub: bobPubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, &record.BlindedRouteData{},
+ ),
+ }
+ aliceToBobHop := &sphinx.HopInfo{
+ NodePub: alicePubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, record.NewNonFinalBlindedRouteDataOnionMessage(
+ fn.NewLeft[*btcec.PublicKey,
+ lnwire.ShortChannelID](bobPubKey),
+ nil, nil,
+ ),
+ ),
+ }
+
+ sendInvoiceRequest(
+ ht, alice, bob, signedIRBytes, []*sphinx.HopInfo{bobHop},
+ )
+ expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+
+ sendInvoiceRequest(
+ ht, alice, bob, signedIRBytes,
+ []*sphinx.HopInfo{aliceToBobHop, bobHop},
+ )
+ expectInvoiceReply(ht, bobMessages, ir, alicePubKey)
+}
+
+// sendInvoiceRequest sends the signed invoice request from the payer to the
+// receiver in an onion message. The reply path goes through replyHops.
+func sendInvoiceRequest(ht *lntest.HarnessTest, receiver,
+ payer *node.HarnessNode, signedIRBytes []byte,
+ replyHops []*sphinx.HopInfo) {
+
+ receiverPubKey, err := btcec.ParsePubKey(receiver.PubKey[:])
+ require.NoError(ht, err)
+
+ // The blinded path to the receiver has one hop, the receiver itself.
+ receiverPath := onionmessage.BuildBlindedPath(ht.T, []*sphinx.HopInfo{
+ {
+ NodePub: receiverPubKey,
+ PlainText: onionmessage.EncodeBlindedRouteData(
+ ht.T, &record.BlindedRouteData{},
+ ),
+ },
+ })
+
+ replyPathInfo := onionmessage.BuildBlindedPath(ht.T, replyHops)
+ replyPath, err := lnwire.NewBlindedPathFromSphinx(replyPathInfo.Path)
+ require.NoError(ht, err)
+
+ finalHopTLVs := []*lnwire.FinalHopTLV{
+ {
+ TLVType: lnwire.InvoiceRequestNamespaceType,
+ Value: signedIRBytes,
+ },
+ }
+ sphinxPath, err := route.OnionMessageBlindedPathToSphinxPath(
+ receiverPath.Path, replyPath, finalHopTLVs,
+ )
+ require.NoError(ht, err)
+
+ onionSessionKey, err := btcec.NewPrivateKey()
+ require.NoError(ht, err)
+
+ onionPkt, err := sphinx.NewOnionPacket(
+ sphinxPath, onionSessionKey, nil,
+ sphinx.DeterministicPacketFiller, sphinx.WithMaxPayloadSize(
+ sphinx.MaxRoutingPayloadSize,
+ ),
+ )
+ require.NoError(ht, err)
+
+ var buf bytes.Buffer
+ require.NoError(ht, onionPkt.Encode(&buf))
+
+ pathKey := receiverPath.SessionKey.PubKey().SerializeCompressed()
+ payer.RPC.SendOnionMessage(
+ &lnrpc.SendOnionMessageRequest{
+ Peer: receiver.PubKey[:],
+ PathKey: pathKey,
+ Onion: buf.Bytes(),
+ },
+ )
+ ht.Logf("Payer sent invoice request with a %d-hop reply path",
+ len(replyHops))
+}
+
+// expectInvoiceReply waits for an invoice on the payer's onion message
+// subscription and checks it as a payer does: against the request and
+// against the receiver, whose offer carries its node ID as offer_issuer_id.
+func expectInvoiceReply(ht *lntest.HarnessTest,
+ messages <-chan *lnrpc.OnionMessageUpdate,
+ ir *bolt12.InvoiceRequest, receiverPubKey *btcec.PublicKey) {
+
+ select {
+ case msg := <-messages:
+ invoiceBytes, hasInvoice := msg.CustomRecords[uint64(
+ lnwire.InvoiceNamespaceType,
+ )]
+ require.True(
+ ht, hasInvoice,
+ "reply should contain invoice (type 66)",
+ )
+
+ invoice, err := bolt12.DecodeInvoice(invoiceBytes)
+ require.NoError(ht, err, "decode invoice")
+
+ err = bolt12.ValidateInvoiceForPayment(
+ invoice, ir, time.Now(), *harnessNetParams.GenesisHash,
+ bolt12.InvoiceKnownFeatures{
+ Invoice: bolt12.Bolt12Features,
+ Blinded: bolt12.Bolt12Features,
+ },
+ receiverPubKey,
+ )
+ require.NoError(ht, err, "validate invoice")
+
+ case <-time.After(lntest.DefaultTimeout):
+ ht.Fatal("payer did not receive the invoice reply")
+ }
+}
+
+// bolt12NodeArgs returns the node arguments that enable BOLT 12 offers. It
+// skips the test when this build or the database backend cannot run them.
+// BOLT 12 needs native SQL and the development migrations. Only a build with
+// a SQL test tag such as test_native_sql applies them.
+func bolt12NodeArgs(ht *lntest.HarnessTest) []string {
+ if !bolt12DevMigrations {
+ ht.Skipf("BOLT 12 needs the development migrations: build " +
+ "the itests with tags=test_native_sql")
+ }
+
+ if !ht.NativeSQLEnabled() {
+ ht.Skipf("BOLT 12 needs --dbbackend=sqlite or postgres " +
+ "with --nativesql")
+ }
+
+ return []string{"--protocol.bolt12-offers"}
+}
### lnrpc/devrpc/config_active.go
@@ -18,4 +18,7 @@ type Config struct {
ActiveNetParams *chaincfg.Params
GraphDB *graphdb.ChannelGraph
Switch *htlcswitch.Switch
+
+ // OfferCreator is nil when the node runs without BOLT 12 offers.
+ OfferCreator OfferCreator
}
### lnrpc/devrpc/dev.pb.go
@@ -149,6 +149,137 @@ func (x *QuiescenceResponse) GetInitiator() bool {
return false
}
+type CreateOfferRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // A UTF-8 description of the purpose of the payment. Required when
+ // amount_msat is set.
+ Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"`
+ // The amount expected per item in millisatoshis. Zero or unset means
+ // the payer chooses the amount.
+ AmountMsat uint64 `protobuf:"varint,2,opt,name=amount_msat,json=amountMsat,proto3" json:"amount_msat,omitempty"`
+ // Seconds since epoch after which the offer expires. Zero or unset
+ // means no expiry.
+ AbsoluteExpiry uint64 `protobuf:"varint,3,opt,name=absolute_expiry,json=absoluteExpiry,proto3" json:"absolute_expiry,omitempty"`
+ // Maximum number of items that can be requested in a single invoice.
+ // Zero means unlimited. If not set, quantity selection is not
+ // supported.
+ QuantityMax *uint64 `protobuf:"varint,4,opt,name=quantity_max,json=quantityMax,proto3,oneof" json:"quantity_max,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreateOfferRequest) Reset() {
+ *x = CreateOfferRequest{}
+ mi := &file_devrpc_dev_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreateOfferRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreateOfferRequest) ProtoMessage() {}
+
+func (x *CreateOfferRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_devrpc_dev_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreateOfferRequest.ProtoReflect.Descriptor instead.
+func (*CreateOfferRequest) Descriptor() ([]byte, []int) {
+ return file_devrpc_dev_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *CreateOfferRequest) GetDescription() string {
+ if x != nil {
+ return x.Description
+ }
+ return ""
+}
+
+func (x *CreateOfferRequest) GetAmountMsat() uint64 {
+ if x != nil {
+ return x.AmountMsat
+ }
+ return 0
+}
+
+func (x *CreateOfferRequest) GetAbsoluteExpiry() uint64 {
+ if x != nil {
+ return x.AbsoluteExpiry
+ }
+ return 0
+}
+
+func (x *CreateOfferRequest) GetQuantityMax() uint64 {
+ if x != nil && x.QuantityMax != nil {
+ return *x.QuantityMax
+ }
+ return 0
+}
+
+type CreateOfferResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The bech32-encoded offer string (lno1...).
+ Offer string `protobuf:"bytes,1,opt,name=offer,proto3" json:"offer,omitempty"`
+ // The 32-byte offer hash: the SHA256 of the offer's TLV records.
+ OfferHash []byte `protobuf:"bytes,2,opt,name=offer_hash,json=offerHash,proto3" json:"offer_hash,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CreateOfferResponse) Reset() {
+ *x = CreateOfferResponse{}
+ mi := &file_devrpc_dev_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CreateOfferResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CreateOfferResponse) ProtoMessage() {}
+
+func (x *CreateOfferResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_devrpc_dev_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CreateOfferResponse.ProtoReflect.Descriptor instead.
+func (*CreateOfferResponse) Descriptor() ([]byte, []int) {
+ return file_devrpc_dev_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *CreateOfferResponse) GetOffer() string {
+ if x != nil {
+ return x.Offer
+ }
+ return ""
+}
+
+func (x *CreateOfferResponse) GetOfferHash() []byte {
+ if x != nil {
+ return x.OfferHash
+ }
+ return nil
+}
+
var File_devrpc_dev_proto protoreflect.FileDescriptor
const file_devrpc_dev_proto_rawDesc = "" +
@@ -158,10 +289,22 @@ const file_devrpc_dev_proto_rawDesc = "" +
"\x11QuiescenceRequest\x12,\n" +
"\achan_id\x18\x01 \x01(\v2\x13.lnrpc.ChannelPointR\x06chanId\"2\n" +
"\x12QuiescenceResponse\x12\x1c\n" +
- "\tinitiator\x18\x01 \x01(\bR\tinitiator2\x88\x01\n" +
+ "\tinitiator\x18\x01 \x01(\bR\tinitiator\"\xb9\x01\n" +
+ "\x12CreateOfferRequest\x12 \n" +
+ "\vdescription\x18\x01 \x01(\tR\vdescription\x12\x1f\n" +
+ "\vamount_msat\x18\x02 \x01(\x04R\n" +
+ "amountMsat\x12'\n" +
+ "\x0fabsolute_expiry\x18\x03 \x01(\x04R\x0eabsoluteExpiry\x12&\n" +
+ "\fquantity_max\x18\x04 \x01(\x04H\x00R\vquantityMax\x88\x01\x01B\x0f\n" +
+ "\r_quantity_max\"J\n" +
+ "\x13CreateOfferResponse\x12\x14\n" +
+ "\x05offer\x18\x01 \x01(\tR\x05offer\x12\x1d\n" +
+ "\n" +
+ "offer_hash\x18\x02 \x01(\fR\tofferHash2\xd0\x01\n" +
"\x03Dev\x12?\n" +
"\vImportGraph\x12\x13.lnrpc.ChannelGraph\x1a\x1b.devrpc.ImportGraphResponse\x12@\n" +
- "\aQuiesce\x12\x19.devrpc.QuiescenceRequest\x1a\x1a.devrpc.QuiescenceResponseB.Z,github.com/lightningnetwork/lnd/lnrpc/devrpcb\x06proto3"
+ "\aQuiesce\x12\x19.devrpc.QuiescenceRequest\x1a\x1a.devrpc.QuiescenceResponse\x12F\n" +
+ "\vCreateOffer\x12\x1a.devrpc.CreateOfferRequest\x1a\x1b.devrpc.CreateOfferResponseB.Z,github.com/lightningnetwork/lnd/lnrpc/devrpcb\x06proto3"
var (
file_devrpc_dev_proto_rawDescOnce sync.Once
@@ -175,22 +318,26 @@ func file_devrpc_dev_proto_rawDescGZIP() []byte {
return file_devrpc_dev_proto_rawDescData
}
-var file_devrpc_dev_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
+var file_devrpc_dev_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_devrpc_dev_proto_goTypes = []any{
(*ImportGraphResponse)(nil), // 0: devrpc.ImportGraphResponse
(*QuiescenceRequest)(nil), // 1: devrpc.QuiescenceRequest
(*QuiescenceResponse)(nil), // 2: devrpc.QuiescenceResponse
- (*lnrpc.ChannelPoint)(nil), // 3: lnrpc.ChannelPoint
- (*lnrpc.ChannelGraph)(nil), // 4: lnrpc.ChannelGraph
+ (*CreateOfferRequest)(nil), // 3: devrpc.CreateOfferRequest
+ (*CreateOfferResponse)(nil), // 4: devrpc.CreateOfferResponse
+ (*lnrpc.ChannelPoint)(nil), // 5: lnrpc.ChannelPoint
+ (*lnrpc.ChannelGraph)(nil), // 6: lnrpc.ChannelGraph
}
var file_devrpc_dev_proto_depIdxs = []int32{
- 3, // 0: devrpc.QuiescenceRequest.chan_id:type_name -> lnrpc.ChannelPoint
- 4, // 1: devrpc.Dev.ImportGraph:input_type -> lnrpc.ChannelGraph
+ 5, // 0: devrpc.QuiescenceRequest.chan_id:type_name -> lnrpc.ChannelPoint
+ 6, // 1: devrpc.Dev.ImportGraph:input_type -> lnrpc.ChannelGraph
1, // 2: devrpc.Dev.Quiesce:input_type -> devrpc.QuiescenceRequest
- 0, // 3: devrpc.Dev.ImportGraph:output_type -> devrpc.ImportGraphResponse
- 2, // 4: devrpc.Dev.Quiesce:output_type -> devrpc.QuiescenceResponse
- 3, // [3:5] is the sub-list for method output_type
- 1, // [1:3] is the sub-list for method input_type
+ 3, // 3: devrpc.Dev.CreateOffer:input_type -> devrpc.CreateOfferRequest
+ 0, // 4: devrpc.Dev.ImportGraph:output_type -> devrpc.ImportGraphResponse
+ 2, // 5: devrpc.Dev.Quiesce:output_type -> devrpc.QuiescenceResponse
+ 4, // 6: devrpc.Dev.CreateOffer:output_type -> devrpc.CreateOfferResponse
+ 4, // [4:7] is the sub-list for method output_type
+ 1, // [1:4] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
@@ -201,13 +348,14 @@ func file_devrpc_dev_proto_init() {
if File_devrpc_dev_proto != nil {
return
}
+ file_devrpc_dev_proto_msgTypes[3].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_devrpc_dev_proto_rawDesc), len(file_devrpc_dev_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 3,
+ NumMessages: 5,
NumExtensions: 0,
NumServices: 1,
},
### lnrpc/devrpc/dev.pb.gw.go
@@ -100,6 +100,40 @@ func local_request_Dev_Quiesce_0(ctx context.Context, marshaler runtime.Marshale
}
+func request_Dev_CreateOffer_0(ctx context.Context, marshaler runtime.Marshaler, client DevClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq CreateOfferRequest
+ var metadata runtime.ServerMetadata
+
+ newReader, berr := utilities.IOReaderFactory(req.Body)
+ if berr != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
+ }
+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+
+ msg, err := client.CreateOffer(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Dev_CreateOffer_0(ctx context.Context, marshaler runtime.Marshaler, server DevServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq CreateOfferRequest
+ var metadata runtime.ServerMetadata
+
+ newReader, berr := utilities.IOReaderFactory(req.Body)
+ if berr != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
+ }
+ if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+
+ msg, err := server.CreateOffer(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
// RegisterDevHandlerServer registers the http handlers for service Dev to "mux".
// UnaryRPC :call DevServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
@@ -156,6 +190,31 @@ func RegisterDevHandlerServer(ctx context.Context, mux *runtime.ServeMux, server
})
+ mux.Handle("POST", pattern_Dev_CreateOffer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ var err error
+ var annotatedContext context.Context
+ annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/devrpc.Dev/CreateOffer", runtime.WithHTTPPathPattern("/v2/dev/createoffer"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Dev_CreateOffer_0(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Dev_CreateOffer_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
return nil
}
@@ -241,17 +300,43 @@ func RegisterDevHandlerClient(ctx context.Context, mux *runtime.ServeMux, client
})
+ mux.Handle("POST", pattern_Dev_CreateOffer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ var err error
+ var annotatedContext context.Context
+ annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/devrpc.Dev/CreateOffer", runtime.WithHTTPPathPattern("/v2/dev/createoffer"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Dev_CreateOffer_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Dev_CreateOffer_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
return nil
}
var (
pattern_Dev_ImportGraph_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "dev", "importgraph"}, ""))
pattern_Dev_Quiesce_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "dev", "quiesce"}, ""))
+
+ pattern_Dev_CreateOffer_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "dev", "createoffer"}, ""))
)
var (
forward_Dev_ImportGraph_0 = runtime.ForwardResponseMessage
forward_Dev_Quiesce_0 = runtime.ForwardResponseMessage
+
+ forward_Dev_CreateOffer_0 = runtime.ForwardResponseMessage
)
### lnrpc/devrpc/dev.pb.json.go
@@ -71,4 +71,29 @@ func RegisterDevJSONCallbacks(registry map[string]func(ctx context.Context,
}
callback(string(respBytes), nil)
}
+
+ registry["devrpc.Dev.CreateOffer"] = func(ctx context.Context,
+ conn *grpc.ClientConn, reqJSON string, callback func(string, error)) {
+
+ req := &CreateOfferRequest{}
+ err := marshaler.Unmarshal([]byte(reqJSON), req)
+ if err != nil {
+ callback("", err)
+ return
+ }
+
+ client := NewDevClient(conn)
+ resp, err := client.CreateOffer(ctx, req)
+ if err != nil {
+ callback("", err)
+ return
+ }
+
+ respBytes, err := marshaler.Marshal(resp)
+ if err != nil {
+ callback("", err)
+ return
+ }
+ callback(string(respBytes), nil)
+ }
}
### lnrpc/devrpc/dev.proto
@@ -37,6 +37,13 @@ service Dev {
once interop is confirmed.
*/
rpc Quiesce (QuiescenceRequest) returns (QuiescenceResponse);
+
+ /* lncli: `createoffer`
+ CreateOffer creates a new BOLT 12 offer. The offer is persisted in the
+ offer store and the encoded offer string (lno1...) is returned. The node
+ must run with --protocol.bolt12-offers.
+ */
+ rpc CreateOffer (CreateOfferRequest) returns (CreateOfferResponse);
}
message ImportGraphResponse {
@@ -52,3 +59,30 @@ message QuiescenceResponse {
// negotiation completes
bool initiator = 1;
}
+
+message CreateOfferRequest {
+ // A UTF-8 description of the purpose of the payment. Required when
+ // amount_msat is set.
+ string description = 1;
+
+ // The amount expected per item in millisatoshis. Zero or unset means
+ // the payer chooses the amount.
+ uint64 amount_msat = 2;
+
+ // Seconds since epoch after which the offer expires. Zero or unset
+ // means no expiry.
+ uint64 absolute_expiry = 3;
+
+ // Maximum number of items that can be requested in a single invoice.
+ // Zero means unlimited. If not set, quantity selection is not
+ // supported.
+ optional uint64 quantity_max = 4;
+}
+
+message CreateOfferResponse {
+ // The bech32-encoded offer string (lno1...).
+ string offer = 1;
+
+ // The 32-byte offer hash: the SHA256 of the offer's TLV records.
+ bytes offer_hash = 2;
+}
### lnrpc/devrpc/dev.swagger.json
@@ -16,6 +16,39 @@
"application/json"
],
"paths": {
+ "/v2/dev/createoffer": {
+ "post": {
+ "summary": "lncli: `createoffer`\nCreateOffer creates a new BOLT 12 offer. The offer is persisted in the\noffer store and the encoded offer string (lno1...) is returned. The node\nmust run with --protocol.bolt12-offers.",
+ "operationId": "Dev_CreateOffer",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/devrpcCreateOfferResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/devrpcCreateOfferRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Dev"
+ ]
+ }
+ },
"/v2/dev/importgraph": {
"post": {
"summary": "lncli: `importgraph`\nImportGraph imports a ChannelGraph into the graph database. Should only be\nused for development.",
@@ -85,6 +118,44 @@
}
},
"definitions": {
+ "devrpcCreateOfferRequest": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A UTF-8 description of the purpose of the payment. Required when\namount_msat is set."
+ },
+ "amount_msat": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The amount expected per item in millisatoshis. Zero or unset means\nthe payer chooses the amount."
+ },
+ "absolute_expiry": {
+ "type": "string",
+ "format": "uint64",
+ "description": "Seconds since epoch after which the offer expires. Zero or unset\nmeans no expiry."
+ },
+ "quantity_max": {
+ "type": "string",
+ "format": "uint64",
+ "description": "Maximum number of items that can be requested in a single invoice.\nZero means unlimited. If not set, quantity selection is not\nsupported."
+ }
+ }
+ },
+ "devrpcCreateOfferResponse": {
+ "type": "object",
+ "properties": {
+ "offer": {
+ "type": "string",
+ "description": "The bech32-encoded offer string (lno1...)."
+ },
+ "offer_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The 32-byte offer hash: the SHA256 of the offer's TLV records."
+ }
+ }
+ },
"devrpcImportGraphResponse": {
"type": "object"
},
### lnrpc/devrpc/dev.yaml
@@ -9,3 +9,6 @@ http:
- selector: devrpc.Dev.Quiesce
post: "/v2/dev/quiesce"
body: "*"
+ - selector: devrpc.Dev.CreateOffer
+ post: "/v2/dev/createoffer"
+ body: "*"
### lnrpc/devrpc/dev_grpc.pb.go
@@ -28,6 +28,11 @@ type DevClient interface {
//RPC is for testing purposes only. The commit that adds it will be removed
//once interop is confirmed.
Quiesce(ctx context.Context, in *QuiescenceRequest, opts ...grpc.CallOption) (*QuiescenceResponse, error)
+ // lncli: `createoffer`
+ //CreateOffer creates a new BOLT 12 offer. The offer is persisted in the
+ //offer store and the encoded offer string (lno1...) is returned. The node
+ //must run with --protocol.bolt12-offers.
+ CreateOffer(ctx context.Context, in *CreateOfferRequest, opts ...grpc.CallOption) (*CreateOfferResponse, error)
}
type devClient struct {
@@ -56,6 +61,15 @@ func (c *devClient) Quiesce(ctx context.Context, in *QuiescenceRequest, opts ...
return out, nil
}
+func (c *devClient) CreateOffer(ctx context.Context, in *CreateOfferRequest, opts ...grpc.CallOption) (*CreateOfferResponse, error) {
+ out := new(CreateOfferResponse)
+ err := c.cc.Invoke(ctx, "/devrpc.Dev/CreateOffer", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// DevServer is the server API for Dev service.
// All implementations must embed UnimplementedDevServer
// for forward compatibility
@@ -69,6 +83,11 @@ type DevServer interface {
//RPC is for testing purposes only. The commit that adds it will be removed
//once interop is confirmed.
Quiesce(context.Context, *QuiescenceRequest) (*QuiescenceResponse, error)
+ // lncli: `createoffer`
+ //CreateOffer creates a new BOLT 12 offer. The offer is persisted in the
+ //offer store and the encoded offer string (lno1...) is returned. The node
+ //must run with --protocol.bolt12-offers.
+ CreateOffer(context.Context, *CreateOfferRequest) (*CreateOfferResponse, error)
mustEmbedUnimplementedDevServer()
}
@@ -82,6 +101,9 @@ func (UnimplementedDevServer) ImportGraph(context.Context, *lnrpc.ChannelGraph)
func (UnimplementedDevServer) Quiesce(context.Context, *QuiescenceRequest) (*QuiescenceResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Quiesce not implemented")
}
+func (UnimplementedDevServer) CreateOffer(context.Context, *CreateOfferRequest) (*CreateOfferResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method CreateOffer not implemented")
+}
func (UnimplementedDevServer) mustEmbedUnimplementedDevServer() {}
// UnsafeDevServer may be embedded to opt out of forward compatibility for this service.
@@ -131,6 +153,24 @@ func _Dev_Quiesce_Handler(srv interface{}, ctx context.Context, dec func(interfa
return interceptor(ctx, in, info, handler)
}
+func _Dev_CreateOffer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateOfferRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DevServer).CreateOffer(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/devrpc.Dev/CreateOffer",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DevServer).CreateOffer(ctx, req.(*CreateOfferRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// Dev_ServiceDesc is the grpc.ServiceDesc for Dev service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -146,6 +186,10 @@ var Dev_ServiceDesc = grpc.ServiceDesc{
MethodName: "Quiesce",
Handler: _Dev_Quiesce_Handler,
},
+ {
+ MethodName: "CreateOffer",
+ Handler: _Dev_CreateOffer_Handler,
+ },
},
Streams: []grpc.StreamDesc{},
Metadata: "devrpc/dev.proto",
### lnrpc/devrpc/dev_server.go
@@ -6,6 +6,7 @@ package devrpc
import (
"context"
"encoding/hex"
+ "errors"
"fmt"
"strconv"
"strings"
@@ -22,7 +23,10 @@ import (
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/offers"
"google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
"gopkg.in/macaroon-bakery.v2/bakery"
)
@@ -45,6 +49,10 @@ var (
Entity: "offchain",
Action: "write",
}},
+ "/devrpc.Dev/CreateOffer": {{
+ Entity: "offchain",
+ Action: "write",
+ }},
}
)
@@ -387,3 +395,46 @@ func (s *Server) Quiesce(_ context.Context, in *QuiescenceRequest) (
return nil, fmt.Errorf("server shutting down")
}
}
+
+// errBolt12Disabled is returned by CreateOffer when the node runs without
+// BOLT 12 offers.
+var errBolt12Disabled = status.Error(codes.FailedPrecondition, "BOLT 12 "+
+ "offers are disabled: start lnd with --protocol.bolt12-offers in a "+
+ "development build with native SQL")
+
+// CreateOffer creates a persisted BOLT 12 offer and returns its encoded
+// string and offer hash.
+func (s *Server) CreateOffer(ctx context.Context,
+ req *CreateOfferRequest) (*CreateOfferResponse, error) {
+
+ if s.cfg.OfferCreator == nil {
+ return nil, errBolt12Disabled
+ }
+
+ // BOLT 12 requires a description for an offer with an amount. The
+ // encoder enforces it too, but its error has no gRPC code.
+ if req.AmountMsat > 0 && req.Description == "" {
+ return nil, status.Error(codes.InvalidArgument, "an offer "+
+ "with an amount requires a description")
+ }
+
+ result, err := s.cfg.OfferCreator.CreateOffer(
+ ctx, req.Description, req.AmountMsat, req.AbsoluteExpiry,
+ fn.OptionFromPtr(req.QuantityMax),
+ )
+ switch {
+ case errors.Is(err, offers.ErrExpiryNotInFuture):
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+
+ case errors.Is(err, offers.ErrOfferExists):
+ return nil, status.Error(codes.AlreadyExists, err.Error())
+
+ case err != nil:
+ return nil, err
+ }
+
+ return &CreateOfferResponse{
+ Offer: result.Encoded,
+ OfferHash: result.Hash[:],
+ }, nil
+}
### lnrpc/devrpc/dev_server_offer_test.go
@@ -0,0 +1,138 @@
+//go:build dev
+// +build dev
+
+package devrpc
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/offers"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// fakeOfferHash is the offer hash that fakeOfferCreator returns.
+var fakeOfferHash = [32]byte{1}
+
+// fakeOfferCreator returns a fixed result and records the quantity limit.
+type fakeOfferCreator struct {
+ err error
+ quantityMax fn.Option[uint64]
+}
+
+// CreateOffer returns err, or a fixed offer when err is nil.
+func (f *fakeOfferCreator) CreateOffer(_ context.Context, _ string,
+ _, _ uint64,
+ quantityMax fn.Option[uint64]) (*offers.CreateOfferResult, error) {
+
+ f.quantityMax = quantityMax
+ if f.err != nil {
+ return nil, f.err
+ }
+
+ return &offers.CreateOfferResult{
+ Encoded: "lno1test",
+ Hash: fakeOfferHash,
+ }, nil
+}
+
+// TestCreateOffer checks the gRPC code of each CreateOffer result.
+func TestCreateOffer(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ creator *fakeOfferCreator
+ req *CreateOfferRequest
+ code codes.Code
+ }{
+ {
+ name: "offers disabled",
+ req: &CreateOfferRequest{Description: "coffee"},
+ code: codes.FailedPrecondition,
+ },
+ {
+ name: "amount without description",
+ creator: &fakeOfferCreator{},
+ req: &CreateOfferRequest{AmountMsat: 1},
+ code: codes.InvalidArgument,
+ },
+ {
+ name: "expiry in the past",
+ creator: &fakeOfferCreator{
+ err: offers.ErrExpiryNotInFuture,
+ },
+ req: &CreateOfferRequest{Description: "coffee"},
+ code: codes.InvalidArgument,
+ },
+ {
+ name: "offer exists",
+ creator: &fakeOfferCreator{
+ err: offers.ErrOfferExists,
+ },
+ req: &CreateOfferRequest{Description: "coffee"},
+ code: codes.AlreadyExists,
+ },
+ {
+ name: "store failure",
+ creator: &fakeOfferCreator{
+ err: errors.New("disk full"),
+ },
+ req: &CreateOfferRequest{Description: "coffee"},
+ code: codes.Unknown,
+ },
+ {
+ name: "success",
+ creator: &fakeOfferCreator{},
+ req: &CreateOfferRequest{Description: "coffee"},
+ code: codes.OK,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ cfg := &Config{}
+ if tc.creator != nil {
+ cfg.OfferCreator = tc.creator
+ }
+ server, _, err := New(cfg)
+ require.NoError(t, err)
+
+ resp, err := server.CreateOffer(t.Context(), tc.req)
+ require.Equal(t, tc.code, status.Code(err))
+ if tc.code != codes.OK {
+ return
+ }
+
+ require.Equal(t, "lno1test", resp.Offer)
+ require.Equal(t, fakeOfferHash[:], resp.OfferHash)
+ })
+ }
+}
+
+// TestCreateOfferQuantityMax checks that an unset quantity_max reaches the
+// creator as None, and a set one as Some.
+func TestCreateOfferQuantityMax(t *testing.T) {
+ t.Parallel()
+
+ creator := &fakeOfferCreator{}
+ server, _, err := New(&Config{OfferCreator: creator})
+ require.NoError(t, err)
+
+ _, err = server.CreateOffer(t.Context(), &CreateOfferRequest{})
+ require.NoError(t, err)
+ require.True(t, creator.quantityMax.IsNone())
+
+ qty := uint64(1)
+ _, err = server.CreateOffer(t.Context(), &CreateOfferRequest{
+ QuantityMax: &qty,
+ })
+ require.NoError(t, err)
+ require.Equal(t, fn.Some(qty), creator.quantityMax)
+}
### lnrpc/devrpc/offer_creator.go
@@ -0,0 +1,18 @@
+package devrpc
+
+import (
+ "context"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/offers"
+)
+
+// OfferCreator creates and stores the BOLT 12 offers of this node.
+type OfferCreator interface {
+ // CreateOffer creates an offer from the node's identity, stores it,
+ // and returns its encoded string and offer hash.
+ CreateOffer(ctx context.Context, description string, amountMsat,
+ absoluteExpiry uint64,
+ quantityMax fn.Option[uint64]) (*offers.CreateOfferResult,
+ error)
+}
### lntest/harness.go
@@ -221,6 +221,17 @@ func (h *HarnessTest) Context() context.Context {
return h.runCtx
}
+// NativeSQLEnabled returns true when the nodes run on a SQL database backend
+// with native SQL tables.
+func (h *HarnessTest) NativeSQLEnabled() bool {
+ if !h.manager.nativeSQL {
+ return false
+ }
+
+ return h.manager.dbBackend == node.BackendSqlite ||
+ h.manager.dbBackend == node.BackendPostgres
+}
+
// setupWatchOnlyNode initializes a node with the watch-only accounts of an
// associated remote signing instance.
func (h *HarnessTest) setupWatchOnlyNode(name string,
### lntest/rpc/lnd.go
@@ -766,6 +766,19 @@ func (h *HarnessRPC) SubscribeOnionMessages() (OnionMessageClient,
return stream, cancel
}
+// CreateOffer makes a RPC call to the node's dev CreateOffer and asserts.
+func (h *HarnessRPC) CreateOffer(
+ req *devrpc.CreateOfferRequest) *devrpc.CreateOfferResponse {
+
+ ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
+ defer cancel()
+
+ resp, err := h.Dev.CreateOffer(ctxt, req)
+ h.NoError(err, "CreateOffer")
+
+ return resp
+}
+
// GetChanInfo makes a RPC call to the node's GetChanInfo and returns the
// response.
func (h *HarnessRPC) GetChanInfo(
### lnwire/blinded_path_sphinx.go
@@ -0,0 +1,89 @@
+package lnwire
+
+import (
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+)
+
+// NewBlindedPathFromSphinx rebuilds a sphinx-form blinded path as the lnwire
+// equivalent. A nil path yields a nil path and no error.
+func NewBlindedPathFromSphinx(p *sphinx.BlindedPath) (*BlindedPath, error) {
+ if p == nil {
+ return nil, nil
+ }
+
+ hops := make([]BlindedHop, len(p.BlindedHops))
+ for i, h := range p.BlindedHops {
+ hops[i].BlindedNodeID = h.BlindedNodePub
+ hops[i].EncryptedData = h.CipherText
+ }
+
+ introNode, err := NewPubkeyIntro(p.IntroductionPoint)
+ if err != nil {
+ return nil, err
+ }
+
+ return &BlindedPath{
+ IntroductionNode: introNode,
+ BlindingPoint: p.BlindingPoint,
+ Hops: hops,
+ }, nil
+}
+
+// ToSphinx assembles the sphinx-form representation used by the routing layer.
+// It accepts only a pubkey-form introduction node, because the sciddir form
+// needs a channel-graph lookup.
+func (p *BlindedPath) ToSphinx() (*sphinx.BlindedPath, error) {
+ if p.IntroductionNode == nil {
+ return nil, fmt.Errorf("nil intro node")
+ }
+
+ introPub, err := introductionNodePubkey(p.IntroductionNode)
+ if err != nil {
+ return nil, err
+ }
+
+ if p.BlindingPoint == nil {
+ return nil, fmt.Errorf("nil blinding point")
+ }
+
+ hops := make([]*sphinx.BlindedHopInfo, len(p.Hops))
+ for i := range p.Hops {
+ if p.Hops[i].BlindedNodeID == nil {
+ return nil, fmt.Errorf("nil blinded hop %d", i)
+ }
+
+ hops[i] = &sphinx.BlindedHopInfo{
+ BlindedNodePub: p.Hops[i].BlindedNodeID,
+ CipherText: p.Hops[i].EncryptedData,
+ }
+ }
+
+ return &sphinx.BlindedPath{
+ IntroductionPoint: introPub,
+ BlindingPoint: p.BlindingPoint,
+ BlindedHops: hops,
+ }, nil
+}
+
+// introductionNodePubkey extracts the key of a pubkey-form introduction
+// node. It returns an error for any other form.
+func introductionNodePubkey(intro IntroductionNode) (*btcec.PublicKey, error) {
+ switch v := intro.(type) {
+ case PubkeyIntro:
+ if v.Pubkey == nil {
+ return nil, fmt.Errorf("%w: nil pubkey",
+ ErrInvalidIntroNode)
+ }
+
+ return v.Pubkey, nil
+
+ case SciddirIntro:
+ return nil, fmt.Errorf("sciddir intro is not supported")
+
+ default:
+ return nil, fmt.Errorf("%w: %T", ErrInvalidIntroNode, intro)
+ }
+}
### lnwire/blinded_path_test.go
@@ -6,6 +6,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
"github.com/stretchr/testify/require"
+ "pgregory.net/rapid"
)
// validPubkeyIntro returns an on-curve PubkeyIntro plus the matching
@@ -412,3 +413,97 @@ func TestEncodeBlindedPathsRejects(t *testing.T) {
})
}
}
+
+// TestBlindedPathSphinxRoundTrip checks that NewBlindedPathFromSphinx inverts
+// ToSphinx for a path with a pubkey-form introduction node.
+func TestBlindedPathSphinxRoundTrip(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ path := RandBlindedPath(rt)
+ intro, err := NewPubkeyIntro(RandPubKey(rt))
+ require.NoError(rt, err)
+ path.IntroductionNode = intro
+
+ sphinxPath, err := path.ToSphinx()
+ require.NoError(rt, err)
+
+ got, err := NewBlindedPathFromSphinx(sphinxPath)
+ require.NoError(rt, err)
+ require.Equal(rt, path, got)
+ })
+}
+
+// TestToSphinxRejects checks that ToSphinx rejects a path that the routing
+// layer cannot use.
+func TestToSphinxRejects(t *testing.T) {
+ t.Parallel()
+
+ pubIntro, _ := validPubkeyIntro(t)
+ sciddirIntro, err := NewSciddirIntro(
+ 0x00, [8]byte{1, 2, 3, 4, 5, 6, 7, 8},
+ )
+ require.NoError(t, err)
+
+ hop := BlindedHop{
+ BlindedNodeID: validBlindingPoint(t),
+ EncryptedData: []byte{0xaa, 0xbb},
+ }
+
+ tests := []struct {
+ name string
+ intro IntroductionNode
+ point *btcec.PublicKey
+ hops []BlindedHop
+ err string
+ }{
+ {
+ name: "sciddir intro",
+ intro: sciddirIntro,
+ point: validBlindingPoint(t),
+ hops: []BlindedHop{hop},
+ err: "not supported",
+ },
+ {
+ name: "nil intro",
+ point: validBlindingPoint(t),
+ hops: []BlindedHop{hop},
+ err: "nil intro node",
+ },
+ {
+ name: "nil intro pubkey",
+ intro: PubkeyIntro{},
+ point: validBlindingPoint(t),
+ hops: []BlindedHop{hop},
+ err: "nil pubkey",
+ },
+ {
+ name: "nil blinding point",
+ intro: pubIntro,
+ hops: []BlindedHop{hop},
+ err: "nil blinding point",
+ },
+ {
+ name: "nil blinded hop",
+ intro: pubIntro,
+ point: validBlindingPoint(t),
+ hops: []BlindedHop{hop, {}},
+ err: "nil blinded hop 1",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ path := &BlindedPath{
+ IntroductionNode: tc.intro,
+ BlindingPoint: tc.point,
+ Hops: tc.hops,
+ }
+
+ _, err := path.ToSphinx()
+ require.ErrorContains(t, err, tc.err)
+ })
+ }
+}
### onionmessage/actor.go
@@ -214,7 +214,9 @@ func (a *OnionPeerActor) Receive(ctx context.Context,
return fn.Err[*Response](err)
}
- // Handle the routing action.
+ // Handle the routing action. A delivered message also gives the path
+ // id of the path it arrived on.
+ var pathID []byte
payload := fn.ElimEither(routingAction,
func(fwdAction forwardAction) *lnwire.OnionMessagePayload {
log.DebugS(logCtx, "Forwarding onion message",
@@ -247,6 +249,8 @@ func (a *OnionPeerActor) Receive(ctx context.Context,
log.DebugS(logCtx, "Delivering onion message "+
"to self")
+ pathID = dlvrAction.pathID
+
return dlvrAction.payload
})
@@ -259,6 +263,8 @@ func (a *OnionPeerActor) Receive(ctx context.Context,
Peer: a.peerPubKey,
PathKey: pathKeyArr,
OnionBlob: req.msg.OnionBlob,
+ Delivered: routingAction.IsRight(),
+ PathID: pathID,
}
// If we have a payload, add its contents to our update.
### onionmessage/actor_test.go
@@ -10,6 +10,7 @@ import (
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
+ "github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
@@ -234,6 +235,30 @@ func buildDeliverHops(t *testing.T, h *actorHarness) hopBuildResult {
}
}
+// testPathID is the path id that buildDeliverPathIDHops puts into the final
+// hop.
+var testPathID = []byte{9, 8, 7, 6}
+
+// buildDeliverPathIDHops constructs a final hop whose recipient data carries a
+// path id, as on a blinded path that this node created.
+func buildDeliverPathIDHops(t *testing.T, h *actorHarness) hopBuildResult {
+ rd := &record.BlindedRouteData{
+ PathID: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType6](testPathID),
+ ),
+ }
+ plain := EncodeBlindedRouteData(t, rd)
+ hops := []*sphinx.HopInfo{
+ {NodePub: h.nodeKey.PubKey(), PlainText: plain},
+ }
+
+ return hopBuildResult{
+ blindedPath: BuildBlindedPath(t, hops),
+ privKeys: []*btcec.PrivateKey{h.nodeKey},
+ after: func() {},
+ }
+}
+
// buildForwardUnknownPeerHops constructs hops for testing forward to an
// unknown peer. The sender returns an error, so forwarding will fail but the
// message is still processed.
@@ -386,6 +411,8 @@ func TestOnionPeerActorRouting(t *testing.T) {
name string
buildHops buildHopsFunc
finalHopTLVs []*lnwire.FinalHopTLV
+ delivered bool
+ pathID []byte
}{
{
name: "forward next node",
@@ -404,6 +431,19 @@ func TestOnionPeerActorRouting(t *testing.T) {
Value: []byte{1, 2, 3},
},
},
+ delivered: true,
+ },
+ {
+ name: "deliver with path id",
+ buildHops: buildDeliverPathIDHops,
+ finalHopTLVs: []*lnwire.FinalHopTLV{
+ {
+ TLVType: customTLVType,
+ Value: []byte{1, 2, 3},
+ },
+ },
+ delivered: true,
+ pathID: testPathID,
},
{
name: "forward concatenated path",
@@ -444,6 +484,10 @@ func TestOnionPeerActorRouting(t *testing.T) {
t, expectedData,
update.EncryptedRecipientData,
)
+ require.Equal(
+ t, tc.delivered, update.Delivered,
+ )
+ require.Equal(t, tc.pathID, update.PathID)
for _, fht := range tc.finalHopTLVs {
tlvType := fht.TLVType
### onionmessage/hop.go
@@ -31,12 +31,16 @@ type forwardAction struct {
}
// deliverAction contains the information needed to deliver the payload to any
-// subscribers. Since we only support forwarding onion messages, this is only
-// needed in itest to verify correct handling and behavior.
+// subscribers.
type deliverAction struct {
// payload contains the decoded payload for this hop, which may include
// custom records and routing information.
payload *lnwire.OnionMessagePayload
+
+ // pathID is the path_id in the recipient data of this hop. The creator
+ // of the blinded path sets it, so it is set only when the message
+ // arrived on a path that has one.
+ pathID []byte
}
type routingAction = fn.Either[forwardAction, deliverAction]
@@ -123,32 +127,13 @@ func createRoutingAction(ctx context.Context, resolver NodeIDResolver,
nextPathKey *btcec.PublicKey) (routingAction, error) {
if isForwarding(packet) {
- var nextNodeID *btcec.PublicKey
- if routeData.NextNodeID.IsSome() {
- n, err := routeData.NextNodeID.UnwrapOrErr(
- ErrNextNodeIdEmpty,
- )
- if err != nil {
- return routingAction{}, err
- }
- nextNodeID = n.Val
- } else {
- scid, err := routeData.ShortChannelID.UnwrapOrErr(
- ErrSCIDEmpty,
- )
- if err != nil {
- return routingAction{}, err
- }
- nextNodeID, err = resolver.RemotePubFromSCID(
- ctx, scid.Val,
- )
- if err != nil {
- return routingAction{}, err
- }
+ nextNodeID, err := nextNodeID(ctx, resolver, routeData)
+ if err != nil {
+ return routingAction{}, err
}
buf := new(bytes.Buffer)
- err := packet.NextPacket.Encode(buf)
+ err = packet.NextPacket.Encode(buf)
if err != nil {
return routingAction{}, err
}
@@ -162,11 +147,39 @@ func createRoutingAction(ctx context.Context, resolver NodeIDResolver,
}), nil
}
+ var pathID []byte
+ routeData.PathID.WhenSome(func(r tlv.RecordT[tlv.TlvType6, []byte]) {
+ pathID = r.Val
+ })
+
return fn.NewRight[forwardAction](deliverAction{
payload: payload,
+ pathID: pathID,
}), nil
}
+// nextNodeID returns the key of the next node that the route data names, by
+// its node id or by a channel to it.
+func nextNodeID(ctx context.Context, resolver NodeIDResolver,
+ routeData *record.BlindedRouteData) (*btcec.PublicKey, error) {
+
+ if routeData.NextNodeID.IsSome() {
+ n, err := routeData.NextNodeID.UnwrapOrErr(ErrNextNodeIdEmpty)
+ if err != nil {
+ return nil, err
+ }
+
+ return n.Val, nil
+ }
+
+ scid, err := routeData.ShortChannelID.UnwrapOrErr(ErrSCIDEmpty)
+ if err != nil {
+ return nil, err
+ }
+
+ return resolver.RemotePubFromSCID(ctx, scid.Val)
+}
+
// deriveNextPathKey derives the next path key using the router and current
// path key. If an override is provided, it is used instead.
func deriveNextPathKey(router OnionRouter, currentPathKey *btcec.PublicKey,
### onionmessage/hop_peeler.go
@@ -0,0 +1,98 @@
+package onionmessage
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/record"
+)
+
+// ErrPathEndsAtSelf is returned when every hop of a blinded path belongs to
+// this node, so no other node is left to send to.
+var ErrPathEndsAtSelf = errors.New("blinded path ends at this node")
+
+// HopPeeler removes the hops of this node at the start of a blinded path.
+// A sender calls it before it builds an onion message on a path whose
+// introduction node is this node, because no peer connection leads to the own
+// node.
+type HopPeeler struct {
+ router OnionRouter
+ resolver NodeIDResolver
+ ourPub *btcec.PublicKey
+}
+
+// NewHopPeeler creates a HopPeeler for the node with the key ourPub. The
+// router must decrypt with the private key of ourPub.
+func NewHopPeeler(router OnionRouter, resolver NodeIDResolver,
+ ourPub *btcec.PublicKey) *HopPeeler {
+
+ return &HopPeeler{
+ router: router,
+ resolver: resolver,
+ ourPub: ourPub,
+ }
+}
+
+// PeelOwnHops returns path without the hops of this node at its start. It
+// returns path as it is when its introduction node is another node. It does
+// not change path.
+func (p *HopPeeler) PeelOwnHops(ctx context.Context,
+ path *sphinx.BlindedPath) (*sphinx.BlindedPath, error) {
+
+ for path.IntroductionPoint.IsEqual(p.ourPub) {
+ if len(path.BlindedHops) < 2 {
+ return nil, ErrPathEndsAtSelf
+ }
+
+ next, err := p.peel(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+ path = next
+ }
+
+ return path, nil
+}
+
+// peel removes the first hop of path, which belongs to this node.
+func (p *HopPeeler) peel(ctx context.Context,
+ path *sphinx.BlindedPath) (*sphinx.BlindedPath, error) {
+
+ // The decryption works in place, and the caller still owns path.
+ cipherText := bytes.Clone(path.BlindedHops[0].CipherText)
+ plainText, err := p.router.DecryptBlindedHopData(
+ path.BlindingPoint, cipherText,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("decrypt own hop: %w", err)
+ }
+
+ routeData, err := record.DecodeBlindedRouteData(
+ bytes.NewReader(plainText),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("decode own hop: %w", err)
+ }
+
+ nextNode, err := nextNodeID(ctx, p.resolver, routeData)
+ if err != nil {
+ return nil, fmt.Errorf("next node of own hop: %w", err)
+ }
+
+ nextPathKey := deriveNextPathKey(
+ p.router, path.BlindingPoint, routeData.NextBlindingOverride,
+ )
+ if nextPathKey == nil {
+ return nil, errors.New("derive the next path key")
+ }
+
+ return &sphinx.BlindedPath{
+ IntroductionPoint: nextNode,
+ BlindingPoint: nextPathKey,
+ BlindedHops: path.BlindedHops[1:],
+ }, nil
+}
### onionmessage/hop_peeler_test.go
@@ -0,0 +1,195 @@
+package onionmessage
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/stretchr/testify/require"
+)
+
+// newTestRouter returns a started onion router for key.
+func newTestRouter(t *testing.T, key *btcec.PrivateKey) *sphinx.Router {
+ t.Helper()
+
+ router := sphinx.NewRouter(
+ &sphinx.PrivKeyECDH{PrivKey: key}, sphinx.NewNoOpReplayLog(),
+ )
+ require.NoError(t, router.Start())
+ t.Cleanup(router.Stop)
+
+ return router
+}
+
+// forwardHop returns a hop of node that forwards to the next node.
+func forwardHop(t *testing.T, node *btcec.PublicKey,
+ next fn.Either[*btcec.PublicKey, lnwire.ShortChannelID],
+ override *btcec.PublicKey) *sphinx.HopInfo {
+
+ return &sphinx.HopInfo{
+ NodePub: node,
+ PlainText: EncodeBlindedRouteData(
+ t, record.NewNonFinalBlindedRouteDataOnionMessage(
+ next, override, nil,
+ ),
+ ),
+ }
+}
+
+// finalHop returns the last hop of a path, at node.
+func finalHop(t *testing.T, node *btcec.PublicKey) *sphinx.HopInfo {
+ return &sphinx.HopInfo{
+ NodePub: node,
+ PlainText: EncodeBlindedRouteData(
+ t, &record.BlindedRouteData{},
+ ),
+ }
+}
+
+// requireDecryptable checks that the introduction node of path can decrypt
+// its hop, which needs the right blinding point.
+func requireDecryptable(t *testing.T, path *sphinx.BlindedPath,
+ introKey *btcec.PrivateKey) {
+
+ t.Helper()
+
+ router := newTestRouter(t, introKey)
+ cipherText := bytes.Clone(path.BlindedHops[0].CipherText)
+ plainText, err := router.DecryptBlindedHopData(
+ path.BlindingPoint, cipherText,
+ )
+ require.NoError(t, err)
+
+ _, err = record.DecodeBlindedRouteData(bytes.NewReader(plainText))
+ require.NoError(t, err)
+}
+
+// TestHopPeeler checks that the peeler removes the hops of this node at
+// the start of a blinded path, and that the next node can use the result.
+func TestHopPeeler(t *testing.T) {
+ t.Parallel()
+
+ ourKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ otherKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ ourPub, otherPub := ourKey.PubKey(), otherKey.PubKey()
+
+ scid := lnwire.NewShortChanIDFromInt(42)
+ resolver := newMockNodeIDResolver()
+ resolver.addPeer(scid, otherPub)
+
+ peeler := NewHopPeeler(
+ newTestRouter(t, ourKey), resolver, ourPub,
+ )
+
+ toOther := fn.NewLeft[*btcec.PublicKey, lnwire.ShortChannelID](
+ otherPub,
+ )
+ toOtherByChannel := fn.NewRight[*btcec.PublicKey](scid)
+ toUs := fn.NewLeft[*btcec.PublicKey, lnwire.ShortChannelID](ourPub)
+
+ t.Run("next node by node id", func(t *testing.T) {
+ t.Parallel()
+
+ path := BuildBlindedPath(t, []*sphinx.HopInfo{
+ forwardHop(t, ourPub, toOther, nil),
+ finalHop(t, otherPub),
+ }).Path
+ ownCipherText := bytes.Clone(path.BlindedHops[0].CipherText)
+
+ got, err := peeler.PeelOwnHops(t.Context(), path)
+ require.NoError(t, err)
+ require.True(t, otherPub.IsEqual(got.IntroductionPoint))
+ require.Equal(t, path.BlindedHops[1:], got.BlindedHops)
+ requireDecryptable(t, got, otherKey)
+
+ // The caller's path is unchanged.
+ require.Equal(
+ t, ownCipherText, path.BlindedHops[0].CipherText,
+ )
+ })
+
+ t.Run("next node by channel", func(t *testing.T) {
+ t.Parallel()
+
+ path := BuildBlindedPath(t, []*sphinx.HopInfo{
+ forwardHop(t, ourPub, toOtherByChannel, nil),
+ finalHop(t, otherPub),
+ }).Path
+
+ got, err := peeler.PeelOwnHops(t.Context(), path)
+ require.NoError(t, err)
+ require.True(t, otherPub.IsEqual(got.IntroductionPoint))
+ requireDecryptable(t, got, otherKey)
+ })
+
+ t.Run("two own hops", func(t *testing.T) {
+ t.Parallel()
+
+ path := BuildBlindedPath(t, []*sphinx.HopInfo{
+ forwardHop(t, ourPub, toUs, nil),
+ forwardHop(t, ourPub, toOther, nil),
+ finalHop(t, otherPub),
+ }).Path
+
+ got, err := peeler.PeelOwnHops(t.Context(), path)
+ require.NoError(t, err)
+ require.True(t, otherPub.IsEqual(got.IntroductionPoint))
+ require.Len(t, got.BlindedHops, 1)
+ requireDecryptable(t, got, otherKey)
+ })
+
+ t.Run("blinding override", func(t *testing.T) {
+ t.Parallel()
+
+ // The own hop leads into a path that the other node built,
+ // so the next blinding point is the override.
+ otherPath := BuildBlindedPath(t, []*sphinx.HopInfo{
+ finalHop(t, otherPub),
+ })
+ ownPath := BuildBlindedPath(t, []*sphinx.HopInfo{
+ forwardHop(
+ t, ourPub, toOther,
+ otherPath.Path.BlindingPoint,
+ ),
+ })
+ path := ConcatBlindedPaths(t, ownPath, otherPath).Path
+
+ got, err := peeler.PeelOwnHops(t.Context(), path)
+ require.NoError(t, err)
+ require.True(
+ t, otherPath.Path.BlindingPoint.IsEqual(
+ got.BlindingPoint,
+ ),
+ )
+ requireDecryptable(t, got, otherKey)
+ })
+
+ t.Run("other introduction node", func(t *testing.T) {
+ t.Parallel()
+
+ path := BuildBlindedPath(t, []*sphinx.HopInfo{
+ finalHop(t, otherPub),
+ }).Path
+
+ got, err := peeler.PeelOwnHops(t.Context(), path)
+ require.NoError(t, err)
+ require.Same(t, path, got)
+ })
+
+ t.Run("path ends at this node", func(t *testing.T) {
+ t.Parallel()
+
+ path := BuildBlindedPath(t, []*sphinx.HopInfo{
+ finalHop(t, ourPub),
+ }).Path
+
+ _, err := peeler.PeelOwnHops(t.Context(), path)
+ require.ErrorIs(t, err, ErrPathEndsAtSelf)
+ })
+}
### onionmessage/onion_endpoint.go
@@ -33,4 +33,15 @@ type OnionMessageUpdate struct {
// the receiver for the last leg of the route, and the sender for the
// first leg up to the introduction point.
EncryptedRecipientData []byte
+
+ // PathID is the path_id in the recipient data of the final hop. It is
+ // set only for a delivered message that arrived on a blinded path whose
+ // creator set one. Only the creator of the path can check it.
+ PathID []byte
+
+ // Delivered is true when this node is the final hop of the message.
+ // For a forwarded message, CustomRecords and ReplyPath come from the
+ // payload of this hop, and BOLT 4 tells a forwarding node to ignore
+ // them.
+ Delivered bool
}
### rpcserver.go
@@ -60,6 +60,7 @@ import (
"github.com/lightningnetwork/lnd/labels"
"github.com/lightningnetwork/lnd/lncfg"
"github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/devrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
@@ -681,6 +682,54 @@ func newRPCServer(cfg *Config, interceptorChain *rpcperms.InterceptorChain,
}
}
+// addPermissions adds the macaroon permissions of the main RPC server, of
+// the sub-servers and of the external subservers to the interceptor chain.
+func (r *rpcServer) addPermissions(macService *macaroons.Service,
+ subServerPerms []lnrpc.MacaroonPerms) error {
+
+ // We merge the set of sub server macaroon permissions with the main
+ // RPC server permissions so we can unite them under a single set of
+ // interceptors.
+ for m, ops := range MainRPCServerPermissions() {
+ err := r.interceptorChain.AddPermission(m, ops)
+ if err != nil {
+ return err
+ }
+ }
+
+ for _, subServerPerm := range subServerPerms {
+ for method, ops := range subServerPerm {
+ err := r.interceptorChain.AddPermission(method, ops)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ // External subserver possibly need to register their own permissions
+ // and macaroon validator.
+ for method, ops := range r.implCfg.ExternalValidator.Permissions() {
+ err := r.interceptorChain.AddPermission(method, ops)
+ if err != nil {
+ return err
+ }
+
+ // Give the external subservers the possibility to also use
+ // their own validator to check any macaroons attached to calls
+ // to this method. This allows them to have their own root key
+ // ID database and permission entities.
+ err = macService.RegisterExternalValidator(
+ method, r.implCfg.ExternalValidator,
+ )
+ if err != nil {
+ return fmt.Errorf("could not register external "+
+ "macaroon validator: %v", err)
+ }
+ }
+
+ return nil
+}
+
// addDeps populates all dependencies needed by the RPC server, and any
// of the sub-servers that it maintains. When this is done, the RPC server can
// be started, and start accepting RPC calls.
@@ -794,6 +843,13 @@ func (r *rpcServer) addDeps(ctx context.Context, s *server,
subServerPerms []lnrpc.MacaroonPerms
)
+ // The dev RPC creates offers only when the node runs with BOLT 12
+ // offers.
+ var offerCreator fn.Option[devrpc.OfferCreator]
+ if s.offerStore != nil {
+ offerCreator = fn.Some[devrpc.OfferCreator](s)
+ }
+
// Before we create any of the sub-servers, we need to ensure that all
// the dependencies they need are properly populated within each sub
// server configuration struct.
@@ -807,7 +863,7 @@ func (r *rpcServer) addDeps(ctx context.Context, s *server,
genInvoiceFeatures, genAmpInvoiceFeatures,
s.getNodeAnnouncement, s.updateAndBroadcastSelfNode, parseAddr,
rpcsLog, s.aliasMgr, r.implCfg.AuxDataParser,
- invoiceHtlcModifier,
+ invoiceHtlcModifier, offerCreator,
)
if err != nil {
return err
@@ -830,44 +886,9 @@ func (r *rpcServer) addDeps(ctx context.Context, s *server,
subServerPerms = append(subServerPerms, macPerms)
}
- // Next, we need to merge the set of sub server macaroon permissions
- // with the main RPC server permissions so we can unite them under a
- // single set of interceptors.
- for m, ops := range MainRPCServerPermissions() {
- err := r.interceptorChain.AddPermission(m, ops)
- if err != nil {
- return err
- }
- }
-
- for _, subServerPerm := range subServerPerms {
- for method, ops := range subServerPerm {
- err := r.interceptorChain.AddPermission(method, ops)
- if err != nil {
- return err
- }
- }
- }
-
- // External subserver possibly need to register their own permissions
- // and macaroon validator.
- for method, ops := range r.implCfg.ExternalValidator.Permissions() {
- err := r.interceptorChain.AddPermission(method, ops)
- if err != nil {
- return err
- }
-
- // Give the external subservers the possibility to also use
- // their own validator to check any macaroons attached to calls
- // to this method. This allows them to have their own root key
- // ID database and permission entities.
- err = macService.RegisterExternalValidator(
- method, r.implCfg.ExternalValidator,
- )
- if err != nil {
- return fmt.Errorf("could not register external "+
- "macaroon validator: %v", err)
- }
+ err = r.addPermissions(macService, subServerPerms)
+ if err != nil {
+ return err
}
// Finally, with all the set up complete, add the last dependencies to
@@ -5699,6 +5720,7 @@ func (r *rpcServer) SubscribeChannelEvents(req *lnrpc.ChannelEventSubscription,
if errors.Is(updateStream.Context().Err(), context.Canceled) {
return nil
}
+
return updateStream.Context().Err()
case <-r.quit:
### server.go
@@ -30,6 +30,7 @@ import (
"github.com/lightningnetwork/lnd/actor"
"github.com/lightningnetwork/lnd/aliasmgr"
"github.com/lightningnetwork/lnd/autopilot"
+ "github.com/lightningnetwork/lnd/bolt12handler"
"github.com/lightningnetwork/lnd/brontide"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/chainio"
@@ -70,6 +71,7 @@ import (
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/nat"
"github.com/lightningnetwork/lnd/netann"
+ "github.com/lightningnetwork/lnd/offers"
"github.com/lightningnetwork/lnd/onionmessage"
paymentsdb "github.com/lightningnetwork/lnd/payments/db"
"github.com/lightningnetwork/lnd/peer"
@@ -468,6 +470,13 @@ type server struct {
// turned off).
onionLimiter onionmessage.IngressLimiter
+ // bolt12Handler handles incoming BOLT 12 invoice requests and
+ // generates signed invoices in response.
+ bolt12Handler *bolt12handler.Handler
+
+ // offerStore persists and queries BOLT 12 offers.
+ offerStore offers.Store
+
// txPublisher is a publisher with fee-bumping capability.
txPublisher *sweep.TxPublisher
@@ -863,6 +872,8 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
onionMessageServer: subscribe.NewServer(),
+ offerStore: dbs.OfferDB,
+
actorSystem: actor.NewActorSystem(),
tlsManager: tlsManager,
@@ -887,6 +898,26 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
dbs.InvoiceDB, expiryWatcher, ®istryConfig,
)
+ // BOLT 12 needs native SQL, so set it up only with the offer store.
+ if s.offerStore != nil {
+ signer := bolt12handler.NewKeyRingSigner(
+ cc.KeyRing, nodeKeyDesc.KeyLocator,
+ nodeKeyECDH.PubKey(),
+ )
+ replier := bolt12handler.NewServerOnionReplier(s)
+
+ // Use the final CLTV delta of BOLT 11 invoices.
+ s.bolt12Handler, err = bolt12handler.NewHandler(
+ s.offerStore, s.invoices, replier, signer, nil,
+ clock.NewDefaultClock(),
+ *s.cfg.ActiveNetParams.GenesisHash,
+ uint16(cfg.Bitcoin.TimeLockDelta),
+ )
+ if err != nil {
+ return nil, err
+ }
+ }
+
s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
@@ -2417,6 +2448,32 @@ func (s *server) Start(ctx context.Context) error {
return
}
+ if s.bolt12Handler != nil {
+ cleanup = cleanup.add(func() error {
+ s.bolt12Handler.Stop()
+
+ return nil
+ })
+ resolver := bolt12handler.NewGraphIntroResolver(
+ s.graphDB,
+ )
+ ourPub := s.identityECDH.PubKey()
+ peeler := onionmessage.NewHopPeeler(
+ s.sphinxOnionMsg,
+ onionmessage.NewGraphNodeResolver(
+ s.graphDB, ourPub,
+ ),
+ ourPub,
+ )
+ err := s.bolt12Handler.Start(
+ ctx, s, resolver, peeler,
+ )
+ if err != nil {
+ startErr = err
+ return
+ }
+ }
+
if s.hostAnn != nil {
cleanup = cleanup.add(s.hostAnn.Stop)
if err := s.hostAnn.Start(); err != nil {
@@ -2944,9 +3001,14 @@ func (s *server) Stop() error {
if err := s.sphinxPayment.Stop(); err != nil {
srvrLog.Warnf("failed to stop sphinx: %v", err)
}
+ // Stop the invoice registry first. A running invoice request
+ // can wait in the registry until the registry stops.
if err := s.invoices.Stop(); err != nil {
srvrLog.Warnf("failed to stop invoices: %v", err)
}
+ if s.bolt12Handler != nil {
+ s.bolt12Handler.Stop()
+ }
if err := s.interceptableSwitch.Stop(); err != nil {
srvrLog.Warnf("failed to stop interceptable "+
"switch: %v", err)
@@ -4581,6 +4643,45 @@ func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
return s.onionMessageServer.Subscribe()
}
+// offerChains returns the offer_chains of an offer for the chain with the
+// given genesis hash. BOLT 12 says to omit the field for Bitcoin mainnet,
+// which a reader assumes when the field is absent. Other chains need it, so
+// that a payer can check the chain.
+func offerChains(genesisHash chainhash.Hash) [][32]byte {
+ if genesisHash == *chaincfg.MainNetParams.GenesisHash {
+ return nil
+ }
+
+ return [][32]byte{genesisHash}
+}
+
+// CreateOffer creates a new BOLT 12 offer, persists it in the offer
+// store, and returns the encoded offer string and offer hash. The caller
+// checks that the offer store is set.
+func (s *server) CreateOffer(ctx context.Context,
+ description string, amountMsat uint64,
+ absoluteExpiry uint64,
+ quantityMax fn.Option[uint64]) (*offers.CreateOfferResult, error) {
+
+ identity := fn.NewLeft[
+ *btcec.PublicKey, []lnwire.BlindedPath,
+ ](s.identityECDH.PubKey())
+
+ chains := offerChains(*s.cfg.ActiveNetParams.GenesisHash)
+
+ return offers.CreateOffer(
+ ctx, s.offerStore, clock.NewDefaultClock(),
+ offers.CreateOfferParams{
+ Identity: identity,
+ Description: description,
+ AmountMsat: amountMsat,
+ AbsoluteExpiry: absoluteExpiry,
+ QuantityMax: quantityMax,
+ Chains: chains,
+ },
+ )
+}
+
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
// the channelNotifier's NotifyOpenChannelEvent.
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
### server_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"time"
+ "github.com/btcsuite/btcd/chaincfg/v2"
"github.com/btcsuite/btcd/wire/v2"
"github.com/lightningnetwork/lnd/aliasmgr"
"github.com/lightningnetwork/lnd/chainreg"
@@ -500,3 +501,15 @@ func TestLivenessMonitorExitCodes(t *testing.T) {
})
}
}
+
+// TestOfferChains checks that a mainnet offer has no offer_chains and that an
+// offer on another chain names that chain.
+func TestOfferChains(t *testing.T) {
+ t.Parallel()
+
+ mainnet := *chaincfg.MainNetParams.GenesisHash
+ require.Nil(t, offerChains(mainnet))
+
+ regtest := *chaincfg.RegressionNetParams.GenesisHash
+ require.Equal(t, [][32]byte{regtest}, offerChains(regtest))
+}
### subrpcserver_config.go
@@ -135,7 +135,8 @@ func (s *subRPCServerConfigs) PopulateDependencies(cfg *Config,
parseAddr func(addr string) (net.Addr, error),
rpcLogger btclog.Logger, aliasMgr *aliasmgr.Manager,
auxDataParser fn.Option[AuxDataParser],
- invoiceHtlcModifier *invoices.HtlcModificationInterceptor) error {
+ invoiceHtlcModifier *invoices.HtlcModificationInterceptor,
+ offerCreator fn.Option[devrpc.OfferCreator]) error {
// First, we'll use reflect to obtain a version of the config struct
// that allows us to programmatically inspect its fields.
@@ -391,6 +392,12 @@ func (s *subRPCServerConfigs) PopulateDependencies(cfg *Config,
reflect.ValueOf(htlcSwitch),
)
+ offerCreator.WhenSome(func(c devrpc.OfferCreator) {
+ subCfgValue.FieldByName("OfferCreator").Set(
+ reflect.ValueOf(c),
+ )
+ })
+
case *peersrpc.Config:
subCfgValue := extractReflectValue(subCfg)
Why this scored 39/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.