Merge pull request #11282 from lightningnetwork/elle-base-branch-payment-service
What changed, and why it matters
This is a large feature merge for LND that adds a new optional RPC subsystem called switchrpc. It lets an external program hand a pre-built onion packet to LND for direct dispatch over a Lightning channel, instead of LND doing its own pathfinding. The change is opt-in and compiled only when the 'switchrpc' build tag is used. It also reworks how in-flight payment attempts are stored so the same attempt ID cannot be used twice, preventing accidental duplicate payments when an external caller retries after a network timeout. The release notes explicitly warn that running the local router and an external router at the same time is unsafe and can cause loss of funds.
Treat this as a significant new attack surface, not as a routine bug fix. If switchrpc is enabled, restrict RPC access strictly to the trusted external router, run only one controller at a time, and monitor for misconfiguration that could enable both local and external routing concurrently. Review the switchrpc ACL/auth bindings before production use. No immediate patch is required because the feature is opt-in and build-tagged, but operators should understand the documented funds-loss risk.
Security signals we found
New optional RPC surface (switchrpc) that accepts externally crafted onion packets and directly dispatches HTLCs
Idempotency/deduplication added via InitAttempt durable write-ahead log and ErrPaymentIDAlreadyExists
Startup orphan cleanup fails half-open or pre-commit attempts to avoid hangs
External lifecycle marker prevents local-mode binary from deleting remote-controller attempt state
Release notes warn: concurrent local + external router usage leads to undefined behavior and potential loss of funds
Build tag gated: switchrpc is not compiled by default
Evidence from the diff
The commit introduces the switchrpc gRPC subserver (SendOnion, BuildOnion, TrackOnion, DeleteAttempts, DisableRemoteRouter), a new AttemptStore interface in htlcswitch, durable InitAttempt/StoreResult/SubscribeResult semantics in networkResultStore, and startup cleanup of orphaned attempts. It refactors ChannelUpdateHandler to expose a read-only ChannelInfoProvider, adds DecodeHopIterator for external onion validation, and changes parseFailedPayment to return either a decrypted error or raw encrypted error bytes when no deobfuscator is supplied. The external-lifecycle marker prevents a non-switchrpc binary from wiping attempt state needed by a remote controller.
Changed components
lnrpc/switchrpchtlcswitch/networkResultStorehtlcswitch/switch.gohtlcswitch/hop/iterator.gorouting/payment lifecyclelnrpc/routerrpcbuild tags (switchrpc_on.go / switchrpc_off.go)Inspect captured patch +11385 / −224
### .golangci.yml
@@ -16,6 +16,7 @@ run:
- neutrinorpc
- peersrpc
- signrpc
+ - switchrpc
- walletrpc
- watchtowerrpc
- kvdb_etcd
### build/switchrpc_off.go
@@ -0,0 +1,7 @@
+//go:build !switchrpc
+// +build !switchrpc
+
+package build
+
+// SwitchRPC indicates that the binary was built with the switchrpc build tag.
+const SwitchRPC = false
### build/switchrpc_on.go
@@ -0,0 +1,7 @@
+//go:build switchrpc
+// +build switchrpc
+
+package build
+
+// SwitchRPC indicates that the binary was built with the switchrpc build tag.
+const SwitchRPC = true
### docs/release-notes/unreleased/11282.md
@@ -0,0 +1,113 @@
+# New Features
+
+## Functional Enhancements
+
+* Introduced a [`RouteOrigin`
+ interface](https://github.com/lightningnetwork/lnd/pull/10764) that
+ generalizes where routes can originate from. The pathfinder previously
+ terminated at a single concrete source vertex; `RouteOrigin` replaces this
+ with a predicate so the backward search can terminate at any vertex in a
+ caller-provided set, selecting whichever provides the cheapest path. The
+ default `singleOrigin` preserves existing behavior for all callers. This is
+ the source-end counterpart to `AdditionalEdge`, which extends the graph at
+ the destination end via route hints.
+
+* Introduced a new `AttemptStore` interface within `htlcswitch`, and expanded
+ its `kvdb` implementation, `networkResultStore`. A [new `InitAttempt` method](https://github.com/lightningnetwork/lnd/pull/10049),
+ which serves as a "durable write of intent" or "write-ahead log" to checkpoint
+ an attempt in a new `PENDING` state prior to dispatch, now provides the
+ foundational durable storage required for external tracking of the HTLC
+ attempt lifecycle. This is a preparatory step that enables the new
+ idempotent `switchrpc.SendOnion` RPC, which offers "at most once"
+ processing of htlc dispatch requests for remote clients. Care was taken to
+ avoid modifications to the existing flows for dispatching local payments,
+ preserving the existing battle-tested logic.
+
+* Added a new switchrpc RPC sub-system
+ ([#9489](https://github.com/lightningnetwork/lnd/pull/9489),
+ [#11282](https://github.com/lightningnetwork/lnd/pull/11282))
+ with `SendOnion`, `BuildOnion`, and `TrackOnion` endpoints. This allows the
+ daemon to offload path-finding, onion construction and payment life-cycle
+ management to an external entity and instead accept onion payments for direct
+ delivery to the network. The new gRPC server should be used with caution. It
+ is currently only safe to allow a *single* entity (either the local router or
+ *one* external router) to dispatch attempts via the Switch at any given time.
+ Running multiple controllers concurrently will lead to undefined behavior and
+ potential loss of funds. The compilation of the server is hidden behind the
+ non-default `switchrpc` build tag.
+
+* The `SendOnion` RPC is now fully [idempotent](https://github.com/lightningnetwork/lnd/pull/10473), providing a critical
+ reliability improvement for external payment orchestrators (such as a remote
+ `ChannelRouter`). Callers can now safely retry a `SendOnion` request after a
+ network timeout or ambiguous error without risking a duplicate payment. If a
+ request with the same `attempt_id` has already been processed, the RPC will
+ now return a `DUPLICATE_HTLC` error, serving as a definitive acknowledgment
+ that the dispatch was received. This allows clients to build more resilient
+ payment-sending logic.
+
+* The `switchrpc.TrackOnion` RPC has been
+ [overhauled](https://github.com/lightningnetwork/lnd/pull/10472) to provide a
+ more robust and type-safe error handling mechanism. The `TrackOnionResponse`
+ message now uses a top-level `oneof` to enforce a compile-time guarantee that
+ a response contains either a `preimage` (for success) or structured
+ `FailureDetails` (for a payment failure). This replaces the previous
+ string-based error reporting. Application-level payment failures are now
+ clearly separated from RPC-level failures (e.g., attempt not found), which are
+ communicated via standard gRPC status codes. This is a **breaking change** for
+ any clients of the `TrackOnion` RPC.
+
+* The `switchrpc.SendOnion` RPC has been
+ [overhauled](https://github.com/lightningnetwork/lnd/pull/10545) to provide a
+ more robust, client-friendly, and forward-compatible API. The
+ `SendOnionResponse` is now an empty message; a gRPC status of `OK` indicates
+ successful dispatch. Application-level dispatch failures carry structured
+ `SendOnionFailureDetails` in the gRPC status details, classifying each failure
+ as either `DefiniteFailure` (safe to fail the attempt) or `IndefiniteFailure`
+ (client MUST retry). This is a **breaking change** for any clients of the
+ `SendOnion` RPC.
+
+* To support scenarios where an external entity, such as a remote router,
+ manages the payment lifecycle via the Switch RPC server, the node must
+ preserve the history of HTLC attempts across restarts. This [behavior](https://github.com/lightningnetwork/lnd/pull/10178) is now
+ conditional on how the lnd binary is built. When compiled with the `switchrpc`
+ build tag, the local `routing.ChannelRouter`'s automatic cleanup of the
+ dispatcher's (Switch) attempt store on startup is disabled. This shifts the
+ responsibility of state cleanup to the external controller, which is expected
+ to use an RPC interface (e.g., switchrpc) to manage the lifecycle of attempts.
+ Tying this behavior to a build tag, rather than a runtime flag, makes the
+ binary's purpose explicit and prevents potential misconfigurations.
+
+* Added [`DisableRemoteRouter` rpc](https://github.com/lightningnetwork/lnd/pull/10178)
+ to `switchrpc` which marks the database as no longer being used by a remote
+ router. This is useful for migrating from a remote router setup back to the
+ default embedded router. The external controller should first clean its
+ results from the attempt store via `DeleteAttempts` (#10602); this RPC will
+ fail if there are any remaining attempt entries.
+
+* The `ChannelRouter` now supports a [configurable attempt reconciliation
+ hook](https://github.com/lightningnetwork/lnd/pull/10621) that runs for each
+ in-flight HTLC attempt during startup, before result collection begins. This
+ enables write-first crash recovery for deployments where the router and switch
+ run in separate processes (e.g. a remote `ChannelRouter` dispatching via
+ `switchrpc.SendOnion`). The callback lets the caller confirm dispatch status by
+ idempotently re-submitting each attempt, resolving the ambiguity that arises
+ when a crash occurs between persisting an attempt and receiving the switch's
+ acknowledgement. The default is a no-op, so existing single-process lnd
+ deployments are unaffected.
+
+* Added a new [`switchrpc.DeleteAttempts`](https://github.com/lightningnetwork/lnd/pull/10602)
+ RPC that allows an external router to clean up terminal (settled or failed)
+ attempt records from the `AttemptStore`. The RPC accepts a batch of attempt
+ IDs and returns per-ID results indicating whether each was deleted, already
+ deleted, still pending (in-flight), or not found. Deleting a terminal attempt
+ record removes the duplicate protection established by InitAttempt, allowing a
+ subsequent SendOnion call with the same attempt ID to succeed. Clients should
+ only delete attempt IDs they have fully finalized and will never reuse.
+
+# Improvements
+
+## RPC Updates
+
+* [Add `source_pub_key` to `Route` proto message](https://github.com/lightningnetwork/lnd/pull/9153)
+ so that routes can be constructed and unmarshalled from the perspective of
+ different nodes. Defaults to the node's own public key.
### htlcswitch/hop/iterator.go
@@ -719,7 +719,7 @@ func (p *OnionProcessor) ReconstructHopIterator(r io.Reader, rHash []byte,
// Attempt to process the Sphinx packet. We include the payment hash of
// the HTLC as it's authenticated within the Sphinx packet itself as
- // associated data in order to thwart attempts a replay attacks. In the
+ // associated data in order to thwart replay attacks. In the
// case of a replay, an attacker is *forced* to use the same payment
// hash twice, thereby losing their money entirely.
sphinxPacket, err := p.router.ReconstructOnionPacket(
@@ -766,6 +766,69 @@ func (r *DecodeHopIteratorResponse) Result() (Iterator, lnwire.FailCode) {
return r.HopIterator, r.FailCode
}
+// DecodeHopIterator attempts to decode a valid sphinx packet from the passed
+// io.Reader instance using the rHash as the associated data when checking the
+// relevant MACs during the decoding process.
+func (p *OnionProcessor) DecodeHopIterator(r io.Reader, rHash []byte,
+ incomingCltv uint32, incomingAmount lnwire.MilliSatoshi,
+ blindingPoint lnwire.BlindingPointRecord) (Iterator, lnwire.FailCode) {
+
+ onionPkt := &sphinx.OnionPacket{}
+ if err := onionPkt.Decode(r); err != nil {
+ switch {
+ case errors.Is(err, sphinx.ErrInvalidOnionVersion):
+ return nil, lnwire.CodeInvalidOnionVersion
+ case errors.Is(err, sphinx.ErrInvalidOnionKey):
+ return nil, lnwire.CodeInvalidOnionKey
+ default:
+ log.Errorf("unable to decode onion packet: %v", err)
+ return nil, lnwire.CodeInvalidOnionKey
+ }
+ }
+
+ // If a blinding point was provided in the update_add_htlc message,
+ // pass it through so the sphinx router can derive the correct shared
+ // secret for blinded hops.
+ var opts []sphinx.ProcessOnionOpt
+ blindingPoint.WhenSome(func(
+ b tlv.RecordT[lnwire.BlindingPointTlvType,
+ *btcec.PublicKey]) {
+
+ opts = append(opts, sphinx.WithBlindingPoint(b.Val))
+ })
+
+ // Attempt to process the Sphinx packet. We include the payment hash of
+ // the HTLC as it's authenticated within the Sphinx packet itself as
+ // associated data in order to thwart replay attacks. In the
+ // case of a replay, an attacker is *forced* to use the same payment
+ // hash twice, thereby losing their money entirely.
+ sphinxPacket, err := p.router.ProcessOnionPacket(
+ onionPkt, rHash, incomingCltv, opts...,
+ )
+ if err != nil {
+ switch {
+ case errors.Is(err, sphinx.ErrInvalidOnionVersion):
+ return nil, lnwire.CodeInvalidOnionVersion
+ case errors.Is(err, sphinx.ErrInvalidOnionHMAC):
+ return nil, lnwire.CodeInvalidOnionHmac
+ case errors.Is(err, sphinx.ErrInvalidOnionKey):
+ return nil, lnwire.CodeInvalidOnionKey
+ default:
+ log.Errorf("unable to process onion packet: %v", err)
+ return nil, lnwire.CodeInvalidOnionKey
+ }
+ }
+
+ return makeSphinxHopIterator(p.router, onionPkt, sphinxPacket,
+ BlindingKit{
+ Processor: p.router,
+ UpdateAddBlinding: blindingPoint,
+ IncomingAmount: incomingAmount,
+ IncomingCltv: incomingCltv,
+ }, rHash,
+ ), lnwire.CodeNone
+}
+
// DecodeHopIterators performs batched decoding and validation of incoming
// sphinx packets. For the same `id`, this method will return the same iterators
// and failcodes upon subsequent invocations.
### htlcswitch/hop/iterator_test.go
@@ -106,6 +106,170 @@ func TestSphinxHopIteratorForwardingInstructions(t *testing.T) {
}
}
+// TestDecodeHopIterator tests that DecodeHopIterator can successfully process
+// a real onion packet constructed by the sphinx library and return a valid hop
+// iterator with the correct forwarding information. It also tests various error
+// cases such as truncated packets and corrupted HMACs.
+func TestDecodeHopIterator(t *testing.T) {
+ t.Parallel()
+
+ // Generate a fresh private key for our onion processor (the
+ // "receiving" node).
+ receiverPrivKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ sphinxRouter := sphinx.NewRouter(
+ &sphinx.PrivKeyECDH{PrivKey: receiverPrivKey},
+ sphinx.NewNoOpReplayLog(),
+ )
+ require.NoError(t, sphinxRouter.Start())
+ defer sphinxRouter.Stop()
+
+ processor := NewOnionProcessor(sphinxRouter)
+
+ // Session key used by the "sender" to construct the onion.
+ sessionKey, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ // Build a TLV payload for the final hop with amount and CLTV.
+ var (
+ fwdAmt uint64 = 500_000
+ outgoingCltv uint32 = 144
+ incomingCltv uint32 = 200
+ incomingAmt lnwire.MilliSatoshi = 600_000
+ noBlinding lnwire.BlindingPointRecord
+ )
+ var payloadBuf bytes.Buffer
+ tlvRecords := []tlv.Record{
+ record.NewAmtToFwdRecord(&fwdAmt),
+ record.NewLockTimeRecord(&outgoingCltv),
+ }
+ tlvStream, err := tlv.NewStream(tlvRecords...)
+ require.NoError(t, err)
+ require.NoError(t, tlvStream.Encode(&payloadBuf))
+
+ // Build a one-hop payment path to the receiver.
+ var path sphinx.PaymentPath
+ path[0] = sphinx.OnionHop{
+ NodePub: *receiverPrivKey.PubKey(),
+ HopPayload: sphinx.HopPayload{
+ Type: sphinx.PayloadTLV,
+ Payload: payloadBuf.Bytes(),
+ },
+ }
+
+ // Create the onion packet.
+ rHash := [32]byte{0xaa, 0xbb, 0xcc}
+ onionPkt, err := sphinx.NewOnionPacket(
+ &path, sessionKey, rHash[:],
+ sphinx.DeterministicPacketFiller,
+ )
+ require.NoError(t, err)
+
+ // serializeOnion is a helper that encodes an onion packet to bytes.
+ serializeOnion := func(pkt *sphinx.OnionPacket) []byte {
+ var buf bytes.Buffer
+ require.NoError(t, pkt.Encode(&buf))
+ return buf.Bytes()
+ }
+
+ validOnionBytes := serializeOnion(onionPkt)
+
+ tests := []struct {
+ name string
+ onionBytes []byte
+ rHash []byte
+ expectedFail lnwire.FailCode
+ checkPayload bool
+ }{
+ {
+ name: "valid onion",
+ onionBytes: validOnionBytes,
+ rHash: rHash[:],
+ expectedFail: lnwire.CodeNone,
+ checkPayload: true,
+ },
+ {
+ name: "truncated packet",
+ onionBytes: validOnionBytes[:10],
+ rHash: rHash[:],
+ expectedFail: lnwire.CodeInvalidOnionKey,
+ },
+ {
+ name: "empty reader",
+ onionBytes: []byte{},
+ rHash: rHash[:],
+ expectedFail: lnwire.CodeInvalidOnionKey,
+ },
+ {
+ name: "corrupted HMAC",
+ onionBytes: func() []byte {
+ corrupted := make([]byte, len(validOnionBytes))
+ copy(corrupted, validOnionBytes)
+ // Flip a byte in the HMAC (last 32 bytes of
+ // the packet).
+ corrupted[len(corrupted)-1] ^= 0xff
+
+ return corrupted
+ }(),
+ rHash: rHash[:],
+ expectedFail: lnwire.CodeInvalidOnionHmac,
+ },
+ {
+ name: "wrong payment hash",
+ onionBytes: validOnionBytes,
+ rHash: bytes.Repeat([]byte{0xff}, 32),
+ expectedFail: lnwire.CodeInvalidOnionHmac,
+ },
+ {
+ name: "invalid version byte",
+ onionBytes: func() []byte {
+ corrupted := make([]byte, len(validOnionBytes))
+ copy(corrupted, validOnionBytes)
+ // Set an invalid version (first byte).
+ corrupted[0] = 0xff
+
+ return corrupted
+ }(),
+ rHash: rHash[:],
+ expectedFail: lnwire.CodeInvalidOnionVersion,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ reader := bytes.NewReader(tc.onionBytes)
+ iterator, failCode := processor.DecodeHopIterator(
+ reader, tc.rHash, incomingCltv, incomingAmt,
+ noBlinding,
+ )
+
+ require.Equal(t, tc.expectedFail, failCode)
+
+ if !tc.checkPayload {
+ return
+ }
+
+ require.NotNil(t, iterator)
+
+ payload, role, err := iterator.HopPayload()
+ require.NoError(t, err)
+ require.Equal(t, RouteRoleCleartext, role)
+
+ fwdInfo := payload.ForwardingInfo()
+ require.Equal(
+ t, lnwire.MilliSatoshi(fwdAmt),
+ fwdInfo.AmountToForward,
+ )
+ require.Equal(
+ t, outgoingCltv, fwdInfo.OutgoingCLTV,
+ )
+ })
+ }
+}
+
// TestForwardingAmountCalc tests calculation of forwarding amounts from the
// hop's forwarding parameters.
func TestForwardingAmountCalc(t *testing.T) {
### htlcswitch/hop/log.go
@@ -2,13 +2,28 @@ package hop
import (
"github.com/btcsuite/btclog/v2"
+ "github.com/lightningnetwork/lnd/build"
)
+// Subsystem defines the logging sub system name of this package.
+const Subsystem = "HOPS"
+
// log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller
// requests it.
var log btclog.Logger
+// The default amount of logging is none.
+func init() {
+ UseLogger(build.NewSubLogger(Subsystem, nil))
+}
+
+// DisableLog disables all library log output. Logging output is disabled
+// by default until UseLogger is called.
+func DisableLog() {
+ UseLogger(btclog.Disabled)
+}
+
// UseLogger uses a specified Logger to output package logging info. This
// function is called from the parent package htlcswitch logger initialization.
func UseLogger(logger btclog.Logger) {
### htlcswitch/interfaces.go
@@ -113,20 +113,18 @@ type scidAliasHandler interface {
zeroConfConfirmed() bool
}
-// ChannelUpdateHandler is an interface that provides methods that allow
-// sending lnwire.Message to the underlying link as well as querying state.
-type ChannelUpdateHandler interface {
- // HandleChannelUpdate handles the htlc requests as settle/add/fail
- // which sent to us from remote peer we have a channel with.
- //
- // NOTE: This function MUST be non-blocking (or block as little as
- // possible).
- HandleChannelUpdate(lnwire.Message)
-
+// ChannelInfoProvider provides a read-only view of a ChannelLink that exposes
+// forwarding bandwidth and eligibility information to external subsystems.
+type ChannelInfoProvider interface {
// ChanID returns the channel ID for the channel link. The channel ID
// is a more compact representation of a channel's full outpoint.
ChanID() lnwire.ChannelID
+ // ShortChanID returns the short channel ID for the channel link. The
+ // short channel ID encodes the exact location in the main chain that
+ // the original funding output can be found.
+ ShortChanID() lnwire.ShortChannelID
+
// Bandwidth returns the amount of milli-satoshis which current link
// might pass through channel link. The value returned from this method
// represents the up to date available flow through the channel. This
@@ -145,6 +143,19 @@ type ChannelUpdateHandler interface {
// htlc to the channel, taking the amount of the htlc to add as a
// parameter.
MayAddOutgoingHtlc(lnwire.MilliSatoshi) error
+}
+
+// ChannelUpdateHandler is an interface that provides methods that allow
+// sending lnwire.Message to the underlying link as well as querying state.
+type ChannelUpdateHandler interface {
+ // HandleChannelUpdate handles the htlc requests as settle/add/fail
+ // which sent to us from remote peer we have a channel with.
+ //
+ // NOTE: This function MUST be non-blocking (or block as little as
+ // possible).
+ HandleChannelUpdate(lnwire.Message)
+
+ ChannelInfoProvider
// EnableAdds sets the ChannelUpdateHandler state to allow
// UpdateAddHtlc's in the specified direction. It returns true if the
@@ -266,11 +277,6 @@ type ChannelLink interface {
// ChannelPoint returns the channel outpoint for the channel link.
ChannelPoint() wire.OutPoint
- // ShortChanID returns the short channel ID for the channel link. The
- // short channel ID encodes the exact location in the main chain that
- // the original funding output can be found.
- ShortChanID() lnwire.ShortChannelID
-
// UpdateShortChanID updates the short channel ID for a link. This may
// be required in the event that a link is created before the short
// chan ID for it is known, or a re-org occurs, and the funding
@@ -623,3 +629,83 @@ type AuxTrafficShaper interface {
// meaning that it's from a custom channel.
IsCustomHTLC(htlcRecords lnwire.CustomRecords) bool
}
+
+// AttemptStore defines the interface for initializing, managing, and tracking
+// the lifecycle of HTLC payment attempts. It supports both local and remote
+// payment lifecycle controllers.
+//
+// NOTE: This store is designed to be managed by a *single* logical dispatcher
+// (e.g., a ChannelRouter instance, or a remote payment orchestrator) at a time
+// to avoid collisions of attemptIDs and ensure an unambiguous source of truth
+// for payment state. Concurrent usage by multiple dispatchers is NOT supported.
+type AttemptStore interface {
+ // InitAttempt persists the intent to dispatch a payment attempt,
+ // creating a durable record that serves as an idempotency key. This
+ // method should be called before the HTLC is dispatched to the network.
+ //
+ // NOTE: This method provides a guarantee that only one HTLC can be
+ // initialized for a given attempt ID until the ID is explicitly cleaned
+ // from the store.
+ InitAttempt(attemptID uint64) error
+
+ // StoreResult stores the result of a given payment attempt (identified
+ // by attemptID). This will be called when a result is received from the
+ // network.
+ StoreResult(attemptID uint64, result *networkResult) error
+
+ // FailPendingAttempt transitions an initialized attempt from an
+ // initialized to a failed state and records the provided reason. This
+ // is the synchronous rollback mechanism for attempts that fail before
+ // being committed to the forwarding engine. It returns an error if the
+ // underlying storage fails.
+ FailPendingAttempt(attemptID uint64, reason *LinkError) error
+
+ // FetchPendingAttempts returns a list of all attempt IDs that are
+ // currently in the pending state.
+ //
+ // NOTE: This function is primarily used by the Switch's startup logic
+ // to identify and clean up internally orphaned payment attempts. These
+ // occur when an attempt is initialized via InitAttempt but a crash
+ // prevents its full dispatch to the network (e.g., between InitAttempt
+ // and CommitCircuits). By fetching these pending attempts, the Switch
+ // can transition their state to FAILED, preventing external callers
+ // from indefinitely hanging on GetAttemptResult for an un-dispatched
+ // attempt.
+ FetchPendingAttempts() ([]uint64, error)
+
+ // GetResult returns the network result for the specified attempt ID if
+ // it's available.
+ //
+ // NOTE: This method should return ErrAttemptResultPending for attempts
+ // that have been initialized via InitAttempt but for which a final
+ // result (settle/fail) has not yet been stored. ErrPaymentIDNotFound is
+ // returned for attempts that are unknown.
+ GetResult(attemptID uint64) (*networkResult, error)
+
+ // SubscribeResult subscribes to be notified when a result for a
+ // specific attempt ID becomes available. It returns a channel that will
+ // receive the result.
+ //
+ // NOTE: For backwards compatibility, the returned channel should only
+ // receive a value for attempts that have a final result (settle/fail).
+ // Subscribers should *not* be notified of the initial pending state
+ // created by InitAttempt.
+ SubscribeResult(attemptID uint64) (<-chan *networkResult, error)
+
+ // CleanStore removes all attempt results from the store except for
+ // those listed in the keepPids map. This allows for a "delete all
+ // except" approach to cleanup.
+ CleanStore(keepPids map[uint64]struct{}) error
+
+ // DeleteAttempts removes terminal (settled or failed) attempt results
+ // from the store. The returned map reports the outcome for each
+ // requested attempt ID.
+ DeleteAttempts(attemptIDs []uint64) (map[uint64]DeletionStatus, error)
+
+ // DisableRemoteRouter checks for attempt entries and, if none are
+ // found, deletes the remote router marker from the database. The
+ // external controller that dispatched the attempts is responsible
+ // for cleaning results from the store (e.g. via DeleteAttempts)
+ // before calling this method.
+ DisableRemoteRouter() error
+}
### htlcswitch/mock.go
@@ -502,7 +502,8 @@ func newMockIteratorDecoder() *mockIteratorDecoder {
}
func (p *mockIteratorDecoder) DecodeHopIterator(r io.Reader, rHash []byte,
- cltv uint32) (hop.Iterator, lnwire.FailCode) {
+ cltv uint32, _ lnwire.MilliSatoshi,
+ _ lnwire.BlindingPointRecord) (hop.Iterator, lnwire.FailCode) {
var b [4]byte
_, err := r.Read(b[:])
@@ -552,6 +553,7 @@ func (p *mockIteratorDecoder) DecodeHopIterators(id []byte,
for _, req := range reqs {
iterator, failcode := p.DecodeHopIterator(
req.OnionReader, req.RHash, req.IncomingCltv,
+ req.IncomingAmount, req.BlindingPoint,
)
if p.decodeFail {
@@ -1208,3 +1210,30 @@ func (h *mockHTLCNotifier) NotifyFinalHtlcEvent(key models.CircuitKey,
info channeldb.FinalHtlcInfo) {
}
+
+// mockErrorDecryptor is a mock implementation of the ErrorDecrypter interface
+// that allows tests to control the outcome of a DecryptError call.
+type mockErrorDecryptor struct {
+ // result is the ForwardingError to be returned when the mock's
+ // DecryptError method is called.
+ result *ForwardingError
+
+ // err is the error to be returned when the mock's DecryptError method
+ // is called.
+ err error
+}
+
+// DecryptError is a mock implementation of the DecryptError method. It simply
+// returns the values that are configured in the mockErrorDecryptor struct,
+// allowing tests to simulate both successful and failed decryptions.
+//
+// NOTE: This is part of the ErrorDecrypter interface.
+func (m *mockErrorDecryptor) DecryptError(reason lnwire.OpaqueReason) (
+ *ForwardingError, error) {
+
+ if m.err != nil {
+ return nil, m.err
+ }
+
+ return m.result, nil
+}
### htlcswitch/payment_result.go
@@ -4,7 +4,9 @@ import (
"bytes"
"encoding/binary"
"errors"
+ "fmt"
"io"
+ "slices"
"sync"
"github.com/lightningnetwork/lnd/channeldb"
@@ -26,6 +28,63 @@ var (
// ErrPaymentIDAlreadyExists is returned if we try to write a pending
// payment whose paymentID already exists.
ErrPaymentIDAlreadyExists = errors.New("paymentID already exists")
+
+ // ErrAttemptResultPending is returned if we try to get a result
+ // for a pending payment whose result is not yet available.
+ ErrAttemptResultPending = errors.New(
+ "attempt result not yet available",
+ )
+
+ // ErrAmbiguousAttemptInit is returned when any internal error (eg:
+ // with db read or write) occurs during an InitAttempt call that
+ // prevents a definitive outcome. This indicates that the state of the
+ // payment attempt's inititialization is unknown. Callers should retry
+ // the operation to resolve the ambiguity.
+ ErrAmbiguousAttemptInit = errors.New(
+ "ambiguous result for payment attempt registration",
+ )
+
+ // ErrAttemptEntriesExist is returned when DisableRemoteRouter is
+ // called but there are still attempt entries in the network result
+ // store that have not been cleaned up.
+ ErrAttemptEntriesExist = errors.New(
+ "attempt entries exist in store",
+ )
+
+ // externalLifecycleMarkerBucket is a top-level bucket whose
+ // existence indicates that the payment lifecycle is managed
+ // externally. It prevents a local-mode binary from cleaning the
+ // attempt store on startup, which would destroy state needed by
+ // the external manager.
+ externalLifecycleMarkerBucket = []byte("external-lifecycle-marker")
+)
+
+// DeletionStatus represents the outcome of deleting a single attempt from
+// the store.
+type DeletionStatus int
+
+const (
+ // DeletionOK indicates the attempt was successfully deleted.
+ DeletionOK DeletionStatus = iota
+
+ // DeletionPending indicates the attempt is still in-flight and cannot
+ // be deleted.
+ DeletionPending
+
+ // DeletionNotFound indicates the attempt ID was not found in the
+ // store. This may indicate a client bug (wrong ID, wrong backend).
+ DeletionNotFound
+
+ // DeletionFailed indicates that the attempt record exists but could
+ // not be processed (e.g. deserialization error). The record remains
+ // in the store.
+ DeletionFailed
+)
+
+const (
+ // pendingHtlcMsgType is a custom message type used to represent a
+ // pending HTLC in the network result store.
+ pendingHtlcMsgType lnwire.MessageType = 32768
)
// PaymentResult wraps a decoded result received from the network after a
@@ -39,6 +98,11 @@ type PaymentResult struct {
// irrevocably canceled. If the payment failed during forwarding, this
// error will be a *ForwardingError.
Error error
+
+ // EncryptedError will contain the raw bytes of an encrypted error
+ // in the event of a payment failure if the switch is instructed to
+ // defer error processing to external sub-systems.
+ EncryptedError []byte
}
// networkResult is the raw result received from the network after a payment
@@ -90,23 +154,175 @@ type networkResultStore struct {
results map[uint64][]chan *networkResult
resultsMtx sync.Mutex
- // attemptIDMtx is a multimutex used to make sure the database and
- // result subscribers map is consistent for each attempt ID in case of
- // concurrent callers.
+ // attemptIDMtx is a multimutex used to serialize operations for a
+ // given attempt ID. It ensures InitAttempt's idempotency by protecting
+ // its read-then-write sequence from concurrent calls, and it maintains
+ // consistency between the database state and result subscribers.
attemptIDMtx *multimutex.Mutex[uint64]
}
-func newNetworkResultStore(db kvdb.Backend) *networkResultStore {
+func newNetworkResultStore(db kvdb.Backend,
+ externalLifecycle bool) (*networkResultStore, error) {
+
+ // Check for a state mismatch. If the payment lifecycle is managed
+ // locally but the database has been marked for external management,
+ // we must exit to prevent data loss.
+ if !externalLifecycle {
+ var isMarkedExternal bool
+ err := db.View(func(tx kvdb.RTx) error {
+ if tx.ReadBucket(externalLifecycleMarkerBucket) != nil {
+ isMarkedExternal = true
+ }
+
+ return nil
+ }, func() {
+ isMarkedExternal = false
+ })
+ if err != nil {
+ return nil, fmt.Errorf("unable to check for "+
+ "external lifecycle marker: %w", err)
+ }
+
+ if isMarkedExternal {
+ return nil, fmt.Errorf("the htlc attempt database is " +
+ "marked for external lifecycle management " +
+ "by a switchrpc build, but this binary is " +
+ "in local management mode. Halting to " +
+ "prevent data loss. To use this database, " +
+ "restart with an lnd build that includes " +
+ "the `switchrpc` build tag")
+ }
+ }
+
+ // If the payment lifecycle is managed externally, write the marker.
+ // This is placed after the check above to ensure we don't write and
+ // then immediately fail in a misconfigured dev environment.
+ if externalLifecycle {
+ err := db.Update(func(tx kvdb.RwTx) error {
+ _, err := tx.CreateTopLevelBucket(
+ externalLifecycleMarkerBucket,
+ )
+
+ return err
+ }, func() {})
+ if err != nil {
+ return nil, fmt.Errorf("unable to write external "+
+ "lifecycle marker: %w", err)
+ }
+ }
+
return &networkResultStore{
backend: db,
results: make(map[uint64][]chan *networkResult),
attemptIDMtx: multimutex.NewMutex[uint64](),
+ }, nil
+}
+
+// InitAttempt initializes the payment attempt with the given attemptID.
+//
+// If any record (even a pending result placeholder) already exists in the
+// store, this method returns ErrPaymentIDAlreadyExists. This guarantees that
+// only one HTLC will be initialized and dispatched for a given attempt ID until
+// the ID is explicitly cleaned from attempt store.
+//
+// If any unexpected internal error occurs (such as a database read or write
+// failure), it will be wrapped in ErrAmbiguousAttemptInit. This signals
+// to the caller that the state of the registration is uncertain and that the
+// operation MUST be retried to resolve the ambiguity.
+//
+// NOTE: This is part of the AttemptStore interface. Subscribed clients do not
+// receive notice of this initialization.
+func (store *networkResultStore) InitAttempt(attemptID uint64) error {
+ // We get a mutex for this attempt ID to serialize init, store, and
+ // subscribe operations. This is needed to ensure consistency between
+ // the database state and the subscribers in case of concurrent calls.
+ store.attemptIDMtx.Lock(attemptID)
+ defer store.attemptIDMtx.Unlock(attemptID)
+
+ err := kvdb.Update(store.backend, func(tx kvdb.RwTx) error {
+ // Check if any attempt by this ID is already initialized or
+ // whether a result for the attempt exists in the store.
+ existingResult, err := fetchResult(tx, attemptID)
+ if err != nil && !errors.Is(err, ErrPaymentIDNotFound) {
+ return err
+ }
+
+ // If the result is already in-progress, return an error
+ // indicating that the attempt already exists.
+ if existingResult != nil {
+ log.Warnf("Already initialized attempt for ID=%v",
+ attemptID)
+
+ return ErrPaymentIDAlreadyExists
+ }
+
+ // Create an empty networkResult to serve as place holder until
+ // a result from the network is received.
+ //
+ // TODO(calvin): When migrating to native SQL storage, replace
+ // this custom message placeholder with a proper status enum or
+ // struct to represent the pending state of an attempt.
+ pendingMsg, err := lnwire.NewCustom(pendingHtlcMsgType, nil)
+ if err != nil {
+ // This should not happen with a static message type,
+ // but if it does, it's an internal error that prevents
+ // a definitive outcome, so we must treat it as
+ // ambiguous.
+ return err
+ }
+ inProgressResult := &networkResult{
+ msg: pendingMsg,
+ unencrypted: true,
+ isResolution: false,
+ }
+
+ var b bytes.Buffer
+ err = serializeNetworkResult(&b, inProgressResult)
+ if err != nil {
+ return err
+ }
+
+ var attemptIDBytes [8]byte
+ binary.BigEndian.PutUint64(attemptIDBytes[:], attemptID)
+
+ // Mark an attempt with this ID as having been seen by storing
+ // the pending placeholder. No network result is available yet,
+ // so we do not notify subscribers.
+ bucket, err := tx.CreateTopLevelBucket(
+ networkResultStoreBucketKey,
+ )
+ if err != nil {
+ return err
+ }
+
+ return bucket.Put(attemptIDBytes[:], b.Bytes())
+ }, func() {
+ // No need to reset existingResult here as it's scoped to the
+ // transaction.
+ })
+
+ if err != nil {
+ if errors.Is(err, ErrPaymentIDAlreadyExists) {
+ return ErrPaymentIDAlreadyExists
+ }
+
+ // If any unexpected internal error occurs (such as a database
+ // failure), it will be wrapped in ErrAmbiguousAttemptInit.
+ // This signals to the caller that the state of the attempt
+ // initialization is uncertain and that the operation MUST be
+ // retried to resolve the ambiguity.
+ return fmt.Errorf("%w: %w", ErrAmbiguousAttemptInit, err)
}
+
+ log.Debugf("Initialized attempt for local payment with attemptID=%v",
+ attemptID)
+
+ return nil
}
-// storeResult stores the networkResult for the given attemptID, and notifies
+// StoreResult stores the networkResult for the given attemptID, and notifies
// any subscribers.
-func (store *networkResultStore) storeResult(attemptID uint64,
+func (store *networkResultStore) StoreResult(attemptID uint64,
result *networkResult) error {
// We get a mutex for this attempt ID. This is needed to ensure
@@ -117,7 +333,19 @@ func (store *networkResultStore) storeResult(attemptID uint64,
log.Debugf("Storing result for attemptID=%v", attemptID)
- // Serialize the payment result.
+ if err := store.storeResult(attemptID, result); err != nil {
+ return err
+ }
+
+ store.notifySubscribers(attemptID, result)
+
+ return nil
+}
+
+// storeResult persists the given result to the database.
+func (store *networkResultStore) storeResult(attemptID uint64,
+ result *networkResult) error {
+
var b bytes.Buffer
if err := serializeNetworkResult(&b, result); err != nil {
return err
@@ -126,7 +354,7 @@ func (store *networkResultStore) storeResult(attemptID uint64,
var attemptIDBytes [8]byte
binary.BigEndian.PutUint64(attemptIDBytes[:], attemptID)
- err := kvdb.Batch(store.backend, func(tx kvdb.RwTx) error {
+ return kvdb.Batch(store.backend, func(tx kvdb.RwTx) error {
networkResults, err := tx.CreateTopLevelBucket(
networkResultStoreBucketKey,
)
@@ -136,25 +364,25 @@ func (store *networkResultStore) storeResult(attemptID uint64,
return networkResults.Put(attemptIDBytes[:], b.Bytes())
})
- if err != nil {
- return err
- }
+}
+
+// notifySubscribers notifies any subscribers of the final result for the given
+// attempt ID.
+func (store *networkResultStore) notifySubscribers(attemptID uint64,
+ result *networkResult) {
- // Now that the result is stored in the database, we can notify any
- // active subscribers.
store.resultsMtx.Lock()
for _, res := range store.results[attemptID] {
res <- result
}
+
delete(store.results, attemptID)
store.resultsMtx.Unlock()
-
- return nil
}
-// subscribeResult is used to get the HTLC attempt result for the given attempt
+// SubscribeResult is used to get the HTLC attempt result for the given attempt
// ID. It returns a channel on which the result will be delivered when ready.
-func (store *networkResultStore) subscribeResult(attemptID uint64) (
+func (store *networkResultStore) SubscribeResult(attemptID uint64) (
<-chan *networkResult, error) {
// We get a mutex for this payment ID. This is needed to ensure
@@ -194,11 +422,21 @@ func (store *networkResultStore) subscribeResult(attemptID uint64) (
return nil, err
}
- // If the result was found, we can send it on the result channel
- // imemdiately.
+ // If a result is back from the network, we can send it on the result
+ // channel immediately. If the result is still our initialized place
+ // holder, then treat it as not yet available.
if result != nil {
- resultChan <- result
- return resultChan, nil
+ if result.msg.MsgType() != pendingHtlcMsgType {
+ log.Debugf("Obtained full result for attemptID=%v",
+ attemptID)
+
+ resultChan <- result
+
+ return resultChan, nil
+ }
+
+ log.Debugf("Awaiting result (settle/fail) for attemptID=%v",
+ attemptID)
}
// Otherwise we store the result channel for when the result is
@@ -212,16 +450,32 @@ func (store *networkResultStore) subscribeResult(attemptID uint64) (
return resultChan, nil
}
-// getResult attempts to immediately fetch the result for the given pid from
-// the store. If no result is available, ErrPaymentIDNotFound is returned.
-func (store *networkResultStore) getResult(pid uint64) (
+// GetResult attempts to immediately fetch the *final* network result for the
+// given attempt ID from the store.
+//
+// NOTE: This method will return ErrAttemptResultPending for attempts
+// that have been initialized via InitAttempt but for which a final result
+// (settle/fail) has not yet been stored. ErrPaymentIDNotFound is returned
+// for attempts that are unknown.
+func (store *networkResultStore) GetResult(pid uint64) (
*networkResult, error) {
var result *networkResult
err := kvdb.View(store.backend, func(tx kvdb.RTx) error {
var err error
result, err = fetchResult(tx, pid)
- return err
+ if err != nil {
+ return err
+ }
+
+ // If the attempt is still in-flight, treat it as not yet
+ // available to preserve existing expectation for the behavior
+ // of this method.
+ if result.msg.MsgType() == pendingHtlcMsgType {
+ return ErrAttemptResultPending
+ }
+
+ return nil
}, func() {
result = nil
})
@@ -253,12 +507,12 @@ func fetchResult(tx kvdb.RTx, pid uint64) (*networkResult, error) {
return deserializeNetworkResult(r)
}
-// cleanStore removes all entries from the store, except the payment IDs given.
+// CleanStore removes all entries from the store, except the payment IDs given.
// NOTE: Since every result not listed in the keep map will be deleted, care
// should be taken to ensure no new payment attempts are being made
// concurrently while this process is ongoing, as its result might end up being
// deleted.
-func (store *networkResultStore) cleanStore(keep map[uint64]struct{}) error {
+func (store *networkResultStore) CleanStore(keep map[uint64]struct{}) error {
return kvdb.Update(store.backend, func(tx kvdb.RwTx) error {
networkResults, err := tx.CreateTopLevelBucket(
networkResultStoreBucketKey,
@@ -337,3 +591,294 @@ func (store *networkResultStore) cleanStore(keep map[uint64]struct{}) error {
return nil
}, func() {})
}
+
+// DeleteAttempts removes terminal (settled or failed) attempt results from the
+// store. Pending (in-flight) attempts are not deleted. The returned map reports
+// the outcome for each requested attempt ID.
+//
+// This is the safe, "positive space" alternative to CleanStore. Unlike
+// CleanStore which requires a complete snapshot of in-flight attempts (and is
+// therefore vulnerable to stale-snapshot race conditions in a distributed
+// system), DeleteAttempts only operates on explicitly named, finished items.
+func (store *networkResultStore) DeleteAttempts(
+ attemptIDs []uint64) (map[uint64]DeletionStatus, error) {
+
+ results := make(map[uint64]DeletionStatus, len(attemptIDs))
+
+ if len(attemptIDs) == 0 {
+ return results, nil
+ }
+
+ // Reject duplicates and sort IDs before acquiring per-ID mutexes
+ // below. This prevents deadlocks from locking the same ID twice
+ // (duplicates) or from inconsistent lock ordering across concurrent
+ // callers (unsorted).
+ seen := make(map[uint64]struct{}, len(attemptIDs))
+ for _, id := range attemptIDs {
+ if _, ok := seen[id]; ok {
+ return nil, fmt.Errorf("duplicate attempt ID %d", id)
+ }
+
+ seen[id] = struct{}{}
+ }
+ slices.Sort(attemptIDs)
+
+ // Acquire per-ID mutexes for all requested IDs. This ensures
+ // consistency with concurrent Init/Store/Subscribe operations on the
+ // same attempt IDs.
+ for _, id := range attemptIDs {
+ store.attemptIDMtx.Lock(id)
+ }
+ defer func() {
+ for _, id := range attemptIDs {
+ store.attemptIDMtx.Unlock(id)
+ }
+ }()
+
+ err := kvdb.Update(store.backend, func(tx kvdb.RwTx) error {
+ bucket, err := tx.CreateTopLevelBucket(
+ networkResultStoreBucketKey,
+ )
+ if err != nil {
+ return err
+ }
+
+ for _, id := range attemptIDs {
+ var attemptIDBytes [8]byte
+ binary.BigEndian.PutUint64(attemptIDBytes[:], id)
+
+ resultBytes := bucket.Get(attemptIDBytes[:])
+
+ // If the key doesn't exist, report NotFound.
+ if resultBytes == nil {
+ results[id] = DeletionNotFound
+
+ continue
+ }
+
+ // Deserialize to check the state.
+ r := bytes.NewReader(resultBytes)
+ result, err := deserializeNetworkResult(r)
+ if err != nil {
+ log.Warnf("Unable to deserialize result "+
+ "for attempt %d during delete: %v",
+ id, err)
+
+ results[id] = DeletionFailed
+
+ continue
+ }
+
+ // Do not delete pending (in-flight) attempts.
+ if result.msg.MsgType() == pendingHtlcMsgType {
+ results[id] = DeletionPending
+
+ continue
+ }
+
+ // Terminal result — safe to delete.
+ if err := bucket.Delete(attemptIDBytes[:]); err != nil {
+ return fmt.Errorf("failed to delete "+
+ "attempt %d: %w", id, err)
+ }
+
+ results[id] = DeletionOK
+ }
+
+ return nil
+ }, func() {
+ // Reset the results map on transaction retry.
+ results = make(map[uint64]DeletionStatus, len(attemptIDs))
+ })
+ if err != nil {
+ return nil, fmt.Errorf("DeleteAttempts failed: %w", err)
+ }
+
+ deletedCount := 0
+ for _, status := range results {
+ if status == DeletionOK {
+ deletedCount++
+ }
+ }
+
+ if deletedCount > 0 {
+ log.Infof("Deleted %d terminal attempt(s) from network "+
+ "result store", deletedCount)
+ }
+
+ return results, nil
+}
+
+// FetchPendingAttempts returns a list of all attempt IDs that are currently in
+// the pending state.
+//
+// NOTE: This function is NOT safe for concurrent access.
+func (store *networkResultStore) FetchPendingAttempts() ([]uint64, error) {
+ var pending []uint64
+ err := kvdb.View(store.backend, func(tx kvdb.RTx) error {
+ bucket := tx.ReadBucket(networkResultStoreBucketKey)
+ if bucket == nil {
+ return nil
+ }
+
+ return bucket.ForEach(func(k, v []byte) error {
+ // If the key is not 8 bytes, it's not a valid attempt
+ // ID.
+ if len(k) != 8 {
+ log.Warnf("Found invalid key of length %d in "+
+ "network result store", len(k))
+
+ return nil
+ }
+
+ // Deserialize the result to check its type.
+ r := bytes.NewReader(v)
+ result, err := deserializeNetworkResult(r)
+ if err != nil {
+ // If we can't deserialize, we'll log it and
+ // continue. The result will be removed by a
+ // call to CleanStore.
+ log.Warnf("Unable to deserialize result for "+
+ "key %x: %v", k, err)
+
+ return nil
+ }
+
+ // If the result is a pending result, add the attempt
+ // ID to our list.
+ if result.msg.MsgType() == pendingHtlcMsgType {
+ attemptID := binary.BigEndian.Uint64(k)
+ pending = append(pending, attemptID)
+ }
+
+ return nil
+ })
+ }, func() {
+ pending = nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return pending, nil
+}
+
+// FailPendingAttempt transitions an initialized attempt from a `pending` to a
+// `failed` state, recording the provided reason. This ensures that attempts
+// which fail before being committed to the forwarding engine are properly
+// finalized. This transition unblocks any subscribers that might be waiting on
+// a final outcome for an initialized but un-dispatched attempt.
+//
+// NOTE: This method is specifically for attempts that have been initialized
+// via InitAttempt but fail *before* being dispatched to the network. Normal
+// failures (e.g., from an HTLC being failed on-chain or by a peer) are
+// recorded via the StoreResult method and should not use FailPendingAttempt.
+func (store *networkResultStore) FailPendingAttempt(attemptID uint64,
+ linkErr *LinkError) error {
+
+ // We get a mutex for this attempt ID to ensure consistency between the
+ // database state and the subscribers in case of concurrent calls.
+ store.attemptIDMtx.Lock(attemptID)
+ defer store.attemptIDMtx.Unlock(attemptID)
+
+ // First, create the failure result.
+ failureResult, err := newInternalFailureResult(linkErr)
+ if err != nil {
+ return fmt.Errorf("failed to create failure message for "+
+ "attempt %d: %w", attemptID, err)
+ }
+
+ var b bytes.Buffer
+ if err := serializeNetworkResult(&b, failureResult); err != nil {
+ return fmt.Errorf("failed to serialize failure result: %w", err)
+ }
+ serializedFailureResult := b.Bytes()
+
+ var attemptIDBytes [8]byte
+ binary.BigEndian.PutUint64(attemptIDBytes[:], attemptID)
+
+ err = kvdb.Update(store.backend, func(tx kvdb.RwTx) error {
+ // Verify that the attempt exists and is in the pending
+ // state, otherwise we should not fail it.
+ existingResult, err := fetchResult(tx, attemptID)
+ if err != nil {
+ return err
+ }
+
+ if existingResult.msg.MsgType() != pendingHtlcMsgType {
+ return fmt.Errorf("attempt %d not in pending state",
+ attemptID)
+ }
+
+ // Write the failure result to the store to unblock any
+ // subscribers awaiting a final result.
+ bucket, err := tx.CreateTopLevelBucket(
+ networkResultStoreBucketKey,
+ )
+ if err != nil {
+ return err
+ }
+
+ return bucket.Put(attemptIDBytes[:], serializedFailureResult)
+ }, func() {
+ })
+
+ if err != nil {
+ return fmt.Errorf("failed to fail pending attempt %d: %w",
+ attemptID, err)
+ }
+
+ // Lastly, update any subscribers which may be waiting on the result
+ // of this attempt.
+ store.notifySubscribers(attemptID, failureResult)
+
+ return nil
+}
+
+// newInternalFailureResult creates a networkResult representing a terminal,
+// internally generated failure.
+func newInternalFailureResult(linkErr *LinkError) (*networkResult, error) {
+ // First, we need to serialize the wire message from our link error
+ // into a byte slice. This is what the downstream parsers expect.
+ var reasonBytes bytes.Buffer
+ wireMsg := linkErr.WireMessage()
+ if err := lnwire.EncodeFailure(&reasonBytes, wireMsg, 0); err != nil {
+ return nil, err
+ }
+
+ // We'll create a synthetic UpdateFailHTLC to represent this internal
+ // failure, following the pattern used by the contract resolver.
+ failMsg := &lnwire.UpdateFailHTLC{
+ Reason: lnwire.OpaqueReason(reasonBytes.Bytes()),
+ }
+
+ return &networkResult{
+ msg: failMsg,
+ // This is a local failure.
+ unencrypted: true,
+ }, nil
+}
+
+// DisableRemoteRouter checks for attempt entries in the network result store
+// and if none are found, deletes the remote router marker from the database.
+func (store *networkResultStore) DisableRemoteRouter() error {
+ return store.backend.Update(func(tx kvdb.RwTx) error {
+ // First, check if there are any attempt entries.
+ bucket := tx.ReadBucket(networkResultStoreBucketKey)
+ if bucket != nil {
+ cursor := bucket.ReadCursor()
+ k, _ := cursor.First()
+ if k != nil {
+ return ErrAttemptEntriesExist
+ }
+ }
+
+ // If the attempt store is empty, we can delete the marker.
+ err := tx.DeleteTopLevelBucket(externalLifecycleMarkerBucket)
+ if err != nil && !errors.Is(err, kvdb.ErrBucketNotFound) {
+ return err
+ }
+
+ return nil
+ }, func() {})
+}
### htlcswitch/payment_result_test.go
@@ -3,8 +3,11 @@ package htlcswitch
import (
"bytes"
"encoding/binary"
+ "fmt"
"math/rand"
"reflect"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -14,6 +17,7 @@ import (
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
+ "pgregory.net/rapid"
)
// TestNetworkResultSerialization checks that NetworkResults are properly
@@ -105,7 +109,8 @@ func TestNetworkResultStore(t *testing.T) {
db := channeldb.OpenForTesting(t, t.TempDir())
- store := newNetworkResultStore(db)
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
var results []*networkResult
for i := 0; i < numResults; i++ {
@@ -120,7 +125,7 @@ func TestNetworkResultStore(t *testing.T) {
// Subscribe to 2 of them.
var subs []<-chan *networkResult
for i := uint64(0); i < 2; i++ {
- sub, err := store.subscribeResult(i)
+ sub, err := store.SubscribeResult(i)
if err != nil {
t.Fatalf("unable to subscribe: %v", err)
}
@@ -129,7 +134,7 @@ func TestNetworkResultStore(t *testing.T) {
// Store three of them.
for i := uint64(0); i < 3; i++ {
- err := store.storeResult(i, results[i])
+ err := store.StoreResult(i, results[i])
if err != nil {
t.Fatalf("unable to store result: %v", err)
}
@@ -146,7 +151,7 @@ func TestNetworkResultStore(t *testing.T) {
// Let the third one subscribe now. THe result should be received
// immediately.
- sub, err := store.subscribeResult(2)
+ sub, err := store.SubscribeResult(2)
require.NoError(t, err, "unable to subscribe")
select {
case <-sub:
@@ -156,22 +161,22 @@ func TestNetworkResultStore(t *testing.T) {
// Try fetching the result directly for the non-stored one. This should
// fail.
- _, err = store.getResult(3)
+ _, err = store.GetResult(3)
if err != ErrPaymentIDNotFound {
t.Fatalf("expected ErrPaymentIDNotFound, got %v", err)
}
// Add the result and try again.
- err = store.storeResult(3, results[3])
+ err = store.StoreResult(3, results[3])
require.NoError(t, err, "unable to store result")
- _, err = store.getResult(3)
+ _, err = store.GetResult(3)
require.NoError(t, err, "unable to get result")
// Since we don't delete results from the store (yet), make sure we
// will get subscriptions for all of them.
for i := uint64(0); i < numResults; i++ {
- sub, err := store.subscribeResult(i)
+ sub, err := store.SubscribeResult(i)
if err != nil {
t.Fatalf("unable to subscribe: %v", err)
}
@@ -182,9 +187,108 @@ func TestNetworkResultStore(t *testing.T) {
t.Fatalf("no result received")
}
}
+
+ t.Run("InitAttempt duplicate prevention", func(t *testing.T) {
+ var id uint64 = 100
+
+ // Fetch the result directly. We expect to observe
+ // ErrPaymentIDNotFound since we've not yet initialized this
+ // payment attempt.
+ _, err = store.GetResult(id)
+ require.ErrorIs(t, err, ErrPaymentIDNotFound,
+ "expected not found error for uninitialized attempt")
+
+ // First initialization should succeed.
+ err := store.InitAttempt(id)
+ require.NoError(t, err, "unexpected InitAttempt failure")
+
+ // Now, try fetching the result directly. We expect to observe
+ // ErrAttemptResultPending since it's initialized but not
+ // yet finalized.
+ _, err = store.GetResult(id)
+ require.ErrorIs(t, err, ErrAttemptResultPending,
+ "expected result unavailable error for pending attempt")
+
+ // Subscribe for the result following the initialization. No
+ // result should be received immediately as StoreResult has not
+ // yet updated the initialized attempt into a finalized attempt.
+ sub, err := store.SubscribeResult(id)
+ require.NoError(t, err, "unable to subscribe")
+ select {
+ case <-sub:
+ t.Fatalf("unexpected non-final result notification " +
+ "received")
+ case <-time.After(1 * time.Second):
+ }
+
+ // Second initialization should fail (already initialized).
+ // Try initializing an attempt with the same ID before a full
+ // settle or fail result is back from the network (simulated by
+ // StoreResult).
+ err = store.InitAttempt(id)
+ require.ErrorIs(t, err, ErrPaymentIDAlreadyExists,
+ "expected duplicate InitAttempt to fail")
+
+ // Store a result to simulate a full settle or fail HTLC result
+ // coming back from the network.
+ netResult := &networkResult{
+ msg: &lnwire.UpdateFulfillHTLC{},
+ unencrypted: true,
+ isResolution: true,
+ }
+ err = store.StoreResult(id, netResult)
+ require.NoError(t, err, "unable to store result after init")
+
+ // Try InitAttempt again — still should fail even after a full
+ // result is back from the network.
+ err = store.InitAttempt(id)
+ require.ErrorIs(t, err, ErrPaymentIDAlreadyExists,
+ "expected InitAttempt to fail after result stored")
+
+ // Now we confirm that the subscriber is notified of the final
+ // attempt result.
+ select {
+ case <-sub:
+ case <-time.After(1 * time.Second):
+ t.Fatalf("failed to receive final (settle/fail) result")
+ }
+
+ // Verify that ID can be re-used only after explicit deletion of
+ // attempts via CleanStore or a DeleteAttempts style method.
+ err = store.CleanStore(map[uint64]struct{}{})
+ require.NoError(t, err)
+
+ // Now InitAttempt should succeed again.
+ err = store.InitAttempt(id)
+ require.NoError(t, err, "InitAttempt should succeed after "+
+ "cleanup")
+ })
+
+ t.Run("Concurrent InitAttempt", func(t *testing.T) {
+ var (
+ id uint64 = 999
+ wg sync.WaitGroup
+ success atomic.Int32
+ )
+
+ // Launch 10 concurrent routines trying to init the same ID.
+ for range 10 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if err := store.InitAttempt(id); err == nil {
+ success.Add(1)
+ }
+ }()
+ }
+ wg.Wait()
+
+ // Only exactly one call should succeed.
+ require.EqualValues(t, 1, success.Load())
+ })
}
-// TestNetworkResultStoreCleanStore tests that cleanStore prunes the store down
+// TestNetworkResultStoreCleanStore tests that CleanStore prunes the store down
// to exactly the requested attempt IDs. It opens the store via
// kvdb.GetTestBackend so that, under the postgres/sqlite build tags, the SQL
// drop-and-recreate path is exercised (TestNetworkResultStore above goes
@@ -245,7 +349,8 @@ func TestNetworkResultStoreCleanStore(t *testing.T) {
cleanup()
})
- store := newNetworkResultStore(backend)
+ store, err := newNetworkResultStore(backend, false)
+ require.NoError(t, err)
// Store a result for every attempt ID.
for i := range test.numResults {
@@ -255,16 +360,16 @@ func TestNetworkResultStoreCleanStore(t *testing.T) {
unencrypted: true,
isResolution: true,
}
- require.NoError(t, store.storeResult(i, n))
+ require.NoError(t, store.StoreResult(i, n))
}
// Prune, keeping only the IDs in the keep set.
- require.NoError(t, store.cleanStore(test.keep))
+ require.NoError(t, store.CleanStore(test.keep))
// Every kept ID must still be present; every other ID
// must have been removed.
for i := range test.numResults {
- result, err := store.getResult(i)
+ result, err := store.GetResult(i)
if _, ok := test.keep[i]; ok {
require.NoErrorf(t, err,
"kept id %d missing", i)
@@ -328,7 +433,8 @@ func BenchmarkPostgresNetworkResultStoreCleanStore(b *testing.B) {
cleanup()
})
- store := newNetworkResultStore(backend)
+ store, err := newNetworkResultStore(backend, false)
+ require.NoError(b, err)
keep := make(map[uint64]struct{}, test.numKeep)
for i := range test.numKeep {
keep[i] = struct{}{}
@@ -375,8 +481,767 @@ func BenchmarkPostgresNetworkResultStoreCleanStore(b *testing.B) {
require.NoError(b, populate())
b.StartTimer()
- require.NoError(b, store.cleanStore(keep))
+ require.NoError(b, store.CleanStore(keep))
}
})
}
}
+
+// TestNetworkResultStoreFailAndFetch tests the FailPendingAttempt and
+// FetchPendingAttempts methods of the networkResultStore.
+func TestNetworkResultStoreFailAndFetch(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ // Test FetchPendingAttempts on an empty store.
+ pending, err := store.FetchPendingAttempts()
+ require.NoError(t, err, "fetch on empty store failed")
+ require.Empty(t, pending, "expected no pending attempts on empty store")
+
+ // Initialize some attempts.
+ require.NoError(t, store.InitAttempt(1))
+ require.NoError(t, store.InitAttempt(2))
+ require.NoError(t, store.InitAttempt(3))
+
+ // Test FetchPendingAttempts with active pending attempts.
+ pending, err = store.FetchPendingAttempts()
+ require.NoError(t, err, "fetch with pending failed")
+ require.ElementsMatch(t, []uint64{1, 2, 3}, pending,
+ "unexpected pending attempts")
+
+ // Test FailPendingAttempt.
+ failReason := NewLinkError(&lnwire.FailTemporaryNodeFailure{})
+ err = store.FailPendingAttempt(2, failReason)
+ require.NoError(t, err, "FailPendingAttempt failed")
+
+ // Verify that the failed attempt is no longer pending.
+ pending, err = store.FetchPendingAttempts()
+ require.NoError(t, err, "fetch after fail failed")
+ require.ElementsMatch(t, []uint64{1, 3}, pending,
+ "failed attempt should not be pending")
+
+ // Verify that GetResult now returns the correct failure.
+ result, err := store.GetResult(2)
+ require.NoError(t, err, "GetResult for failed attempt failed")
+ require.NotNil(t, result, "result should not be nil")
+
+ failMsg, ok := result.msg.(*lnwire.UpdateFailHTLC)
+ require.True(t, ok, "expected an UpdateFailHTLC message")
+
+ // Decode the reason and check that it matches our original failure.
+ reason, err := lnwire.DecodeFailure(
+ bytes.NewReader(failMsg.Reason), 0,
+ )
+ require.NoError(t, err, "unable to decode failure reason")
+
+ _, ok = reason.(*lnwire.FailTemporaryNodeFailure)
+ require.True(t, ok, "expected temporary node failure")
+
+ // Test misuse of FailPendingAttempt.
+ t.Run("FailPendingAttempt misuse", func(t *testing.T) {
+ // Fail a non-existent attempt.
+ err := store.FailPendingAttempt(999,
+ NewLinkError(&lnwire.FailTemporaryNodeFailure{}),
+ )
+ require.Error(t, err,
+ "expected error when failing non-existent attempt")
+ require.Contains(t, err.Error(), "not found",
+ "expected not found error")
+
+ // Initialize and settle an attempt, then confirm that
+ // FailPendingAttempt cannot overwrite the successful result.
+ var id uint64 = 100
+ require.NoError(t, store.InitAttempt(id), "init attempt failed")
+ settleResult := &networkResult{
+ msg: &lnwire.UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(id, settleResult),
+ "store settle result failed")
+
+ err = store.FailPendingAttempt(id, NewLinkError(
+ &lnwire.FailTemporaryNodeFailure{}),
+ )
+ require.Error(t, err,
+ "expected error when failing settled attempt")
+
+ // Initialize and then store a HTLC failure result from the
+ // network. FailPendingAttempt should not overwrite the real
+ // failure reason.
+ var id2 uint64 = 101
+ require.NoError(t, store.InitAttempt(id2),
+ "init attempt 2 failed")
+
+ failResult := &networkResult{
+ msg: &lnwire.UpdateFailHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(id2, failResult),
+ "store fail result failed")
+
+ err = store.FailPendingAttempt(
+ id2,
+ NewLinkError(&lnwire.FailTemporaryNodeFailure{}),
+ )
+ require.Error(t, err,
+ "expected error when failing already failed attempt")
+ })
+}
+
+// TestDeleteAttempts tests the DeleteAttempts method of the
+// networkResultStore, verifying that it correctly deletes terminal attempts,
+// refuses to delete pending attempts, and reports per-ID results.
+func TestDeleteAttempts(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ // Helper to create and store a settled result.
+ storeSettled := func(t *testing.T, id uint64) {
+ t.Helper()
+ require.NoError(t, store.InitAttempt(id))
+ settleResult := &networkResult{
+ msg: &lnwire.UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(id, settleResult))
+ }
+
+ // Helper to create and store a failed result.
+ storeFailed := func(t *testing.T, id uint64) {
+ t.Helper()
+ require.NoError(t, store.InitAttempt(id))
+ failResult := &networkResult{
+ msg: &lnwire.UpdateFailHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(id, failResult))
+ }
+
+ t.Run("empty ID list", func(t *testing.T) {
+ results, err := store.DeleteAttempts(nil)
+ require.NoError(t, err)
+ require.Empty(t, results)
+
+ results, err = store.DeleteAttempts([]uint64{})
+ require.NoError(t, err)
+ require.Empty(t, results)
+ })
+
+ t.Run("delete settled attempt", func(t *testing.T) {
+ var id uint64 = 10
+ storeSettled(t, id)
+
+ // Verify it exists before deletion.
+ _, err := store.GetResult(id)
+ require.NoError(t, err)
+
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionOK, results[id])
+
+ // Verify the record is gone.
+ _, err = store.GetResult(id)
+ require.ErrorIs(t, err, ErrPaymentIDNotFound)
+ })
+
+ t.Run("delete failed attempt", func(t *testing.T) {
+ var id uint64 = 20
+ storeFailed(t, id)
+
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionOK, results[id])
+
+ // Verify the record is gone.
+ _, err = store.GetResult(id)
+ require.ErrorIs(t, err, ErrPaymentIDNotFound)
+ })
+
+ t.Run("refuse to delete pending attempt", func(t *testing.T) {
+ var id uint64 = 30
+ require.NoError(t, store.InitAttempt(id))
+
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionPending, results[id])
+
+ // Verify the record is still present.
+ _, err = store.GetResult(id)
+ require.ErrorIs(t, err, ErrAttemptResultPending)
+ })
+
+ t.Run("reject duplicate IDs", func(t *testing.T) {
+ _, err := store.DeleteAttempts([]uint64{1, 2, 1})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "duplicate attempt ID 1")
+ })
+
+ t.Run("delete unknown attempt ID", func(t *testing.T) {
+ results, err := store.DeleteAttempts([]uint64{9999})
+ require.NoError(t, err)
+ require.Equal(t, DeletionNotFound, results[uint64(9999)])
+ })
+
+ t.Run("unreadable message", func(t *testing.T) {
+ // Write corrupt bytes directly to the store for a known
+ // attempt ID.
+ var id uint64 = 35
+ var attemptIDBytes [8]byte
+ binary.BigEndian.PutUint64(attemptIDBytes[:], id)
+
+ err := kvdb.Update(db, func(tx kvdb.RwTx) error {
+ bucket, err := tx.CreateTopLevelBucket(
+ networkResultStoreBucketKey,
+ )
+ if err != nil {
+ return err
+ }
+
+ return bucket.Put(
+ attemptIDBytes[:], []byte("corrupted-attempt"),
+ )
+ }, func() {})
+ require.NoError(t, err)
+
+ // DeleteAttempts should report DeletionFailed for the
+ // unreadable entry.
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionFailed, results[id])
+ })
+
+ t.Run("mixed batch", func(t *testing.T) {
+ var (
+ settledID uint64 = 40
+ failedID uint64 = 41
+ pendingID uint64 = 42
+ unknownID uint64 = 43
+ )
+
+ storeSettled(t, settledID)
+ storeFailed(t, failedID)
+ require.NoError(t, store.InitAttempt(pendingID))
+
+ results, err := store.DeleteAttempts([]uint64{
+ settledID, failedID, pendingID, unknownID,
+ })
+ require.NoError(t, err)
+ require.Len(t, results, 4)
+
+ require.Equal(t, DeletionOK, results[settledID])
+ require.Equal(t, DeletionOK, results[failedID])
+ require.Equal(t, DeletionPending, results[pendingID])
+ require.Equal(t, DeletionNotFound, results[unknownID])
+
+ // Verify settled and failed are gone.
+ _, err = store.GetResult(settledID)
+ require.ErrorIs(t, err, ErrPaymentIDNotFound)
+ _, err = store.GetResult(failedID)
+ require.ErrorIs(t, err, ErrPaymentIDNotFound)
+
+ // Verify pending is still there.
+ _, err = store.GetResult(pendingID)
+ require.ErrorIs(t, err, ErrAttemptResultPending)
+ })
+
+ t.Run("idempotent re-delete", func(t *testing.T) {
+ var id uint64 = 50
+ storeSettled(t, id)
+
+ // First delete succeeds.
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionOK, results[id])
+
+ // Second delete reports not found.
+ results, err = store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionNotFound, results[id])
+ })
+
+ t.Run("InitAttempt succeeds after delete", func(t *testing.T) {
+ var id uint64 = 60
+ storeSettled(t, id)
+
+ // Delete the attempt.
+ results, err := store.DeleteAttempts([]uint64{id})
+ require.NoError(t, err)
+ require.Equal(t, DeletionOK, results[id])
+
+ // Re-initializing the same ID should now succeed since the
+ // record was fully removed.
+ err = store.InitAttempt(id)
+ require.NoError(t, err)
+ })
+}
+
+// TestDeleteAttemptsProperties uses property-based testing to verify
+// DeleteAttempts invariants hold across randomly generated inputs. Rather than
+// hand-picking specific scenarios (like TestDeleteAttempts above), this test
+// lets the rapid framework generate hundreds of random mixes of pending,
+// settled, failed, and non-existent attempt IDs and checks that key properties
+// always hold.
+func TestDeleteAttemptsProperties(t *testing.T) {
+ t.Parallel()
+
+ // Property 1: Pending records are never deleted. No matter what mix of
+ // IDs is requested, pending attempts must always survive.
+ t.Run("pending records always survive", func(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ // Generate a random number of records.
+ numPending := rapid.IntRange(1, 10).Draw(
+ rt, "numPending",
+ )
+ numSettled := rapid.IntRange(0, 10).Draw(
+ rt, "numSettled",
+ )
+ numFailed := rapid.IntRange(0, 10).Draw(
+ rt, "numFailed",
+ )
+
+ var nextID uint64 = 1
+ pendingIDs := make([]uint64, 0, numPending)
+ allIDs := make([]uint64, 0)
+
+ // Create pending records.
+ for range numPending {
+ id := nextID
+ nextID++
+ require.NoError(t, store.InitAttempt(id))
+ pendingIDs = append(pendingIDs, id)
+ allIDs = append(allIDs, id)
+ }
+
+ // Create settled records.
+ for range numSettled {
+ id := nextID
+ nextID++
+ require.NoError(t, store.InitAttempt(id))
+ settleResult := &networkResult{
+ msg: &lnwire.
+ UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ id, settleResult,
+ ))
+ allIDs = append(allIDs, id)
+ }
+
+ // Create failed records.
+ for range numFailed {
+ id := nextID
+ nextID++
+ require.NoError(t, store.InitAttempt(id))
+ failResult := &networkResult{
+ msg: &lnwire.UpdateFailHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ id, failResult,
+ ))
+ allIDs = append(allIDs, id)
+ }
+
+ // Add some non-existent IDs.
+ numGhost := rapid.IntRange(0, 5).Draw(rt, "numGhost")
+ for i := range numGhost {
+ allIDs = append(allIDs, nextID+uint64(100+i))
+ }
+
+ // Delete all of them.
+ results, err := store.DeleteAttempts(allIDs)
+ require.NoError(t, err)
+
+ // PROPERTY: Every pending record must report
+ // DeletionPending and still be readable in the store.
+ for _, id := range pendingIDs {
+ require.Equal(
+ t, DeletionPending, results[id],
+ "pending attempt %d was not protected",
+ id,
+ )
+
+ _, err := store.GetResult(id)
+ require.ErrorIs(
+ t, err, ErrAttemptResultPending,
+ "pending attempt %d was deleted "+
+ "from store", id,
+ )
+ }
+ })
+ })
+
+ // Property 2: Result count always equals request count. Every requested
+ // ID gets exactly one status in the response.
+ t.Run("result count equals request count", func(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ numIDs := rapid.IntRange(0, 20).Draw(rt, "numIDs")
+ ids := make([]uint64, numIDs)
+ for i := range ids {
+ ids[i] = uint64(i + 1)
+
+ // Randomly decide: store a record or leave it
+ // non-existent.
+ action := rapid.IntRange(0, 2).Draw(
+ rt, fmt.Sprintf("action_%d", i),
+ )
+
+ switch action {
+ case 0:
+ // Leave non-existent.
+ case 1:
+ // Pending.
+ require.NoError(t, store.InitAttempt(
+ ids[i],
+ ))
+ case 2:
+ // Terminal (settled).
+ require.NoError(t, store.InitAttempt(
+ ids[i],
+ ))
+ result := &networkResult{
+ msg: &lnwire.
+ UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ ids[i], result,
+ ))
+ }
+ }
+
+ results, err := store.DeleteAttempts(ids)
+ require.NoError(t, err)
+
+ // PROPERTY: Exactly one result per requested ID.
+ require.Len(t, results, numIDs)
+ for _, id := range ids {
+ _, ok := results[id]
+ require.True(
+ t, ok,
+ "missing result for ID %d", id,
+ )
+ }
+ })
+ })
+
+ // Property 3: Deletion is idempotent. Deleting the same terminal IDs
+ // twice never returns an error — the second call reports NotFound for
+ // each already-deleted record.
+ t.Run("deletion is idempotent", func(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ numTerminal := rapid.IntRange(1, 10).Draw(
+ rt, "numTerminal",
+ )
+ ids := make([]uint64, numTerminal)
+ for i := range ids {
+ ids[i] = uint64(i + 1)
+ require.NoError(t, store.InitAttempt(ids[i]))
+ result := &networkResult{
+ msg: &lnwire.
+ UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ ids[i], result,
+ ))
+ }
+
+ // First delete — all should succeed.
+ results1, err := store.DeleteAttempts(ids)
+ require.NoError(t, err)
+ for _, id := range ids {
+ require.Equal(
+ t, DeletionOK, results1[id],
+ "first delete of %d should succeed",
+ id,
+ )
+ }
+
+ // Second delete — no error, all report gone.
+ results2, err := store.DeleteAttempts(ids)
+ require.NoError(t, err)
+
+ // PROPERTY: Re-deleting never errors. Each ID reports
+ // NotFound (the record is gone).
+ for _, id := range ids {
+ require.Equal(
+ t, DeletionNotFound, results2[id],
+ "re-delete of %d returned "+
+ "unexpected status %v",
+ id, results2[id],
+ )
+ }
+ })
+ })
+
+ // Property 4: Terminal records are always removed. After a successful
+ // delete, every terminal record must be gone from the store.
+ t.Run("terminal records are removed", func(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ numTerminal := rapid.IntRange(1, 15).Draw(
+ rt, "numTerminal",
+ )
+ ids := make([]uint64, numTerminal)
+ for i := range ids {
+ ids[i] = uint64(i + 1)
+ require.NoError(t, store.InitAttempt(ids[i]))
+
+ // Randomly choose settled or failed.
+ var msg lnwire.Message
+ if rapid.Bool().Draw(rt,
+ fmt.Sprintf("settled_%d", i)) {
+
+ msg = &lnwire.UpdateFulfillHTLC{}
+ } else {
+ msg = &lnwire.UpdateFailHTLC{}
+ }
+
+ result := &networkResult{
+ msg: msg,
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ ids[i], result,
+ ))
+ }
+
+ results, err := store.DeleteAttempts(ids)
+ require.NoError(t, err)
+
+ // PROPERTY: Every terminal record reports DeletionOK
+ // and is gone from the store.
+ for _, id := range ids {
+ require.Equal(
+ t, DeletionOK, results[id],
+ "terminal attempt %d not deleted",
+ id,
+ )
+
+ _, err := store.GetResult(id)
+ require.ErrorIs(
+ t, err, ErrPaymentIDNotFound,
+ "terminal attempt %d still in "+
+ "store after delete", id,
+ )
+ }
+ })
+ })
+
+ // Property 5: Non-target IDs are unaffected. Deleting a subset of
+ // terminal IDs must not disturb any other records in the store.
+ t.Run("non-target IDs unaffected", func(t *testing.T) {
+ t.Parallel()
+
+ rapid.Check(t, func(rt *rapid.T) {
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+
+ numTarget := rapid.IntRange(1, 10).Draw(
+ rt, "numTarget",
+ )
+ numBystander := rapid.IntRange(1, 10).Draw(
+ rt, "numBystander",
+ )
+
+ var nextID uint64 = 1
+ targetIDs := make([]uint64, numTarget)
+ bystanderIDs := make([]uint64, numBystander)
+
+ // Create terminal records to delete.
+ for i := range targetIDs {
+ targetIDs[i] = nextID
+ nextID++
+ require.NoError(t, store.InitAttempt(
+ targetIDs[i],
+ ))
+ result := &networkResult{
+ msg: &lnwire.
+ UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ targetIDs[i], result,
+ ))
+ }
+
+ // Create bystander records (mix of pending and
+ // terminal) that should not be touched.
+ for i := range bystanderIDs {
+ bystanderIDs[i] = nextID
+ nextID++
+ require.NoError(t, store.InitAttempt(
+ bystanderIDs[i],
+ ))
+
+ // Randomly leave some as pending, settle
+ // others.
+ if rapid.Bool().Draw(rt,
+ fmt.Sprintf("settle_%d", i)) {
+
+ result := &networkResult{
+ msg: &lnwire.
+ UpdateFulfillHTLC{},
+ unencrypted: true,
+ }
+ require.NoError(t, store.StoreResult(
+ bystanderIDs[i], result,
+ ))
+ }
+ }
+
+ // Delete only the target IDs.
+ _, err = store.DeleteAttempts(targetIDs)
+ require.NoError(t, err)
+
+ // PROPERTY: Every bystander record is still in the
+ // store, unmodified.
+ for _, id := range bystanderIDs {
+ _, err := store.GetResult(id)
+
+ // GetResult returns nil error for terminal
+ // results and ErrAttemptResultPending for
+ // pending ones. Either is fine — the point
+ // is it's not ErrPaymentIDNotFound.
+ require.NotErrorIs(
+ t, err, ErrPaymentIDNotFound,
+ "bystander attempt %d was deleted",
+ id,
+ )
+ }
+ })
+ })
+}
+
+// TestDisableRemoteRouter tests that the DisableRemoteRouter method behaves as
+// expected.
+func TestDisableRemoteRouter(t *testing.T) {
+ t.Parallel()
+
+ checkMarker := func(t *testing.T, db kvdb.Backend) bool {
+ var marked bool
+ err := db.View(func(tx kvdb.RTx) error {
+ if tx.ReadBucket(externalLifecycleMarkerBucket) != nil {
+ marked = true
+ }
+
+ return nil
+ }, func() {
+ marked = false
+ })
+ require.NoError(t, err)
+
+ return marked
+ }
+
+ // Test case 1: In-flight payments exist.
+ t.Run("in-flight payments", func(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, true)
+ require.NoError(t, err)
+ require.True(t, checkMarker(t, db))
+
+ // Add a payment result to simulate an in-flight payment.
+ err = store.storeResult(0, &networkResult{
+ msg: &lnwire.UpdateAddHTLC{},
+ })
+ require.NoError(t, err)
+
+ // Attempt to disable the remote router.
+ err = store.DisableRemoteRouter()
+ require.ErrorIs(t, err, ErrAttemptEntriesExist)
+
+ // The marker should still exist.
+ require.True(t, checkMarker(t, db))
+ })
+
+ // Test case 2: No in-flight payments.
+ t.Run("no in-flight payments", func(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, true)
+ require.NoError(t, err)
+ require.True(t, checkMarker(t, db))
+
+ // Attempt to disable the remote router.
+ err = store.DisableRemoteRouter()
+ require.NoError(t, err)
+
+ // The marker should be gone.
+ require.False(t, checkMarker(t, db))
+ })
+
+ // Test case 3: No in-flight payments and no marker.
+ t.Run("no marker", func(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+ store, err := newNetworkResultStore(db, false)
+ require.NoError(t, err)
+ require.False(t, checkMarker(t, db))
+
+ // Attempt to disable the remote router.
+ err = store.DisableRemoteRouter()
+ require.NoError(t, err)
+
+ // The marker should still be gone.
+ require.False(t, checkMarker(t, db))
+ })
+}
+
+// TestMarkerCollision verifies that creating a network result store in local
+// mode (externalLifecycle=false) fails when the database is already marked for
+// external lifecycle management. This prevents the local router from
+// accidentally cleaning attempt data that a remote controller depends on.
+func TestMarkerCollision(t *testing.T) {
+ t.Parallel()
+
+ db := channeldb.OpenForTesting(t, t.TempDir())
+
+ // First, create a store in external mode to write the marker.
+ _, err := newNetworkResultStore(db, true)
+ require.NoError(t, err)
+
+ // Now, try to create a store in local mode on the same DB. This
+ // should fail because the DB is marked for external management.
+ _, err = newNetworkResultStore(db, false)
+ require.Error(t, err)
+ require.Contains(t, err.Error(),
+ "marked for external lifecycle management",
+ )
+}
### htlcswitch/switch.go
@@ -314,6 +314,11 @@ type Config struct {
// IsAlias returns whether or not a given SCID is an alias.
IsAlias func(scid lnwire.ShortChannelID) bool
+
+ // ExternalPaymentLifecycle indicates that the payment lifecycle is
+ // managed by an external entity, and the dispatcher's payment store
+ // should not be cleaned on startup.
+ ExternalPaymentLifecycle bool
}
// Switch is the central messaging bus for all incoming/outgoing HTLCs.
@@ -340,12 +345,12 @@ type Switch struct {
// service was initialized with.
cfg *Config
- // networkResults stores the results of payments initiated by the user.
+ // attemptStore stores the results of payments initiated by the user.
// The store is used to later look up the payments and notify the
// user of the result when they are complete. Each payment attempt
// should be given a unique integer ID when it is created, otherwise
// results might be overwritten.
- networkResults *networkResultStore
+ attemptStore AttemptStore
// circuits is storage for payment circuits which are used to
// forward the settle/fail htlc updates back to the add htlc initiator.
@@ -470,6 +475,13 @@ func New(cfg Config, currentHeight uint32) (*Switch, error) {
return nil, err
}
+ networkResultStore, err := newNetworkResultStore(
+ cfg.DB, cfg.ExternalPaymentLifecycle,
+ )
+ if err != nil {
+ return nil, err
+ }
+
s := &Switch{
bestHeight: currentHeight,
cfg: &cfg,
@@ -479,7 +491,7 @@ func New(cfg Config, currentHeight uint32) (*Switch, error) {
interfaceIndex: make(map[[33]byte]map[lnwire.ChannelID]ChannelLink),
pendingLinkIndex: make(map[lnwire.ChannelID]ChannelLink),
linkStopIndex: make(map[lnwire.ChannelID]chan struct{}),
- networkResults: newNetworkResultStore(cfg.DB),
+ attemptStore: networkResultStore,
htlcPlex: make(chan *plexPacket),
chanCloseRequests: make(chan *ChanClose),
resolutionMsgs: make(chan *resolutionMsg),
@@ -537,16 +549,21 @@ func (s *Switch) ProcessContractResolution(msg contractcourt.ResolutionMsg) erro
// HasAttemptResult reads the network result store to fetch the specified
// attempt. Returns true if the attempt result exists.
func (s *Switch) HasAttemptResult(attemptID uint64) (bool, error) {
- _, err := s.networkResults.getResult(attemptID)
+ _, err := s.attemptStore.GetResult(attemptID)
if err == nil {
return true, nil
}
- if !errors.Is(err, ErrPaymentIDNotFound) {
- return false, err
+ // If we have not heard of this attempt ID, or have dispatched the
+ // attempt but have not yet received the final (settle/fail) result,
+ // then we return a nil error.
+ if errors.Is(err, ErrPaymentIDNotFound) ||
+ errors.Is(err, ErrAttemptResultPending) {
+
+ return false, nil
}
- return false, nil
+ return false, err
}
// GetAttemptResult returns the result of the HTLC attempt with the given
@@ -574,17 +591,33 @@ func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
// is already available.
// Assumption: no one will add this attempt ID other than the caller.
if s.circuits.LookupCircuit(inKey) == nil {
- res, err := s.networkResults.getResult(attemptID)
- if err != nil {
+ res, err := s.attemptStore.GetResult(attemptID)
+ switch {
+ // We have a final result, we can send it immediately.
+ case err == nil:
+ c := make(chan *networkResult, 1)
+ c <- res
+ nChan = c
+
+ // The attempt is known, but the result is not yet available,
+ // so we fall through to subscribe.
+ case errors.Is(err, ErrAttemptResultPending):
+ log.Tracef("Attempt %d known, but result not yet "+
+ "available. Subscribing for result.", attemptID)
+
+ // If the error is anything else, we return it to the caller.
+ default:
return nil, err
}
- c := make(chan *networkResult, 1)
- c <- res
- nChan = c
- } else {
+ }
+
+ // If nChan is still nil, it means we need to subscribe. This happens
+ // if the circuit was found, or if GetResult told us the result is not
+ // yet available.
+ if nChan == nil {
// The HTLC was committed to the circuits, subscribe for a
// result.
- nChan, err = s.networkResults.subscribeResult(attemptID)
+ nChan, err = s.attemptStore.SubscribeResult(attemptID)
if err != nil {
return nil, err
}
@@ -636,7 +669,19 @@ func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
// preiodically to let the switch clean up payment results that we have
// handled.
func (s *Switch) CleanStore(keepPids map[uint64]struct{}) error {
- return s.networkResults.cleanStore(keepPids)
+ return s.attemptStore.CleanStore(keepPids)
+}
+
+// AttemptStore provides access to the Switch's underlying attempt store.
+func (s *Switch) AttemptStore() AttemptStore {
+ return s.attemptStore
+}
+
+// DisableRemoteRouter calls the underlying result store, telling it to check
+// for attempt entries and if none are found, to delete the remote router
+// marker from the database.
+func (s *Switch) DisableRemoteRouter() error {
+ return s.attemptStore.DisableRemoteRouter()
}
// SendHTLC is used by other subsystems which aren't belong to htlc switch
@@ -1063,7 +1108,7 @@ func (s *Switch) handleLocalResponse(pkt *htlcPacket) {
// Store the result to the db. This will also notify subscribers about
// the result.
- if err := s.networkResults.storeResult(attemptID, n); err != nil {
+ if err := s.attemptStore.StoreResult(attemptID, n); err != nil {
log.Errorf("Unable to store attempt result for pid=%v: %v",
attemptID, err)
return
@@ -1130,31 +1175,57 @@ func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
case *lnwire.UpdateFailHTLC:
// TODO(yy): construct deobfuscator here to avoid creating it
// in paymentLifecycle even for settled HTLCs.
- paymentErr := s.parseFailedPayment(
+ paymentResult := s.parseFailedPayment(
deobfuscator, attemptID, paymentHash, n.unencrypted,
n.isResolution, htlc,
)
- return &PaymentResult{
- Error: paymentErr,
- }, nil
+ // ElimEither allows us to safely handle both cases of the
+ // either.
+ result := fn.ElimEither(
+ paymentResult,
+ // If a decrypted error is present, we use that.
+ func(pErr error) *PaymentResult {
+ return &PaymentResult{
+ Error: pErr,
+ }
+ },
+ // If no decrypted error is present, we use the raw
+ // encrypted error.
+ func(encryptedErr []byte) *PaymentResult {
+ return &PaymentResult{
+ EncryptedError: encryptedErr,
+ }
+ },
+ )
+ return result, nil
default:
return nil, fmt.Errorf("received unknown response type: %T",
htlc)
}
}
-// parseFailedPayment determines the appropriate failure message to return to
-// a user initiated payment. The three cases handled are:
-// 1. An unencrypted failure, which should already plaintext.
-// 2. A resolution from the chain arbitrator, which possibly has no failure
-// reason attached.
-// 3. A failure from the remote party, which will need to be decrypted using
-// the payment deobfuscator.
+// parseFailedPayment determines the appropriate failure message for a failed
+// user-initiated payment. It returns a mutually exclusive pair: either a raw,
+// encrypted error blob, or a decrypted error.
+//
+// The cases handled are:
+// 1. An unencrypted failure: This occurs when the payment fails locally before
+// clearing the first link. The failure reason is already in plaintext.
+// 2. A resolution from the chain arbitrator: This occurs for on-chain
+// timeouts, which may not have a specific failure reason.
+// 3. A failure from a remote hop: This is the standard case for a multi-hop
+// payment failure.
+// - If a deobfuscator is provided, this function will attempt to decrypt
+// the failure reason.
+// - If a deobfuscator is NOT provided, the function returns the raw,
+// onion-encrypted failure blob. This blob is only fully decryptable by the
+// entity which built the onion packet.
func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
attemptID uint64, paymentHash lntypes.Hash, unencrypted,
- isResolution bool, htlc *lnwire.UpdateFailHTLC) error {
+ isResolution bool, htlc *lnwire.UpdateFailHTLC) fn.Either[error,
+ []byte] {
switch {
@@ -1179,17 +1250,17 @@ func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
linkError.FailureDetail.FailureString(),
paymentHash, attemptID, err)
- return linkError
+ return fn.NewLeft[error, []byte](linkError)
}
// If we successfully decoded the failure reason, return it.
- return NewLinkError(failureMsg)
+ return fn.NewLeft[error, []byte](NewLinkError(failureMsg))
// A payment had to be timed out on chain before it got past
// the first hop. In this case, we'll report a permanent
// channel failure as this means us, or the remote party had to
// go on chain.
- case isResolution && htlc.Reason == nil:
+ case isResolution && len(htlc.Reason) == 0:
linkError := NewDetailedLinkError(
&lnwire.FailPermanentChannelFailure{},
OutgoingFailureOnChainTimeout,
@@ -1199,11 +1270,17 @@ func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
linkError.FailureDetail.FailureString(),
paymentHash, attemptID)
- return linkError
+ return fn.NewLeft[error, []byte](linkError)
// A regular multi-hop payment error that we'll need to
// decrypt.
default:
+ // If we don't have a deobfuscator, we cannot proceed. Return
+ // the encrypted reason to the caller.
+ if deobfuscator == nil {
+ return fn.NewRight[error, []byte](htlc.Reason)
+ }
+
// We'll attempt to fully decrypt the onion encrypted
// error. If we're unable to then we'll bail early.
failure, err := deobfuscator.DecryptError(htlc.Reason)
@@ -1212,10 +1289,12 @@ func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
"(hash=%v, pid=%d): %v",
paymentHash, attemptID, err)
- return ErrUnreadableFailureMessage
+ return fn.NewLeft[error, []byte](
+ ErrUnreadableFailureMessage,
+ )
}
- return failure
+ return fn.NewLeft[error, []byte](failure)
}
}
@@ -1876,6 +1955,13 @@ func (s *Switch) Start() error {
log.Infof("HTLC Switch starting")
+ // Before starting the main event loop, we'll check for any orphaned
+ // HTLC attempts that may have been left behind by a previous crash.
+ if err := s.cleanupOrphanedAttempts(); err != nil {
+ return fmt.Errorf("failed to cleanup orphaned attempts: %w",
+ err)
+ }
+
blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
if err != nil {
return err
@@ -1963,6 +2049,88 @@ func (s *Switch) reforwardFwdResponses() error {
return s.ForwardPackets(nil, switchPackets...)
}
+// cleanupOrphanedAttempts is a helper function that is called on startup to
+// clean up any orphaned HTLC attempts. An orphaned attempt is one that has
+// been initialized in the attempt store but for which no corresponding circuit
+// exists in the circuit map. This can happen if the node crashes after
+// initializing an attempt but before committing the circuit.
+func (s *Switch) cleanupOrphanedAttempts() error {
+ pending, err := s.attemptStore.FetchPendingAttempts()
+ if err != nil {
+ return fmt.Errorf("failed to fetch pending attempts: %w", err)
+ }
+
+ if len(pending) == 0 {
+ return nil
+ }
+
+ log.Infof("Found %d pending HTLC attempts, checking for orphans",
+ len(pending))
+
+ for _, attemptID := range pending {
+ // For each pending attempt, we check if a corresponding circuit
+ // exists.
+ inKey := CircuitKey{
+ ChanID: hop.Source,
+ HtlcID: attemptID,
+ }
+ circuit := s.circuits.LookupCircuit(inKey)
+
+ // If no circuit exists, this is an orphan from a crash
+ // between InitAttempt and CommitCircuits. We'll fail it with
+ // a temporary node failure.
+ if circuit == nil {
+ log.Warnf("Found orphaned HTLC attempt with id %d "+
+ "(no circuit), failing", attemptID)
+
+ err := s.attemptStore.FailPendingAttempt(
+ attemptID,
+ NewLinkError(
+ &lnwire.FailTemporaryNodeFailure{},
+ ),
+ )
+ if err != nil {
+ log.Errorf("Unable to fail orphaned attempt "+
+ "%d: %v", attemptID, err)
+ }
+
+ continue
+ }
+
+ // If a circuit *does* exist, we must perform a second check.
+ // If the circuit is still "half-open" (it has not been
+ // assigned a keystone by the outgoing link), then it's an
+ // orphan from a crash between CommitCircuits and the handoff
+ // to the link. We must also fail this to prevent a hang.
+ //
+ // TODO(calvin): cleanup of dangling circuits for locally
+ // initated payments as described here:
+ // https://github.com/lightningnetwork/lnd/issues/10423.
+ if !circuit.HasKeystone() {
+ log.Warnf("Found orphaned HTLC attempt with id %d "+
+ "(half-open circuit), failing", attemptID)
+
+ err := s.attemptStore.FailPendingAttempt(
+ attemptID,
+ NewLinkError(
+ &lnwire.FailTemporaryNodeFailure{},
+ ),
+ )
+ if err != nil {
+ log.Errorf("Unable to fail orphaned attempt "+
+ "%d: %v", attemptID, err)
+ }
+
+ continue
+ }
+
+ // If the circuit exists and is fully open, it's a legitimate
+ // in-flight HTLC that will be resumed by the router.
+ }
+
+ return nil
+}
+
// reforwardResolutions fetches the set of resolution messages stored on-disk
// and reforwards them if their circuits are still open. If the circuits have
// been deleted, then we will delete the resolution message from the database.
@@ -2662,6 +2830,30 @@ func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
return handlers, nil
}
+// GetLinksByPubkey fetches all the links connected to a particular node
+// identified by the serialized compressed form of its public key.
+func (s *Switch) GetLinksByPubkey(hopPubkey [33]byte) ([]ChannelInfoProvider,
+ error) {
+
+ s.indexMtx.RLock()
+ defer s.indexMtx.RUnlock()
+
+ links, err := s.getLinks(hopPubkey)
+ if err != nil {
+ return nil, err
+ }
+
+ handlers := make([]ChannelInfoProvider, 0, len(links))
+
+ // Range over the returned []ChannelLink to convert them into
+ // []ChannelInfoProvider.
+ for _, link := range links {
+ handlers = append(handlers, link)
+ }
+
+ return handlers, nil
+}
+
// getLinks is function which returns the channel links of the peer by hop
// destination id.
//
### htlcswitch/switch_test.go
@@ -1,6 +1,7 @@
package htlcswitch
import (
+ "bytes"
"context"
"crypto/rand"
"crypto/sha256"
@@ -3237,7 +3238,7 @@ func TestSwitchGetAttemptResult(t *testing.T) {
isResolution: true,
}
- err = s.networkResults.storeResult(paymentID, n)
+ err = s.attemptStore.StoreResult(paymentID, n)
require.NoError(t, err, "unable to store result")
// The result should be available.
@@ -6135,3 +6136,459 @@ func TestChanCloseErrChan(t *testing.T) {
}
})
}
+
+// TestSwitchFailOrphanedAttempt demonstrates that a caller to GetAttemptResult
+// will hang if an attempt is orphaned in a state where it has been initialized
+// but not actually dispatched. We then verify that a this scenario is resolved
+// via FailPendingAttempt storing a final failed result, thereby unblocking the
+// GetAttemptResult subscriber.
+func TestSwitchFailOrphanedAttempt(t *testing.T) {
+ t.Parallel()
+
+ s, err := initSwitchWithTempDB(t, 0)
+ require.NoError(t, err)
+ require.NoError(t, s.Start())
+ t.Cleanup(func() { require.NoError(t, s.Stop()) })
+
+ // Manually initialize an attempt in the store. This simulates the "bad"
+ // state where an attempt is pending but has no corresponding circuit.
+ attemptID := uint64(1)
+ err = s.attemptStore.InitAttempt(attemptID)
+ require.NoError(t, err, "unable to initialize attempt")
+
+ // Now, call GetAttemptResult. This function returns a channel that will
+ // deliver the result.
+ resChan, err := s.GetAttemptResult(
+ attemptID, lntypes.Hash{}, nil,
+ )
+ require.NoError(t, err)
+
+ // We expect the call to hang. We'll use a timeout to verify that no
+ // result is received from the channel.
+ select {
+ case <-resChan:
+ t.Fatalf("received result unexpectedly, should have hung")
+ case <-time.After(100 * time.Millisecond):
+ // This is the expected path, the call has "hung" for 100ms.
+ }
+
+ // Now, simulate the fix by manually calling FailPendingAttempt.
+ err = s.attemptStore.FailPendingAttempt(attemptID, NewLinkError(
+ &lnwire.FailTemporaryNodeFailure{}),
+ )
+ require.NoError(t, err, "unable to fail attempt")
+
+ // The channel should now un-block and deliver the final failed
+ // result.
+ select {
+ case result := <-resChan:
+ // We expect a result with an error, indicating failure.
+ require.Error(t, result.Error, "expected a failed result")
+ case <-time.After(1 * time.Second):
+ t.Fatalf("did not receive result after manual failure")
+ }
+}
+
+// TestSwitchOrphanCleanup tests that the switch's startup procedure will
+// correctly identify and clean up any orphaned attempts. This includes both
+// simple pending orphans (from a crash after InitAttempt) and "half-open"
+// circuit orphans (from a crash after CommitCircuits).
+func TestSwitchOrphanCleanup(t *testing.T) {
+ t.Parallel()
+
+ const attemptID = uint64(1)
+
+ testCases := []struct {
+ name string
+ setupOrphan func(t *testing.T, s *Switch, cdb *channeldb.DB)
+ }{
+ {
+ name: "pre-commit orphan",
+ setupOrphan: func(t *testing.T, s *Switch,
+ _ *channeldb.DB) {
+
+ // Manually initialize an attempt to simulate
+ // the state of the database if the node crashed
+ // after InitAttempt but before CommitCircuits.
+ err := s.attemptStore.InitAttempt(attemptID)
+ require.NoError(t, err, "unable to init")
+ },
+ },
+ {
+ name: "half-open circuit orphan",
+ setupOrphan: func(t *testing.T, s *Switch,
+ _ *channeldb.DB) {
+
+ // Manually initialize an attempt and commit a
+ // circuit to simulate the state of the database
+ // if the node crashed after CommitCircuits but
+ // before the packet was handed off to the link.
+ err := s.attemptStore.InitAttempt(attemptID)
+ require.NoError(t, err, "unable to init")
+
+ htlc := &lnwire.UpdateAddHTLC{
+ PaymentHash: lntypes.Hash{0x01},
+ }
+
+ // We'll create a dummy outgoing channel ID to
+ // attach to the circuit. The existence of an
+ // outgoingChanID is what makes this a
+ // "half-open" orphan, as the switch knows it
+ // was intended to be forwarded somewhere.
+ const outgoingChanID = 123
+ packet := &htlcPacket{
+ incomingChanID: hop.Source,
+ incomingHTLCID: attemptID,
+ outgoingChanID: lnwire.
+ NewShortChanIDFromInt(
+ outgoingChanID,
+ ),
+ htlc: htlc,
+ amount: htlc.Amount,
+ }
+
+ circuit := newPaymentCircuit(
+ &htlc.PaymentHash, packet,
+ )
+ _, err = s.circuits.CommitCircuits(circuit)
+ require.NoError(t, err, "commit failed")
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ // Create a temporary database path that will persist
+ // across restarts.
+ tempPath := t.TempDir()
+
+ // First, we'll create a database and a switch
+ // instance.
+ cdb1 := channeldb.OpenForTesting(t, tempPath)
+ s1, err := initSwitchWithDB(0, cdb1)
+ require.NoError(t, err)
+ require.NoError(t, s1.Start())
+
+ // Call the specific setup function for this test case
+ // to create the desired orphan state.
+ tc.setupOrphan(t, s1, cdb1)
+
+ // We must stop the switch and close its database to
+ // ensure the state is flushed to disk at tempPath.
+ require.NoError(t, s1.Stop())
+ require.NoError(t, cdb1.Close())
+
+ // Now, we'll create a new database instance from the
+ // same path and a new switch. This simulates a node
+ // restart.
+ cdb2 := channeldb.OpenForTesting(t, tempPath)
+ t.Cleanup(func() { cdb2.Close() })
+
+ s2, err := initSwitchWithDB(0, cdb2)
+ require.NoError(t, err)
+ require.NoError(t, s2.Start())
+ t.Cleanup(func() { require.NoError(t, s2.Stop()) })
+
+ // After startup, we query the store for our orphaned
+ // attempt ID. We expect to find a final FAILED
+ // result, as the janitor should have cleaned it up.
+ result, err := s2.attemptStore.GetResult(attemptID)
+ require.NoError(t, err, "expected final result")
+ require.NotNil(t, result, "result should not be nil")
+
+ // The result should be a failure message.
+ failMsg, ok := result.msg.(*lnwire.UpdateFailHTLC)
+ require.True(t, ok, "expected fail message")
+
+ // The cleanup routine uses a generic failure reason.
+ require.True(t, result.unencrypted, "unencrypted")
+ reason, err := lnwire.DecodeFailure(
+ bytes.NewReader(failMsg.Reason), 0,
+ )
+ require.NoError(t, err, "unable to decode failure")
+
+ // We expect a FailTemporaryNodeFailure.
+ _, ok = reason.(*lnwire.FailTemporaryNodeFailure)
+ require.True(t, ok, "expected temp node failure")
+ })
+ }
+}
+
+// TestExtractResult is a unit test for the extractResult function. It verifies
+// that the function correctly processes network results under various
+// conditions.
+func TestExtractResult(t *testing.T) {
+ t.Parallel()
+
+ // Define mock data to be used across test cases.
+ preimage := lntypes.Preimage{1}
+ hash := preimage.Hash()
+ attemptID := uint64(42)
+ encryptedReason := []byte("encrypted reason")
+
+ // Create a mock deobfuscator that will successfully "decrypt" the
+ // reason.
+ decryptedFailure := NewLinkError(
+ lnwire.NewTemporaryChannelFailure(nil),
+ )
+ mockDeobfuscator := &mockErrorDecryptor{
+ result: &ForwardingError{
+ msg: decryptedFailure.WireMessage(),
+ },
+ }
+
+ // Create a mock unencrypted failure message.
+ var unencryptedReasonBytes bytes.Buffer
+ unencryptedFailure := lnwire.NewTemporaryChannelFailure(nil)
+ err := lnwire.EncodeFailure(&unencryptedReasonBytes,
+ unencryptedFailure, 0,
+ )
+ require.NoError(t, err)
+
+ //nolint:ll
+ tests := []struct {
+ name string
+ deobfuscator ErrorDecrypter
+ networkResult *networkResult
+ expectedResult *PaymentResult
+ expectedErr bool
+ }{
+ // 1. A successful payment (UpdateFulfillHTLC) correctly
+ // returns the preimage.
+ {
+ name: "success with preimage",
+ deobfuscator: nil,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFulfillHTLC{
+ PaymentPreimage: preimage,
+ },
+ },
+ expectedResult: &PaymentResult{
+ Preimage: preimage,
+ },
+ },
+ // 2. A failed payment (UpdateFailHTLC) with no deobfuscator
+ // correctly returns the opaque, encrypted error reason.
+ {
+ name: "fail with no deobfuscator",
+ deobfuscator: nil,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: encryptedReason,
+ },
+ },
+ expectedResult: &PaymentResult{
+ EncryptedError: encryptedReason,
+ },
+ },
+ // 3. A failed payment with a deobfuscator correctly decrypts
+ // and returns the underlying failure message.
+ {
+ name: "fail with deobfuscator",
+ deobfuscator: mockDeobfuscator,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: encryptedReason,
+ },
+ },
+ expectedResult: &PaymentResult{
+ Error: NewForwardingError(
+ decryptedFailure.WireMessage(), 0,
+ ),
+ },
+ },
+ // 4. An unencrypted, local failure is correctly decoded and
+ // returned.
+ {
+ name: "unencrypted local failure",
+ deobfuscator: nil,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: unencryptedReasonBytes.Bytes(),
+ },
+ unencrypted: true,
+ },
+ expectedResult: &PaymentResult{
+ Error: NewLinkError(unencryptedFailure),
+ },
+ },
+ // 5. An unencrypted, local failure is correctly decoded and
+ // returned.
+ {
+ name: "unencrypted local failure no reason",
+ deobfuscator: nil,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: []byte{},
+ },
+ unencrypted: true,
+ },
+ expectedResult: &PaymentResult{
+ Error: &LinkError{
+ msg: unencryptedFailure,
+ FailureDetail: OutgoingFailureDecodeError,
+ },
+ },
+ },
+ // 6. An on-chain resolution failure is correctly identified
+ // and returned.
+ {
+ name: "on-chain resolution failure",
+ deobfuscator: nil,
+ networkResult: &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: nil,
+ },
+ isResolution: true,
+ },
+ expectedResult: &PaymentResult{
+ Error: NewDetailedLinkError(
+ &lnwire.FailPermanentChannelFailure{},
+ OutgoingFailureOnChainTimeout,
+ ),
+ },
+ },
+ // 7. An unknown message type results in an error.
+ {
+ name: "unknown message type",
+ deobfuscator: nil,
+ networkResult: &networkResult{msg: &lnwire.UpdateAddHTLC{}},
+ expectedErr: true,
+ },
+ }
+
+ // Initialize a bare-bones switch. It's only needed for context,
+ // the functions under test have no side effects on it.
+ s, err := initSwitchWithTempDB(t, testStartingHeight)
+ require.NoError(t, err)
+ err = s.Start()
+ require.NoError(t, err)
+ defer func() {
+ err := s.Stop()
+ require.NoError(t, err)
+ }()
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ result, err := s.extractResult(
+ tt.deobfuscator, tt.networkResult,
+ attemptID, hash,
+ )
+
+ if tt.expectedErr {
+ require.Error(t, err)
+ return
+ }
+
+ require.NoError(t, err)
+ require.Equal(t, tt.expectedResult, result)
+ })
+ }
+}
+
+// TestOnChainResolutionFailure verifies that an on-chain resolution failure
+// read back from the result store is classified as a permanent on-chain
+// channel failure, rather than being misclassified as an unreadable failure.
+//
+// The result must travel through the store: the lnwire codec turns a nil
+// reason into a non-nil empty slice, and only the persisted (disk-fetch) path
+// exercises that transformation. The in-memory path is covered by
+// TestExtractResult.
+func TestOnChainResolutionFailure(t *testing.T) {
+ t.Parallel()
+
+ s, err := initSwitchWithTempDB(t, testStartingHeight)
+ require.NoError(t, err, "unable to init switch")
+ require.NoError(t, s.Start(), "unable to start switch")
+ defer func() {
+ require.NoError(t, s.Stop(), "unable to stop switch")
+ }()
+
+ // rhash is only cosmetic here: parseFailedPayment uses the payment hash
+ // solely for log lines, not for result lookup (that is keyed by attempt
+ // ID).
+ rhash := lntypes.Hash{1}
+
+ // onChainTimeout is the error the resolution branch produces for an
+ // on-chain HTLC timeout.
+ onChainTimeout := NewDetailedLinkError(
+ &lnwire.FailPermanentChannelFailure{},
+ OutgoingFailureOnChainTimeout,
+ )
+
+ tests := []struct {
+ name string
+ isResolution bool
+ reason lnwire.OpaqueReason
+ wantErr error
+ }{
+ // An on-chain resolution with a nil reason round-trips to a
+ // non-nil empty slice. This is the case the fix addresses.
+ {
+ name: "on-chain resolution, empty reason",
+ isResolution: true,
+ reason: nil,
+ wantErr: onChainTimeout,
+ },
+
+ // A resolution carrying a real reason must still decrypt, so
+ // the widened predicate cannot swallow populated reasons.
+ {
+ name: "on-chain resolution, non-empty reason",
+ isResolution: true,
+ reason: lnwire.OpaqueReason{1, 2, 3},
+ wantErr: ErrUnreadableFailureMessage,
+ },
+ }
+
+ for i, tt := range tests {
+ attemptID := uint64(i + 1)
+
+ t.Run(tt.name, func(t *testing.T) {
+ // A deobfuscator that fails to decrypt, standing in for
+ // an empty/invalid reason. If the resolution branch is
+ // wrongly skipped, this surfaces as
+ // ErrUnreadableFailureMessage.
+ deobfuscator := &mockErrorDecryptor{
+ err: ErrUnreadableFailureMessage,
+ }
+
+ // Store the result, which serializes the reason and
+ // transforms a nil reason into a non-nil empty slice on
+ // read-back.
+ storedResult := &networkResult{
+ msg: &lnwire.UpdateFailHTLC{
+ Reason: tt.reason,
+ },
+ isResolution: tt.isResolution,
+ }
+ err := s.attemptStore.StoreResult(
+ attemptID, storedResult,
+ )
+ require.NoError(t, err, "unable to store result")
+
+ // Fetch the result through the normal path and confirm
+ // it is classified as expected.
+ resultChan, err := s.GetAttemptResult(
+ attemptID, rhash, deobfuscator,
+ )
+ require.NoError(t, err, "unable to get result")
+
+ // We expect a result immediately since it is already in
+ // the store.
+ select {
+ case res := <-resultChan:
+ require.NotNil(t, res.Error,
+ "expected error for failed result")
+ require.Equal(t, tt.wantErr, res.Error)
+
+ case <-time.After(1 * time.Second):
+ t.Fatalf("result not received")
+ }
+ })
+ }
+}
### itest/list_on_test.go
@@ -859,6 +859,22 @@ var allTestCases = []*lntest.TestCase{
Name: "postgres network separation",
TestFunc: testPostgresNetworkSeparation,
},
+ {
+ Name: "send onion",
+ TestFunc: testSendOnion,
+ },
+ {
+ Name: "send onion twice",
+ TestFunc: testSendOnionTwice,
+ },
+ {
+ Name: "send onion concurrency",
+ TestFunc: testSendOnionConcurrency,
+ },
+ {
+ Name: "track onion",
+ TestFunc: testTrackOnion,
+ },
}
// appendPrefixed is used to add a prefix to each test name in the subtests
### itest/lnd_sendonion_test.go
@@ -0,0 +1,469 @@
+package itest
+
+import (
+ "sync"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcutil/v2"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/switchrpc"
+ "github.com/lightningnetwork/lnd/lntest"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// testSendOnion tests the basic success case for the SendOnion RPC. It
+// constructs a multi-hop route from Alice -> Bob -> Carol -> Dave, builds an
+// onion packet for this route, and then asserts that Alice can successfully
+// dispatch the payment using the SendOnion RPC. The test concludes by using
+// TrackOnion to wait for and verify the payment's success preimage.
+func testSendOnion(ht *lntest.HarnessTest) {
+ // Create a four-node context consisting of Alice, Bob, Carol, and
+ // Dave with the following topology:
+ // Alice -> Bob -> Carol -> Dave
+ const chanAmt = btcutil.Amount(100000)
+ const numNodes = 4
+ nodeCfgs := make([][]string, numNodes)
+ chanPoints, nodes := ht.CreateSimpleNetwork(
+ nodeCfgs, lntest.OpenChannelParams{Amt: chanAmt},
+ )
+ alice, bob, carol, dave := nodes[0], nodes[1], nodes[2], nodes[3]
+ defer ht.CloseChannel(alice, chanPoints[0])
+ defer ht.CloseChannel(bob, chanPoints[1])
+ defer ht.CloseChannel(carol, chanPoints[2])
+
+ // Make sure Alice knows about all channels.
+ aliceBobChan := ht.AssertChannelInGraph(alice, chanPoints[0])
+
+ const (
+ numPayments = 1
+ paymentAmt = 10000
+ )
+
+ // Request an invoice from Dave so he is expecting payment.
+ _, rHashes, invoices := ht.CreatePayReqs(dave, paymentAmt, numPayments)
+ var preimage lntypes.Preimage
+ copy(preimage[:], invoices[0].RPreimage)
+
+ // Query for routes to pay from Alice to Dave.
+ routesReq := &lnrpc.QueryRoutesRequest{
+ PubKey: dave.PubKeyStr,
+ Amt: paymentAmt,
+ }
+ routes := alice.RPC.QueryRoutes(routesReq)
+ route := routes.Routes[0]
+ finalHop := route.Hops[len(route.Hops)-1]
+ finalHop.MppRecord = &lnrpc.MPPRecord{
+ PaymentAddr: invoices[0].PaymentAddr,
+ TotalAmtMsat: int64(lnwire.NewMSatFromSatoshis(paymentAmt)),
+ }
+
+ // Construct an onion for the route from Alice to Dave.
+ paymentHash := rHashes[0]
+ onionReq := &switchrpc.BuildOnionRequest{
+ Route: route,
+ PaymentHash: paymentHash,
+ }
+ onionResp := alice.RPC.BuildOnion(onionReq)
+
+ // Dispatch a payment via the SendOnion RPC.
+ sendReq := &switchrpc.SendOnionRequest{
+ FirstHopChanId: aliceBobChan.ChannelId,
+ Amount: route.TotalAmtMsat,
+ Timelock: route.TotalTimeLock,
+ PaymentHash: paymentHash,
+ OnionBlob: onionResp.OnionBlob,
+ AttemptId: 1,
+ }
+
+ err := alice.RPC.SendOnion(sendReq)
+ require.NoError(ht, err, "expected successful onion send")
+
+ // Query for the result of the payment via onion and confirm that it
+ // succeeded.
+ trackReq := &switchrpc.TrackOnionRequest{
+ AttemptId: 1,
+ PaymentHash: paymentHash,
+ SessionKey: onionResp.SessionKey,
+ HopPubkeys: onionResp.HopPubkeys,
+ }
+ trackResp := alice.RPC.TrackOnion(trackReq)
+ require.Equal(ht, invoices[0].RPreimage, trackResp.GetPreimage())
+
+ // The invoice should show as settled for Dave.
+ ht.AssertInvoiceSettled(dave, invoices[0].PaymentAddr)
+}
+
+// testSendOnionTwice tests that the switch correctly rejects a duplicate
+// payment attempt for an HTLC that is already in-flight. It sends an onion,
+// then immediately sends the exact same onion with the same attempt ID. The
+// test asserts that the second attempt is rejected with a DUPLICATE_HTLC
+// error. It also verifies that sending again after the original HTLC has
+// settled is also rejected.
+func testSendOnionTwice(ht *lntest.HarnessTest) {
+ // Create a four-node context consisting of Alice, Bob, Carol, and
+ // Dave with the following topology:
+ // Alice -> Bob -> Carol -> Dave
+ const chanAmt = btcutil.Amount(100000)
+ const numNodes = 4
+ nodeCfgs := make([][]string, numNodes)
+ chanPoints, nodes := ht.CreateSimpleNetwork(
+ nodeCfgs, lntest.OpenChannelParams{Amt: chanAmt},
+ )
+ alice, bob, carol, dave := nodes[0], nodes[1], nodes[2], nodes[3]
+ defer ht.CloseChannel(alice, chanPoints[0])
+ defer ht.CloseChannel(bob, chanPoints[1])
+ defer ht.CloseChannel(carol, chanPoints[2])
+
+ const paymentAmt = 10000
+
+ // Create a preimage, that will be held by Dave.
+ var preimage lntypes.Preimage
+ copy(preimage[:], ht.Random32Bytes())
+ payHash := preimage.Hash()
+
+ // Add a hodl invoice at Dave's end.
+ invoiceReq := &invoicesrpc.AddHoldInvoiceRequest{
+ Value: int64(paymentAmt),
+ CltvExpiry: finalCltvDelta,
+ Hash: payHash[:],
+ }
+ invoice := dave.RPC.AddHoldInvoice(invoiceReq)
+
+ // Query for routes to Dave.
+ routesReq := &lnrpc.QueryRoutesRequest{
+ PubKey: dave.PubKeyStr,
+ Amt: paymentAmt,
+ }
+ routes := alice.RPC.QueryRoutes(routesReq)
+ route := routes.Routes[0]
+ finalHop := route.Hops[len(route.Hops)-1]
+ finalHop.MppRecord = &lnrpc.MPPRecord{
+ PaymentAddr: invoice.PaymentAddr,
+ TotalAmtMsat: int64(lnwire.NewMSatFromSatoshis(paymentAmt)),
+ }
+
+ // Build the onion.
+ onionReq := &switchrpc.BuildOnionRequest{
+ Route: route,
+ PaymentHash: payHash[:],
+ }
+ onionResp := alice.RPC.BuildOnion(onionReq)
+
+ // Send the onion for the first time.
+ sendReq := &switchrpc.SendOnionRequest{
+ FirstHopPubkey: bob.PubKey[:],
+ Amount: route.TotalAmtMsat,
+ Timelock: route.TotalTimeLock,
+ PaymentHash: payHash[:],
+ OnionBlob: onionResp.OnionBlob,
+ AttemptId: 1,
+ }
+ err := alice.RPC.SendOnion(sendReq)
+ require.NoError(ht, err, "expected successful onion send")
+
+ // Assert that the HTLC reaches Dave.
+ invoiceStream := dave.RPC.SubscribeSingleInvoice(payHash[:])
+ ht.AssertInvoiceState(invoiceStream, lnrpc.Invoice_ACCEPTED)
+
+ // While the first onion is still in-flight, we'll send the same onion
+ // again with the same attempt ID. This should error as our Switch will
+ // detect duplicate ADDs for *in-flight* HTLCs.
+ err = alice.RPC.SendOnion(sendReq)
+ require.Error(ht, err, "expected failure on onion send")
+
+ // Check that we get the expected gRPC error.
+ s, ok := status.FromError(err)
+ require.True(ht, ok, "expected gRPC status error")
+ require.Equal(ht, codes.AlreadyExists, s.Code(),
+ "unexpected error code")
+
+ // Dave settles the invoice.
+ dave.RPC.SettleInvoice(preimage[:])
+
+ // Ensure Dave's invoice is settled.
+ ht.AssertInvoiceSettled(dave, invoice.PaymentAddr)
+
+ // Track the payment and verify success.
+ trackReq := &switchrpc.TrackOnionRequest{
+ AttemptId: 1,
+ PaymentHash: payHash[:],
+ SessionKey: onionResp.SessionKey,
+ HopPubkeys: onionResp.HopPubkeys,
+ }
+ trackResp := alice.RPC.TrackOnion(trackReq)
+ require.Equal(ht, preimage[:], trackResp.GetPreimage())
+
+ // Now that the original HTLC attempt has settled, we'll send the same
+ // onion again with the same attempt ID. Confirm that this is also
+ // prevented.
+ err = alice.RPC.SendOnion(sendReq)
+ require.Error(ht, err, "expected failure on onion send")
+
+ // Check that we get the expected gRPC error.
+ s, ok = status.FromError(err)
+ require.True(ht, ok, "expected gRPC status error")
+ require.Equal(ht, codes.AlreadyExists, s.Code(),
+ "unexpected error code")
+
+ // Now that we've confirmed that duplicate sends are rejected for
+ // settled attempts, delete the attempt record from the store.
+ deleteReq := &switchrpc.DeleteAttemptsRequest{
+ AttemptIds: []uint64{1},
+ }
+ deleteResp := alice.RPC.DeleteAttempts(deleteReq)
+ require.Len(ht, deleteResp.Results, 1)
+ require.Equal(ht,
+ switchrpc.AttemptDeletionStatus_DELETION_OK,
+ deleteResp.Results[0].Status,
+ )
+
+ // Deleting the same attempt again should return NOT_FOUND,
+ // confirming the record was fully removed.
+ deleteResp = alice.RPC.DeleteAttempts(deleteReq)
+ require.Len(ht, deleteResp.Results, 1)
+ require.Equal(ht,
+ switchrpc.AttemptDeletionStatus_DELETION_NOT_FOUND,
+ deleteResp.Results[0].Status,
+ )
+}
+
+// testSendOnionConcurrency simulates a client that crashes and attempts to
+// retry a payment with the same attempt ID concurrently. This test provides a
+// strong guarantee that the SendOnion RPC is idempotent and correctly prevents
+// duplicate payment attempts from succeeding.
+func testSendOnionConcurrency(ht *lntest.HarnessTest) {
+ // Create a two-node context consisting of Alice and Bob.
+ const chanAmt = btcutil.Amount(100000)
+ const numNodes = 2
+ nodeCfgs := make([][]string, numNodes)
+ chanPoints, nodes := ht.CreateSimpleNetwork(
+ nodeCfgs, lntest.OpenChannelParams{Amt: chanAmt},
+ )
+ alice, bob := nodes[0], nodes[1]
+
+ // Make sure Alice knows about the channel.
+ aliceBobChan := ht.AssertChannelInGraph(alice, chanPoints[0])
+
+ const paymentAmt = 10000
+
+ // Request an invoice from Bob so he is expecting payment.
+ _, rHashes, invoices := ht.CreatePayReqs(bob, paymentAmt, 1)
+ paymentHash := rHashes[0]
+
+ // Query for a route to pay from Alice to Bob.
+ routesReq := &lnrpc.QueryRoutesRequest{
+ PubKey: bob.PubKeyStr,
+ Amt: paymentAmt,
+ }
+ routes := alice.RPC.QueryRoutes(routesReq)
+ route := routes.Routes[0]
+ finalHop := route.Hops[len(route.Hops)-1]
+ finalHop.MppRecord = &lnrpc.MPPRecord{
+ PaymentAddr: invoices[0].PaymentAddr,
+ TotalAmtMsat: int64(lnwire.NewMSatFromSatoshis(paymentAmt)),
+ }
+
+ // Construct the onion for the route.
+ onionReq := &switchrpc.BuildOnionRequest{
+ Route: route,
+ PaymentHash: paymentHash,
+ }
+ onionResp := alice.RPC.BuildOnion(onionReq)
+
+ // Create the SendOnion request that all goroutines will use.
+ // The AttemptId MUST be the same for all calls.
+ sendReq := &switchrpc.SendOnionRequest{
+ FirstHopChanId: aliceBobChan.ChannelId,
+ Amount: route.TotalAmtMsat,
+ Timelock: route.TotalTimeLock,
+ PaymentHash: paymentHash,
+ OnionBlob: onionResp.OnionBlob,
+ AttemptId: 42,
+ }
+
+ const numConcurrentRequests = 50
+ var wg sync.WaitGroup
+ wg.Add(numConcurrentRequests)
+
+ // Use channels to collect the results from each goroutine.
+ resultsChan := make(chan error, numConcurrentRequests)
+
+ // Launch all requests concurrently to simulate a retry storm.
+ for range numConcurrentRequests {
+ go func() {
+ defer wg.Done()
+
+ err := alice.RPC.SendOnion(sendReq)
+ resultsChan <- err
+ }()
+ }
+
+ wg.Wait()
+ close(resultsChan)
+
+ // We expect exactly one successful dispatch and the rest to be
+ // rejected as duplicates.
+ successCount := 0
+ duplicateCount := 0
+
+ for err := range resultsChan {
+ // A nil error indicates a successful dispatch.
+ if err == nil {
+ successCount++
+ continue
+ }
+
+ // For non-nil errors, we should receive a gRPC status error.
+ s, ok := status.FromError(err)
+
+ // If it's not a gRPC status error, it's an unexpected
+ // condition.
+ require.Truef(ht, ok, "unexpected error from SendOnion: %v, "+
+ "code: %v", s.Err().Error(), s.Code())
+
+ // Check if the error code indicates a duplicate acknowledgment.
+ if s.Code() == codes.AlreadyExists {
+ duplicateCount++
+ } else {
+ ht.Fatalf("unexpected error from SendOnion: %v, "+
+ "code: %v", s.Err().Error(), s.Code())
+ }
+ }
+
+ // Confirm that only a single dispatch succeeds.
+ require.Equal(ht, 1, successCount, "expected exactly one success")
+ require.Equal(ht, numConcurrentRequests-1, duplicateCount,
+ "expected all other attempts to be duplicates")
+
+ // The invoice should eventually show as settled for Bob.
+ ht.AssertInvoiceSettled(bob, invoices[0].PaymentAddr)
+}
+
+// testTrackOnion exercises the SwitchRPC server's TrackOnion endpoint,
+// confirming that we can receive the result of an onion dispatch and decrypt
+// the error result. We also verify that the error received from the dispatched
+// onion is the same whether error is processed by the server or the rpc client.
+func testTrackOnion(ht *lntest.HarnessTest) {
+ // Create a four-node context consisting of Alice, Bob, Carol, and
+ // Dave with the following topology:
+ // Alice -> Bob -> Carol -> Dave
+ const chanAmt = btcutil.Amount(100000)
+ const numNodes = 4
+ nodeCfgs := make([][]string, numNodes)
+ chanPoints, nodes := ht.CreateSimpleNetwork(
+ nodeCfgs, lntest.OpenChannelParams{Amt: chanAmt},
+ )
+ alice, bob, carol, dave := nodes[0], nodes[1], nodes[2], nodes[3]
+ defer ht.CloseChannel(alice, chanPoints[0])
+ defer ht.CloseChannel(bob, chanPoints[1])
+ defer ht.CloseChannel(carol, chanPoints[2])
+
+ const paymentAmt = 10000
+
+ // Query for routes to pay from Alice to Dave.
+ routesReq := &lnrpc.QueryRoutesRequest{
+ PubKey: dave.PubKeyStr,
+ Amt: paymentAmt,
+ }
+ routes := alice.RPC.QueryRoutes(routesReq)
+ route := routes.Routes[0]
+
+ finalHop := route.Hops[len(route.Hops)-1]
+ finalHop.MppRecord = &lnrpc.MPPRecord{
+ PaymentAddr: ht.Random32Bytes(),
+ TotalAmtMsat: int64(lnwire.NewMSatFromSatoshis(paymentAmt)),
+ }
+
+ // Build the onion to use for our payment.
+ paymentHash := ht.Random32Bytes()
+ onionReq := &switchrpc.BuildOnionRequest{
+ Route: route,
+ PaymentHash: paymentHash,
+ }
+ onionResp := alice.RPC.BuildOnion(onionReq)
+
+ // Dispatch a payment via SendOnion.
+ firstHop := bob.PubKey
+ sendReq := &switchrpc.SendOnionRequest{
+ FirstHopPubkey: firstHop[:],
+ Amount: route.TotalAmtMsat,
+ Timelock: route.TotalTimeLock,
+ PaymentHash: paymentHash,
+ OnionBlob: onionResp.OnionBlob,
+ AttemptId: 1,
+ }
+
+ err := alice.RPC.SendOnion(sendReq)
+ require.NoError(ht, err, "expected successful onion send")
+
+ // Track the payment providing all necessary information to delegate
+ // error decryption to the server. We expect this to fail as Dave is not
+ // expecting payment.
+ trackReq := &switchrpc.TrackOnionRequest{
+ AttemptId: 1,
+ PaymentHash: paymentHash,
+ SessionKey: onionResp.SessionKey,
+ HopPubkeys: onionResp.HopPubkeys,
+ }
+ trackResp := alice.RPC.TrackOnion(trackReq)
+ serverFailure := trackResp.GetFailureDetails()
+ require.NotNil(ht, serverFailure, "expected onion tracking error")
+
+ serverFwdFailure := serverFailure.GetForwardingFailure()
+ require.NotNil(ht, serverFwdFailure, "expected forwarding failure")
+
+ // Now we'll track the same payment attempt, but we'll specify that
+ // we want to handle the error decryption ourselves client side.
+ trackReq = &switchrpc.TrackOnionRequest{
+ AttemptId: 1,
+ PaymentHash: paymentHash,
+ }
+ trackResp = alice.RPC.TrackOnion(trackReq)
+ clientFailure := trackResp.GetFailureDetails()
+ require.NotNil(ht, clientFailure, "expected client tracking error")
+
+ encryptedErrorBytes := clientFailure.GetEncryptedErrorData()
+ require.NotNil(ht, encryptedErrorBytes, "expected encrypted error")
+
+ // Decrypt and inspect the error from the TrackOnion RPC response.
+ sessionKey, _ := btcec.PrivKeyFromBytes(onionResp.SessionKey)
+ var pubKeys []*btcec.PublicKey
+ for _, keyBytes := range onionResp.HopPubkeys {
+ pubKey, err := btcec.ParsePubKey(keyBytes)
+ require.NoError(ht, err, "Failed to parse public key")
+ pubKeys = append(pubKeys, pubKey)
+ }
+
+ // Construct the circuit to create the error decryptor
+ circuit := &sphinx.Circuit{
+ SessionKey: sessionKey,
+ PaymentPath: pubKeys,
+ }
+ errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
+ OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
+ }
+
+ // Simulate an RPC client decrypting the onion error.
+ encryptedError := lnwire.OpaqueReason(encryptedErrorBytes)
+ clientFwdErr, err := errorDecryptor.DecryptError(encryptedError)
+ require.NoError(ht, err, "unable to decrypt error")
+
+ // Finally, assert that the structured forwarding failure is the same
+ // whether it was decrypted on the server or on the client.
+ serverFwdErr, err := switchrpc.UnmarshallForwardingError(
+ serverFwdFailure,
+ )
+ require.NoError(ht, err, "unable to decode server forwarding failure")
+
+ require.Equal(ht, serverFwdFailure.FailureSourceIndex,
+ uint32(clientFwdErr.FailureSourceIdx), "source index mismatch")
+ require.Equal(ht, serverFwdErr.WireMessage(),
+ clientFwdErr.WireMessage(), "wire message mismatch")
+}
### lnrpc/lightning.pb.go
@@ -10680,8 +10680,12 @@ type Route struct {
//
//Custom channel data that might be populated in custom channels.
CustomChannelData []byte `protobuf:"bytes,8,opt,name=custom_channel_data,json=customChannelData,proto3" json:"custom_channel_data,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ //
+ //The source node from whose perspective the route was built. Defaults to
+ //the node's own public key.
+ SourcePubKey string `protobuf:"bytes,9,opt,name=source_pub_key,json=sourcePubKey,proto3" json:"source_pub_key,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *Route) Reset() {
@@ -10772,6 +10776,13 @@ func (x *Route) GetCustomChannelData() []byte {
return nil
}
+func (x *Route) GetSourcePubKey() string {
+ if x != nil {
+ return x.SourcePubKey
+ }
+ return ""
+}
+
type NodeInfoRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The 33-byte hex-encoded compressed public of the target node
@@ -19717,7 +19728,7 @@ const file_lightning_proto_rawDesc = "" +
"root_share\x18\x01 \x01(\fR\trootShare\x12\x15\n" +
"\x06set_id\x18\x02 \x01(\fR\x05setId\x12\x1f\n" +
"\vchild_index\x18\x03 \x01(\rR\n" +
- "childIndex\"\xc4\x02\n" +
+ "childIndex\"\xea\x02\n" +
"\x05Route\x12&\n" +
"\x0ftotal_time_lock\x18\x01 \x01(\rR\rtotalTimeLock\x12!\n" +
"\n" +
@@ -19728,7 +19739,8 @@ const file_lightning_proto_rawDesc = "" +
"\x0ftotal_fees_msat\x18\x05 \x01(\x03R\rtotalFeesMsat\x12$\n" +
"\x0etotal_amt_msat\x18\x06 \x01(\x03R\ftotalAmtMsat\x121\n" +
"\x15first_hop_amount_msat\x18\a \x01(\x03R\x12firstHopAmountMsat\x12.\n" +
- "\x13custom_channel_data\x18\b \x01(\fR\x11customChannelData\"\x83\x01\n" +
+ "\x13custom_channel_data\x18\b \x01(\fR\x11customChannelData\x12$\n" +
+ "\x0esource_pub_key\x18\t \x01(\tR\fsourcePubKey\"\x83\x01\n" +
"\x0fNodeInfoRequest\x12\x17\n" +
"\apub_key\x18\x01 \x01(\tR\x06pubKey\x12)\n" +
"\x10include_channels\x18\x02 \x01(\bR\x0fincludeChannels\x12,\n" +
### lnrpc/lightning.proto
@@ -3458,6 +3458,12 @@ message Route {
Custom channel data that might be populated in custom channels.
*/
bytes custom_channel_data = 8;
+
+ /*
+ The source node from whose perspective the route was built. Defaults to
+ the node's own public key.
+ */
+ string source_pub_key = 9;
}
message NodeInfoRequest {
### lnrpc/lightning.swagger.json
@@ -7451,6 +7451,10 @@
"type": "string",
"format": "byte",
"description": "Custom channel data that might be populated in custom channels."
+ },
+ "source_pub_key": {
+ "type": "string",
+ "description": "The source node from whose perspective the route was built. Defaults to\nthe node's own public key."
}
},
"description": "A path through the channel graph which runs over one or more channels in\nsuccession. This struct carries all the information required to craft the\nSphinx onion packet, and send the payment along the first hop in the path. A\nroute is only selected as valid if all the channels have sufficient capacity to\ncarry the initial payment amount after fees are accounted for."
### lnrpc/routerrpc/router.pb.go
@@ -2086,8 +2086,12 @@ type BuildRouteRequest struct {
//the custom range >= 65536. When using REST, the values must be encoded as
//base64.
FirstHopCustomRecords map[uint64][]byte `protobuf:"bytes,6,rep,name=first_hop_custom_records,json=firstHopCustomRecords,proto3" json:"first_hop_custom_records,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ //
+ //An optional source node public key from whose perspective the route is to be
+ //built. If empty, the router's identity key is assumed.
+ SourcePubKey []byte `protobuf:"bytes,7,opt,name=source_pub_key,json=sourcePubKey,proto3" json:"source_pub_key,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *BuildRouteRequest) Reset() {
@@ -2162,6 +2166,13 @@ func (x *BuildRouteRequest) GetFirstHopCustomRecords() map[uint64][]byte {
return nil
}
+func (x *BuildRouteRequest) GetSourcePubKey() []byte {
+ if x != nil {
+ return x.SourcePubKey
+ }
+ return nil
+}
+
type BuildRouteResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
//
@@ -3835,15 +3846,16 @@ const file_routerrpc_router_proto_rawDesc = "" +
"\bamt_msat\x18\x03 \x01(\x03R\aamtMsat\"k\n" +
"\x18QueryProbabilityResponse\x12 \n" +
"\vprobability\x18\x01 \x01(\x01R\vprobability\x12-\n" +
- "\ahistory\x18\x02 \x01(\v2\x13.routerrpc.PairDataR\ahistory\"\x86\x03\n" +
+ "\ahistory\x18\x02 \x01(\v2\x13.routerrpc.PairDataR\ahistory\"\xac\x03\n" +
"\x11BuildRouteRequest\x12\x19\n" +
"\bamt_msat\x18\x01 \x01(\x03R\aamtMsat\x12(\n" +
"\x10final_cltv_delta\x18\x02 \x01(\x05R\x0efinalCltvDelta\x12,\n" +
"\x10outgoing_chan_id\x18\x03 \x01(\x04B\x020\x01R\x0eoutgoingChanId\x12\x1f\n" +
"\vhop_pubkeys\x18\x04 \x03(\fR\n" +
"hopPubkeys\x12!\n" +
"\fpayment_addr\x18\x05 \x01(\fR\vpaymentAddr\x12p\n" +
- "\x18first_hop_custom_records\x18\x06 \x03(\v27.routerrpc.BuildRouteRequest.FirstHopCustomRecordsEntryR\x15firstHopCustomRecords\x1aH\n" +
+ "\x18first_hop_custom_records\x18\x06 \x03(\v27.routerrpc.BuildRouteRequest.FirstHopCustomRecordsEntryR\x15firstHopCustomRecords\x12$\n" +
+ "\x0esource_pub_key\x18\a \x01(\fR\fsourcePubKey\x1aH\n" +
"\x1aFirstHopCustomRecordsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\x04R\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"8\n" +
### lnrpc/routerrpc/router.proto
@@ -741,6 +741,12 @@ message BuildRouteRequest {
base64.
*/
map<uint64, bytes> first_hop_custom_records = 6;
+
+ /*
+ An optional source node public key from whose perspective the route is to be
+ built. If empty, the router's identity key is assumed.
+ */
+ bytes source_pub_key = 7;
}
message BuildRouteResponse {
### lnrpc/routerrpc/router.swagger.json
@@ -1244,6 +1244,10 @@
"type": "string",
"format": "byte",
"description": "Custom channel data that might be populated in custom channels."
+ },
+ "source_pub_key": {
+ "type": "string",
+ "description": "The source node from whose perspective the route was built. Defaults to\nthe node's own public key."
}
},
"description": "A path through the channel graph which runs over one or more channels in\nsuccession. This struct carries all the information required to craft the\nSphinx onion packet, and send the payment along the first hop in the path. A\nroute is only selected as valid if all the channels have sufficient capacity to\ncarry the initial payment amount after fees are accounted for."
@@ -1377,6 +1381,11 @@
"format": "byte"
},
"description": "An optional field that can be used to pass an arbitrary set of TLV records\nto the first hop peer of this payment. This can be used to pass application\nspecific data during the payment attempt. Record types are required to be in\nthe custom range \u003e= 65536. When using REST, the values must be encoded as\nbase64."
+ },
+ "source_pub_key": {
+ "type": "string",
+ "format": "byte",
+ "description": "An optional source node public key from whose perspective the route is to be\nbuilt. If empty, the router's identity key is assumed."
}
}
},
### lnrpc/routerrpc/router_backend.go
@@ -634,6 +634,7 @@ func (r *RouterBackend) MarshallRoute(route *route.Route) (*lnrpc.Route, error)
TotalAmtMsat: int64(route.TotalAmount),
Hops: make([]*lnrpc.Hop, len(route.Hops)),
FirstHopAmountMsat: int64(route.FirstHopAmount.Val.Int()),
+ SourcePubKey: route.SourcePubKey.String(),
}
// Encode the route's custom channel data (if available).
@@ -835,7 +836,25 @@ func (r *RouterBackend) UnmarshallHop(rpcHop *lnrpc.Hop,
func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
*route.Route, error) {
- prevNodePubKey := r.SelfNode
+ var err error
+
+ // Most routes we construct are from our node's perspective.
+ sourcePubKey := r.SelfNode
+
+ // Optionally override with supplied public key.
+ if rpcroute.SourcePubKey != "" {
+ sourcePubKey, err = route.NewVertexFromStr(
+ rpcroute.SourcePubKey,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("invalid source pubkey: %w", err)
+ }
+ }
+
+ // The previous node starts as the source of the route. This is
+ // used for implicit hop pubkey resolution when hops only specify
+ // a channel ID.
+ prevNodePubKey := sourcePubKey
hops := make([]*route.Hop, len(rpcroute.Hops))
for i, hop := range rpcroute.Hops {
@@ -856,14 +875,13 @@ func (r *RouterBackend) UnmarshallRoute(rpcroute *lnrpc.Route) (
}
hops[i] = routeHop
-
prevNodePubKey = routeHop.PubKeyBytes
}
route, err := route.NewRouteFromHops(
lnwire.MilliSatoshi(rpcroute.TotalAmtMsat),
rpcroute.TotalTimeLock,
- r.SelfNode,
+ sourcePubKey,
hops,
)
if err != nil {
### lnrpc/routerrpc/router_backend_test.go
@@ -3,6 +3,7 @@ package routerrpc
import (
"bytes"
"encoding/hex"
+ "fmt"
"testing"
"time"
@@ -1038,3 +1039,133 @@ func TestMarshallRouteChanCapacity(t *testing.T) {
t, hop1Forward.ToSatoshis(), rpcRoute.Hops[1].ChanCapacity,
)
}
+
+// TestUnmarshallRouteSourcePubKey tests that UnmarshallRoute correctly handles
+// the source_pub_key field on the Route proto message.
+func TestUnmarshallRouteSourcePubKey(t *testing.T) {
+ t.Parallel()
+
+ // Define test vertices. The self node is the default source used
+ // when source_pub_key is empty.
+ selfNode := route.Vertex{1, 2, 3}
+ overrideSource := route.Vertex{4, 5, 6}
+
+ // A hop target that will appear in the route.
+ hopTarget := route.Vertex{7, 8, 9}
+
+ backend := &RouterBackend{
+ SelfNode: selfNode,
+ FetchChannelEndpoints: func(chanID uint64) (route.Vertex,
+ route.Vertex, error) {
+
+ // For channel 12345, return overrideSource and
+ // hopTarget as the two endpoints.
+ if chanID == 12345 {
+ return overrideSource, hopTarget, nil
+ }
+
+ return route.Vertex{}, route.Vertex{},
+ fmt.Errorf("unknown channel: %d", chanID)
+ },
+ }
+
+ t.Run("default source when empty", func(t *testing.T) {
+ t.Parallel()
+
+ rpcRoute := &lnrpc.Route{
+ TotalAmtMsat: 1000,
+ TotalTimeLock: 144,
+ Hops: []*lnrpc.Hop{
+ {
+ PubKey: hex.EncodeToString(
+ hopTarget[:],
+ ),
+ ChanId: 12345,
+ AmtToForward: 1000,
+ },
+ },
+ }
+
+ r, err := backend.UnmarshallRoute(rpcRoute)
+ require.NoError(t, err)
+
+ // With no SourcePubKey set, the route source should
+ // default to the backend's SelfNode.
+ require.Equal(t, selfNode, r.SourcePubKey)
+ })
+
+ t.Run("override source with valid pubkey", func(t *testing.T) {
+ t.Parallel()
+
+ rpcRoute := &lnrpc.Route{
+ TotalAmtMsat: 1000,
+ TotalTimeLock: 144,
+ SourcePubKey: hex.EncodeToString(overrideSource[:]),
+ Hops: []*lnrpc.Hop{
+ {
+ PubKey: hex.EncodeToString(
+ hopTarget[:],
+ ),
+ ChanId: 12345,
+ AmtToForward: 1000,
+ },
+ },
+ }
+
+ r, err := backend.UnmarshallRoute(rpcRoute)
+ require.NoError(t, err)
+
+ // The route source should match the override.
+ require.Equal(t, overrideSource, r.SourcePubKey)
+ })
+
+ t.Run("invalid source pubkey", func(t *testing.T) {
+ t.Parallel()
+
+ rpcRoute := &lnrpc.Route{
+ TotalAmtMsat: 1000,
+ TotalTimeLock: 144,
+ SourcePubKey: "not-a-valid-hex-pubkey",
+ Hops: []*lnrpc.Hop{
+ {
+ PubKey: hex.EncodeToString(
+ hopTarget[:],
+ ),
+ ChanId: 12345,
+ AmtToForward: 1000,
+ },
+ },
+ }
+
+ _, err := backend.UnmarshallRoute(rpcRoute)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "invalid source pubkey")
+ })
+
+ t.Run("implicit hop resolution with src override ", func(t *testing.T) {
+ t.Parallel()
+
+ // Hop omits PubKey, forcing implicit resolution via
+ // FetchChannelEndpoints using the override source.
+ rpcRoute := &lnrpc.Route{
+ TotalAmtMsat: 1000,
+ TotalTimeLock: 144,
+ SourcePubKey: hex.EncodeToString(overrideSource[:]),
+ Hops: []*lnrpc.Hop{
+ {
+ ChanId: 12345,
+ AmtToForward: 1000,
+ },
+ },
+ }
+
+ r, err := backend.UnmarshallRoute(rpcRoute)
+ require.NoError(t, err)
+
+ // The hop should resolve to hopTarget (the other
+ // endpoint of channel 12345, since the source is
+ // overrideSource).
+ require.Equal(t, hopTarget, r.Hops[0].PubKeyBytes)
+ require.Equal(t, overrideSource, r.SourcePubKey)
+ })
+}
### lnrpc/routerrpc/router_server.go
@@ -1731,10 +1731,20 @@ func (s *Server) BuildRoute(_ context.Context,
firstHopBlob = fn.Some(firstHopData)
}
+ // Default to the router's own identity as the route source.
+ sourceNode := s.cfg.RouterBackend.SelfNode
+ if len(req.SourcePubKey) != 0 {
+ src, err := route.NewVertexFromBytes(req.SourcePubKey)
+ if err != nil {
+ return nil, err
+ }
+ sourceNode = src
+ }
+
// Build the route and return it to the caller.
route, err := s.cfg.Router.BuildRoute(
- amt, hops, outgoingChan, req.FinalCltvDelta, payAddr,
- firstHopBlob,
+ sourceNode, amt, hops, outgoingChan, req.FinalCltvDelta,
+ payAddr, firstHopBlob,
)
if err != nil {
return nil, err
### lnrpc/switchrpc/config_active.go
@@ -0,0 +1,81 @@
+//go:build switchrpc
+// +build switchrpc
+
+package switchrpc
+
+import (
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/macaroons"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/routing/route"
+)
+
+// Config is the primary configuration struct for the switch RPC subserver.
+// It contains all the items required for the server to carry out its duties.
+// The fields with struct tags are meant to be parsed as normal configuration
+// options, while if able to be populated, the latter fields MUST also be
+// specified.
+//
+//nolint:ll
+type Config struct {
+ // SwitchMacPath is the path for the switch macaroon. If unspecified
+ // then we assume that the macaroon will be found under the network
+ // directory, named DefaultSwitchMacFilename.
+ SwitchMacPath string `long:"switchmacaroonpath" description:"Path to the switch macaroon"`
+
+ // NetworkDir is the main network directory wherein the switch rpc
+ // server will find the macaroon named DefaultSwitchMacFilename.
+ NetworkDir string
+
+ // MacService is the main macaroon service that we'll use to handle
+ // authentication for the Switch rpc server.
+ MacService *macaroons.Service
+
+ // HtlcDispatcher provides the means by which payment attempts can
+ // be dispatched.
+ HtlcDispatcher routing.PaymentAttemptDispatcher
+
+ // AttemptStore provides the means by which the RPC server can manage
+ // the state of an HTLC attempt, including initializing and failing it.
+ AttemptStore htlcswitch.AttemptStore
+
+ // ChannelInfoAccessor defines an interface for accessing channel
+ // information necessary for dispatching payment attempts, specifically
+ // methods for fetching links by public key.
+ ChannelInfoAccessor ChannelInfoAccessor
+
+ // RouteProcessor provides the capability to convert from external (rpc)
+ // to internal representation of a payment route.
+ RouteProcessor RouteProcessor
+
+ // RemoteRouterController provides the ability to manage the remote router
+ // state.
+ RemoteRouterController RemoteRouterController
+}
+
+// RemoteRouterController defines a restricted interface for managing the remote
+// router state.
+type RemoteRouterController interface {
+ // DisableRemoteRouter disables the remote router, allowing a migration
+ // back to the embedded router.
+ DisableRemoteRouter() error
+}
+
+// ChannelInfoAccessor defines a restricted, read-only view into the switch's
+// active channel links. The information provided can be of use when dispatching
+// payments.
+type ChannelInfoAccessor interface {
+ // GetLinksByPubkey provides a read-only view of all active channel
+ // links associated with a given node public key.
+ GetLinksByPubkey(pubKey [33]byte) ([]htlcswitch.ChannelInfoProvider,
+ error)
+}
+
+// RouteProcessor provides the ability to convert a route from the external rpc
+// representation to our internal format for use when constructing onions.
+type RouteProcessor interface {
+ // UnmarshallRoute unmarshalls an rpc route. For hops that don't specify
+ // a pubkey, the channel graph is queried.
+ UnmarshallRoute(rpcroute *lnrpc.Route) (*route.Route, error)
+}
### lnrpc/switchrpc/config_default.go
@@ -0,0 +1,7 @@
+//go:build !switchrpc
+// +build !switchrpc
+
+package switchrpc
+
+// Config is empty for non-switchrpc builds.
+type Config struct{}
### lnrpc/switchrpc/driver.go
@@ -0,0 +1,82 @@
+//go:build switchrpc
+// +build switchrpc
+
+package switchrpc
+
+import (
+ "fmt"
+
+ "github.com/lightningnetwork/lnd/lnrpc"
+)
+
+// createNewSubServer is a helper method that will create the new router sub
+// server given the main config dispatcher method. If we're unable to find the
+// config that is meant for us in the config dispatcher, then we'll exit with
+// an error.
+func createNewSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
+ *Server, lnrpc.MacaroonPerms, error) {
+
+ // We'll attempt to look up the config that we expect, according to our
+ // subServerName name. If we can't find this, then we'll exit with an
+ // error, as we're unable to properly initialize ourselves without this
+ // config.
+ subServerConf, ok := configRegistry.FetchConfig(subServerName)
+ if !ok {
+ return nil, nil, fmt.Errorf("unable to find config for "+
+ "subserver type %s", subServerName)
+ }
+
+ // Now that we've found an object mapping to our service name, we'll
+ // ensure that it's the type we need.
+ config, ok := subServerConf.(*Config)
+ if !ok {
+ return nil, nil, fmt.Errorf("wrong type of config for "+
+ "subserver %s, expected %T got %T", subServerName,
+ &Config{}, subServerConf)
+ }
+
+ // Before we try to make the new switch service instance, we'll perform
+ // some sanity checks on the arguments to ensure that they're usable.
+ if config.HtlcDispatcher == nil {
+ return nil, nil, fmt.Errorf("dispatcher must be set to " +
+ "create SwitchRPC")
+ }
+ if config.ChannelInfoAccessor == nil {
+ return nil, nil, fmt.Errorf("channel info access must be " +
+ "provided to create SwitchRPC")
+ }
+ if config.RouteProcessor == nil {
+ return nil, nil, fmt.Errorf("route processor must be set to " +
+ "create SwitchRPC")
+ }
+ if config.AttemptStore == nil {
+ return nil, nil, fmt.Errorf("attempt store must be set to " +
+ "create SwitchRPC")
+ }
+
+ if config.RemoteRouterController == nil {
+ return nil, nil, fmt.Errorf("remote router controller must " +
+ "be set to create SwitchRPC")
+ }
+
+ return New(config)
+}
+
+// init registers this package's gRPC subserver so that lnd's main RPC server
+// knows it exists and can later invoke RegisterWithRootServer to attach the
+// service handlers.
+func init() {
+ subServer := &lnrpc.SubServerDriver{
+ SubServerName: subServerName,
+ NewGrpcHandler: func() lnrpc.GrpcHandler {
+ return &ServerShell{}
+ },
+ }
+
+ // If the build tag is active, then we'll register ourselves as a
+ // sub-RPC server within the global lnrpc package namespace.
+ if err := lnrpc.RegisterSubServer(subServer); err != nil {
+ panic(fmt.Sprintf("failed to register sub server driver "+
+ "'%s': %v", subServerName, err))
+ }
+}
### lnrpc/switchrpc/log.go
@@ -0,0 +1,32 @@
+package switchrpc
+
+import (
+ "github.com/btcsuite/btclog/v2"
+ "github.com/lightningnetwork/lnd/build"
+)
+
+// log is a logger that is initialized with no output filters. This
+// means the package will not perform any logging by default until the caller
+// requests it.
+var log btclog.Logger
+
+// Subsystem defines the logging code for this subsystem.
+const Subsystem = "SRPC"
+
+// The default amount of logging is none.
+func init() {
+ UseLogger(build.NewSubLogger(Subsystem, nil))
+}
+
+// DisableLog disables all library log output. Logging output is disabled
+// by default until UseLogger is called.
+func DisableLog() {
+ UseLogger(btclog.Disabled)
+}
+
+// UseLogger uses a specified Logger to output package logging info.
+// This should be used in preference to SetLogWriter if the caller is also
+// using btclog.
+func UseLogger(logger btclog.Logger) {
+ log = logger
+}
### lnrpc/switchrpc/mock.go
@@ -0,0 +1,120 @@
+//go:build switchrpc
+// +build switchrpc
+
+package switchrpc
+
+import (
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/routing/route"
+)
+
+// mockPayer is a mock implementation of the htlcswitch.Payer interface.
+type mockPayer struct {
+ sendErr error
+ getResultResult *htlcswitch.PaymentResult
+ getResultErr error
+ resultChan chan *htlcswitch.PaymentResult
+}
+
+// SendHTLC is a mock implementation of the SendHTLC method.
+func (m *mockPayer) SendHTLC(firstHop lnwire.ShortChannelID,
+ attemptID uint64, htlc *lnwire.UpdateAddHTLC) error {
+
+ return m.sendErr
+}
+
+// GetAttemptResult is a mock implementation of the GetAttemptResult method.
+func (m *mockPayer) GetAttemptResult(attemptID uint64,
+ paymentHash lntypes.Hash,
+ errorDecryptor htlcswitch.ErrorDecrypter) (
+ <-chan *htlcswitch.PaymentResult, error) {
+
+ if m.getResultErr != nil {
+ return nil, m.getResultErr
+ }
+
+ // If a result channel is provided, use it.
+ if m.resultChan != nil {
+ return m.resultChan, nil
+ }
+
+ resultChan := make(chan *htlcswitch.PaymentResult, 1)
+ if m.getResultResult != nil {
+ resultChan <- m.getResultResult
+ }
+
+ return resultChan, nil
+}
+
+// GetAttemptResult is a mock implementation of the GetAttemptResult method.
+func (m *mockPayer) HasAttemptResult(attemptID uint64) (bool, error) {
+ return true, nil
+}
+
+// CleanStore is a mock implementation of the CleanStore method.
+func (m *mockPayer) CleanStore(keepPids map[uint64]struct{}) error {
+ return nil
+}
+
+// mockRouteProcessor is a mock implementation of the routing.RouteProcessor
+// interface.
+type mockRouteProcessor struct {
+ unmarshallErr error
+ unmarshallRoute *route.Route
+}
+
+// UnmarshallRoute is a mock implementation of the UnmarshallRoute method.
+func (m *mockRouteProcessor) UnmarshallRoute(route *lnrpc.Route) (
+ *route.Route, error) {
+
+ return m.unmarshallRoute, m.unmarshallErr
+}
+
+// mockAttemptStore is a mock implementation of the AttemptStore interface.
+type mockAttemptStore struct {
+ htlcswitch.AttemptStore
+ initErr error
+ failErr error
+ deleteErr error
+ deleteResp map[uint64]htlcswitch.DeletionStatus
+}
+
+// InitAttempt returns the mocked initErr.
+func (m *mockAttemptStore) InitAttempt(attemptID uint64) error {
+ return m.initErr
+}
+
+// FailPendingAttempt returns the mocked failErr.
+func (m *mockAttemptStore) FailPendingAttempt(attemptID uint64,
+ reason *htlcswitch.LinkError) error {
+
+ return m.failErr
+}
+
+// DeleteAttempts returns the mocked deleteResp and deleteErr.
+func (m *mockAttemptStore) DeleteAttempts(
+ attemptIDs []uint64) (map[uint64]htlcswitch.DeletionStatus, error) {
+
+ if m.deleteErr != nil {
+ return nil, m.deleteErr
+ }
+
+ return m.deleteResp, nil
+}
+
+// mockErrorDecrypter is a mock implementation of htlcswitch.ErrorDecrypter.
+type mockErrorDecrypter struct {
+ decryptedErr htlcswitch.ForwardingError
+ receivedData lnwire.OpaqueReason
+}
+
+func (m *mockErrorDecrypter) DecryptError(
+ err lnwire.OpaqueReason) (*htlcswitch.ForwardingError, error) {
+
+ m.receivedData = err
+
+ return &m.decryptedErr, nil
+}
### lnrpc/switchrpc/switch.pb.go
@@ -0,0 +1,1592 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.11
+// protoc v3.21.12
+// source: switchrpc/switch.proto
+
+package switchrpc
+
+import (
+ lnrpc "github.com/lightningnetwork/lnd/lnrpc"
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+// IndefiniteFailureCode provides the specific reason for an indefinite failure.
+type IndefiniteFailureCode int32
+
+const (
+ // The reason is unknown. This is the default and is used for failures
+ // where the server could not classify the error, such as bare gRPC
+ // transport errors observed by the client.
+ IndefiniteFailureCode_REASON_UNKNOWN IndefiniteFailureCode = 0
+ // The server is in the process of shutting down.
+ IndefiniteFailureCode_SWITCH_EXITING IndefiniteFailureCode = 1
+ // A critical failure occurred when the server attempted to write the
+ // idempotency record for the payment attempt.
+ IndefiniteFailureCode_HTLC_INIT_FAILED IndefiniteFailureCode = 2
+)
+
+// Enum value maps for IndefiniteFailureCode.
+var (
+ IndefiniteFailureCode_name = map[int32]string{
+ 0: "REASON_UNKNOWN",
+ 1: "SWITCH_EXITING",
+ 2: "HTLC_INIT_FAILED",
+ }
+ IndefiniteFailureCode_value = map[string]int32{
+ "REASON_UNKNOWN": 0,
+ "SWITCH_EXITING": 1,
+ "HTLC_INIT_FAILED": 2,
+ }
+)
+
+func (x IndefiniteFailureCode) Enum() *IndefiniteFailureCode {
+ p := new(IndefiniteFailureCode)
+ *p = x
+ return p
+}
+
+func (x IndefiniteFailureCode) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (IndefiniteFailureCode) Descriptor() protoreflect.EnumDescriptor {
+ return file_switchrpc_switch_proto_enumTypes[0].Descriptor()
+}
+
+func (IndefiniteFailureCode) Type() protoreflect.EnumType {
+ return &file_switchrpc_switch_proto_enumTypes[0]
+}
+
+func (x IndefiniteFailureCode) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use IndefiniteFailureCode.Descriptor instead.
+func (IndefiniteFailureCode) EnumDescriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{0}
+}
+
+// AttemptDeletionStatus describes the outcome of a single attempt deletion.
+type AttemptDeletionStatus int32
+
+const (
+ // The attempt result was successfully deleted from the store.
+ AttemptDeletionStatus_DELETION_OK AttemptDeletionStatus = 0
+ // The attempt is still in-flight (pending) and cannot be safely deleted.
+ AttemptDeletionStatus_DELETION_PENDING AttemptDeletionStatus = 1
+ // The attempt ID was not found in the store. This may indicate a client
+ // bug (wrong ID, wrong backend) since the server has no record of this
+ // attempt ever existing.
+ AttemptDeletionStatus_DELETION_NOT_FOUND AttemptDeletionStatus = 2
+ // The attempt record exists but could not be processed (e.g.
+ // deserialization error). The record remains in the store.
+ AttemptDeletionStatus_DELETION_FAILED AttemptDeletionStatus = 3
+)
+
+// Enum value maps for AttemptDeletionStatus.
+var (
+ AttemptDeletionStatus_name = map[int32]string{
+ 0: "DELETION_OK",
+ 1: "DELETION_PENDING",
+ 2: "DELETION_NOT_FOUND",
+ 3: "DELETION_FAILED",
+ }
+ AttemptDeletionStatus_value = map[string]int32{
+ "DELETION_OK": 0,
+ "DELETION_PENDING": 1,
+ "DELETION_NOT_FOUND": 2,
+ "DELETION_FAILED": 3,
+ }
+)
+
+func (x AttemptDeletionStatus) Enum() *AttemptDeletionStatus {
+ p := new(AttemptDeletionStatus)
+ *p = x
+ return p
+}
+
+func (x AttemptDeletionStatus) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (AttemptDeletionStatus) Descriptor() protoreflect.EnumDescriptor {
+ return file_switchrpc_switch_proto_enumTypes[1].Descriptor()
+}
+
+func (AttemptDeletionStatus) Type() protoreflect.EnumType {
+ return &file_switchrpc_switch_proto_enumTypes[1]
+}
+
+func (x AttemptDeletionStatus) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use AttemptDeletionStatus.Descriptor instead.
+func (AttemptDeletionStatus) EnumDescriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{1}
+}
+
+type SendOnionRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The raw onion packet to be sent across the network.
+ OnionBlob []byte `protobuf:"bytes,1,opt,name=onion_blob,json=onionBlob,proto3" json:"onion_blob,omitempty"`
+ // The attempt ID uniquely identifying this payment attempt. The caller can
+ // expect to track results for the payment via this attempt ID.
+ AttemptId uint64 `protobuf:"varint,2,opt,name=attempt_id,json=attemptId,proto3" json:"attempt_id,omitempty"`
+ // The first hop's public key where the onion will be sent.
+ // The first hop must be specified either by channel ID or public key.
+ FirstHopPubkey []byte `protobuf:"bytes,3,opt,name=first_hop_pubkey,json=firstHopPubkey,proto3" json:"first_hop_pubkey,omitempty"`
+ // The channel id of the channel that must be taken to the first hop.
+ // The first hop must be specified either by channel ID or public key.
+ FirstHopChanId uint64 `protobuf:"varint,4,opt,name=first_hop_chan_id,json=firstHopChanId,proto3" json:"first_hop_chan_id,omitempty"`
+ // The total amount in millisatoshis required to complete a payment over
+ // this route. This value includes the cumulative fees at each hop. The HTLC
+ // extended to the first-hop in the route will need to have at least this
+ // many (milli)satoshis.
+ Amount int64 `protobuf:"varint,5,opt,name=amount,proto3" json:"amount,omitempty"`
+ // The absolute timelock or CLTV value that should be extended to the first
+ // hop in the route. All other hops will decrement the time-lock as
+ // described by the onion.
+ Timelock uint32 `protobuf:"varint,6,opt,name=timelock,proto3" json:"timelock,omitempty"`
+ // The payment hash associated with the HTLC. This is needed for tracking
+ // and debugging purposes.
+ PaymentHash []byte `protobuf:"bytes,7,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"`
+ // The optional blinding point to use when constructing the HTLC.
+ // If set, this will be used to blind the next hop in the route.
+ BlindingPoint []byte `protobuf:"bytes,8,opt,name=blinding_point,json=blindingPoint,proto3,oneof" json:"blinding_point,omitempty"`
+ // Optional custom TLV records to include in the UpdateAddHTLC message.
+ CustomRecords map[uint64][]byte `protobuf:"bytes,9,rep,name=custom_records,json=customRecords,proto3" json:"custom_records,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ // Optional opaque extra data to attach to the UpdateAddHTLC message.
+ ExtraData []byte `protobuf:"bytes,10,opt,name=extra_data,json=extraData,proto3,oneof" json:"extra_data,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SendOnionRequest) Reset() {
+ *x = SendOnionRequest{}
+ mi := &file_switchrpc_switch_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SendOnionRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SendOnionRequest) ProtoMessage() {}
+
+func (x *SendOnionRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[0]
+ 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 SendOnionRequest.ProtoReflect.Descriptor instead.
+func (*SendOnionRequest) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *SendOnionRequest) GetOnionBlob() []byte {
+ if x != nil {
+ return x.OnionBlob
+ }
+ return nil
+}
+
+func (x *SendOnionRequest) GetAttemptId() uint64 {
+ if x != nil {
+ return x.AttemptId
+ }
+ return 0
+}
+
+func (x *SendOnionRequest) GetFirstHopPubkey() []byte {
+ if x != nil {
+ return x.FirstHopPubkey
+ }
+ return nil
+}
+
+func (x *SendOnionRequest) GetFirstHopChanId() uint64 {
+ if x != nil {
+ return x.FirstHopChanId
+ }
+ return 0
+}
+
+func (x *SendOnionRequest) GetAmount() int64 {
+ if x != nil {
+ return x.Amount
+ }
+ return 0
+}
+
+func (x *SendOnionRequest) GetTimelock() uint32 {
+ if x != nil {
+ return x.Timelock
+ }
+ return 0
+}
+
+func (x *SendOnionRequest) GetPaymentHash() []byte {
+ if x != nil {
+ return x.PaymentHash
+ }
+ return nil
+}
+
+func (x *SendOnionRequest) GetBlindingPoint() []byte {
+ if x != nil {
+ return x.BlindingPoint
+ }
+ return nil
+}
+
+func (x *SendOnionRequest) GetCustomRecords() map[uint64][]byte {
+ if x != nil {
+ return x.CustomRecords
+ }
+ return nil
+}
+
+func (x *SendOnionRequest) GetExtraData() []byte {
+ if x != nil {
+ return x.ExtraData
+ }
+ return nil
+}
+
+// SendOnionResponse is an empty message. A gRPC status of OK or AlreadyExists
+// indicates a successful dispatch acknowledgment.
+type SendOnionResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SendOnionResponse) Reset() {
+ *x = SendOnionResponse{}
+ mi := &file_switchrpc_switch_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SendOnionResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SendOnionResponse) ProtoMessage() {}
+
+func (x *SendOnionResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[1]
+ 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 SendOnionResponse.ProtoReflect.Descriptor instead.
+func (*SendOnionResponse) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{1}
+}
+
+// SendOnionFailureDetails provides structured details for a dispatch failure
+// and is attached to a FailedPrecondition or Unavailable gRPC status.
+type SendOnionFailureDetails struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // A human-readable message for logging and debugging.
+ ErrorMessage string `protobuf:"bytes,1,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
+ // Structured detail for the dispatch failure, grouped by outcome. The
+ // gRPC status code determines the client's primary action
+ // (FailedPrecondition = definitive failure, Unavailable = retry). The
+ // detail within provides context for logging, pathfinding, and forward
+ // compatibility.
+ //
+ // Types that are valid to be assigned to FailureClass:
+ //
+ // *SendOnionFailureDetails_DefiniteFailure
+ // *SendOnionFailureDetails_IndefiniteFailure
+ FailureClass isSendOnionFailureDetails_FailureClass `protobuf_oneof:"failure_class"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SendOnionFailureDetails) Reset() {
+ *x = SendOnionFailureDetails{}
+ mi := &file_switchrpc_switch_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SendOnionFailureDetails) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SendOnionFailureDetails) ProtoMessage() {}
+
+func (x *SendOnionFailureDetails) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[2]
+ 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 SendOnionFailureDetails.ProtoReflect.Descriptor instead.
+func (*SendOnionFailureDetails) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *SendOnionFailureDetails) GetErrorMessage() string {
+ if x != nil {
+ return x.ErrorMessage
+ }
+ return ""
+}
+
+func (x *SendOnionFailureDetails) GetFailureClass() isSendOnionFailureDetails_FailureClass {
+ if x != nil {
+ return x.FailureClass
+ }
+ return nil
+}
+
+func (x *SendOnionFailureDetails) GetDefiniteFailure() *DefiniteFailure {
+ if x != nil {
+ if x, ok := x.FailureClass.(*SendOnionFailureDetails_DefiniteFailure); ok {
+ return x.DefiniteFailure
+ }
+ }
+ return nil
+}
+
+func (x *SendOnionFailureDetails) GetIndefiniteFailure() *IndefiniteFailure {
+ if x != nil {
+ if x, ok := x.FailureClass.(*SendOnionFailureDetails_IndefiniteFailure); ok {
+ return x.IndefiniteFailure
+ }
+ }
+ return nil
+}
+
+type isSendOnionFailureDetails_FailureClass interface {
+ isSendOnionFailureDetails_FailureClass()
+}
+
+type SendOnionFailureDetails_DefiniteFailure struct {
+ DefiniteFailure *DefiniteFailure `protobuf:"bytes,2,opt,name=definite_failure,json=definiteFailure,proto3,oneof"`
+}
+
+type SendOnionFailureDetails_IndefiniteFailure struct {
+ IndefiniteFailure *IndefiniteFailure `protobuf:"bytes,3,opt,name=indefinite_failure,json=indefiniteFailure,proto3,oneof"`
+}
+
+func (*SendOnionFailureDetails_DefiniteFailure) isSendOnionFailureDetails_FailureClass() {}
+
+func (*SendOnionFailureDetails_IndefiniteFailure) isSendOnionFailureDetails_FailureClass() {}
+
+// DefiniteFailure is a guarantee that the HTLC was not and will not be
+// dispatched. The client should fail the payment attempt and may retry with a
+// new route.
+type DefiniteFailure struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // A failure with a clear, unencrypted reason that occurred at our
+ // node before the HTLC was dispatched.
+ LocalFailure *LocalFailure `protobuf:"bytes,1,opt,name=local_failure,json=localFailure,proto3" json:"local_failure,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DefiniteFailure) Reset() {
+ *x = DefiniteFailure{}
+ mi := &file_switchrpc_switch_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DefiniteFailure) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DefiniteFailure) ProtoMessage() {}
+
+func (x *DefiniteFailure) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_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 DefiniteFailure.ProtoReflect.Descriptor instead.
+func (*DefiniteFailure) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *DefiniteFailure) GetLocalFailure() *LocalFailure {
+ if x != nil {
+ return x.LocalFailure
+ }
+ return nil
+}
+
+// IndefiniteFailure indicates that the state of the HTLC dispatch is unknown.
+// This could be due to a transport-level failure or a server-side issue where
+// the idempotency record may or may not have been written. The client MUST
+// retry the exact same request to resolve the ambiguity. Clients can optionally
+// use this code to implement more nuanced behavior, such as logging or emitting
+// more detailed metrics.
+type IndefiniteFailure struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // A stable, machine-readable code for the indefinite failure.
+ Reason IndefiniteFailureCode `protobuf:"varint,1,opt,name=reason,proto3,enum=switchrpc.IndefiniteFailureCode" json:"reason,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *IndefiniteFailure) Reset() {
+ *x = IndefiniteFailure{}
+ mi := &file_switchrpc_switch_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *IndefiniteFailure) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*IndefiniteFailure) ProtoMessage() {}
+
+func (x *IndefiniteFailure) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_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 IndefiniteFailure.ProtoReflect.Descriptor instead.
+func (*IndefiniteFailure) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *IndefiniteFailure) GetReason() IndefiniteFailureCode {
+ if x != nil {
+ return x.Reason
+ }
+ return IndefiniteFailureCode_REASON_UNKNOWN
+}
+
+type TrackOnionRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The payment hash associated with the HTLC. This is needed for tracking
+ // and debugging purposes.
+ PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"`
+ // The attempt ID uniquely identifying this payment attempt. The caller can
+ // expect to track results for the payment via this attempt ID.
+ AttemptId uint64 `protobuf:"varint,2,opt,name=attempt_id,json=attemptId,proto3" json:"attempt_id,omitempty"`
+ // Optional: The session key that was used to construct the onion packet.
+ // This is required by the server to decrypt any failure message.
+ SessionKey []byte `protobuf:"bytes,3,opt,name=session_key,json=sessionKey,proto3,oneof" json:"session_key,omitempty"`
+ // Optional: The public keys of the nodes in the route, used with the
+ // session_key to decrypt any failure message.
+ HopPubkeys [][]byte `protobuf:"bytes,4,rep,name=hop_pubkeys,json=hopPubkeys,proto3" json:"hop_pubkeys,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TrackOnionRequest) Reset() {
+ *x = TrackOnionRequest{}
+ mi := &file_switchrpc_switch_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TrackOnionRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TrackOnionRequest) ProtoMessage() {}
+
+func (x *TrackOnionRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[5]
+ 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 TrackOnionRequest.ProtoReflect.Descriptor instead.
+func (*TrackOnionRequest) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *TrackOnionRequest) GetPaymentHash() []byte {
+ if x != nil {
+ return x.PaymentHash
+ }
+ return nil
+}
+
+func (x *TrackOnionRequest) GetAttemptId() uint64 {
+ if x != nil {
+ return x.AttemptId
+ }
+ return 0
+}
+
+func (x *TrackOnionRequest) GetSessionKey() []byte {
+ if x != nil {
+ return x.SessionKey
+ }
+ return nil
+}
+
+func (x *TrackOnionRequest) GetHopPubkeys() [][]byte {
+ if x != nil {
+ return x.HopPubkeys
+ }
+ return nil
+}
+
+type TrackOnionResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The final result of the payment attempt, which is either a preimage
+ // (success) or detailed failure information.
+ //
+ // Types that are valid to be assigned to Result:
+ //
+ // *TrackOnionResponse_Preimage
+ // *TrackOnionResponse_FailureDetails
+ Result isTrackOnionResponse_Result `protobuf_oneof:"result"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TrackOnionResponse) Reset() {
+ *x = TrackOnionResponse{}
+ mi := &file_switchrpc_switch_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TrackOnionResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TrackOnionResponse) ProtoMessage() {}
+
+func (x *TrackOnionResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[6]
+ 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 TrackOnionResponse.ProtoReflect.Descriptor instead.
+func (*TrackOnionResponse) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *TrackOnionResponse) GetResult() isTrackOnionResponse_Result {
+ if x != nil {
+ return x.Result
+ }
+ return nil
+}
+
+func (x *TrackOnionResponse) GetPreimage() []byte {
+ if x != nil {
+ if x, ok := x.Result.(*TrackOnionResponse_Preimage); ok {
+ return x.Preimage
+ }
+ }
+ return nil
+}
+
+func (x *TrackOnionResponse) GetFailureDetails() *FailureDetails {
+ if x != nil {
+ if x, ok := x.Result.(*TrackOnionResponse_FailureDetails); ok {
+ return x.FailureDetails
+ }
+ }
+ return nil
+}
+
+type isTrackOnionResponse_Result interface {
+ isTrackOnionResponse_Result()
+}
+
+type TrackOnionResponse_Preimage struct {
+ // The preimage obtained by making the payment. If this field is set,
+ // the payment succeeded.
+ Preimage []byte `protobuf:"bytes,1,opt,name=preimage,proto3,oneof"`
+}
+
+type TrackOnionResponse_FailureDetails struct {
+ // The application-level failure for the payment attempt. If this field
+ // is set, the payment attempt failed.
+ FailureDetails *FailureDetails `protobuf:"bytes,2,opt,name=failure_details,json=failureDetails,proto3,oneof"`
+}
+
+func (*TrackOnionResponse_Preimage) isTrackOnionResponse_Result() {}
+
+func (*TrackOnionResponse_FailureDetails) isTrackOnionResponse_Result() {}
+
+// FailureDetails provides structured information about why a payment attempt
+// failed on the network. This message is included in a successful
+// TrackOnionResponse when the queried attempt ultimately failed.
+type FailureDetails struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // A human-readable error_message for logging or display.
+ ErrorMessage string `protobuf:"bytes,1,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
+ // The failure contains specific, structured details about the error.
+ // Exactly one variant is set when this message is present.
+ //
+ // Types that are valid to be assigned to Failure:
+ //
+ // *FailureDetails_LocalFailure
+ // *FailureDetails_ForwardingFailure
+ // *FailureDetails_EncryptedErrorData
+ // *FailureDetails_UnreadableFailure
+ // *FailureDetails_SwitchError
+ Failure isFailureDetails_Failure `protobuf_oneof:"failure"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *FailureDetails) Reset() {
+ *x = FailureDetails{}
+ mi := &file_switchrpc_switch_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *FailureDetails) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*FailureDetails) ProtoMessage() {}
+
+func (x *FailureDetails) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[7]
+ 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 FailureDetails.ProtoReflect.Descriptor instead.
+func (*FailureDetails) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *FailureDetails) GetErrorMessage() string {
+ if x != nil {
+ return x.ErrorMessage
+ }
+ return ""
+}
+
+func (x *FailureDetails) GetFailure() isFailureDetails_Failure {
+ if x != nil {
+ return x.Failure
+ }
+ return nil
+}
+
+func (x *FailureDetails) GetLocalFailure() *LocalFailure {
+ if x != nil {
+ if x, ok := x.Failure.(*FailureDetails_LocalFailure); ok {
+ return x.LocalFailure
+ }
+ }
+ return nil
+}
+
+func (x *FailureDetails) GetForwardingFailure() *ForwardingFailure {
+ if x != nil {
+ if x, ok := x.Failure.(*FailureDetails_ForwardingFailure); ok {
+ return x.ForwardingFailure
+ }
+ }
+ return nil
+}
+
+func (x *FailureDetails) GetEncryptedErrorData() []byte {
+ if x != nil {
+ if x, ok := x.Failure.(*FailureDetails_EncryptedErrorData); ok {
+ return x.EncryptedErrorData
+ }
+ }
+ return nil
+}
+
+func (x *FailureDetails) GetUnreadableFailure() *UnreadableFailure {
+ if x != nil {
+ if x, ok := x.Failure.(*FailureDetails_UnreadableFailure); ok {
+ return x.UnreadableFailure
+ }
+ }
+ return nil
+}
+
+func (x *FailureDetails) GetSwitchError() *SwitchError {
+ if x != nil {
+ if x, ok := x.Failure.(*FailureDetails_SwitchError); ok {
+ return x.SwitchError
+ }
+ }
+ return nil
+}
+
+type isFailureDetails_Failure interface {
+ isFailureDetails_Failure()
+}
+
+type FailureDetails_LocalFailure struct {
+ // local_failure is set when the failure originates at the local
+ // node (e.g. unable to forward due to insufficient balance,
+ // channel policy violations, or other link-level rejections). The
+ // wire message is available in plaintext without onion decryption.
+ LocalFailure *LocalFailure `protobuf:"bytes,2,opt,name=local_failure,json=localFailure,proto3,oneof"`
+}
+
+type FailureDetails_ForwardingFailure struct {
+ // forwarding_failure is set when the HTLC was forwarded into the
+ // network and a remote node returned an error. The onion error
+ // was successfully decrypted, yielding the failure source index.
+ // The wire_message may be empty if the inner failure could not
+ // be decoded.
+ ForwardingFailure *ForwardingFailure `protobuf:"bytes,3,opt,name=forwarding_failure,json=forwardingFailure,proto3,oneof"`
+}
+
+type FailureDetails_EncryptedErrorData struct {
+ // encrypted_error_data contains the raw onion-encrypted error
+ // blob. This is returned when no decryption keys were provided
+ // in the TrackOnionRequest (i.e. no session key or hop public
+ // keys), deferring decryption entirely to the client.
+ EncryptedErrorData []byte `protobuf:"bytes,4,opt,name=encrypted_error_data,json=encryptedErrorData,proto3,oneof"`
+}
+
+type FailureDetails_UnreadableFailure struct {
+ // unreadable_failure indicates that decryption keys were provided
+ // and decryption was attempted, but failed. The original error
+ // cannot be recovered.
+ UnreadableFailure *UnreadableFailure `protobuf:"bytes,5,opt,name=unreadable_failure,json=unreadableFailure,proto3,oneof"`
+}
+
+type FailureDetails_SwitchError struct {
+ // switch_error indicates an unexpected internal error that does
+ // not fall into any of the above categories.
+ SwitchError *SwitchError `protobuf:"bytes,6,opt,name=switch_error,json=switchError,proto3,oneof"`
+}
+
+func (*FailureDetails_LocalFailure) isFailureDetails_Failure() {}
+
+func (*FailureDetails_ForwardingFailure) isFailureDetails_Failure() {}
+
+func (*FailureDetails_EncryptedErrorData) isFailureDetails_Failure() {}
+
+func (*FailureDetails_UnreadableFailure) isFailureDetails_Failure() {}
+
+func (*FailureDetails_SwitchError) isFailureDetails_Failure() {}
+
+// ForwardingFailure represents an HTLC failure that occurred at a remote node
+// in the payment route. The onion error was successfully decrypted, revealing
+// the failing hop.
+type ForwardingFailure struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // failure_source_index is the 0-based index of the node within the payment
+ // route that reported the failure. Index 0 refers to the local node.
+ FailureSourceIndex uint32 `protobuf:"varint,1,opt,name=failure_source_index,json=failureSourceIndex,proto3" json:"failure_source_index,omitempty"`
+ // The raw, serialized lnwire.FailureMessage reported by the failing node.
+ // This field may be empty if the failure message could not be decoded.
+ WireMessage []byte `protobuf:"bytes,2,opt,name=wire_message,json=wireMessage,proto3" json:"wire_message,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ForwardingFailure) Reset() {
+ *x = ForwardingFailure{}
+ mi := &file_switchrpc_switch_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ForwardingFailure) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ForwardingFailure) ProtoMessage() {}
+
+func (x *ForwardingFailure) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[8]
+ 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 ForwardingFailure.ProtoReflect.Descriptor instead.
+func (*ForwardingFailure) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *ForwardingFailure) GetFailureSourceIndex() uint32 {
+ if x != nil {
+ return x.FailureSourceIndex
+ }
+ return 0
+}
+
+func (x *ForwardingFailure) GetWireMessage() []byte {
+ if x != nil {
+ return x.WireMessage
+ }
+ return nil
+}
+
+// LocalFailure represents a failure that originates at the local node. No
+// onion decryption is involved because the failure occurred before the HTLC
+// left our node.
+type LocalFailure struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The raw, serialized `lnwire.FailureMessage`.
+ WireMessage []byte `protobuf:"bytes,1,opt,name=wire_message,json=wireMessage,proto3" json:"wire_message,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *LocalFailure) Reset() {
+ *x = LocalFailure{}
+ mi := &file_switchrpc_switch_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *LocalFailure) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LocalFailure) ProtoMessage() {}
+
+func (x *LocalFailure) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[9]
+ 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 LocalFailure.ProtoReflect.Descriptor instead.
+func (*LocalFailure) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{9}
+}
+
+func (x *LocalFailure) GetWireMessage() []byte {
+ if x != nil {
+ return x.WireMessage
+ }
+ return nil
+}
+
+// SwitchError indicates that an error occurred within the switch subsystem.
+type SwitchError struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SwitchError) Reset() {
+ *x = SwitchError{}
+ mi := &file_switchrpc_switch_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SwitchError) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SwitchError) ProtoMessage() {}
+
+func (x *SwitchError) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[10]
+ 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 SwitchError.ProtoReflect.Descriptor instead.
+func (*SwitchError) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{10}
+}
+
+// UnreadableFailure indicates that decryption keys were provided and
+// decryption was attempted, but failed. The original failure information
+// cannot be recovered.
+type UnreadableFailure struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UnreadableFailure) Reset() {
+ *x = UnreadableFailure{}
+ mi := &file_switchrpc_switch_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UnreadableFailure) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UnreadableFailure) ProtoMessage() {}
+
+func (x *UnreadableFailure) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[11]
+ 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 UnreadableFailure.ProtoReflect.Descriptor instead.
+func (*UnreadableFailure) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{11}
+}
+
+// BuildOnionRequest includes the necessary information to construct a Sphinx
+// onion packet.
+type BuildOnionRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The route for which the onion packet should be built.
+ Route *lnrpc.Route `protobuf:"bytes,1,opt,name=route,proto3" json:"route,omitempty"`
+ // The payment hash associated with the HTLC.
+ PaymentHash []byte `protobuf:"bytes,2,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"`
+ // A session key for onion packet construction, if not provided, a new one
+ // will be generated.
+ SessionKey []byte `protobuf:"bytes,3,opt,name=session_key,json=sessionKey,proto3,oneof" json:"session_key,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BuildOnionRequest) Reset() {
+ *x = BuildOnionRequest{}
+ mi := &file_switchrpc_switch_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BuildOnionRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BuildOnionRequest) ProtoMessage() {}
+
+func (x *BuildOnionRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[12]
+ 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 BuildOnionRequest.ProtoReflect.Descriptor instead.
+func (*BuildOnionRequest) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{12}
+}
+
+func (x *BuildOnionRequest) GetRoute() *lnrpc.Route {
+ if x != nil {
+ return x.Route
+ }
+ return nil
+}
+
+func (x *BuildOnionRequest) GetPaymentHash() []byte {
+ if x != nil {
+ return x.PaymentHash
+ }
+ return nil
+}
+
+func (x *BuildOnionRequest) GetSessionKey() []byte {
+ if x != nil {
+ return x.SessionKey
+ }
+ return nil
+}
+
+// BuildOnionResponse contains the constructed onion packet.
+type BuildOnionResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The constructed onion packet in bytes.
+ OnionBlob []byte `protobuf:"bytes,1,opt,name=onion_blob,json=onionBlob,proto3" json:"onion_blob,omitempty"`
+ // The session key used for building the onion packet.
+ SessionKey []byte `protobuf:"bytes,2,opt,name=session_key,json=sessionKey,proto3" json:"session_key,omitempty"`
+ // The serialized public keys of all nodes along the route for the
+ // constructed onion.
+ HopPubkeys [][]byte `protobuf:"bytes,3,rep,name=hop_pubkeys,json=hopPubkeys,proto3" json:"hop_pubkeys,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BuildOnionResponse) Reset() {
+ *x = BuildOnionResponse{}
+ mi := &file_switchrpc_switch_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BuildOnionResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BuildOnionResponse) ProtoMessage() {}
+
+func (x *BuildOnionResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[13]
+ 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 BuildOnionResponse.ProtoReflect.Descriptor instead.
+func (*BuildOnionResponse) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{13}
+}
+
+func (x *BuildOnionResponse) GetOnionBlob() []byte {
+ if x != nil {
+ return x.OnionBlob
+ }
+ return nil
+}
+
+func (x *BuildOnionResponse) GetSessionKey() []byte {
+ if x != nil {
+ return x.SessionKey
+ }
+ return nil
+}
+
+func (x *BuildOnionResponse) GetHopPubkeys() [][]byte {
+ if x != nil {
+ return x.HopPubkeys
+ }
+ return nil
+}
+
+type DeleteAttemptsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The attempt IDs to delete from the server's attempt store. Only terminal
+ // (settled or failed) attempts will be deleted. Pending (in-flight)
+ // attempts are skipped and reported with a DELETION_PENDING status.
+ AttemptIds []uint64 `protobuf:"varint,1,rep,packed,name=attempt_ids,json=attemptIds,proto3" json:"attempt_ids,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DeleteAttemptsRequest) Reset() {
+ *x = DeleteAttemptsRequest{}
+ mi := &file_switchrpc_switch_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DeleteAttemptsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DeleteAttemptsRequest) ProtoMessage() {}
+
+func (x *DeleteAttemptsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[14]
+ 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 DeleteAttemptsRequest.ProtoReflect.Descriptor instead.
+func (*DeleteAttemptsRequest) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{14}
+}
+
+func (x *DeleteAttemptsRequest) GetAttemptIds() []uint64 {
+ if x != nil {
+ return x.AttemptIds
+ }
+ return nil
+}
+
+type DeleteAttemptsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Per-attempt deletion outcomes. The order corresponds to the order of
+ // attempt_ids in the request.
+ Results []*AttemptDeletionResult `protobuf:"bytes,1,rep,name=results,proto3" json:"results,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DeleteAttemptsResponse) Reset() {
+ *x = DeleteAttemptsResponse{}
+ mi := &file_switchrpc_switch_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DeleteAttemptsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DeleteAttemptsResponse) ProtoMessage() {}
+
+func (x *DeleteAttemptsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[15]
+ 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 DeleteAttemptsResponse.ProtoReflect.Descriptor instead.
+func (*DeleteAttemptsResponse) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *DeleteAttemptsResponse) GetResults() []*AttemptDeletionResult {
+ if x != nil {
+ return x.Results
+ }
+ return nil
+}
+
+// AttemptDeletionResult reports the outcome of deleting a single attempt.
+type AttemptDeletionResult struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The attempt ID this result corresponds to.
+ AttemptId uint64 `protobuf:"varint,1,opt,name=attempt_id,json=attemptId,proto3" json:"attempt_id,omitempty"`
+ // The outcome of the deletion for this attempt.
+ Status AttemptDeletionStatus `protobuf:"varint,2,opt,name=status,proto3,enum=switchrpc.AttemptDeletionStatus" json:"status,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *AttemptDeletionResult) Reset() {
+ *x = AttemptDeletionResult{}
+ mi := &file_switchrpc_switch_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *AttemptDeletionResult) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AttemptDeletionResult) ProtoMessage() {}
+
+func (x *AttemptDeletionResult) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[16]
+ 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 AttemptDeletionResult.ProtoReflect.Descriptor instead.
+func (*AttemptDeletionResult) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{16}
+}
+
+func (x *AttemptDeletionResult) GetAttemptId() uint64 {
+ if x != nil {
+ return x.AttemptId
+ }
+ return 0
+}
+
+func (x *AttemptDeletionResult) GetStatus() AttemptDeletionStatus {
+ if x != nil {
+ return x.Status
+ }
+ return AttemptDeletionStatus_DELETION_OK
+}
+
+type DisableRemoteRouterRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DisableRemoteRouterRequest) Reset() {
+ *x = DisableRemoteRouterRequest{}
+ mi := &file_switchrpc_switch_proto_msgTypes[17]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DisableRemoteRouterRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DisableRemoteRouterRequest) ProtoMessage() {}
+
+func (x *DisableRemoteRouterRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[17]
+ 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 DisableRemoteRouterRequest.ProtoReflect.Descriptor instead.
+func (*DisableRemoteRouterRequest) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{17}
+}
+
+type DisableRemoteRouterResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DisableRemoteRouterResponse) Reset() {
+ *x = DisableRemoteRouterResponse{}
+ mi := &file_switchrpc_switch_proto_msgTypes[18]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DisableRemoteRouterResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DisableRemoteRouterResponse) ProtoMessage() {}
+
+func (x *DisableRemoteRouterResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_switchrpc_switch_proto_msgTypes[18]
+ 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 DisableRemoteRouterResponse.ProtoReflect.Descriptor instead.
+func (*DisableRemoteRouterResponse) Descriptor() ([]byte, []int) {
+ return file_switchrpc_switch_proto_rawDescGZIP(), []int{18}
+}
+
+var File_switchrpc_switch_proto protoreflect.FileDescriptor
+
+const file_switchrpc_switch_proto_rawDesc = "" +
+ "\n" +
+ "\x16switchrpc/switch.proto\x12\tswitchrpc\x1a\x0flightning.proto\"\x87\x04\n" +
+ "\x10SendOnionRequest\x12\x1d\n" +
+ "\n" +
+ "onion_blob\x18\x01 \x01(\fR\tonionBlob\x12\x1d\n" +
+ "\n" +
+ "attempt_id\x18\x02 \x01(\x04R\tattemptId\x12(\n" +
+ "\x10first_hop_pubkey\x18\x03 \x01(\fR\x0efirstHopPubkey\x12)\n" +
+ "\x11first_hop_chan_id\x18\x04 \x01(\x04R\x0efirstHopChanId\x12\x16\n" +
+ "\x06amount\x18\x05 \x01(\x03R\x06amount\x12\x1a\n" +
+ "\btimelock\x18\x06 \x01(\rR\btimelock\x12!\n" +
+ "\fpayment_hash\x18\a \x01(\fR\vpaymentHash\x12*\n" +
+ "\x0eblinding_point\x18\b \x01(\fH\x00R\rblindingPoint\x88\x01\x01\x12U\n" +
+ "\x0ecustom_records\x18\t \x03(\v2..switchrpc.SendOnionRequest.CustomRecordsEntryR\rcustomRecords\x12\"\n" +
+ "\n" +
+ "extra_data\x18\n" +
+ " \x01(\fH\x01R\textraData\x88\x01\x01\x1a@\n" +
+ "\x12CustomRecordsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\x04R\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01B\x11\n" +
+ "\x0f_blinding_pointB\r\n" +
+ "\v_extra_data\"\x13\n" +
+ "\x11SendOnionResponse\"\xe7\x01\n" +
+ "\x17SendOnionFailureDetails\x12#\n" +
+ "\rerror_message\x18\x01 \x01(\tR\ferrorMessage\x12G\n" +
+ "\x10definite_failure\x18\x02 \x01(\v2\x1a.switchrpc.DefiniteFailureH\x00R\x0fdefiniteFailure\x12M\n" +
+ "\x12indefinite_failure\x18\x03 \x01(\v2\x1c.switchrpc.IndefiniteFailureH\x00R\x11indefiniteFailureB\x0f\n" +
+ "\rfailure_class\"O\n" +
+ "\x0fDefiniteFailure\x12<\n" +
+ "\rlocal_failure\x18\x01 \x01(\v2\x17.switchrpc.LocalFailureR\flocalFailure\"M\n" +
+ "\x11IndefiniteFailure\x128\n" +
+ "\x06reason\x18\x01 \x01(\x0e2 .switchrpc.IndefiniteFailureCodeR\x06reason\"\xac\x01\n" +
+ "\x11TrackOnionRequest\x12!\n" +
+ "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12\x1d\n" +
+ "\n" +
+ "attempt_id\x18\x02 \x01(\x04R\tattemptId\x12$\n" +
+ "\vsession_key\x18\x03 \x01(\fH\x00R\n" +
+ "sessionKey\x88\x01\x01\x12\x1f\n" +
+ "\vhop_pubkeys\x18\x04 \x03(\fR\n" +
+ "hopPubkeysB\x0e\n" +
+ "\f_session_key\"\x82\x01\n" +
+ "\x12TrackOnionResponse\x12\x1c\n" +
+ "\bpreimage\x18\x01 \x01(\fH\x00R\bpreimage\x12D\n" +
+ "\x0ffailure_details\x18\x02 \x01(\v2\x19.switchrpc.FailureDetailsH\x00R\x0efailureDetailsB\b\n" +
+ "\x06result\"\x8f\x03\n" +
+ "\x0eFailureDetails\x12#\n" +
+ "\rerror_message\x18\x01 \x01(\tR\ferrorMessage\x12>\n" +
+ "\rlocal_failure\x18\x02 \x01(\v2\x17.switchrpc.LocalFailureH\x00R\flocalFailure\x12M\n" +
+ "\x12forwarding_failure\x18\x03 \x01(\v2\x1c.switchrpc.ForwardingFailureH\x00R\x11forwardingFailure\x122\n" +
+ "\x14encrypted_error_data\x18\x04 \x01(\fH\x00R\x12encryptedErrorData\x12M\n" +
+ "\x12unreadable_failure\x18\x05 \x01(\v2\x1c.switchrpc.UnreadableFailureH\x00R\x11unreadableFailure\x12;\n" +
+ "\fswitch_error\x18\x06 \x01(\v2\x16.switchrpc.SwitchErrorH\x00R\vswitchErrorB\t\n" +
+ "\afailure\"h\n" +
+ "\x11ForwardingFailure\x120\n" +
+ "\x14failure_source_index\x18\x01 \x01(\rR\x12failureSourceIndex\x12!\n" +
+ "\fwire_message\x18\x02 \x01(\fR\vwireMessage\"1\n" +
+ "\fLocalFailure\x12!\n" +
+ "\fwire_message\x18\x01 \x01(\fR\vwireMessage\"\r\n" +
+ "\vSwitchError\"\x13\n" +
+ "\x11UnreadableFailure\"\x90\x01\n" +
+ "\x11BuildOnionRequest\x12\"\n" +
+ "\x05route\x18\x01 \x01(\v2\f.lnrpc.RouteR\x05route\x12!\n" +
+ "\fpayment_hash\x18\x02 \x01(\fR\vpaymentHash\x12$\n" +
+ "\vsession_key\x18\x03 \x01(\fH\x00R\n" +
+ "sessionKey\x88\x01\x01B\x0e\n" +
+ "\f_session_key\"u\n" +
+ "\x12BuildOnionResponse\x12\x1d\n" +
+ "\n" +
+ "onion_blob\x18\x01 \x01(\fR\tonionBlob\x12\x1f\n" +
+ "\vsession_key\x18\x02 \x01(\fR\n" +
+ "sessionKey\x12\x1f\n" +
+ "\vhop_pubkeys\x18\x03 \x03(\fR\n" +
+ "hopPubkeys\"8\n" +
+ "\x15DeleteAttemptsRequest\x12\x1f\n" +
+ "\vattempt_ids\x18\x01 \x03(\x04R\n" +
+ "attemptIds\"T\n" +
+ "\x16DeleteAttemptsResponse\x12:\n" +
+ "\aresults\x18\x01 \x03(\v2 .switchrpc.AttemptDeletionResultR\aresults\"p\n" +
+ "\x15AttemptDeletionResult\x12\x1d\n" +
+ "\n" +
+ "attempt_id\x18\x01 \x01(\x04R\tattemptId\x128\n" +
+ "\x06status\x18\x02 \x01(\x0e2 .switchrpc.AttemptDeletionStatusR\x06status\"\x1c\n" +
+ "\x1aDisableRemoteRouterRequest\"\x1d\n" +
+ "\x1bDisableRemoteRouterResponse*U\n" +
+ "\x15IndefiniteFailureCode\x12\x12\n" +
+ "\x0eREASON_UNKNOWN\x10\x00\x12\x12\n" +
+ "\x0eSWITCH_EXITING\x10\x01\x12\x14\n" +
+ "\x10HTLC_INIT_FAILED\x10\x02*k\n" +
+ "\x15AttemptDeletionStatus\x12\x0f\n" +
+ "\vDELETION_OK\x10\x00\x12\x14\n" +
+ "\x10DELETION_PENDING\x10\x01\x12\x16\n" +
+ "\x12DELETION_NOT_FOUND\x10\x02\x12\x13\n" +
+ "\x0fDELETION_FAILED\x10\x032\xa3\x03\n" +
+ "\x06Switch\x12F\n" +
+ "\tSendOnion\x12\x1b.switchrpc.SendOnionRequest\x1a\x1c.switchrpc.SendOnionResponse\x12I\n" +
+ "\n" +
+ "TrackOnion\x12\x1c.switchrpc.TrackOnionRequest\x1a\x1d.switchrpc.TrackOnionResponse\x12I\n" +
+ "\n" +
+ "BuildOnion\x12\x1c.switchrpc.BuildOnionRequest\x1a\x1d.switchrpc.BuildOnionResponse\x12U\n" +
+ "\x0eDeleteAttempts\x12 .switchrpc.DeleteAttemptsRequest\x1a!.switchrpc.DeleteAttemptsResponse\x12d\n" +
+ "\x13DisableRemoteRouter\x12%.switchrpc.DisableRemoteRouterRequest\x1a&.switchrpc.DisableRemoteRouterResponseB1Z/github.com/lightningnetwork/lnd/lnrpc/switchrpcb\x06proto3"
+
+var (
+ file_switchrpc_switch_proto_rawDescOnce sync.Once
+ file_switchrpc_switch_proto_rawDescData []byte
+)
+
+func file_switchrpc_switch_proto_rawDescGZIP() []byte {
+ file_switchrpc_switch_proto_rawDescOnce.Do(func() {
+ file_switchrpc_switch_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_switchrpc_switch_proto_rawDesc), len(file_switchrpc_switch_proto_rawDesc)))
+ })
+ return file_switchrpc_switch_proto_rawDescData
+}
+
+var file_switchrpc_switch_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
+var file_switchrpc_switch_proto_msgTypes = make([]protoimpl.MessageInfo, 20)
+var file_switchrpc_switch_proto_goTypes = []any{
+ (IndefiniteFailureCode)(0), // 0: switchrpc.IndefiniteFailureCode
+ (AttemptDeletionStatus)(0), // 1: switchrpc.AttemptDeletionStatus
+ (*SendOnionRequest)(nil), // 2: switchrpc.SendOnionRequest
+ (*SendOnionResponse)(nil), // 3: switchrpc.SendOnionResponse
+ (*SendOnionFailureDetails)(nil), // 4: switchrpc.SendOnionFailureDetails
+ (*DefiniteFailure)(nil), // 5: switchrpc.DefiniteFailure
+ (*IndefiniteFailure)(nil), // 6: switchrpc.IndefiniteFailure
+ (*TrackOnionRequest)(nil), // 7: switchrpc.TrackOnionRequest
+ (*TrackOnionResponse)(nil), // 8: switchrpc.TrackOnionResponse
+ (*FailureDetails)(nil), // 9: switchrpc.FailureDetails
+ (*ForwardingFailure)(nil), // 10: switchrpc.ForwardingFailure
+ (*LocalFailure)(nil), // 11: switchrpc.LocalFailure
+ (*SwitchError)(nil), // 12: switchrpc.SwitchError
+ (*UnreadableFailure)(nil), // 13: switchrpc.UnreadableFailure
+ (*BuildOnionRequest)(nil), // 14: switchrpc.BuildOnionRequest
+ (*BuildOnionResponse)(nil), // 15: switchrpc.BuildOnionResponse
+ (*DeleteAttemptsRequest)(nil), // 16: switchrpc.DeleteAttemptsRequest
+ (*DeleteAttemptsResponse)(nil), // 17: switchrpc.DeleteAttemptsResponse
+ (*AttemptDeletionResult)(nil), // 18: switchrpc.AttemptDeletionResult
+ (*DisableRemoteRouterRequest)(nil), // 19: switchrpc.DisableRemoteRouterRequest
+ (*DisableRemoteRouterResponse)(nil), // 20: switchrpc.DisableRemoteRouterResponse
+ nil, // 21: switchrpc.SendOnionRequest.CustomRecordsEntry
+ (*lnrpc.Route)(nil), // 22: lnrpc.Route
+}
+var file_switchrpc_switch_proto_depIdxs = []int32{
+ 21, // 0: switchrpc.SendOnionRequest.custom_records:type_name -> switchrpc.SendOnionRequest.CustomRecordsEntry
+ 5, // 1: switchrpc.SendOnionFailureDetails.definite_failure:type_name -> switchrpc.DefiniteFailure
+ 6, // 2: switchrpc.SendOnionFailureDetails.indefinite_failure:type_name -> switchrpc.IndefiniteFailure
+ 11, // 3: switchrpc.DefiniteFailure.local_failure:type_name -> switchrpc.LocalFailure
+ 0, // 4: switchrpc.IndefiniteFailure.reason:type_name -> switchrpc.IndefiniteFailureCode
+ 9, // 5: switchrpc.TrackOnionResponse.failure_details:type_name -> switchrpc.FailureDetails
+ 11, // 6: switchrpc.FailureDetails.local_failure:type_name -> switchrpc.LocalFailure
+ 10, // 7: switchrpc.FailureDetails.forwarding_failure:type_name -> switchrpc.ForwardingFailure
+ 13, // 8: switchrpc.FailureDetails.unreadable_failure:type_name -> switchrpc.UnreadableFailure
+ 12, // 9: switchrpc.FailureDetails.switch_error:type_name -> switchrpc.SwitchError
+ 22, // 10: switchrpc.BuildOnionRequest.route:type_name -> lnrpc.Route
+ 18, // 11: switchrpc.DeleteAttemptsResponse.results:type_name -> switchrpc.AttemptDeletionResult
+ 1, // 12: switchrpc.AttemptDeletionResult.status:type_name -> switchrpc.AttemptDeletionStatus
+ 2, // 13: switchrpc.Switch.SendOnion:input_type -> switchrpc.SendOnionRequest
+ 7, // 14: switchrpc.Switch.TrackOnion:input_type -> switchrpc.TrackOnionRequest
+ 14, // 15: switchrpc.Switch.BuildOnion:input_type -> switchrpc.BuildOnionRequest
+ 16, // 16: switchrpc.Switch.DeleteAttempts:input_type -> switchrpc.DeleteAttemptsRequest
+ 19, // 17: switchrpc.Switch.DisableRemoteRouter:input_type -> switchrpc.DisableRemoteRouterRequest
+ 3, // 18: switchrpc.Switch.SendOnion:output_type -> switchrpc.SendOnionResponse
+ 8, // 19: switchrpc.Switch.TrackOnion:output_type -> switchrpc.TrackOnionResponse
+ 15, // 20: switchrpc.Switch.BuildOnion:output_type -> switchrpc.BuildOnionResponse
+ 17, // 21: switchrpc.Switch.DeleteAttempts:output_type -> switchrpc.DeleteAttemptsResponse
+ 20, // 22: switchrpc.Switch.DisableRemoteRouter:output_type -> switchrpc.DisableRemoteRouterResponse
+ 18, // [18:23] is the sub-list for method output_type
+ 13, // [13:18] is the sub-list for method input_type
+ 13, // [13:13] is the sub-list for extension type_name
+ 13, // [13:13] is the sub-list for extension extendee
+ 0, // [0:13] is the sub-list for field type_name
+}
+
+func init() { file_switchrpc_switch_proto_init() }
+func file_switchrpc_switch_proto_init() {
+ if File_switchrpc_switch_proto != nil {
+ return
+ }
+ file_switchrpc_switch_proto_msgTypes[0].OneofWrappers = []any{}
+ file_switchrpc_switch_proto_msgTypes[2].OneofWrappers = []any{
+ (*SendOnionFailureDetails_DefiniteFailure)(nil),
+ (*SendOnionFailureDetails_IndefiniteFailure)(nil),
+ }
+ file_switchrpc_switch_proto_msgTypes[5].OneofWrappers = []any{}
+ file_switchrpc_switch_proto_msgTypes[6].OneofWrappers = []any{
+ (*TrackOnionResponse_Preimage)(nil),
+ (*TrackOnionResponse_FailureDetails)(nil),
+ }
+ file_switchrpc_switch_proto_msgTypes[7].OneofWrappers = []any{
+ (*FailureDetails_LocalFailure)(nil),
+ (*FailureDetails_ForwardingFailure)(nil),
+ (*FailureDetails_EncryptedErrorData)(nil),
+ (*FailureDetails_UnreadableFailure)(nil),
+ (*FailureDetails_SwitchError)(nil),
+ }
+ file_switchrpc_switch_proto_msgTypes[12].OneofWrappers = []any{}
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_switchrpc_switch_proto_rawDesc), len(file_switchrpc_switch_proto_rawDesc)),
+ NumEnums: 2,
+ NumMessages: 20,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_switchrpc_switch_proto_goTypes,
+ DependencyIndexes: file_switchrpc_switch_proto_depIdxs,
+ EnumInfos: file_switchrpc_switch_proto_enumTypes,
+ MessageInfos: file_switchrpc_switch_proto_msgTypes,
+ }.Build()
+ File_switchrpc_switch_proto = out.File
+ file_switchrpc_switch_proto_goTypes = nil
+ file_switchrpc_switch_proto_depIdxs = nil
+}
### lnrpc/switchrpc/switch.pb.gw.go
@@ -0,0 +1,511 @@
+// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
+// source: switchrpc/switch.proto
+
+/*
+Package switchrpc is a reverse proxy.
+
+It translates gRPC into RESTful JSON APIs.
+*/
+package switchrpc
+
+import (
+ "context"
+ "io"
+ "net/http"
+
+ "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
+ "github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
+)
+
+// Suppress "imported and not used" errors
+var _ codes.Code
+var _ io.Reader
+var _ status.Status
+var _ = runtime.String
+var _ = utilities.NewDoubleArray
+var _ = metadata.Join
+
+func request_Switch_SendOnion_0(ctx context.Context, marshaler runtime.Marshaler, client SwitchClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq SendOnionRequest
+ 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.SendOnion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Switch_SendOnion_0(ctx context.Context, marshaler runtime.Marshaler, server SwitchServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq SendOnionRequest
+ 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.SendOnion(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+func request_Switch_TrackOnion_0(ctx context.Context, marshaler runtime.Marshaler, client SwitchClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq TrackOnionRequest
+ 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.TrackOnion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Switch_TrackOnion_0(ctx context.Context, marshaler runtime.Marshaler, server SwitchServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq TrackOnionRequest
+ 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.TrackOnion(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+func request_Switch_BuildOnion_0(ctx context.Context, marshaler runtime.Marshaler, client SwitchClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq BuildOnionRequest
+ 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.BuildOnion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Switch_BuildOnion_0(ctx context.Context, marshaler runtime.Marshaler, server SwitchServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq BuildOnionRequest
+ 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.BuildOnion(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+func request_Switch_DeleteAttempts_0(ctx context.Context, marshaler runtime.Marshaler, client SwitchClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq DeleteAttemptsRequest
+ 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.DeleteAttempts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Switch_DeleteAttempts_0(ctx context.Context, marshaler runtime.Marshaler, server SwitchServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq DeleteAttemptsRequest
+ 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.DeleteAttempts(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+func request_Switch_DisableRemoteRouter_0(ctx context.Context, marshaler runtime.Marshaler, client SwitchClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq DisableRemoteRouterRequest
+ 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.DisableRemoteRouter(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+
+}
+
+func local_request_Switch_DisableRemoteRouter_0(ctx context.Context, marshaler runtime.Marshaler, server SwitchServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var protoReq DisableRemoteRouterRequest
+ 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.DisableRemoteRouter(ctx, &protoReq)
+ return msg, metadata, err
+
+}
+
+// RegisterSwitchHandlerServer registers the http handlers for service Switch to "mux".
+// UnaryRPC :call SwitchServer directly.
+// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
+// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterSwitchHandlerFromEndpoint instead.
+func RegisterSwitchHandlerServer(ctx context.Context, mux *runtime.ServeMux, server SwitchServer) error {
+
+ mux.Handle("POST", pattern_Switch_SendOnion_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, "/switchrpc.Switch/SendOnion", runtime.WithHTTPPathPattern("/v2/switch/onion"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Switch_SendOnion_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_Switch_SendOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_TrackOnion_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, "/switchrpc.Switch/TrackOnion", runtime.WithHTTPPathPattern("/v2/switch/track"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Switch_TrackOnion_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_Switch_TrackOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_BuildOnion_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, "/switchrpc.Switch/BuildOnion", runtime.WithHTTPPathPattern("/v2/switch/build"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Switch_BuildOnion_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_Switch_BuildOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_DeleteAttempts_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, "/switchrpc.Switch/DeleteAttempts", runtime.WithHTTPPathPattern("/v2/switch/deleteattempts"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Switch_DeleteAttempts_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_Switch_DeleteAttempts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_DisableRemoteRouter_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, "/switchrpc.Switch/DisableRemoteRouter", runtime.WithHTTPPathPattern("/v2/switch/disableremoterouter"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_Switch_DisableRemoteRouter_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_Switch_DisableRemoteRouter_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ return nil
+}
+
+// RegisterSwitchHandlerFromEndpoint is same as RegisterSwitchHandler but
+// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
+func RegisterSwitchHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
+ conn, err := grpc.DialContext(ctx, endpoint, opts...)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ if cerr := conn.Close(); cerr != nil {
+ grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
+ }
+ return
+ }
+ go func() {
+ <-ctx.Done()
+ if cerr := conn.Close(); cerr != nil {
+ grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
+ }
+ }()
+ }()
+
+ return RegisterSwitchHandler(ctx, mux, conn)
+}
+
+// RegisterSwitchHandler registers the http handlers for service Switch to "mux".
+// The handlers forward requests to the grpc endpoint over "conn".
+func RegisterSwitchHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
+ return RegisterSwitchHandlerClient(ctx, mux, NewSwitchClient(conn))
+}
+
+// RegisterSwitchHandlerClient registers the http handlers for service Switch
+// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "SwitchClient".
+// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "SwitchClient"
+// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
+// "SwitchClient" to call the correct interceptors.
+func RegisterSwitchHandlerClient(ctx context.Context, mux *runtime.ServeMux, client SwitchClient) error {
+
+ mux.Handle("POST", pattern_Switch_SendOnion_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, "/switchrpc.Switch/SendOnion", runtime.WithHTTPPathPattern("/v2/switch/onion"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Switch_SendOnion_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Switch_SendOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_TrackOnion_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, "/switchrpc.Switch/TrackOnion", runtime.WithHTTPPathPattern("/v2/switch/track"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Switch_TrackOnion_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Switch_TrackOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_BuildOnion_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, "/switchrpc.Switch/BuildOnion", runtime.WithHTTPPathPattern("/v2/switch/build"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Switch_BuildOnion_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Switch_BuildOnion_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_DeleteAttempts_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, "/switchrpc.Switch/DeleteAttempts", runtime.WithHTTPPathPattern("/v2/switch/deleteattempts"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Switch_DeleteAttempts_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Switch_DeleteAttempts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ mux.Handle("POST", pattern_Switch_DisableRemoteRouter_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, "/switchrpc.Switch/DisableRemoteRouter", runtime.WithHTTPPathPattern("/v2/switch/disableremoterouter"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_Switch_DisableRemoteRouter_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+
+ forward_Switch_DisableRemoteRouter_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+
+ })
+
+ return nil
+}
+
+var (
+ pattern_Switch_SendOnion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "switch", "onion"}, ""))
+
+ pattern_Switch_TrackOnion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "switch", "track"}, ""))
+
+ pattern_Switch_BuildOnion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "switch", "build"}, ""))
+
+ pattern_Switch_DeleteAttempts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "switch", "deleteattempts"}, ""))
+
+ pattern_Switch_DisableRemoteRouter_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "switch", "disableremoterouter"}, ""))
+)
+
+var (
+ forward_Switch_SendOnion_0 = runtime.ForwardResponseMessage
+
+ forward_Switch_TrackOnion_0 = runtime.ForwardResponseMessage
+
+ forward_Switch_BuildOnion_0 = runtime.ForwardResponseMessage
+
+ forward_Switch_DeleteAttempts_0 = runtime.ForwardResponseMessage
+
+ forward_Switch_DisableRemoteRouter_0 = runtime.ForwardResponseMessage
+)
### lnrpc/switchrpc/switch.proto
@@ -0,0 +1,388 @@
+syntax = "proto3";
+
+package switchrpc;
+
+import "lightning.proto";
+
+option go_package = "github.com/lightningnetwork/lnd/lnrpc/switchrpc";
+
+// Switch is a service that offers advanced interaction with the HTLC fowarding
+// subsystem of the daemon.
+service Switch {
+ /*
+ SendOnion provides an idempotent API for dispatching a pre-formed onion
+ packet, which is the primary entry point for a remote router.
+
+ To safely handle network failures, a client can and should retry this RPC
+ after a timeout or disconnection. Retries MUST use the exact same
+ attempt_id to allow the server to correctly detect duplicate requests.
+
+ A client interacting with this RPC must handle four distinct categories
+ of outcomes, determined by the gRPC status code:
+
+ 1. SUCCESS (gRPC code OK): A definitive confirmation that the HTLC has
+ been successfully dispatched. The client can proceed to track the
+ payment's final result via the TrackOnion RPC.
+
+ 2. DUPLICATE ACKNOWLEDGMENT (gRPC code AlreadyExists): A definitive
+ acknowledgment that a request with the same attempt_id has already
+ been successfully processed. A retrying client should interpret this
+ as a success and proceed to tracking the payment's result.
+
+ 3. INDEFINITE FAILURE (gRPC code Unavailable or DeadlineExceeded): The
+ state of the HTLC dispatch is unknown. The client MUST retry the exact
+ same request to resolve the ambiguity. A client MUST NOT treat this as
+ a definitive failure and move on to a new attempt ID; doing so risks a
+ duplicate in-flight HTLC.
+
+ 4. DEFINITIVE FAILURE (gRPC code FailedPrecondition, InvalidArgument,
+ etc.): The HTLC was not and will not be dispatched. The client should
+ fail the attempt and may retry with a new route and/or attempt_id.
+
+ In the case of a FailedPrecondition or Unavailable failure, the gRPC
+ error may include a SendOnionFailureDetails message with additional
+ context for logging and pathfinding.
+ */
+ rpc SendOnion (SendOnionRequest) returns (SendOnionResponse);
+
+ /*
+ TrackOnion allows callers to query whether or not a payment dispatched via
+ SendOnion succeeded or failed.
+
+ This RPC is designed to be called after a successful dispatch has been
+ explicitly confirmed via the SendOnion RPC. It should not be used to
+ determine whether an HTLC dispatch was received in an ambiguous network
+ scenario. That ambiguity must be resolved by retrying the idempotent
+ SendOnion RPC until a definitive acknowledgement is received from the Switch
+ RPC server.
+
+ Once dispatch is confirmed, TrackOnion provides the mechanism to wait for
+ the result of the in-flight HTLC. A client must handle three distinct
+ categories of outcomes:
+
+ 1. PAYMENT SUCCESS (gRPC code OK, preimage set): The payment settled
+ successfully. The response contains the payment preimage.
+
+ 2. PAYMENT FAILURE (gRPC code OK, failure_details set): The payment failed
+ at the application level. The failure_details oneof describes the specific
+ failure type: a ForwardingFailure from a remote hop, a LocalFailure
+ from the local node, an UnreadableFailure if the error could not be
+ decoded, or a SwitchError for other switch-level failures. When
+ encrypted_error_data is populated, the client may perform its own
+ decryption.
+
+ 3. QUERY FAILURE (gRPC error status): The query itself could not be
+ completed. NotFound indicates the payment ID is unknown. Unavailable
+ signals the switch is shutting down. Canceled or DeadlineExceeded
+ reflects client-side timeouts. These are safe to retry.
+ */
+ rpc TrackOnion (TrackOnionRequest) returns (TrackOnionResponse);
+
+ /*
+ BuildOnion attempts to build an onion packet for the specified route.
+ */
+ rpc BuildOnion (BuildOnionRequest) returns (BuildOnionResponse);
+
+ /*
+ DeleteAttempts removes terminal (settled or failed) payment attempt records
+ from the server's attempt store. The client explicitly names the attempt
+ IDs to delete, enabling online garbage collection of completed attempt
+ data.
+
+ The server processes each attempt ID independently and reports per-ID
+ results. Pending (in-flight) attempts are never deleted; they are reported
+ with a DELETION_PENDING status. Unknown attempt IDs are reported with
+ DELETION_NOT_FOUND. Unprocessable records are reported with
+ DELETION_FAILED. The overall RPC succeeds (gRPC OK) as long as the
+ request could be processed, even if individual attempts were not deleted.
+
+ Clients MUST only delete attempts whose outcome (settled or failed) has
+ been durably recorded and will never need to be retried. Deleting an
+ attempt removes the server's idempotency protection for that attempt ID.
+ */
+ rpc DeleteAttempts (DeleteAttemptsRequest) returns (DeleteAttemptsResponse);
+
+ /*
+ DisableRemoteRouter marks the database as no longer being used by a remote
+ router. This is useful for migrating from a remote router setup back to the
+ default embedded router. This RPC will fail if there are any attempt entries
+ remaining in the network result store.
+ */
+ rpc DisableRemoteRouter (DisableRemoteRouterRequest)
+ returns (DisableRemoteRouterResponse);
+}
+
+message SendOnionRequest {
+ // The raw onion packet to be sent across the network.
+ bytes onion_blob = 1;
+
+ // The attempt ID uniquely identifying this payment attempt. The caller can
+ // expect to track results for the payment via this attempt ID.
+ uint64 attempt_id = 2;
+
+ // The first hop's public key where the onion will be sent.
+ // The first hop must be specified either by channel ID or public key.
+ bytes first_hop_pubkey = 3;
+
+ // The channel id of the channel that must be taken to the first hop.
+ // The first hop must be specified either by channel ID or public key.
+ uint64 first_hop_chan_id = 4;
+
+ // The total amount in millisatoshis required to complete a payment over
+ // this route. This value includes the cumulative fees at each hop. The HTLC
+ // extended to the first-hop in the route will need to have at least this
+ // many (milli)satoshis.
+ int64 amount = 5;
+
+ // The absolute timelock or CLTV value that should be extended to the first
+ // hop in the route. All other hops will decrement the time-lock as
+ // described by the onion.
+ uint32 timelock = 6;
+
+ // The payment hash associated with the HTLC. This is needed for tracking
+ // and debugging purposes.
+ bytes payment_hash = 7;
+
+ // The optional blinding point to use when constructing the HTLC.
+ // If set, this will be used to blind the next hop in the route.
+ optional bytes blinding_point = 8;
+
+ // Optional custom TLV records to include in the UpdateAddHTLC message.
+ map<uint64, bytes> custom_records = 9;
+
+ // Optional opaque extra data to attach to the UpdateAddHTLC message.
+ optional bytes extra_data = 10;
+}
+
+// SendOnionResponse is an empty message. A gRPC status of OK or AlreadyExists
+// indicates a successful dispatch acknowledgment.
+message SendOnionResponse {
+}
+
+// SendOnionFailureDetails provides structured details for a dispatch failure
+// and is attached to a FailedPrecondition or Unavailable gRPC status.
+message SendOnionFailureDetails {
+ // A human-readable message for logging and debugging.
+ string error_message = 1;
+
+ // Structured detail for the dispatch failure, grouped by outcome. The
+ // gRPC status code determines the client's primary action
+ // (FailedPrecondition = definitive failure, Unavailable = retry). The
+ // detail within provides context for logging, pathfinding, and forward
+ // compatibility.
+ oneof failure_class {
+ DefiniteFailure definite_failure = 2;
+ IndefiniteFailure indefinite_failure = 3;
+ }
+}
+
+// DefiniteFailure is a guarantee that the HTLC was not and will not be
+// dispatched. The client should fail the payment attempt and may retry with a
+// new route.
+message DefiniteFailure {
+ // A failure with a clear, unencrypted reason that occurred at our
+ // node before the HTLC was dispatched.
+ LocalFailure local_failure = 1;
+}
+
+// IndefiniteFailure indicates that the state of the HTLC dispatch is unknown.
+// This could be due to a transport-level failure or a server-side issue where
+// the idempotency record may or may not have been written. The client MUST
+// retry the exact same request to resolve the ambiguity. Clients can optionally
+// use this code to implement more nuanced behavior, such as logging or emitting
+// more detailed metrics.
+message IndefiniteFailure {
+ // A stable, machine-readable code for the indefinite failure.
+ IndefiniteFailureCode reason = 1;
+}
+
+// IndefiniteFailureCode provides the specific reason for an indefinite failure.
+enum IndefiniteFailureCode {
+ // The reason is unknown. This is the default and is used for failures
+ // where the server could not classify the error, such as bare gRPC
+ // transport errors observed by the client.
+ REASON_UNKNOWN = 0;
+
+ // The server is in the process of shutting down.
+ SWITCH_EXITING = 1;
+
+ // A critical failure occurred when the server attempted to write the
+ // idempotency record for the payment attempt.
+ HTLC_INIT_FAILED = 2;
+}
+
+message TrackOnionRequest {
+ // The payment hash associated with the HTLC. This is needed for tracking
+ // and debugging purposes.
+ bytes payment_hash = 1;
+
+ // The attempt ID uniquely identifying this payment attempt. The caller can
+ // expect to track results for the payment via this attempt ID.
+ uint64 attempt_id = 2;
+
+ // Optional: The session key that was used to construct the onion packet.
+ // This is required by the server to decrypt any failure message.
+ optional bytes session_key = 3;
+
+ // Optional: The public keys of the nodes in the route, used with the
+ // session_key to decrypt any failure message.
+ repeated bytes hop_pubkeys = 4;
+}
+
+message TrackOnionResponse {
+ // The final result of the payment attempt, which is either a preimage
+ // (success) or detailed failure information.
+ oneof result {
+ // The preimage obtained by making the payment. If this field is set,
+ // the payment succeeded.
+ bytes preimage = 1;
+
+ // The application-level failure for the payment attempt. If this field
+ // is set, the payment attempt failed.
+ FailureDetails failure_details = 2;
+ }
+}
+
+// FailureDetails provides structured information about why a payment attempt
+// failed on the network. This message is included in a successful
+// TrackOnionResponse when the queried attempt ultimately failed.
+message FailureDetails {
+ // A human-readable error_message for logging or display.
+ string error_message = 1;
+
+ // The failure contains specific, structured details about the error.
+ // Exactly one variant is set when this message is present.
+ oneof failure {
+ // local_failure is set when the failure originates at the local
+ // node (e.g. unable to forward due to insufficient balance,
+ // channel policy violations, or other link-level rejections). The
+ // wire message is available in plaintext without onion decryption.
+ LocalFailure local_failure = 2;
+
+ // forwarding_failure is set when the HTLC was forwarded into the
+ // network and a remote node returned an error. The onion error
+ // was successfully decrypted, yielding the failure source index.
+ // The wire_message may be empty if the inner failure could not
+ // be decoded.
+ ForwardingFailure forwarding_failure = 3;
+
+ // encrypted_error_data contains the raw onion-encrypted error
+ // blob. This is returned when no decryption keys were provided
+ // in the TrackOnionRequest (i.e. no session key or hop public
+ // keys), deferring decryption entirely to the client.
+ bytes encrypted_error_data = 4;
+
+ // unreadable_failure indicates that decryption keys were provided
+ // and decryption was attempted, but failed. The original error
+ // cannot be recovered.
+ UnreadableFailure unreadable_failure = 5;
+
+ // switch_error indicates an unexpected internal error that does
+ // not fall into any of the above categories.
+ SwitchError switch_error = 6;
+ }
+}
+
+// ForwardingFailure represents an HTLC failure that occurred at a remote node
+// in the payment route. The onion error was successfully decrypted, revealing
+// the failing hop.
+message ForwardingFailure {
+ // failure_source_index is the 0-based index of the node within the payment
+ // route that reported the failure. Index 0 refers to the local node.
+ uint32 failure_source_index = 1;
+
+ // The raw, serialized lnwire.FailureMessage reported by the failing node.
+ // This field may be empty if the failure message could not be decoded.
+ bytes wire_message = 2;
+}
+
+// LocalFailure represents a failure that originates at the local node. No
+// onion decryption is involved because the failure occurred before the HTLC
+// left our node.
+message LocalFailure {
+ // The raw, serialized `lnwire.FailureMessage`.
+ bytes wire_message = 1;
+}
+
+// SwitchError indicates that an error occurred within the switch subsystem.
+message SwitchError {
+}
+
+// UnreadableFailure indicates that decryption keys were provided and
+// decryption was attempted, but failed. The original failure information
+// cannot be recovered.
+message UnreadableFailure {
+}
+
+// BuildOnionRequest includes the necessary information to construct a Sphinx
+// onion packet.
+message BuildOnionRequest {
+ // The route for which the onion packet should be built.
+ lnrpc.Route route = 1;
+
+ // The payment hash associated with the HTLC.
+ bytes payment_hash = 2;
+
+ // A session key for onion packet construction, if not provided, a new one
+ // will be generated.
+ optional bytes session_key = 3;
+}
+
+// BuildOnionResponse contains the constructed onion packet.
+message BuildOnionResponse {
+ // The constructed onion packet in bytes.
+ bytes onion_blob = 1;
+
+ // The session key used for building the onion packet.
+ bytes session_key = 2;
+
+ // The serialized public keys of all nodes along the route for the
+ // constructed onion.
+ repeated bytes hop_pubkeys = 3;
+}
+
+message DeleteAttemptsRequest {
+ // The attempt IDs to delete from the server's attempt store. Only terminal
+ // (settled or failed) attempts will be deleted. Pending (in-flight)
+ // attempts are skipped and reported with a DELETION_PENDING status.
+ repeated uint64 attempt_ids = 1;
+}
+
+message DeleteAttemptsResponse {
+ // Per-attempt deletion outcomes. The order corresponds to the order of
+ // attempt_ids in the request.
+ repeated AttemptDeletionResult results = 1;
+}
+
+// AttemptDeletionResult reports the outcome of deleting a single attempt.
+message AttemptDeletionResult {
+ // The attempt ID this result corresponds to.
+ uint64 attempt_id = 1;
+
+ // The outcome of the deletion for this attempt.
+ AttemptDeletionStatus status = 2;
+}
+
+// AttemptDeletionStatus describes the outcome of a single attempt deletion.
+enum AttemptDeletionStatus {
+ // The attempt result was successfully deleted from the store.
+ DELETION_OK = 0;
+
+ // The attempt is still in-flight (pending) and cannot be safely deleted.
+ DELETION_PENDING = 1;
+
+ // The attempt ID was not found in the store. This may indicate a client
+ // bug (wrong ID, wrong backend) since the server has no record of this
+ // attempt ever existing.
+ DELETION_NOT_FOUND = 2;
+
+ // The attempt record exists but could not be processed (e.g.
+ // deserialization error). The record remains in the store.
+ DELETION_FAILED = 3;
+}
+
+message DisableRemoteRouterRequest {
+}
+
+message DisableRemoteRouterResponse {
+}
### lnrpc/switchrpc/switch.swagger.json
@@ -0,0 +1,654 @@
+{
+ "swagger": "2.0",
+ "info": {
+ "title": "switchrpc/switch.proto",
+ "version": "version not set"
+ },
+ "tags": [
+ {
+ "name": "Switch"
+ }
+ ],
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "paths": {
+ "/v2/switch/build": {
+ "post": {
+ "summary": "BuildOnion attempts to build an onion packet for the specified route.",
+ "operationId": "Switch_BuildOnion",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/switchrpcBuildOnionResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "description": "BuildOnionRequest includes the necessary information to construct a Sphinx\nonion packet.",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/switchrpcBuildOnionRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Switch"
+ ]
+ }
+ },
+ "/v2/switch/deleteattempts": {
+ "post": {
+ "summary": "DeleteAttempts removes terminal (settled or failed) payment attempt records\nfrom the server's attempt store. The client explicitly names the attempt\nIDs to delete, enabling online garbage collection of completed attempt\ndata.",
+ "description": "The server processes each attempt ID independently and reports per-ID\nresults. Pending (in-flight) attempts are never deleted; they are reported\nwith a DELETION_PENDING status. Unknown attempt IDs are reported with\nDELETION_NOT_FOUND. Unprocessable records are reported with\nDELETION_FAILED. The overall RPC succeeds (gRPC OK) as long as the\nrequest could be processed, even if individual attempts were not deleted.\n\nClients MUST only delete attempts whose outcome (settled or failed) has\nbeen durably recorded and will never need to be retried. Deleting an\nattempt removes the server's idempotency protection for that attempt ID.",
+ "operationId": "Switch_DeleteAttempts",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/switchrpcDeleteAttemptsResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/switchrpcDeleteAttemptsRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Switch"
+ ]
+ }
+ },
+ "/v2/switch/disableremoterouter": {
+ "post": {
+ "summary": "DisableRemoteRouter marks the database as no longer being used by a remote\nrouter. This is useful for migrating from a remote router setup back to the\ndefault embedded router. This RPC will fail if there are any attempt entries\nremaining in the network result store.",
+ "operationId": "Switch_DisableRemoteRouter",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/switchrpcDisableRemoteRouterResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/switchrpcDisableRemoteRouterRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Switch"
+ ]
+ }
+ },
+ "/v2/switch/onion": {
+ "post": {
+ "summary": "SendOnion provides an idempotent API for dispatching a pre-formed onion\npacket, which is the primary entry point for a remote router.",
+ "description": "To safely handle network failures, a client can and should retry this RPC\nafter a timeout or disconnection. Retries MUST use the exact same\nattempt_id to allow the server to correctly detect duplicate requests.\n\nA client interacting with this RPC must handle four distinct categories\nof outcomes, determined by the gRPC status code:\n\n1. SUCCESS (gRPC code OK): A definitive confirmation that the HTLC has\nbeen successfully dispatched. The client can proceed to track the\npayment's final result via the TrackOnion RPC.\n\n2. DUPLICATE ACKNOWLEDGMENT (gRPC code AlreadyExists): A definitive\nacknowledgment that a request with the same attempt_id has already\nbeen successfully processed. A retrying client should interpret this\nas a success and proceed to tracking the payment's result.\n\n3. INDEFINITE FAILURE (gRPC code Unavailable or DeadlineExceeded): The\nstate of the HTLC dispatch is unknown. The client MUST retry the exact\nsame request to resolve the ambiguity. A client MUST NOT treat this as\na definitive failure and move on to a new attempt ID; doing so risks a\nduplicate in-flight HTLC.\n\n4. DEFINITIVE FAILURE (gRPC code FailedPrecondition, InvalidArgument,\netc.): The HTLC was not and will not be dispatched. The client should\nfail the attempt and may retry with a new route and/or attempt_id.\n\nIn the case of a FailedPrecondition or Unavailable failure, the gRPC\nerror may include a SendOnionFailureDetails message with additional\ncontext for logging and pathfinding.",
+ "operationId": "Switch_SendOnion",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/switchrpcSendOnionResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/switchrpcSendOnionRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Switch"
+ ]
+ }
+ },
+ "/v2/switch/track": {
+ "post": {
+ "summary": "TrackOnion allows callers to query whether or not a payment dispatched via\nSendOnion succeeded or failed.",
+ "description": "This RPC is designed to be called after a successful dispatch has been\nexplicitly confirmed via the SendOnion RPC. It should not be used to\ndetermine whether an HTLC dispatch was received in an ambiguous network\nscenario. That ambiguity must be resolved by retrying the idempotent\nSendOnion RPC until a definitive acknowledgement is received from the Switch\nRPC server.\n\nOnce dispatch is confirmed, TrackOnion provides the mechanism to wait for\nthe result of the in-flight HTLC. A client must handle three distinct\ncategories of outcomes:\n\n1. PAYMENT SUCCESS (gRPC code OK, preimage set): The payment settled\nsuccessfully. The response contains the payment preimage.\n\n2. PAYMENT FAILURE (gRPC code OK, failure_details set): The payment failed\nat the application level. The failure_details oneof describes the specific\nfailure type: a ForwardingFailure from a remote hop, a LocalFailure\nfrom the local node, an UnreadableFailure if the error could not be\ndecoded, or a SwitchError for other switch-level failures. When\nencrypted_error_data is populated, the client may perform its own\ndecryption.\n\n3. QUERY FAILURE (gRPC error status): The query itself could not be\ncompleted. NotFound indicates the payment ID is unknown. Unavailable\nsignals the switch is shutting down. Canceled or DeadlineExceeded\nreflects client-side timeouts. These are safe to retry.",
+ "operationId": "Switch_TrackOnion",
+ "responses": {
+ "200": {
+ "description": "A successful response.",
+ "schema": {
+ "$ref": "#/definitions/switchrpcTrackOnionResponse"
+ }
+ },
+ "default": {
+ "description": "An unexpected error response.",
+ "schema": {
+ "$ref": "#/definitions/rpcStatus"
+ }
+ }
+ },
+ "parameters": [
+ {
+ "name": "body",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/switchrpcTrackOnionRequest"
+ }
+ }
+ ],
+ "tags": [
+ "Switch"
+ ]
+ }
+ }
+ },
+ "definitions": {
+ "lnrpcAMPRecord": {
+ "type": "object",
+ "properties": {
+ "root_share": {
+ "type": "string",
+ "format": "byte"
+ },
+ "set_id": {
+ "type": "string",
+ "format": "byte"
+ },
+ "child_index": {
+ "type": "integer",
+ "format": "int64"
+ }
+ }
+ },
+ "lnrpcHop": {
+ "type": "object",
+ "properties": {
+ "chan_id": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The unique channel ID for the channel. The first 3 bytes are the block\nheight, the next 3 the index within the block, and the last 2 bytes are the\noutput index for the channel."
+ },
+ "chan_capacity": {
+ "type": "string",
+ "format": "int64"
+ },
+ "amt_to_forward": {
+ "type": "string",
+ "format": "int64"
+ },
+ "fee": {
+ "type": "string",
+ "format": "int64"
+ },
+ "expiry": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "amt_to_forward_msat": {
+ "type": "string",
+ "format": "int64"
+ },
+ "fee_msat": {
+ "type": "string",
+ "format": "int64"
+ },
+ "pub_key": {
+ "type": "string",
+ "description": "An optional public key of the hop. If the public key is given, the payment\ncan be executed without relying on a copy of the channel graph."
+ },
+ "tlv_payload": {
+ "type": "boolean",
+ "description": "If set to true, then this hop will be encoded using the new variable length\nTLV format. Note that if any custom tlv_records below are specified, then\nthis field MUST be set to true for them to be encoded properly."
+ },
+ "mpp_record": {
+ "$ref": "#/definitions/lnrpcMPPRecord",
+ "description": "An optional TLV record that signals the use of an MPP payment. If present,\nthe receiver will enforce that the same mpp_record is included in the final\nhop payload of all non-zero payments in the HTLC set. If empty, a regular\nsingle-shot payment is or was attempted."
+ },
+ "amp_record": {
+ "$ref": "#/definitions/lnrpcAMPRecord",
+ "description": "An optional TLV record that signals the use of an AMP payment. If present,\nthe receiver will treat all received payments including the same\n(payment_addr, set_id) pair as being part of one logical payment. The\npayment will be settled by XORing the root_share's together and deriving the\nchild hashes and preimages according to BOLT XX. Must be used in conjunction\nwith mpp_record."
+ },
+ "custom_records": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string",
+ "format": "byte"
+ },
+ "description": "An optional set of key-value TLV records. This is useful within the context\nof the SendToRoute call as it allows callers to specify arbitrary K-V pairs\nto drop off at each hop within the onion."
+ },
+ "metadata": {
+ "type": "string",
+ "format": "byte",
+ "description": "The payment metadata to send along with the payment to the payee."
+ },
+ "blinding_point": {
+ "type": "string",
+ "format": "byte",
+ "description": "Blinding point is an optional blinding point included for introduction\nnodes in blinded paths. This field is mandatory for hops that represents\nthe introduction point in a blinded path."
+ },
+ "encrypted_data": {
+ "type": "string",
+ "format": "byte",
+ "description": "Encrypted data is a receiver-produced blob of data that provides hops\nin a blinded route with forwarding data. As this data is encrypted by\nthe recipient, we will not be able to parse it - it is essentially an\narbitrary blob of data from our node's perspective. This field is\nmandatory for all hops in a blinded path, including the introduction\nnode."
+ },
+ "total_amt_msat": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The total amount that is sent to the recipient (possibly across multiple\nHTLCs), as specified by the sender when making a payment to a blinded path.\nThis value is only set in the final hop payload of a blinded payment. This\nvalue is analogous to the MPPRecord that is used for regular (non-blinded)\nMPP payments."
+ }
+ }
+ },
+ "lnrpcMPPRecord": {
+ "type": "object",
+ "properties": {
+ "payment_addr": {
+ "type": "string",
+ "format": "byte",
+ "description": "A unique, random identifier used to authenticate the sender as the intended\npayer of a multi-path payment. The payment_addr must be the same for all\nsubpayments, and match the payment_addr provided in the receiver's invoice.\nThe same payment_addr must be used on all subpayments. This is also called\npayment secret in specifications (e.g. BOLT 11)."
+ },
+ "total_amt_msat": {
+ "type": "string",
+ "format": "int64",
+ "description": "The total amount in milli-satoshis being sent as part of a larger multi-path\npayment. The caller is responsible for ensuring subpayments to the same node\nand payment_hash sum exactly to total_amt_msat. The same\ntotal_amt_msat must be used on all subpayments."
+ }
+ }
+ },
+ "lnrpcRoute": {
+ "type": "object",
+ "properties": {
+ "total_time_lock": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The cumulative (final) time lock across the entire route. This is the CLTV\nvalue that should be extended to the first hop in the route. All other hops\nwill decrement the time-lock as advertised, leaving enough time for all\nhops to wait for or present the payment preimage to complete the payment."
+ },
+ "total_fees": {
+ "type": "string",
+ "format": "int64",
+ "description": "The sum of the fees paid at each hop within the final route. In the case\nof a one-hop payment, this value will be zero as we don't need to pay a fee\nto ourselves."
+ },
+ "total_amt": {
+ "type": "string",
+ "format": "int64",
+ "description": "The total amount of funds required to complete a payment over this route.\nThis value includes the cumulative fees at each hop. As a result, the HTLC\nextended to the first-hop in the route will need to have at least this many\nsatoshis, otherwise the route will fail at an intermediate node due to an\ninsufficient amount of fees."
+ },
+ "hops": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "$ref": "#/definitions/lnrpcHop"
+ },
+ "description": "Contains details concerning the specific forwarding details at each hop."
+ },
+ "total_fees_msat": {
+ "type": "string",
+ "format": "int64",
+ "description": "The total fees in millisatoshis."
+ },
+ "total_amt_msat": {
+ "type": "string",
+ "format": "int64",
+ "description": "The total amount in millisatoshis."
+ },
+ "first_hop_amount_msat": {
+ "type": "string",
+ "format": "int64",
+ "description": "The actual on-chain amount that was sent out to the first hop. This value is\nonly different from the total_amt_msat field if this is a custom channel\npayment and the value transported in the HTLC is different from the BTC\namount in the HTLC. If this value is zero, then this is an old payment that\ndidn't have this value yet and can be ignored."
+ },
+ "custom_channel_data": {
+ "type": "string",
+ "format": "byte",
+ "description": "Custom channel data that might be populated in custom channels."
+ },
+ "source_pub_key": {
+ "type": "string",
+ "description": "The source node from whose perspective the route was built. Defaults to\nthe node's own public key."
+ }
+ },
+ "description": "A path through the channel graph which runs over one or more channels in\nsuccession. This struct carries all the information required to craft the\nSphinx onion packet, and send the payment along the first hop in the path. A\nroute is only selected as valid if all the channels have sufficient capacity to\ncarry the initial payment amount after fees are accounted for."
+ },
+ "protobufAny": {
+ "type": "object",
+ "properties": {
+ "@type": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": {}
+ },
+ "rpcStatus": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "message": {
+ "type": "string"
+ },
+ "details": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "$ref": "#/definitions/protobufAny"
+ }
+ }
+ }
+ },
+ "switchrpcAttemptDeletionResult": {
+ "type": "object",
+ "properties": {
+ "attempt_id": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The attempt ID this result corresponds to."
+ },
+ "status": {
+ "$ref": "#/definitions/switchrpcAttemptDeletionStatus",
+ "description": "The outcome of the deletion for this attempt."
+ }
+ },
+ "description": "AttemptDeletionResult reports the outcome of deleting a single attempt."
+ },
+ "switchrpcAttemptDeletionStatus": {
+ "type": "string",
+ "enum": [
+ "DELETION_OK",
+ "DELETION_PENDING",
+ "DELETION_NOT_FOUND",
+ "DELETION_FAILED"
+ ],
+ "default": "DELETION_OK",
+ "description": "AttemptDeletionStatus describes the outcome of a single attempt deletion.\n\n - DELETION_OK: The attempt result was successfully deleted from the store.\n - DELETION_PENDING: The attempt is still in-flight (pending) and cannot be safely deleted.\n - DELETION_NOT_FOUND: The attempt ID was not found in the store. This may indicate a client\nbug (wrong ID, wrong backend) since the server has no record of this\nattempt ever existing.\n - DELETION_FAILED: The attempt record exists but could not be processed (e.g.\ndeserialization error). The record remains in the store."
+ },
+ "switchrpcBuildOnionRequest": {
+ "type": "object",
+ "properties": {
+ "route": {
+ "$ref": "#/definitions/lnrpcRoute",
+ "description": "The route for which the onion packet should be built."
+ },
+ "payment_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The payment hash associated with the HTLC."
+ },
+ "session_key": {
+ "type": "string",
+ "format": "byte",
+ "description": "A session key for onion packet construction, if not provided, a new one\nwill be generated."
+ }
+ },
+ "description": "BuildOnionRequest includes the necessary information to construct a Sphinx\nonion packet."
+ },
+ "switchrpcBuildOnionResponse": {
+ "type": "object",
+ "properties": {
+ "onion_blob": {
+ "type": "string",
+ "format": "byte",
+ "description": "The constructed onion packet in bytes."
+ },
+ "session_key": {
+ "type": "string",
+ "format": "byte",
+ "description": "The session key used for building the onion packet."
+ },
+ "hop_pubkeys": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "byte"
+ },
+ "description": "The serialized public keys of all nodes along the route for the\nconstructed onion."
+ }
+ },
+ "description": "BuildOnionResponse contains the constructed onion packet."
+ },
+ "switchrpcDeleteAttemptsRequest": {
+ "type": "object",
+ "properties": {
+ "attempt_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uint64"
+ },
+ "description": "The attempt IDs to delete from the server's attempt store. Only terminal\n(settled or failed) attempts will be deleted. Pending (in-flight)\nattempts are skipped and reported with a DELETION_PENDING status."
+ }
+ }
+ },
+ "switchrpcDeleteAttemptsResponse": {
+ "type": "object",
+ "properties": {
+ "results": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "$ref": "#/definitions/switchrpcAttemptDeletionResult"
+ },
+ "description": "Per-attempt deletion outcomes. The order corresponds to the order of\nattempt_ids in the request."
+ }
+ }
+ },
+ "switchrpcDisableRemoteRouterRequest": {
+ "type": "object"
+ },
+ "switchrpcDisableRemoteRouterResponse": {
+ "type": "object"
+ },
+ "switchrpcFailureDetails": {
+ "type": "object",
+ "properties": {
+ "error_message": {
+ "type": "string",
+ "description": "A human-readable error_message for logging or display."
+ },
+ "local_failure": {
+ "$ref": "#/definitions/switchrpcLocalFailure",
+ "description": "local_failure is set when the failure originates at the local\nnode (e.g. unable to forward due to insufficient balance,\nchannel policy violations, or other link-level rejections). The\nwire message is available in plaintext without onion decryption."
+ },
+ "forwarding_failure": {
+ "$ref": "#/definitions/switchrpcForwardingFailure",
+ "description": "forwarding_failure is set when the HTLC was forwarded into the\nnetwork and a remote node returned an error. The onion error\nwas successfully decrypted, yielding the failure source index.\nThe wire_message may be empty if the inner failure could not\nbe decoded."
+ },
+ "encrypted_error_data": {
+ "type": "string",
+ "format": "byte",
+ "description": "encrypted_error_data contains the raw onion-encrypted error\nblob. This is returned when no decryption keys were provided\nin the TrackOnionRequest (i.e. no session key or hop public\nkeys), deferring decryption entirely to the client."
+ },
+ "unreadable_failure": {
+ "$ref": "#/definitions/switchrpcUnreadableFailure",
+ "description": "unreadable_failure indicates that decryption keys were provided\nand decryption was attempted, but failed. The original error\ncannot be recovered."
+ },
+ "switch_error": {
+ "$ref": "#/definitions/switchrpcSwitchError",
+ "description": "switch_error indicates an unexpected internal error that does\nnot fall into any of the above categories."
+ }
+ },
+ "description": "FailureDetails provides structured information about why a payment attempt\nfailed on the network. This message is included in a successful\nTrackOnionResponse when the queried attempt ultimately failed."
+ },
+ "switchrpcForwardingFailure": {
+ "type": "object",
+ "properties": {
+ "failure_source_index": {
+ "type": "integer",
+ "format": "int64",
+ "description": "failure_source_index is the 0-based index of the node within the payment\nroute that reported the failure. Index 0 refers to the local node."
+ },
+ "wire_message": {
+ "type": "string",
+ "format": "byte",
+ "description": "The raw, serialized lnwire.FailureMessage reported by the failing node.\nThis field may be empty if the failure message could not be decoded."
+ }
+ },
+ "description": "ForwardingFailure represents an HTLC failure that occurred at a remote node\nin the payment route. The onion error was successfully decrypted, revealing\nthe failing hop."
+ },
+ "switchrpcLocalFailure": {
+ "type": "object",
+ "properties": {
+ "wire_message": {
+ "type": "string",
+ "format": "byte",
+ "description": "The raw, serialized `lnwire.FailureMessage`."
+ }
+ },
+ "description": "LocalFailure represents a failure that originates at the local node. No\nonion decryption is involved because the failure occurred before the HTLC\nleft our node."
+ },
+ "switchrpcSendOnionRequest": {
+ "type": "object",
+ "properties": {
+ "onion_blob": {
+ "type": "string",
+ "format": "byte",
+ "description": "The raw onion packet to be sent across the network."
+ },
+ "attempt_id": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The attempt ID uniquely identifying this payment attempt. The caller can\nexpect to track results for the payment via this attempt ID."
+ },
+ "first_hop_pubkey": {
+ "type": "string",
+ "format": "byte",
+ "description": "The first hop's public key where the onion will be sent.\nThe first hop must be specified either by channel ID or public key."
+ },
+ "first_hop_chan_id": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The channel id of the channel that must be taken to the first hop.\nThe first hop must be specified either by channel ID or public key."
+ },
+ "amount": {
+ "type": "string",
+ "format": "int64",
+ "description": "The total amount in millisatoshis required to complete a payment over\nthis route. This value includes the cumulative fees at each hop. The HTLC\nextended to the first-hop in the route will need to have at least this\nmany (milli)satoshis."
+ },
+ "timelock": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The absolute timelock or CLTV value that should be extended to the first\nhop in the route. All other hops will decrement the time-lock as\ndescribed by the onion."
+ },
+ "payment_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The payment hash associated with the HTLC. This is needed for tracking\nand debugging purposes."
+ },
+ "blinding_point": {
+ "type": "string",
+ "format": "byte",
+ "description": "The optional blinding point to use when constructing the HTLC.\nIf set, this will be used to blind the next hop in the route."
+ },
+ "custom_records": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string",
+ "format": "byte"
+ },
+ "description": "Optional custom TLV records to include in the UpdateAddHTLC message."
+ },
+ "extra_data": {
+ "type": "string",
+ "format": "byte",
+ "description": "Optional opaque extra data to attach to the UpdateAddHTLC message."
+ }
+ }
+ },
+ "switchrpcSendOnionResponse": {
+ "type": "object",
+ "description": "SendOnionResponse is an empty message. A gRPC status of OK or AlreadyExists\nindicates a successful dispatch acknowledgment."
+ },
+ "switchrpcSwitchError": {
+ "type": "object",
+ "description": "SwitchError indicates that an error occurred within the switch subsystem."
+ },
+ "switchrpcTrackOnionRequest": {
+ "type": "object",
+ "properties": {
+ "payment_hash": {
+ "type": "string",
+ "format": "byte",
+ "description": "The payment hash associated with the HTLC. This is needed for tracking\nand debugging purposes."
+ },
+ "attempt_id": {
+ "type": "string",
+ "format": "uint64",
+ "description": "The attempt ID uniquely identifying this payment attempt. The caller can\nexpect to track results for the payment via this attempt ID."
+ },
+ "session_key": {
+ "type": "string",
+ "format": "byte",
+ "description": "Optional: The session key that was used to construct the onion packet.\nThis is required by the server to decrypt any failure message."
+ },
+ "hop_pubkeys": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "byte"
+ },
+ "description": "Optional: The public keys of the nodes in the route, used with the\nsession_key to decrypt any failure message."
+ }
+ }
+ },
+ "switchrpcTrackOnionResponse": {
+ "type": "object",
+ "properties": {
+ "preimage": {
+ "type": "string",
+ "format": "byte",
+ "description": "The preimage obtained by making the payment. If this field is set,\nthe payment succeeded."
+ },
+ "failure_details": {
+ "$ref": "#/definitions/switchrpcFailureDetails",
+ "description": "The application-level failure for the payment attempt. If this field\nis set, the payment attempt failed."
+ }
+ }
+ },
+ "switchrpcUnreadableFailure": {
+ "type": "object",
+ "description": "UnreadableFailure indicates that decryption keys were provided and\ndecryption was attempted, but failed. The original failure information\ncannot be recovered."
+ }
+ }
+}
### lnrpc/switchrpc/switch.yaml
@@ -0,0 +1,20 @@
+type: google.api.Service
+config_version: 3
+
+http:
+ rules:
+ - selector: switchrpc.Switch.SendOnion
+ post: "/v2/switch/onion"
+ body: "*"
+ - selector: switchrpc.Switch.TrackOnion
+ post: "/v2/switch/track"
+ body: "*"
+ - selector: switchrpc.Switch.BuildOnion
+ post: "/v2/switch/build"
+ body: "*"
+ - selector: switchrpc.Switch.DeleteAttempts
+ post: "/v2/switch/deleteattempts"
+ body: "*"
+ - selector: switchrpc.Switch.DisableRemoteRouter
+ post: "/v2/switch/disableremoterouter"
+ body: "*"
### lnrpc/switchrpc/switch_grpc.pb.go
@@ -0,0 +1,417 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+
+package switchrpc
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.32.0 or later.
+const _ = grpc.SupportPackageIsVersion7
+
+// SwitchClient is the client API for Switch service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type SwitchClient interface {
+ //
+ //SendOnion provides an idempotent API for dispatching a pre-formed onion
+ //packet, which is the primary entry point for a remote router.
+ //
+ //To safely handle network failures, a client can and should retry this RPC
+ //after a timeout or disconnection. Retries MUST use the exact same
+ //attempt_id to allow the server to correctly detect duplicate requests.
+ //
+ //A client interacting with this RPC must handle four distinct categories
+ //of outcomes, determined by the gRPC status code:
+ //
+ //1. SUCCESS (gRPC code OK): A definitive confirmation that the HTLC has
+ //been successfully dispatched. The client can proceed to track the
+ //payment's final result via the TrackOnion RPC.
+ //
+ //2. DUPLICATE ACKNOWLEDGMENT (gRPC code AlreadyExists): A definitive
+ //acknowledgment that a request with the same attempt_id has already
+ //been successfully processed. A retrying client should interpret this
+ //as a success and proceed to tracking the payment's result.
+ //
+ //3. INDEFINITE FAILURE (gRPC code Unavailable or DeadlineExceeded): The
+ //state of the HTLC dispatch is unknown. The client MUST retry the exact
+ //same request to resolve the ambiguity. A client MUST NOT treat this as
+ //a definitive failure and move on to a new attempt ID; doing so risks a
+ //duplicate in-flight HTLC.
+ //
+ //4. DEFINITIVE FAILURE (gRPC code FailedPrecondition, InvalidArgument,
+ //etc.): The HTLC was not and will not be dispatched. The client should
+ //fail the attempt and may retry with a new route and/or attempt_id.
+ //
+ //In the case of a FailedPrecondition or Unavailable failure, the gRPC
+ //error may include a SendOnionFailureDetails message with additional
+ //context for logging and pathfinding.
+ SendOnion(ctx context.Context, in *SendOnionRequest, opts ...grpc.CallOption) (*SendOnionResponse, error)
+ //
+ //TrackOnion allows callers to query whether or not a payment dispatched via
+ //SendOnion succeeded or failed.
+ //
+ //This RPC is designed to be called after a successful dispatch has been
+ //explicitly confirmed via the SendOnion RPC. It should not be used to
+ //determine whether an HTLC dispatch was received in an ambiguous network
+ //scenario. That ambiguity must be resolved by retrying the idempotent
+ //SendOnion RPC until a definitive acknowledgement is received from the Switch
+ //RPC server.
+ //
+ //Once dispatch is confirmed, TrackOnion provides the mechanism to wait for
+ //the result of the in-flight HTLC. A client must handle three distinct
+ //categories of outcomes:
+ //
+ //1. PAYMENT SUCCESS (gRPC code OK, preimage set): The payment settled
+ //successfully. The response contains the payment preimage.
+ //
+ //2. PAYMENT FAILURE (gRPC code OK, failure_details set): The payment failed
+ //at the application level. The failure_details oneof describes the specific
+ //failure type: a ForwardingFailure from a remote hop, a LocalFailure
+ //from the local node, an UnreadableFailure if the error could not be
+ //decoded, or a SwitchError for other switch-level failures. When
+ //encrypted_error_data is populated, the client may perform its own
+ //decryption.
+ //
+ //3. QUERY FAILURE (gRPC error status): The query itself could not be
+ //completed. NotFound indicates the payment ID is unknown. Unavailable
+ //signals the switch is shutting down. Canceled or DeadlineExceeded
+ //reflects client-side timeouts. These are safe to retry.
+ TrackOnion(ctx context.Context, in *TrackOnionRequest, opts ...grpc.CallOption) (*TrackOnionResponse, error)
+ //
+ //BuildOnion attempts to build an onion packet for the specified route.
+ BuildOnion(ctx context.Context, in *BuildOnionRequest, opts ...grpc.CallOption) (*BuildOnionResponse, error)
+ //
+ //DeleteAttempts removes terminal (settled or failed) payment attempt records
+ //from the server's attempt store. The client explicitly names the attempt
+ //IDs to delete, enabling online garbage collection of completed attempt
+ //data.
+ //
+ //The server processes each attempt ID independently and reports per-ID
+ //results. Pending (in-flight) attempts are never deleted; they are reported
+ //with a DELETION_PENDING status. Unknown attempt IDs are reported with
+ //DELETION_NOT_FOUND. Unprocessable records are reported with
+ //DELETION_FAILED. The overall RPC succeeds (gRPC OK) as long as the
+ //request could be processed, even if individual attempts were not deleted.
+ //
+ //Clients MUST only delete attempts whose outcome (settled or failed) has
+ //been durably recorded and will never need to be retried. Deleting an
+ //attempt removes the server's idempotency protection for that attempt ID.
+ DeleteAttempts(ctx context.Context, in *DeleteAttemptsRequest, opts ...grpc.CallOption) (*DeleteAttemptsResponse, error)
+ //
+ //DisableRemoteRouter marks the database as no longer being used by a remote
+ //router. This is useful for migrating from a remote router setup back to the
+ //default embedded router. This RPC will fail if there are any attempt entries
+ //remaining in the network result store.
+ DisableRemoteRouter(ctx context.Context, in *DisableRemoteRouterRequest, opts ...grpc.CallOption) (*DisableRemoteRouterResponse, error)
+}
+
+type switchClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewSwitchClient(cc grpc.ClientConnInterface) SwitchClient {
+ return &switchClient{cc}
+}
+
+func (c *switchClient) SendOnion(ctx context.Context, in *SendOnionRequest, opts ...grpc.CallOption) (*SendOnionResponse, error) {
+ out := new(SendOnionResponse)
+ err := c.cc.Invoke(ctx, "/switchrpc.Switch/SendOnion", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *switchClient) TrackOnion(ctx context.Context, in *TrackOnionRequest, opts ...grpc.CallOption) (*TrackOnionResponse, error) {
+ out := new(TrackOnionResponse)
+ err := c.cc.Invoke(ctx, "/switchrpc.Switch/TrackOnion", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *switchClient) BuildOnion(ctx context.Context, in *BuildOnionRequest, opts ...grpc.CallOption) (*BuildOnionResponse, error) {
+ out := new(BuildOnionResponse)
+ err := c.cc.Invoke(ctx, "/switchrpc.Switch/BuildOnion", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *switchClient) DeleteAttempts(ctx context.Context, in *DeleteAttemptsRequest, opts ...grpc.CallOption) (*DeleteAttemptsResponse, error) {
+ out := new(DeleteAttemptsResponse)
+ err := c.cc.Invoke(ctx, "/switchrpc.Switch/DeleteAttempts", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *switchClient) DisableRemoteRouter(ctx context.Context, in *DisableRemoteRouterRequest, opts ...grpc.CallOption) (*DisableRemoteRouterResponse, error) {
+ out := new(DisableRemoteRouterResponse)
+ err := c.cc.Invoke(ctx, "/switchrpc.Switch/DisableRemoteRouter", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// SwitchServer is the server API for Switch service.
+// All implementations must embed UnimplementedSwitchServer
+// for forward compatibility
+type SwitchServer interface {
+ //
+ //SendOnion provides an idempotent API for dispatching a pre-formed onion
+ //packet, which is the primary entry point for a remote router.
+ //
+ //To safely handle network failures, a client can and should retry this RPC
+ //after a timeout or disconnection. Retries MUST use the exact same
+ //attempt_id to allow the server to correctly detect duplicate requests.
+ //
+ //A client interacting with this RPC must handle four distinct categories
+ //of outcomes, determined by the gRPC status code:
+ //
+ //1. SUCCESS (gRPC code OK): A definitive confirmation that the HTLC has
+ //been successfully dispatched. The client can proceed to track the
+ //payment's final result via the TrackOnion RPC.
+ //
+ //2. DUPLICATE ACKNOWLEDGMENT (gRPC code AlreadyExists): A definitive
+ //acknowledgment that a request with the same attempt_id has already
+ //been successfully processed. A retrying client should interpret this
+ //as a success and proceed to tracking the payment's result.
+ //
+ //3. INDEFINITE FAILURE (gRPC code Unavailable or DeadlineExceeded): The
+ //state of the HTLC dispatch is unknown. The client MUST retry the exact
+ //same request to resolve the ambiguity. A client MUST NOT treat this as
+ //a definitive failure and move on to a new attempt ID; doing so risks a
+ //duplicate in-flight HTLC.
+ //
+ //4. DEFINITIVE FAILURE (gRPC code FailedPrecondition, InvalidArgument,
+ //etc.): The HTLC was not and will not be dispatched. The client should
+ //fail the attempt and may retry with a new route and/or attempt_id.
+ //
+ //In the case of a FailedPrecondition or Unavailable failure, the gRPC
+ //error may include a SendOnionFailureDetails message with additional
+ //context for logging and pathfinding.
+ SendOnion(context.Context, *SendOnionRequest) (*SendOnionResponse, error)
+ //
+ //TrackOnion allows callers to query whether or not a payment dispatched via
+ //SendOnion succeeded or failed.
+ //
+ //This RPC is designed to be called after a successful dispatch has been
+ //explicitly confirmed via the SendOnion RPC. It should not be used to
+ //determine whether an HTLC dispatch was received in an ambiguous network
+ //scenario. That ambiguity must be resolved by retrying the idempotent
+ //SendOnion RPC until a definitive acknowledgement is received from the Switch
+ //RPC server.
+ //
+ //Once dispatch is confirmed, TrackOnion provides the mechanism to wait for
+ //the result of the in-flight HTLC. A client must handle three distinct
+ //categories of outcomes:
+ //
+ //1. PAYMENT SUCCESS (gRPC code OK, preimage set): The payment settled
+ //successfully. The response contains the payment preimage.
+ //
+ //2. PAYMENT FAILURE (gRPC code OK, failure_details set): The payment failed
+ //at the application level. The failure_details oneof describes the specific
+ //failure type: a ForwardingFailure from a remote hop, a LocalFailure
+ //from the local node, an UnreadableFailure if the error could not be
+ //decoded, or a SwitchError for other switch-level failures. When
+ //encrypted_error_data is populated, the client may perform its own
+ //decryption.
+ //
+ //3. QUERY FAILURE (gRPC error status): The query itself could not be
+ //completed. NotFound indicates the payment ID is unknown. Unavailable
+ //signals the switch is shutting down. Canceled or DeadlineExceeded
+ //reflects client-side timeouts. These are safe to retry.
+ TrackOnion(context.Context, *TrackOnionRequest) (*TrackOnionResponse, error)
+ //
+ //BuildOnion attempts to build an onion packet for the specified route.
+ BuildOnion(context.Context, *BuildOnionRequest) (*BuildOnionResponse, error)
+ //
+ //DeleteAttempts removes terminal (settled or failed) payment attempt records
+ //from the server's attempt store. The client explicitly names the attempt
+ //IDs to delete, enabling online garbage collection of completed attempt
+ //data.
+ //
+ //The server processes each attempt ID independently and reports per-ID
+ //results. Pending (in-flight) attempts are never deleted; they are reported
+ //with a DELETION_PENDING status. Unknown attempt IDs are reported with
+ //DELETION_NOT_FOUND. Unprocessable records are reported with
+ //DELETION_FAILED. The overall RPC succeeds (gRPC OK) as long as the
+ //request could be processed, even if individual attempts were not deleted.
+ //
+ //Clients MUST only delete attempts whose outcome (settled or failed) has
+ //been durably recorded and will never need to be retried. Deleting an
+ //attempt removes the server's idempotency protection for that attempt ID.
+ DeleteAttempts(context.Context, *DeleteAttemptsRequest) (*DeleteAttemptsResponse, error)
+ //
+ //DisableRemoteRouter marks the database as no longer being used by a remote
+ //router. This is useful for migrating from a remote router setup back to the
+ //default embedded router. This RPC will fail if there are any attempt entries
+ //remaining in the network result store.
+ DisableRemoteRouter(context.Context, *DisableRemoteRouterRequest) (*DisableRemoteRouterResponse, error)
+ mustEmbedUnimplementedSwitchServer()
+}
+
+// UnimplementedSwitchServer must be embedded to have forward compatible implementations.
+type UnimplementedSwitchServer struct {
+}
+
+func (UnimplementedSwitchServer) SendOnion(context.Context, *SendOnionRequest) (*SendOnionResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method SendOnion not implemented")
+}
+func (UnimplementedSwitchServer) TrackOnion(context.Context, *TrackOnionRequest) (*TrackOnionResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method TrackOnion not implemented")
+}
+func (UnimplementedSwitchServer) BuildOnion(context.Context, *BuildOnionRequest) (*BuildOnionResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method BuildOnion not implemented")
+}
+func (UnimplementedSwitchServer) DeleteAttempts(context.Context, *DeleteAttemptsRequest) (*DeleteAttemptsResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method DeleteAttempts not implemented")
+}
+func (UnimplementedSwitchServer) DisableRemoteRouter(context.Context, *DisableRemoteRouterRequest) (*DisableRemoteRouterResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method DisableRemoteRouter not implemented")
+}
+func (UnimplementedSwitchServer) mustEmbedUnimplementedSwitchServer() {}
+
+// UnsafeSwitchServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to SwitchServer will
+// result in compilation errors.
+type UnsafeSwitchServer interface {
+ mustEmbedUnimplementedSwitchServer()
+}
+
+func RegisterSwitchServer(s grpc.ServiceRegistrar, srv SwitchServer) {
+ s.RegisterService(&Switch_ServiceDesc, srv)
+}
+
+func _Switch_SendOnion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SendOnionRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SwitchServer).SendOnion(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/switchrpc.Switch/SendOnion",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SwitchServer).SendOnion(ctx, req.(*SendOnionRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Switch_TrackOnion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(TrackOnionRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SwitchServer).TrackOnion(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/switchrpc.Switch/TrackOnion",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SwitchServer).TrackOnion(ctx, req.(*TrackOnionRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Switch_BuildOnion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(BuildOnionRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SwitchServer).BuildOnion(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/switchrpc.Switch/BuildOnion",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SwitchServer).BuildOnion(ctx, req.(*BuildOnionRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Switch_DeleteAttempts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DeleteAttemptsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SwitchServer).DeleteAttempts(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/switchrpc.Switch/DeleteAttempts",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SwitchServer).DeleteAttempts(ctx, req.(*DeleteAttemptsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Switch_DisableRemoteRouter_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DisableRemoteRouterRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SwitchServer).DisableRemoteRouter(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/switchrpc.Switch/DisableRemoteRouter",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SwitchServer).DisableRemoteRouter(ctx, req.(*DisableRemoteRouterRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+// Switch_ServiceDesc is the grpc.ServiceDesc for Switch service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var Switch_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "switchrpc.Switch",
+ HandlerType: (*SwitchServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "SendOnion",
+ Handler: _Switch_SendOnion_Handler,
+ },
+ {
+ MethodName: "TrackOnion",
+ Handler: _Switch_TrackOnion_Handler,
+ },
+ {
+ MethodName: "BuildOnion",
+ Handler: _Switch_BuildOnion_Handler,
+ },
+ {
+ MethodName: "DeleteAttempts",
+ Handler: _Switch_DeleteAttempts_Handler,
+ },
+ {
+ MethodName: "DisableRemoteRouter",
+ Handler: _Switch_DisableRemoteRouter_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "switchrpc/switch.proto",
+}
### lnrpc/switchrpc/switch_server.go
@@ -0,0 +1,1227 @@
+//go:build switchrpc
+// +build switchrpc
+
+package switchrpc
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "math/big"
+ "os"
+ "path/filepath"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
+ sphinx "github.com/lightningnetwork/lightning-onion"
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/macaroons"
+ paymentsdb "github.com/lightningnetwork/lnd/payments/db"
+ "github.com/lightningnetwork/lnd/routing"
+ "github.com/lightningnetwork/lnd/tlv"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+ "gopkg.in/macaroon-bakery.v2/bakery"
+)
+
+const (
+ // subServerName is the name of the sub rpc server. We'll use this name
+ // to register ourselves, and we also require that the main
+ // SubServerConfigDispatcher instance recognize it as the name of our
+ // RPC service.
+ subServerName = "SwitchRPC"
+)
+
+var (
+ // macaroonOps are the set of capabilities that our minted macaroon (if
+ // it doesn't already exist) will have.
+ macaroonOps = []bakery.Op{
+ {
+ Entity: "offchain",
+ Action: "read",
+ },
+ {
+ Entity: "offchain",
+ Action: "write",
+ },
+ }
+
+ // macPermissions maps RPC calls to the permissions they require.
+ macPermissions = map[string][]bakery.Op{
+ "/switchrpc.Switch/SendOnion": {{
+ Entity: "offchain",
+ Action: "write",
+ }},
+ "/switchrpc.Switch/TrackOnion": {{
+ Entity: "offchain",
+ Action: "read",
+ }},
+ "/switchrpc.Switch/BuildOnion": {{
+ Entity: "offchain",
+ Action: "read",
+ }},
+ "/switchrpc.Switch/DeleteAttempts": {{
+ Entity: "offchain",
+ Action: "write",
+ }},
+ "/switchrpc.Switch/DisableRemoteRouter": {{
+ Entity: "offchain",
+ Action: "write",
+ }},
+ }
+
+ // DefaultSwitchMacFilename is the default name of the switch macaroon
+ // that we expect to find via a file handle within the main
+ // configuration file in this package.
+ DefaultSwitchMacFilename = "switch.macaroon"
+
+ // ErrAmbiguousPaymentState is an error returned when a payment attempt
+ // completes in an ambiguous state: no error and no valid preimage.
+ ErrAmbiguousPaymentState = errors.New("payment completed in an " +
+ "ambiguous state: no error and no valid preimage")
+)
+
+// ServerShell is a shell struct holding a reference to the actual sub-server.
+// It is used to register the gRPC sub-server with the root server before we
+// have the necessary dependencies to populate the actual sub-server.
+type ServerShell struct {
+ SwitchServer
+}
+
+// Server is a stand-alone sub RPC server which exposes functionality that
+// allows clients to dispatch htlc attempts through the Lightning Network.
+type Server struct {
+ cfg *Config
+
+ // Required by the grpc-gateway/v2 library for forward compatibility.
+ // Must be after the atomically used variables to not break struct
+ // alignment.
+ UnimplementedSwitchServer
+}
+
+var _ SwitchServer = (*Server)(nil)
+
+// New creates a new instance of the SwitchServer given a configuration struct
+// that contains all external dependencies. If the target macaroon exists, and
+// we're unable to create it, then an error will be returned. We also return
+// the set of permissions that we require as a server. At the time of writing
+// of this documentation, this is the same macaroon as the admin macaroon.
+func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
+ // If the path of the switch macaroon wasn't generated, then we'll
+ // assume that it's found at the default network directory.
+ if cfg.SwitchMacPath == "" {
+ cfg.SwitchMacPath = filepath.Join(
+ cfg.NetworkDir, DefaultSwitchMacFilename,
+ )
+ }
+
+ // Now that we know the full path of the switch macaroon, we can check
+ // to see if we need to create it or not. If stateless_init is set
+ // then we don't write the macaroons.
+ macFilePath := cfg.SwitchMacPath
+ if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
+ !lnrpc.FileExists(macFilePath) {
+
+ log.Infof("Making macaroons for Switch RPC Server at: %v",
+ macFilePath)
+
+ // At this point, we know that the switch macaroon doesn't yet,
+ // exist, so we need to create it with the help of the main
+ // macaroon service.
+ switchMac, err := cfg.MacService.NewMacaroon(
+ context.TODO(), macaroons.DefaultRootKeyID,
+ macaroonOps...,
+ )
+ if err != nil {
+ return nil, nil, err
+ }
+ switchMacBytes, err := switchMac.M().MarshalBinary()
+ if err != nil {
+ return nil, nil, err
+ }
+ err = os.WriteFile(macFilePath, switchMacBytes, 0644)
+ if err != nil {
+ _ = os.Remove(macFilePath)
+ return nil, nil, err
+ }
+ }
+
+ switchServer := &Server{
+ cfg: cfg,
+ }
+
+ return switchServer, macPermissions, nil
+}
+
+// Start launches any helper goroutines required for the Server to function.
+//
+// NOTE: This is part of the lnrpc.SubServer interface.
+func (s *Server) Start() error {
+ return nil
+}
+
+// Stop signals any active goroutines for a graceful closure.
+//
+// NOTE: This is part of the lnrpc.SubServer interface.
+func (s *Server) Stop() error {
+ return nil
+}
+
+// Name returns a unique string representation of the sub-server. This can be
+// used to identify the sub-server and also de-duplicate them.
+//
+// NOTE: This is part of the lnrpc.SubServer interface.
+func (s *Server) Name() string {
+ return subServerName
+}
+
+// RegisterWithRootServer will be called by the root gRPC server to direct a
+// sub RPC server to register itself with the main gRPC root server. Until this
+// is called, each sub-server won't be able to have
+// requests routed towards it.
+//
+// NOTE: This is part of the lnrpc.GrpcHandler interface.
+func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
+ // We make sure that we register it with the main gRPC server to ensure
+ // all our methods are routed properly.
+ RegisterSwitchServer(grpcServer, r)
+
+ log.Debugf("Switch RPC server successfully register with root " +
+ "gRPC server")
+
+ return nil
+}
+
+// RegisterWithRestServer will be called by the root REST mux to direct a sub
+// RPC server to register itself with the main REST mux server. Until this is
+// called, each sub-server won't be able to have requests routed towards it.
+//
+// NOTE: This is part of the lnrpc.GrpcHandler interface.
+func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
+ mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
+
+ // We make sure that we register it with the main REST server to ensure
+ // all our methods are routed properly.
+ err := RegisterSwitchHandlerFromEndpoint(ctx, mux, dest, opts)
+ if err != nil {
+ log.Errorf("Could not register Switch REST server "+
+ "with root REST server: %v", err)
+ return err
+ }
+
+ log.Debugf("Switch REST server successfully registered with " +
+ "root REST server")
+
+ return nil
+}
+
+// CreateSubServer populates the subserver's dependencies using the passed
+// SubServerConfigDispatcher. This method should fully initialize the
+// sub-server instance, making it ready for action. It returns the macaroon
+// permissions that the sub-server wishes to pass on to the root server for all
+// methods routed towards it.
+//
+// NOTE: This is part of the lnrpc.GrpcHandler interface.
+func (r *ServerShell) CreateSubServer(
+ configRegistry lnrpc.SubServerConfigDispatcher) (
+ lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
+
+ subServer, macPermissions, err := createNewSubServer(configRegistry)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ r.SwitchServer = subServer
+
+ return subServer, macPermissions, nil
+}
+
+// SendOnion provides an idempotent API for dispatching a pre-formed onion
+// packet. This RPC is the primary entry point for a remote router that wishes
+// to forward a payment through this lnd instance.
+//
+// To safely handle network failures, a client can and should retry this RPC
+// after a timeout or disconnection. Retries MUST use the exact same
+// attempt id to allow the server to correctly detect duplicate requests.
+//
+// The server guarantees safety against duplicate attempts by following a
+// "write-ahead" style approach. Upon receiving a request, it first writes a
+// durable record of the intent to dispatch the payment, marking the attempt as
+// PENDING. Only after this record is secured does it proceed with validation
+// and dispatch. If any of these subsequent steps fail, the server synchronously
+// transitions the PENDING record to a final FAILED state, ensuring attempts are
+// not "orphaned" in an initialized but not actually dispatched state.
+//
+// A client interacting with this RPC must handle four distinct categories of
+// outcomes, determined by the gRPC status code:
+//
+// 1. SUCCESS (gRPC code OK): A definitive confirmation that the HTLC has been
+// successfully dispatched and is now in-flight. The client can proceed to track
+// the payment's final result via the TrackOnion RPC.
+//
+// 2. DUPLICATE ACKNOWLEDGMENT (gRPC code AlreadyExists): This is not a
+// payment-level failure. It is a definitive acknowledgment that a request with
+// the same attempt id has already been successfully processed. A retrying
+// client should interpret this as a success and proceed to tracking the
+// payment's result.
+//
+// 3. INDEFINITE FAILURE (gRPC code Unavailable or DeadlineExceeded): The state
+// of the HTLC dispatch is unknown. This is returned if the server fails during
+// the critical initial step of writing the PENDING record, or if the server is
+// shutting down. The client MUST retry the *exact same request* with the
+// original attempt id to resolve this ambiguity. A client MUST NOT treat this
+// as a definitive failure and move on to a new attempt ID; doing so risks a
+// duplicate in-flight HTLC.
+//
+// 4. DEFINITIVE FAILURE (gRPC code FailedPrecondition, InvalidArgument, etc.):
+// The HTLC was not and will not be dispatched. The client should fail the
+// attempt and may retry with a new route. To prevent orphaned records, the
+// server transitions the PENDING attempt to a FAILED state.
+//
+// In the case of a FailedPrecondition or Unavailable failure, the gRPC error
+// may include a SendOnionFailureDetails message with additional context for
+// logging and pathfinding.
+func (s *Server) SendOnion(_ context.Context,
+ req *SendOnionRequest) (*SendOnionResponse, error) {
+
+ // First, we initialize the attempt in our persistent store. This serves
+ // as a durable record of our intent to send and gates the attempt id
+ // for concurrent callers, allowing them to safely retry.
+ //
+ // NOTE: This durable write MUST happen before any dynamic validation
+ // (e.g., liquidity, peer connectivity). This ordering guarantees that a
+ // client's retry of a timed-out request will receive a stable acknowle-
+ // dgement as duplicate, rather than a new, misleading transient error.
+ // This prevents the client from incorrectly concluding the original
+ // attempt failed, which would risk a duplicate attempt.
+ attemptID := req.AttemptId
+ initErr := s.cfg.AttemptStore.InitAttempt(attemptID)
+ if initErr != nil {
+ // A record for this attempt ID already exists. This indicates a
+ // client-side retry of a request that was already successfully
+ // registered. We return a distinct error to signal that the
+ // dispatch request is acknowledged and that the caller can
+ // safely proceed to track the result.
+ if errors.Is(initErr, htlcswitch.ErrPaymentIDAlreadyExists) {
+ log.Debugf("Attempt id=%v already exists", attemptID)
+
+ return nil, status.Errorf(codes.AlreadyExists,
+ "payment with attempt ID %d already exists",
+ attemptID)
+ }
+
+ // If we receive an initialization error, we'll return the error
+ // directly to the caller so they can handle the ambiguity.
+ log.Errorf("Unable to initialize attempt id=%d: %v", attemptID,
+ initErr)
+
+ return nil, marshallDispatchFailure(initErr)
+ }
+
+ // Perform all RPC-level pre-dispatch checks.
+ chanID, htlcAdd, validationErr := s.validateAndPrepareOnion(req)
+
+ // If request validation fails, we transition the attempt from an
+ // initialized to a terminally failed state to prevent an orphaned
+ // attempt. An orphaned PENDING record would cause any subsequent
+ // TrackOnion call for this attempt to hang indefinitely.
+ if validationErr != nil {
+ log.Warnf("Validation failed for attempt %d: %v. Failing "+
+ "pending attempt.", req.AttemptId, validationErr)
+
+ s.failPendingAttempt(req.AttemptId, "validation failure")
+
+ // Return the original, more specific validation error to the
+ // client.
+ return nil, validationErr
+ }
+
+ log.Debugf("Dispatching HTLC attempt(id=%v, amt=%v) for payment=%x "+
+ "via channel=%s", req.AttemptId, req.Amount,
+ htlcAdd.PaymentHash, chanID)
+
+ // With the attempt initialized, we now dispatch the HTLC.
+ dispatchErr := s.cfg.HtlcDispatcher.SendHTLC(chanID, attemptID, htlcAdd)
+ if dispatchErr != nil {
+ // If the dispatcher returns ErrDuplicateAdd, we treat it as an
+ // acknowledgment of a prior successful dispatch, not an error.
+ if errors.Is(dispatchErr, htlcswitch.ErrDuplicateAdd) {
+ log.Debugf("Duplicate dispatch for attempt id=%v",
+ attemptID)
+
+ return nil, status.Errorf(codes.AlreadyExists,
+ "payment with attempt ID %d already exists",
+ attemptID)
+ }
+
+ // For any other dispatch error, we transition the attempt to a
+ // failed state to prevent an orphaned record.
+ log.Warnf("Dispatch failed for attempt %d: %v. Failing "+
+ "pending attempt.", req.AttemptId, dispatchErr)
+
+ s.failPendingAttempt(req.AttemptId, "dispatch failure")
+
+ // Translate the internal dispatch error into a gRPC status
+ // with rich details for the client.
+ return nil, marshallDispatchFailure(dispatchErr)
+ }
+
+ // The onion attempt was successfully dispatched.
+ return &SendOnionResponse{}, nil
+}
+
+// failPendingAttempt is a helper which transitions the given attempt from an
+// initialized (PENDING) state to a FAILED state in the persistent store.
+func (s *Server) failPendingAttempt(attemptID uint64, context string) {
+ // We use a generic failure reason, as this is an internal failure.
+ // The original, more specific error is returned to the client.
+ failReason := &lnwire.FailTemporaryNodeFailure{}
+
+ err := s.cfg.AttemptStore.FailPendingAttempt(
+ attemptID, htlcswitch.NewLinkError(failReason),
+ )
+ if err != nil {
+ // If we fail to transition the attempt to a FAILED state
+ // here, the htlc switch's own recovery mechanisms will
+ // eventually clean up any orphaned PENDING attempts after a
+ // restart.
+ log.Errorf("Unable to fail pending attempt %d after %s: %v",
+ attemptID, context, err)
+ }
+}
+
+// validateAndPrepareOnion performs the pre-checks and preparation for a
+// SendOnion request. It returns the channel ID, the HTLC to be sent, and any
+// validation error. All returned errors are gRPC status errors suitable for
+// returning directly to the caller.
+func (s *Server) validateAndPrepareOnion(req *SendOnionRequest) (
+ lnwire.ShortChannelID, *lnwire.UpdateAddHTLC, error) {
+
+ var (
+ chanID lnwire.ShortChannelID
+ htlcAdd *lnwire.UpdateAddHTLC
+ err error
+ )
+
+ if len(req.OnionBlob) != lnwire.OnionPacketSize {
+ err = status.Errorf(
+ codes.InvalidArgument,
+ "onion blob size=%d does not match expected %d bytes",
+ len(req.OnionBlob), lnwire.OnionPacketSize,
+ )
+
+ return chanID, htlcAdd, err
+ }
+
+ if len(req.PaymentHash) == 0 {
+ err = status.Error(
+ codes.InvalidArgument, "payment hash is required")
+
+ return chanID, htlcAdd, err
+ }
+
+ if req.Amount <= 0 {
+ err = status.Error(codes.InvalidArgument,
+ "amount must be greater than zero",
+ )
+
+ return chanID, htlcAdd, err
+ }
+
+ var (
+ amount = lnwire.MilliSatoshi(req.Amount)
+ pubkeySet = len(req.FirstHopPubkey) != 0
+ channelIDSet = req.FirstHopChanId != 0
+ )
+
+ switch {
+ case pubkeySet == channelIDSet:
+ err = status.Error(
+ codes.InvalidArgument,
+ "must specify exactly one of first_hop_pubkey or "+
+ "first_hop_chan_id",
+ )
+
+ return chanID, htlcAdd, err
+
+ case channelIDSet:
+ // Case 1: The caller provided the first hop chan id directly.
+ chanID = lnwire.NewShortChanIDFromInt(req.FirstHopChanId)
+
+ case pubkeySet:
+ // Case 2: Convert the first hop pubkey into a format usable by
+ // the forwarding subsystem.
+ firstHop, parseErr := btcec.ParsePubKey(req.FirstHopPubkey)
+ if parseErr != nil {
+ err = status.Errorf(codes.InvalidArgument,
+ "invalid first hop pubkey=%x: %v",
+ req.FirstHopPubkey, parseErr)
+
+ return chanID, htlcAdd, err
+ }
+
+ // Find an eligible channel ID for the given first-hop pubkey.
+ chanID, err = s.findEligibleChannelID(firstHop, amount)
+ if err != nil {
+ err = status.Errorf(codes.FailedPrecondition,
+ "unable to find eligible channel for "+
+ "pubkey=%x: %v",
+ firstHop.SerializeCompressed(), err)
+
+ return chanID, htlcAdd, err
+ }
+ }
+
+ hash, parseErr := lntypes.MakeHash(req.PaymentHash)
+ if parseErr != nil {
+ err = status.Errorf(codes.InvalidArgument,
+ "invalid payment_hash=%x: %v", req.PaymentHash,
+ parseErr)
+
+ return chanID, htlcAdd, err
+ }
+
+ var blindingPoint lnwire.BlindingPointRecord
+ if len(req.BlindingPoint) > 0 {
+ pubkey, parseErr := btcec.ParsePubKey(req.BlindingPoint)
+ if parseErr != nil {
+ err = status.Errorf(codes.InvalidArgument,
+ "invalid blinding point: %v", parseErr)
+
+ return chanID, htlcAdd, err
+ }
+
+ blindingPoint = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[lnwire.BlindingPointTlvType](
+ pubkey,
+ ),
+ )
+ }
+
+ // Craft an HTLC packet to send to the htlcswitch. The metadata within
+ // this packet will be used to route the payment through the network,
+ // starting with the first-hop.
+ htlcAdd = &lnwire.UpdateAddHTLC{
+ Amount: amount,
+ Expiry: req.Timelock,
+ PaymentHash: hash,
+ OnionBlob: [lnwire.OnionPacketSize]byte(req.OnionBlob),
+ BlindingPoint: blindingPoint,
+ CustomRecords: req.CustomRecords,
+ ExtraData: lnwire.ExtraOpaqueData(req.ExtraData),
+ }
+
+ return chanID, htlcAdd, err
+}
+
+// findEligibleChannelID attempts to find an eligible channel based on the
+// provided public key and the amount to be sent. It returns a channel ID that
+// can carry the given payment amount.
+func (s *Server) findEligibleChannelID(pubKey *btcec.PublicKey,
+ amount lnwire.MilliSatoshi) (lnwire.ShortChannelID, error) {
+
+ var pubKeyArray [33]byte
+ copy(pubKeyArray[:], pubKey.SerializeCompressed())
+
+ links, err := s.cfg.ChannelInfoAccessor.GetLinksByPubkey(pubKeyArray)
+ if err != nil {
+ return lnwire.ShortChannelID{},
+ fmt.Errorf("failed to retrieve channels: %w", err)
+ }
+
+ for _, link := range links {
+ log.Tracef("Considering channel link scid=%v",
+ link.ShortChanID())
+
+ // Ensure the link is eligible to forward payments.
+ if !link.EligibleToForward() {
+ continue
+ }
+
+ // Check if the channel has sufficient bandwidth.
+ if link.Bandwidth() >= amount {
+ // Check if adding an HTLC of this amount is possible.
+ if err := link.MayAddOutgoingHtlc(amount); err == nil {
+ return link.ShortChanID(), nil
+ }
+ }
+ }
+
+ return lnwire.ShortChannelID{},
+ fmt.Errorf("no suitable channel found for amount: %d msat",
+ amount)
+}
+
+// TrackOnion provides callers the means to query whether or not a payment
+// dispatched via SendOnion succeeded or failed.
+//
+// This is a unary, long-polling RPC which blocks until a definitive result
+// (success with preimage or a terminal failure) for the specified attempt ID
+// is available.
+//
+// Clients must be aware of this blocking nature and should typically use a
+// `context` with a timeout. If the RPC call is interrupted (e.g., due to a
+// timeout or network error) before a result is returned, the client is left
+// in an ambiguous state regarding the HTLC's status. In such cases, the
+// client must safely retry the *same* request with the original `paymentHash`
+// and `attemptID`. The server will either return the final result if it has
+// become available or resume waiting.
+//
+// NOTE: It is crucial that clients **do not** interpret an ambiguous error as a
+// definitive failure. Doing so may cause the client to incorrectly mark the
+// attempt as failed and proceed to retry the payment with a new, distinct
+// `attempt_id`, which risks a duplicate payment if the original attempt
+// eventually succeeds.
+func (s *Server) TrackOnion(ctx context.Context,
+ req *TrackOnionRequest) (*TrackOnionResponse, error) {
+
+ hash, err := lntypes.MakeHash(req.PaymentHash)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument,
+ "invalid payment_hash=%x: %v", req.PaymentHash, err)
+ }
+
+ log.Debugf("Looking up status of onion attempt_id=%d for payment=%v",
+ req.AttemptId, hash)
+
+ // Attempt to build the error decryptor with the provided session key
+ // and hop public keys.
+ errorDecryptor, err := buildErrorDecryptor(
+ req.SessionKey, req.HopPubkeys,
+ )
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument,
+ "error building decryptor: %v", err)
+ }
+
+ if errorDecryptor == nil {
+ log.Debug("Unable to build error decrypter with information " +
+ "provided. Will defer error handling to caller")
+ }
+
+ // Query the switch for the result of the payment attempt via onion.
+ resultChan, err := s.cfg.HtlcDispatcher.GetAttemptResult(
+ req.AttemptId, hash, errorDecryptor,
+ )
+ if err != nil {
+ log.Errorf("GetAttemptResult failed for attempt_id=%d of "+
+ " payment=%x: %v", req.AttemptId, hash, err)
+
+ // If the payment ID is not found, we return a NotFound error.
+ if errors.Is(err, htlcswitch.ErrPaymentIDNotFound) {
+ return nil, status.Errorf(codes.NotFound,
+ "payment with attempt ID %d not found",
+ req.AttemptId)
+ }
+
+ // For other errors, we return an internal error.
+ return nil, status.Errorf(codes.Internal,
+ "GetAttemptResult failed: %v", err)
+ }
+
+ // The switch knows about this payment, we'll wait for a result to be
+ // available.
+ var (
+ result *htlcswitch.PaymentResult
+ ok bool
+ )
+
+ select {
+ case result, ok = <-resultChan:
+ if !ok {
+ // This channel is closed when the Switch shuts down. We
+ // return a gRPC error to the client.
+ return nil, status.Error(codes.Unavailable,
+ htlcswitch.ErrSwitchExiting.Error())
+ }
+
+ case <-ctx.Done():
+ // ctx.Done can be triggered by either client cancellation or a
+ // deadline timeout. Return the canonical gRPC status code.
+ return nil, status.FromContextError(ctx.Err()).Err()
+ }
+
+ // The attempt result arrived so the HTLC is no longer in-flight. If
+ // the payment failed, we build a structured response for the client.
+ if result.Error != nil {
+ log.Debugf("HTLC attempt %d failed for payment=%v: %v",
+ req.AttemptId, hash, result.Error)
+
+ details := marshallFailureDetails(result.Error)
+
+ return &TrackOnionResponse{
+ Result: &TrackOnionResponse_FailureDetails{
+ FailureDetails: details,
+ },
+ }, nil
+ }
+
+ // If no decryption keys were provided, the raw onion-encrypted error
+ // is returned as-is, deferring decryption to the client.
+ if len(result.EncryptedError) > 0 {
+ log.Debugf("HTLC attempt %d failed for payment=%v with "+
+ "encrypted error", req.AttemptId, hash)
+
+ details := &FailureDetails{
+ ErrorMessage: "payment attempt failed with encrypted " +
+ "error (client-side decryption required)",
+ Failure: &FailureDetails_EncryptedErrorData{
+ EncryptedErrorData: result.EncryptedError,
+ },
+ }
+
+ return &TrackOnionResponse{
+ Result: &TrackOnionResponse_FailureDetails{
+ FailureDetails: details,
+ },
+ }, nil
+ }
+
+ // If we have reached this point, we expect a valid preimage for a
+ // successful payment.
+ if result.Preimage == (lntypes.Preimage{}) {
+ log.Errorf("Payment %v completed without a valid preimage "+
+ "or error", hash)
+
+ return nil, status.Error(codes.Internal,
+ ErrAmbiguousPaymentState.Error())
+ }
+
+ log.Debugf("Received preimage via onion attempt_id=%d for payment=%v",
+ req.AttemptId, hash)
+
+ return &TrackOnionResponse{
+ Result: &TrackOnionResponse_Preimage{
+ Preimage: result.Preimage[:],
+ },
+ }, nil
+}
+
+// buildErrorDecryptor constructs an error decrypter given a sphinx session
+// key and hop public keys for a payment route.
+func buildErrorDecryptor(sessionKeyBytes []byte,
+ hopPubkeys [][]byte) (htlcswitch.ErrorDecrypter, error) {
+
+ sessionKeyProvided := len(sessionKeyBytes) > 0
+ hopPubkeysProvided := len(hopPubkeys) > 0
+
+ // If neither is provided, the caller wants to handle decryption. This
+ // is a valid use case, so we return no decryptor and no error.
+ if !sessionKeyProvided && !hopPubkeysProvided {
+ return nil, nil
+ }
+
+ // If only one of the two is provided, it's a client error. Both are
+ // required for decryption.
+ if sessionKeyProvided != hopPubkeysProvided {
+ return nil, fmt.Errorf("session_key and hop_pubkeys must be " +
+ "provided together")
+ }
+
+ if err := validateSessionKey(sessionKeyBytes); err != nil {
+ return nil, fmt.Errorf("invalid session key: %w", err)
+ }
+
+ sessionKey, _ := btcec.PrivKeyFromBytes(sessionKeyBytes)
+
+ pubKeys := make([]*btcec.PublicKey, 0, len(hopPubkeys))
+ for _, keyBytes := range hopPubkeys {
+ pubKey, err := btcec.ParsePubKey(keyBytes)
+ if err != nil {
+ return nil, fmt.Errorf("invalid public key: %w", err)
+ }
+ pubKeys = append(pubKeys, pubKey)
+ }
+
+ // Construct the sphinx circuit needed for error decryption using the
+ // provided session key and hop public keys.
+ circuit := reconstructCircuit(sessionKey, pubKeys)
+
+ // Using the created circuit, initialize the error decrypter so we can
+ // parse+decode any failures incurred by this payment within the
+ // switch.
+ return &htlcswitch.SphinxErrorDecrypter{
+ OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
+ }, nil
+}
+
+// validateSessionKey validates the session key to ensure it has the correct
+// length and is within the expected range [1, N-1] for the secp256k1 curve. If
+// the session key is invalid, an error is returned.
+func validateSessionKey(sessionKeyBytes []byte) error {
+ const expectedKeyLength = 32
+
+ // Check length of session key.
+ if len(sessionKeyBytes) != expectedKeyLength {
+ return fmt.Errorf("invalid session key length: got %d, "+
+ "expected %d", len(sessionKeyBytes), expectedKeyLength)
+ }
+
+ // Interpret the key as a big-endian unsigned integer.
+ keyValue := new(big.Int).SetBytes(sessionKeyBytes)
+
+ // Check if the key is in the valid range [1, N-1].
+ if keyValue.Sign() <= 0 || keyValue.Cmp(btcec.S256().N) >= 0 {
+ return fmt.Errorf("session key is out of range")
+ }
+
+ return nil
+}
+
+// reconstructCircuit is a simple helper to assemble a sphinx Circuit from its
+// consituent parts, namely ephemeral session key and hop public keys.
+func reconstructCircuit(sessionKey *btcec.PrivateKey,
+ pubKeys []*btcec.PublicKey) *sphinx.Circuit {
+
+ return &sphinx.Circuit{
+ SessionKey: sessionKey,
+ PaymentPath: pubKeys,
+ }
+}
+
+// BuildOnion constructs a sphinx onion packet for the given route.
+func (s *Server) BuildOnion(_ context.Context,
+ req *BuildOnionRequest) (*BuildOnionResponse, error) {
+
+ if req.Route == nil {
+ return nil, status.Error(codes.InvalidArgument,
+ "route information is required")
+ }
+ if len(req.PaymentHash) == 0 {
+ return nil, status.Error(codes.InvalidArgument,
+ "payment hash is required")
+ }
+
+ var (
+ sessionKey *btcec.PrivateKey
+ err error
+ )
+
+ if len(req.SessionKey) == 0 {
+ sessionKey, err = routing.GenerateNewSessionKey()
+ if err != nil {
+ return nil, status.Errorf(codes.Internal,
+ "failed to generate session key: %v", err)
+ }
+ } else {
+ if err := validateSessionKey(req.SessionKey); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument,
+ "invalid session key: %v", err)
+ }
+
+ sessionKey, _ = btcec.PrivKeyFromBytes(req.SessionKey)
+ }
+
+ // Convert the route to a Sphinx path.
+ route, err := s.cfg.RouteProcessor.UnmarshallRoute(req.Route)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument,
+ "invalid route: %v", err)
+ }
+
+ // Generate the onion packet.
+ onionBlob, circuit, err := paymentsdb.GenerateSphinxPacket(
+ route, req.PaymentHash, sessionKey,
+ )
+ if err != nil {
+ return nil, status.Errorf(codes.Internal,
+ "failed to create onion blob: %v", err)
+ }
+
+ // We'll provide the list of hop public keys for caller convenience.
+ // They may wish to use them + the session key in a future call to
+ // SendOnion so that the server can decrypt and handle errors.
+ hopPubKeys := make([][]byte, len(circuit.PaymentPath))
+ for i, pubKey := range circuit.PaymentPath {
+ hopPubKeys[i] = pubKey.SerializeCompressed()
+ }
+
+ return &BuildOnionResponse{
+ OnionBlob: onionBlob,
+ SessionKey: sessionKey.Serialize(),
+ HopPubkeys: hopPubKeys,
+ }, nil
+}
+
+// DeleteAttempts removes terminal (settled or failed) payment attempt records
+// from the server's attempt store. This enables remote clients to perform
+// online garbage collection of completed attempt data.
+//
+// The server processes each attempt ID independently and reports per-ID
+// results. Pending (in-flight) attempts are never deleted. The overall RPC
+// succeeds (gRPC OK) as long as the request could be processed.
+func (s *Server) DeleteAttempts(_ context.Context,
+ req *DeleteAttemptsRequest) (*DeleteAttemptsResponse, error) {
+
+ log.Debugf("DeleteAttempts called for %d attempt(s)",
+ len(req.AttemptIds))
+
+ // Deduplicate attempt IDs, preserving request order.
+ seen := make(map[uint64]struct{}, len(req.AttemptIds))
+ uniqueIDs := make([]uint64, 0, len(req.AttemptIds))
+ for _, id := range req.AttemptIds {
+ if _, ok := seen[id]; ok {
+ continue
+ }
+ seen[id] = struct{}{}
+ uniqueIDs = append(uniqueIDs, id)
+ }
+
+ storeResults, err := s.cfg.AttemptStore.DeleteAttempts(uniqueIDs)
+ if err != nil {
+ log.Errorf("DeleteAttempts failed: %v", err)
+
+ return nil, status.Errorf(codes.Internal,
+ "failed to delete attempts: %v", err)
+ }
+
+ // Convert the store-level results into proto results, preserving the
+ // request order.
+ results := make([]*AttemptDeletionResult, 0, len(uniqueIDs))
+ for _, id := range uniqueIDs {
+ protoStatus := deletionStatusToProto(storeResults[id])
+
+ results = append(results, &AttemptDeletionResult{
+ AttemptId: id,
+ Status: protoStatus,
+ })
+ }
+
+ return &DeleteAttemptsResponse{Results: results}, nil
+}
+
+// deletionStatusToProto converts an internal DeletionStatus to the
+// corresponding proto enum value.
+func deletionStatusToProto(
+ s htlcswitch.DeletionStatus) AttemptDeletionStatus {
+
+ switch s {
+ case htlcswitch.DeletionOK:
+ return AttemptDeletionStatus_DELETION_OK
+ case htlcswitch.DeletionPending:
+ return AttemptDeletionStatus_DELETION_PENDING
+ case htlcswitch.DeletionNotFound:
+ return AttemptDeletionStatus_DELETION_NOT_FOUND
+ case htlcswitch.DeletionFailed:
+ return AttemptDeletionStatus_DELETION_FAILED
+ default:
+ return AttemptDeletionStatus_DELETION_NOT_FOUND
+ }
+}
+
+// DisableRemoteRouter disables the remote router, allowing a migration back to
+// the embedded router.
+func (s *Server) DisableRemoteRouter(ctx context.Context,
+ req *DisableRemoteRouterRequest) (*DisableRemoteRouterResponse, error) {
+
+ err := s.cfg.RemoteRouterController.DisableRemoteRouter()
+ if err != nil {
+ if errors.Is(err, htlcswitch.ErrAttemptEntriesExist) {
+ return nil, status.Errorf(
+ codes.FailedPrecondition,
+ "unable to disable remote router: %v",
+ err,
+ )
+ }
+
+ return nil, status.Errorf(
+ codes.Internal,
+ "unable to disable remote router: %v", err,
+ )
+ }
+
+ return &DisableRemoteRouterResponse{}, nil
+}
+
+// marshallDispatchFailure translates an error from the underlying HTLC switch
+// into a gRPC status error with rich, structurally-classified details.
+func marshallDispatchFailure(err error) error {
+ details := &SendOnionFailureDetails{
+ ErrorMessage: err.Error(),
+ }
+
+ var (
+ rpcCode codes.Code
+ clearTextErr htlcswitch.ClearTextError
+ indefiniteFail *IndefiniteFailure
+ definiteFail *DefiniteFailure
+ )
+
+ switch {
+ // Handle definite failures.
+ case errors.As(err, &clearTextErr):
+ rpcCode = codes.FailedPrecondition
+
+ var buf bytes.Buffer
+ encodeErr := lnwire.EncodeFailure(
+ &buf, clearTextErr.WireMessage(), 0,
+ )
+ if encodeErr != nil {
+ // The failure is still definite — the switch rejected
+ // the HTLC — we just can't serialize the specific
+ // wire-level reason. We return a DefiniteFailure
+ // so the client can fail the attempt rather than
+ // retrying indefinitely.
+ log.Errorf("Failed to encode ClearTextError wire "+
+ "message: %v", encodeErr)
+
+ definiteFail = &DefiniteFailure{}
+
+ break
+ }
+
+ definiteFail = &DefiniteFailure{
+ LocalFailure: &LocalFailure{
+ WireMessage: buf.Bytes(),
+ },
+ }
+
+ // Handle indefinite failures with specific reasons. These errors
+ // cannot provide acknowledgement on whether or not an htlc for the
+ // given attempt ID has been processed by the server. We signal this
+ // with a specific failure reasons and a top-level gRPC status of
+ // Unavailable. The client MUST retry to resolve the ambiguity.
+ case errors.Is(err, htlcswitch.ErrSwitchExiting):
+ rpcCode = codes.Unavailable
+ indefiniteFail = &IndefiniteFailure{
+ Reason: IndefiniteFailureCode_SWITCH_EXITING,
+ }
+
+ case errors.Is(err, htlcswitch.ErrAmbiguousAttemptInit):
+ rpcCode = codes.Unavailable
+ indefiniteFail = &IndefiniteFailure{
+ Reason: IndefiniteFailureCode_HTLC_INIT_FAILED,
+ }
+
+ // Consider unclassified errors as indefinite for safety.
+ default:
+ rpcCode = codes.Unavailable
+ indefiniteFail = &IndefiniteFailure{
+ Reason: IndefiniteFailureCode_REASON_UNKNOWN,
+ }
+ }
+
+ // Classify the failure as either definite or indefinite.
+ if definiteFail != nil {
+ details.FailureClass =
+ &SendOnionFailureDetails_DefiniteFailure{
+ DefiniteFailure: definiteFail,
+ }
+ } else {
+ details.FailureClass =
+ &SendOnionFailureDetails_IndefiniteFailure{
+ IndefiniteFailure: indefiniteFail,
+ }
+ }
+
+ // Create the gRPC status and attach the structured details.
+ st := status.New(rpcCode, err.Error())
+ stWithDetails, attachErr := st.WithDetails(details)
+ if attachErr != nil {
+ log.Warnf("Unable to attach details to SendOnion error: %v",
+ attachErr)
+
+ return st.Err()
+ }
+
+ return stWithDetails.Err()
+}
+
+// GetSendOnionFailureDetails inspects a gRPC error from a SendOnion call and
+// extracts the rich failure details, if present. It returns the details struct
+// directly, allowing the caller to inspect all fields. It returns nil if no
+// such details are found.
+func GetSendOnionFailureDetails(rpcErr error) *SendOnionFailureDetails {
+ st, ok := status.FromError(rpcErr)
+ if !ok {
+ // Not a gRPC status error.
+ return nil
+ }
+
+ // Search for the specific failure details message within the status.
+ for _, detail := range st.Details() {
+ if failure, ok := detail.(*SendOnionFailureDetails); ok {
+ // We found the details, return them directly.
+ return failure
+ }
+ }
+
+ // No details were found.
+ return nil
+}
+
+// marshallFailureDetails creates the FailureDetails message for the
+// TrackOnion response body.
+func marshallFailureDetails(err error) *FailureDetails {
+ var (
+ clearTextErr htlcswitch.ClearTextError
+ fwdErr *htlcswitch.ForwardingError
+ )
+
+ details := &FailureDetails{
+ ErrorMessage: err.Error(),
+ }
+
+ switch {
+ // A forwarding error from an intermediate routing node. This is
+ // checked first because ForwardingError is more specific and also
+ // satisfies the ClearTextError interface.
+ case errors.As(err, &fwdErr):
+ fwdFailure := &ForwardingFailure{
+ FailureSourceIndex: uint32(
+ fwdErr.FailureSourceIdx,
+ ),
+ }
+
+ // The wire message may be nil when the onion error was
+ // successfully decrypted but the inner failure message
+ // could not be decoded (NewUnknownForwardingError). In
+ // that case we still return the failure source index.
+ if fwdErr.WireMessage() != nil {
+ var buf bytes.Buffer
+
+ encodeErr := lnwire.EncodeFailure(
+ &buf, fwdErr.WireMessage(), 0,
+ )
+ if encodeErr != nil {
+ log.Errorf("Failed to encode wire "+
+ "message: %v", encodeErr)
+ } else {
+ fwdFailure.WireMessage = buf.Bytes()
+ }
+ }
+
+ details.Failure = &FailureDetails_ForwardingFailure{
+ ForwardingFailure: fwdFailure,
+ }
+
+ // A ClearTextError covers local failures (e.g. LinkError) where the
+ // wire message is available in plaintext without decryption.
+ case errors.As(err, &clearTextErr):
+ var buf bytes.Buffer
+
+ encodeErr := lnwire.EncodeFailure(
+ &buf, clearTextErr.WireMessage(), 0,
+ )
+ if encodeErr != nil {
+ log.Errorf("failed to encode wire message: %v",
+ encodeErr)
+ details.Failure = &FailureDetails_SwitchError{
+ SwitchError: &SwitchError{},
+ }
+
+ return details
+ }
+
+ details.Failure = &FailureDetails_LocalFailure{
+ LocalFailure: &LocalFailure{
+ WireMessage: buf.Bytes(),
+ },
+ }
+
+ // NOTE: ErrPaymentIDNotFound and ErrSwitchExiting are handled at
+ // the transport level and will not reach this function.
+ case errors.Is(err, htlcswitch.ErrUnreadableFailureMessage):
+ details.Failure = &FailureDetails_UnreadableFailure{
+ UnreadableFailure: &UnreadableFailure{},
+ }
+
+ // All other unexpected errors will be mapped to a generic internal
+ // error. The specific reason is still available in the top-level
+ // error_message.
+ default:
+ details.Failure = &FailureDetails_SwitchError{
+ SwitchError: &SwitchError{},
+ }
+ }
+
+ return details
+}
+
+// UnmarshallFailureDetails translates a FailureDetails message from a
+// TrackOnion response into a concrete Go error. It handles all cases of the
+// 'oneof failure' field.
+func UnmarshallFailureDetails(details *FailureDetails,
+ deobfuscator htlcswitch.ErrorDecrypter) (error, error) {
+
+ if details == nil {
+ return nil, errors.New("cannot unmarshall nil FailureDetails")
+ }
+
+ // Use a type switch on the 'oneof failure' field to handle the primary
+ // structured error cases.
+ switch failure := details.Failure.(type) {
+ case *FailureDetails_ForwardingFailure:
+ return UnmarshallForwardingError(failure.ForwardingFailure)
+
+ case *FailureDetails_LocalFailure:
+ return UnmarshallLinkError(failure.LocalFailure)
+
+ case *FailureDetails_EncryptedErrorData:
+ if deobfuscator == nil {
+ return htlcswitch.ErrUnreadableFailureMessage, nil
+ }
+
+ // The client provides the decryption key/logic.
+ return deobfuscator.DecryptError(failure.EncryptedErrorData)
+
+ case *FailureDetails_UnreadableFailure:
+ return htlcswitch.ErrUnreadableFailureMessage, nil
+
+ case *FailureDetails_SwitchError:
+ // The specific reason is in the top-level message.
+ return errors.New(details.ErrorMessage), nil
+ }
+
+ // Fallback for safety, though the oneof should always be populated
+ // on a failure response.
+ return nil, fmt.Errorf("unknown or empty failure reason in "+
+ "response: %v", details.ErrorMessage)
+}
+
+// UnmarshallForwardingError converts a protobuf ForwardingFailure message into
+// an htlcswitch.ForwardingError.
+func UnmarshallForwardingError(f *ForwardingFailure) (
+ *htlcswitch.ForwardingError, error) {
+
+ if f == nil {
+ return nil, fmt.Errorf("cannot parse nil ForwardingFailure")
+ }
+
+ wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode wire message: %w", err)
+ }
+
+ return htlcswitch.NewForwardingError(
+ wireMsg, int(f.FailureSourceIndex),
+ ), nil
+}
+
+// UnmarshallLinkError converts a protobuf LocalFailure message into an
+// htlcswitch.LinkError.
+func UnmarshallLinkError(f *LocalFailure) (*htlcswitch.LinkError, error) {
+ if f == nil {
+ return nil, fmt.Errorf("cannot parse nil LocalFailure")
+ }
+
+ wireMsg, err := UnmarshallFailureMessage(f.WireMessage)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode wire message: %w", err)
+ }
+
+ return htlcswitch.NewLinkError(wireMsg), nil
+}
+
+// UnmarshallFailureMessage decodes a raw wire message byte slice into a rich
+// lnwire.FailureMessage object.
+func UnmarshallFailureMessage(wireMsg []byte) (lnwire.FailureMessage, error) {
+ r := bytes.NewReader(wireMsg)
+
+ return lnwire.DecodeFailure(r, 0)
+}
### lnrpc/switchrpc/switch_server_test.go
@@ -0,0 +1,1530 @@
+//go:build switchrpc
+// +build switchrpc
+
+package switchrpc
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/htlcswitch"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lntypes"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/routing/route"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// TestSendOnion is a unit test that rigorously verifies the behavior of the
+// SendOnion RPC handler in isolation. It ensures that the server correctly
+// implements its side of the RPC contract by sending the correct signals back
+// to the client under various conditions. The test guarantees:
+// 1. Correct translation of internal htlcswitch errors (e.g., ErrDuplicateAdd)
+// into the specific error codes defined in the protobuf contract.
+// 2. Robust validation of incoming requests, ensuring malformed requests are
+// rejected with the appropriate gRPC status code.
+// 3. Correct propagation of success signals when the underlying dispatcher
+// succeeds.
+func TestSendOnion(t *testing.T) {
+ t.Parallel()
+
+ // Create a valid request that can be used as a template for tests.
+ makeValidRequest := func() *SendOnionRequest {
+ return &SendOnionRequest{
+ OnionBlob: make([]byte, lnwire.OnionPacketSize),
+ PaymentHash: make([]byte, 32),
+ AttemptId: 1,
+ Amount: 1000,
+ FirstHopChanId: 12345,
+ }
+ }
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+
+ // setup is a function that modifies the server or request for a
+ // specific test case.
+ setup func(*testing.T, *Server, *SendOnionRequest)
+
+ // expectedErrCode is the gRPC error code we expect from the
+ // call.
+ expectedErrCode codes.Code
+
+ // checkFailureDetails is a function that asserts the contents
+ // of the SendOnionFailureDetails message.
+ checkFailureDetails func(*testing.T, *SendOnionFailureDetails)
+ }{
+ {
+ name: "valid request",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ // Mock a successful dispatch.
+ payer, ok := s.cfg.HtlcDispatcher.(*mockPayer)
+ require.True(t, ok)
+ payer.sendErr = nil
+ },
+ expectedErrCode: codes.OK,
+ },
+ {
+ name: "missing onion blob",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ req.OnionBlob = nil
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "invalid onion blob size",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ req.OnionBlob = make([]byte, 1)
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "missing payment hash",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ req.PaymentHash = nil
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "zero amount",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ req.Amount = 0
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "dispatcher internal error",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ // Mock a generic error from the dispatcher.
+ payer, ok := s.cfg.HtlcDispatcher.(*mockPayer)
+ require.True(t, ok)
+ payer.sendErr = errors.New("internal error")
+ },
+ expectedErrCode: codes.Unavailable,
+ checkFailureDetails: func(t *testing.T,
+ details *SendOnionFailureDetails) {
+
+ require.Contains(t, details.ErrorMessage,
+ "internal error")
+ },
+ },
+ {
+ // The ErrPaymentIDAlreadyExists error is the means by
+ // which an rpc client is safe to retry the SendOnion
+ // RPC until an explicit acknowledgement of HTLC
+ // dispatch can be received from the server. The
+ // acknowledgement is expected to be signalled by a
+ // AlreadyExists grpc status code.
+ name: "duplicate attempt initialization",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ // Mock a duplicate error from the attempt
+ // store.
+ store, ok := s.cfg.AttemptStore.(*mockAttemptStore)
+ require.True(t, ok)
+ store.initErr = htlcswitch.ErrPaymentIDAlreadyExists
+ },
+ expectedErrCode: codes.AlreadyExists,
+ },
+ {
+ // ErrDuplicateAdd from the switch/dispatcher is a
+ // last line of defense against duplicate htlc attempts.
+ // Under normal operation, InitAttempt catches
+ // duplicates first and we never reach SendHTLC. This
+ // path could be reached if the InitAttempt record were
+ // removed (e.g., via a future DeleteAttempts RPC) while
+ // the circuit is still registered.
+ name: "dispatcher duplicate htlc error",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ payer, ok := s.cfg.HtlcDispatcher.(*mockPayer)
+ require.True(t, ok)
+ payer.sendErr = htlcswitch.ErrDuplicateAdd
+ },
+ expectedErrCode: codes.AlreadyExists,
+ },
+ {
+ name: "ambiguous attempt init error",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ store, ok := s.cfg.AttemptStore.(*mockAttemptStore)
+ require.True(t, ok)
+ store.initErr = htlcswitch.ErrAmbiguousAttemptInit
+ },
+ expectedErrCode: codes.Unavailable,
+ checkFailureDetails: func(t *testing.T,
+ details *SendOnionFailureDetails) {
+
+ indefinite := details.GetIndefiniteFailure()
+ require.NotNil(t, indefinite)
+ require.Equal(t,
+ IndefiniteFailureCode_HTLC_INIT_FAILED,
+ indefinite.Reason,
+ )
+ },
+ },
+ {
+ name: "attempt init returns generic internal error",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ // Mock a generic, unexpected error from
+ // InitAttempt to test the defensive fallback
+ // error path.
+ store, ok := s.cfg.AttemptStore.(*mockAttemptStore)
+ require.True(t, ok)
+ store.initErr = errors.New("unexpected DB error")
+ },
+ expectedErrCode: codes.Unavailable,
+ checkFailureDetails: func(t *testing.T,
+ details *SendOnionFailureDetails) {
+
+ indefinite := details.GetIndefiniteFailure()
+ require.NotNil(t, indefinite)
+ require.Equal(t,
+ IndefiniteFailureCode_REASON_UNKNOWN,
+ indefinite.Reason,
+ )
+ },
+ },
+ {
+ name: "clear text error",
+ setup: func(t *testing.T, s *Server,
+ req *SendOnionRequest) {
+
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ linkErr := htlcswitch.NewDetailedLinkError(
+ wireMsg,
+ htlcswitch.OutgoingFailureInsufficientBalance,
+ )
+
+ payer, ok := s.cfg.HtlcDispatcher.(*mockPayer)
+ require.True(t, ok)
+ payer.sendErr = linkErr
+ },
+ expectedErrCode: codes.FailedPrecondition,
+ checkFailureDetails: func(t *testing.T,
+ details *SendOnionFailureDetails) {
+
+ definite := details.GetDefiniteFailure()
+ require.NotNil(t, definite)
+
+ failure := definite.GetLocalFailure()
+ require.NotNil(t, failure)
+
+ _, err := UnmarshallFailureMessage(
+ failure.WireMessage,
+ )
+ require.NoError(t, err)
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ // Create a new server for each test case to ensure
+ // isolation.
+ server, _, err := New(&Config{
+ HtlcDispatcher: &mockPayer{},
+ AttemptStore: &mockAttemptStore{},
+ })
+ require.NoError(t, err)
+
+ req := makeValidRequest()
+
+ // Apply the test-specific setup.
+ if tc.setup != nil {
+ tc.setup(t, server, req)
+ }
+
+ resp, err := server.SendOnion(t.Context(), req)
+
+ // If we expected OK, assert a nil error and non-nil
+ // response.
+ if tc.expectedErrCode == codes.OK {
+ require.NoError(t, err)
+ require.NotNil(t, resp)
+ return
+ }
+
+ // Otherwise, we expect a gRPC status error.
+ require.Error(t, err)
+
+ // If we don't need to check details, we're done.
+ if tc.checkFailureDetails == nil {
+ s, ok := status.FromError(err)
+ require.True(t, ok)
+ require.Equal(t, tc.expectedErrCode, s.Code())
+
+ return
+ }
+
+ // Otherwise confirm the failure details are as
+ // expected.
+ details := requireSendOnionFailureDetails(
+ t, err, tc.expectedErrCode,
+ )
+ tc.checkFailureDetails(t, details)
+ })
+ }
+}
+
+// requireSendOnionFailureDetails is a test helper that asserts a SendOnion call
+// failed with a specific gRPC status code and extracts the embedded
+// SendOnionFailureDetails message.
+func requireSendOnionFailureDetails(t *testing.T, err error,
+ expectedRPCCode codes.Code) *SendOnionFailureDetails {
+
+ s, ok := status.FromError(err)
+ require.True(t, ok, "expected gRPC status error")
+ require.Equal(t, expectedRPCCode, s.Code(),
+ "unexpected gRPC status code")
+
+ details := s.Details()
+ require.Len(t, details, 1, "expected one failure detail")
+
+ failureDetails, ok := details[0].(*SendOnionFailureDetails)
+ require.True(t, ok, "expected SendOnionFailureDetails")
+
+ return failureDetails
+}
+
+// TestTrackOnion is a unit test that rigorously verifies the behavior of the
+// TrackOnion RPC handler in isolation.
+func TestTrackOnion(t *testing.T) {
+ t.Parallel()
+
+ preimage := lntypes.Preimage{1, 2, 3}
+ preimageBytes := preimage[:]
+
+ // Create a valid request that can be used as a template for tests.
+ makeValidRequest := func() *TrackOnionRequest {
+ return &TrackOnionRequest{
+ PaymentHash: make([]byte, 32),
+ AttemptId: 1,
+ }
+ }
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+
+ // setup is a function that modifies the server or request for a
+ // specific test case.
+ setup func(*testing.T, *mockPayer, *TrackOnionRequest)
+
+ // getCtx is a function that returns the context to use for the
+ // RPC call.
+ getCtx func() context.Context
+
+ // expectedErrCode is the gRPC error code we expect from the
+ // call.
+ expectedErrCode codes.Code
+
+ // checkResponse is a function that asserts the response from the
+ // RPC call.
+ checkResponse func(*testing.T, *TrackOnionResponse)
+ }{
+ {
+ name: "payment success",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ m.getResultResult = &htlcswitch.PaymentResult{
+ Preimage: preimage,
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ require.Equal(t, preimageBytes, resp.GetPreimage())
+ },
+ },
+ {
+ name: "payment failed with generic internal error",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ m.getResultResult = &htlcswitch.PaymentResult{
+ Error: errors.New("test error"),
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ details := resp.GetFailureDetails()
+ require.NotNil(t, details)
+ require.NotNil(t, details.GetSwitchError())
+ require.Contains(t, details.ErrorMessage, "test error")
+ },
+ },
+ {
+ name: "payment failed with clear text error",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ linkErr := htlcswitch.NewLinkError(wireMsg)
+ m.getResultResult = &htlcswitch.PaymentResult{
+ Error: linkErr,
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ details := resp.GetFailureDetails()
+ require.NotNil(t, details)
+ require.NotNil(t, details.GetLocalFailure())
+ require.Empty(t, details.GetForwardingFailure())
+ },
+ },
+ {
+ name: "payment failed with forwarding error",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ fwdErr := htlcswitch.NewForwardingError(wireMsg, 1)
+ m.getResultResult = &htlcswitch.PaymentResult{
+ Error: fwdErr,
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ details := resp.GetFailureDetails()
+ require.NotNil(t, details)
+ require.NotNil(t, details.GetForwardingFailure())
+ require.Empty(t, details.GetLocalFailure())
+ require.Equal(t, uint32(1),
+ details.GetForwardingFailure().FailureSourceIndex)
+ },
+ },
+ {
+ name: "payment failed with unknown forwarding error",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ // NewUnknownForwardingError has a nil wire
+ // message. Without the nil guard in
+ // marshallFailureDetails this would panic.
+ fwdErr := htlcswitch.NewUnknownForwardingError(2)
+ m.getResultResult = &htlcswitch.PaymentResult{
+ Error: fwdErr,
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ details := resp.GetFailureDetails()
+ require.NotNil(t, details)
+ require.NotNil(t, details.GetForwardingFailure())
+ require.Equal(t, uint32(2),
+ details.GetForwardingFailure().FailureSourceIndex)
+ require.Empty(t,
+ details.GetForwardingFailure().WireMessage)
+ },
+ },
+ {
+ name: "payment not found",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ m.getResultErr = htlcswitch.ErrPaymentIDNotFound
+ },
+ getCtx: t.Context,
+ expectedErrCode: codes.NotFound,
+ },
+ {
+ name: "invalid payment hash",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ req.PaymentHash = []byte{1, 2, 3}
+ },
+ getCtx: t.Context,
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "context canceled",
+ setup: nil, // No setup needed, mock will block.
+ getCtx: func() context.Context {
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ return ctx
+ },
+ expectedErrCode: codes.Canceled,
+ },
+ {
+ name: "invalid decryptor args",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ // Provide an invalid session key and a valid
+ // hop public key to trigger an error in
+ // buildErrorDecryptor.
+ req.SessionKey = []byte{1, 2, 3}
+ req.HopPubkeys = [][]byte{{
+ 2, 153, 44, 150, 184, 220, 236, 177, 70, 240, 51,
+ 88, 154, 232, 72, 158, 23, 39, 58, 18, 201, 79, 200, 164, 48,
+ 103, 208, 148, 27, 216, 153, 206, 77,
+ }}
+ },
+ getCtx: t.Context,
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "encrypted error",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ m.getResultResult = &htlcswitch.PaymentResult{
+ EncryptedError: []byte("encrypted error"),
+ }
+ },
+ getCtx: t.Context,
+ checkResponse: func(t *testing.T, resp *TrackOnionResponse) {
+ details := resp.GetFailureDetails()
+ require.NotNil(t, details)
+ require.Equal(t, []byte("encrypted error"),
+ details.GetEncryptedErrorData())
+ },
+ },
+ {
+ name: "switch exiting",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ // To simulate the switch exiting, we'll
+ // provide a result channel that is already
+ // closed.
+ closedChan := make(chan *htlcswitch.PaymentResult)
+ close(closedChan)
+ m.resultChan = closedChan
+ },
+ getCtx: t.Context,
+ expectedErrCode: codes.Unavailable,
+ },
+ {
+ name: "ambiguous result",
+ setup: func(t *testing.T, m *mockPayer,
+ req *TrackOnionRequest) {
+
+ m.getResultResult = &htlcswitch.PaymentResult{
+ // A result with no error and a zero-value
+ // preimage.
+ Error: nil,
+ Preimage: lntypes.Preimage{},
+ }
+ },
+ getCtx: t.Context,
+ expectedErrCode: codes.Internal,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ mockPayer := &mockPayer{}
+
+ // Create a new server for each test case to ensure
+ // isolation.
+ server, _, err := New(&Config{
+ HtlcDispatcher: mockPayer,
+ })
+ require.NoError(t, err)
+
+ req := makeValidRequest()
+
+ // Apply the test-specific setup.
+ if tc.setup != nil {
+ tc.setup(t, mockPayer, req)
+ }
+
+ resp, err := server.TrackOnion(tc.getCtx(), req)
+
+ // Check for gRPC level errors.
+ if tc.expectedErrCode != codes.OK {
+ require.Error(t, err)
+ s, ok := status.FromError(err)
+ require.True(t, ok)
+ require.Equal(t, tc.expectedErrCode, s.Code())
+
+ return
+ }
+
+ // If no gRPC error was expected, check the response.
+ require.NoError(t, err)
+ tc.checkResponse(t, resp)
+ })
+ }
+}
+
+// TestBuildOnion is a unit test that verifies the behavior of the BuildOnion
+// RPC handler, ensuring that it correctly validates inputs, handles dependency
+// failures, and constructs a valid response upon success.
+func TestBuildOnion(t *testing.T) {
+ t.Parallel()
+
+ // Create a valid session key for the "provided key" test case.
+ validSessionKeyBytes := []byte{
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
+ }
+
+ // Create a mock route to be returned by the processor.
+ // We need to generate some mock public keys for the hops.
+ privKey1, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ pubKey1 := privKey1.PubKey()
+
+ privKey2, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ pubKey2 := privKey2.PubKey()
+
+ // The mock route needs to have realistic values for amounts,
+ // timelocks, and channel IDs, otherwise sphinx packet construction
+ // will fail.
+ paymentAmt := lnwire.MilliSatoshi(10000)
+ finalCltv := uint32(40)
+
+ mockRoute := &route.Route{
+ TotalAmount: paymentAmt,
+ Hops: []*route.Hop{
+ {
+ PubKeyBytes: route.NewVertex(pubKey1),
+ AmtToForward: paymentAmt,
+ OutgoingTimeLock: finalCltv + 10,
+ ChannelID: 1,
+ },
+ {
+ PubKeyBytes: route.NewVertex(pubKey2),
+ AmtToForward: paymentAmt,
+ OutgoingTimeLock: finalCltv,
+ ChannelID: 2,
+ },
+ },
+ }
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+
+ // setup is a function that modifies the server or request for a
+ // specific test case.
+ setup func(*testing.T, *mockRouteProcessor, *BuildOnionRequest)
+
+ // expectedErrCode is the gRPC error code we expect.
+ expectedErrCode codes.Code
+
+ // checkResponse is a function that validates the response on
+ // success.
+ checkResponse func(*testing.T, *BuildOnionResponse)
+ }{
+ {
+ name: "success new session key",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ m.unmarshallRoute = mockRoute
+ },
+ checkResponse: func(t *testing.T, resp *BuildOnionResponse) {
+ require.Len(t, resp.OnionBlob, lnwire.OnionPacketSize)
+ require.Len(t, resp.SessionKey, 32)
+ require.Len(t, resp.HopPubkeys, len(mockRoute.Hops))
+
+ // Check that expected route is constructed.
+ for i, hop := range mockRoute.Hops {
+ require.Equal(t, hop.PubKeyBytes[:],
+ resp.HopPubkeys[i])
+ }
+ },
+ },
+ {
+ name: "success with provided session key",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ m.unmarshallRoute = mockRoute
+ req.SessionKey = validSessionKeyBytes
+ },
+ checkResponse: func(t *testing.T, resp *BuildOnionResponse) {
+ require.Len(t, resp.OnionBlob, lnwire.OnionPacketSize)
+ require.Equal(t, validSessionKeyBytes, resp.SessionKey)
+ require.Len(t, resp.HopPubkeys, len(mockRoute.Hops))
+
+ // Check that expected route is constructed.
+ for i, hop := range mockRoute.Hops {
+ require.Equal(t, hop.PubKeyBytes[:],
+ resp.HopPubkeys[i])
+ }
+ },
+ },
+ {
+ name: "missing route",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ req.Route = nil
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "missing payment hash",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ req.PaymentHash = nil
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "invalid session key",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ req.SessionKey = []byte{1, 2, 3}
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ {
+ name: "route unmarshall fails",
+ setup: func(t *testing.T, m *mockRouteProcessor,
+ req *BuildOnionRequest) {
+
+ m.unmarshallErr = errors.New("unmarshall error")
+ },
+ expectedErrCode: codes.InvalidArgument,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ mockProcessor := &mockRouteProcessor{}
+ server := &Server{
+ cfg: &Config{RouteProcessor: mockProcessor},
+ }
+
+ req := &BuildOnionRequest{
+ Route: &lnrpc.Route{},
+ PaymentHash: make([]byte, 32),
+ }
+
+ if tc.setup != nil {
+ tc.setup(t, mockProcessor, req)
+ }
+
+ resp, err := server.BuildOnion(t.Context(), req)
+
+ if tc.expectedErrCode != codes.OK {
+ require.Error(t, err)
+ s, ok := status.FromError(err)
+ require.True(t, ok)
+ require.Equal(t, tc.expectedErrCode, s.Code())
+
+ return
+ }
+
+ require.NoError(t, err)
+ if tc.checkResponse != nil {
+ tc.checkResponse(t, resp)
+ }
+ })
+ }
+}
+
+// TestDeleteAttempts is a unit test that verifies the behavior of the
+// DeleteAttempts RPC handler in isolation. It ensures correct translation of
+// store-level deletion results into the proto response, proper ordering of
+// results to match the request, and correct gRPC error handling when the
+// store fails.
+func TestDeleteAttempts(t *testing.T) {
+ t.Parallel()
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+
+ // setup configures the mock store and returns the request.
+ setup func(*testing.T, *mockAttemptStore) *DeleteAttemptsRequest
+
+ // expectedErrCode is the gRPC error code we expect from the
+ // call. codes.OK means we expect a successful response.
+ expectedErrCode codes.Code
+
+ // checkResponse validates the response on success.
+ checkResponse func(*testing.T, *DeleteAttemptsResponse)
+ }{
+ {
+ name: "successful batch delete with mixed results",
+ setup: func(t *testing.T,
+ store *mockAttemptStore) *DeleteAttemptsRequest {
+
+ store.deleteResp = map[uint64]htlcswitch.DeletionStatus{
+ 1: htlcswitch.DeletionOK,
+ 2: htlcswitch.DeletionPending,
+ 3: htlcswitch.DeletionNotFound,
+ 4: htlcswitch.DeletionFailed,
+ }
+
+ return &DeleteAttemptsRequest{
+ AttemptIds: []uint64{1, 2, 3, 4},
+ }
+ },
+ expectedErrCode: codes.OK,
+ checkResponse: func(t *testing.T,
+ resp *DeleteAttemptsResponse) {
+
+ require.Len(t, resp.Results, 4)
+
+ // Verify results preserve request order.
+ require.Equal(t, uint64(1),
+ resp.Results[0].AttemptId)
+ require.Equal(t,
+ AttemptDeletionStatus_DELETION_OK,
+ resp.Results[0].Status,
+ )
+
+ require.Equal(t, uint64(2),
+ resp.Results[1].AttemptId)
+ require.Equal(t,
+ AttemptDeletionStatus_DELETION_PENDING,
+ resp.Results[1].Status,
+ )
+
+ require.Equal(t, uint64(3),
+ resp.Results[2].AttemptId)
+ require.Equal(t,
+ AttemptDeletionStatus_DELETION_NOT_FOUND,
+ resp.Results[2].Status,
+ )
+
+ require.Equal(t, uint64(4),
+ resp.Results[3].AttemptId)
+ require.Equal(t,
+ AttemptDeletionStatus_DELETION_FAILED,
+ resp.Results[3].Status,
+ )
+ },
+ },
+ {
+ name: "empty request returns empty results",
+ setup: func(t *testing.T,
+ store *mockAttemptStore) *DeleteAttemptsRequest {
+
+ store.deleteResp = map[uint64]htlcswitch.DeletionStatus{}
+
+ return &DeleteAttemptsRequest{
+ AttemptIds: []uint64{},
+ }
+ },
+ expectedErrCode: codes.OK,
+ checkResponse: func(t *testing.T,
+ resp *DeleteAttemptsResponse) {
+
+ require.Empty(t, resp.Results)
+ },
+ },
+ {
+ name: "duplicate IDs deduplicated",
+ setup: func(t *testing.T,
+ store *mockAttemptStore) *DeleteAttemptsRequest {
+
+ store.deleteResp = map[uint64]htlcswitch.DeletionStatus{
+ 1: htlcswitch.DeletionOK,
+ 2: htlcswitch.DeletionOK,
+ }
+
+ return &DeleteAttemptsRequest{
+ AttemptIds: []uint64{1, 2, 1},
+ }
+ },
+ expectedErrCode: codes.OK,
+ checkResponse: func(t *testing.T,
+ resp *DeleteAttemptsResponse) {
+
+ // Duplicates are silently collapsed.
+ require.Len(t, resp.Results, 2)
+ },
+ },
+ {
+ name: "store error returns internal gRPC error",
+ setup: func(t *testing.T,
+ store *mockAttemptStore) *DeleteAttemptsRequest {
+
+ store.deleteErr = errors.New("db failure")
+
+ return &DeleteAttemptsRequest{
+ AttemptIds: []uint64{1},
+ }
+ },
+ expectedErrCode: codes.Internal,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ mockStore := &mockAttemptStore{}
+
+ server, _, err := New(&Config{
+ HtlcDispatcher: &mockPayer{},
+ AttemptStore: mockStore,
+ })
+ require.NoError(t, err)
+
+ req := tc.setup(t, mockStore)
+
+ resp, err := server.DeleteAttempts(
+ t.Context(), req,
+ )
+
+ if tc.expectedErrCode != codes.OK {
+ require.Error(t, err)
+ s, ok := status.FromError(err)
+ require.True(t, ok)
+ require.Equal(t,
+ tc.expectedErrCode, s.Code(),
+ )
+
+ return
+ }
+
+ require.NoError(t, err)
+ require.NotNil(t, resp)
+
+ if tc.checkResponse != nil {
+ tc.checkResponse(t, resp)
+ }
+ })
+ }
+}
+
+// TestDeletionStatusToProto verifies the mapping from internal DeletionStatus
+// values to their proto enum counterparts.
+func TestDeletionStatusToProto(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ input htlcswitch.DeletionStatus
+ expected AttemptDeletionStatus
+ }{
+ {
+ name: "OK",
+ input: htlcswitch.DeletionOK,
+ expected: AttemptDeletionStatus_DELETION_OK,
+ },
+ {
+ name: "Pending",
+ input: htlcswitch.DeletionPending,
+ expected: AttemptDeletionStatus_DELETION_PENDING,
+ },
+ {
+ name: "NotFound",
+ input: htlcswitch.DeletionNotFound,
+ expected: AttemptDeletionStatus_DELETION_NOT_FOUND,
+ },
+ {
+ name: "Failed",
+ input: htlcswitch.DeletionFailed,
+ expected: AttemptDeletionStatus_DELETION_FAILED,
+ },
+ {
+ name: "unknown defaults to NotFound",
+ input: htlcswitch.DeletionStatus(99),
+ expected: AttemptDeletionStatus_DELETION_NOT_FOUND,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ result := deletionStatusToProto(tc.input)
+ require.Equal(t, tc.expected, result)
+ })
+ }
+}
+
+// TestMarshallFailureDetails tests the conversion of internal errors types
+// produced by the Switch into the wire/rpc representation.
+func TestMarshallFailureDetails(t *testing.T) {
+ t.Parallel()
+
+ mockWireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ mockLinkErr := htlcswitch.NewLinkError(mockWireMsg)
+ mockFwdErr := htlcswitch.NewForwardingError(mockWireMsg, 1)
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+ err error
+ expectedDetails *FailureDetails
+ }{
+ {
+ name: "unreadable",
+ err: htlcswitch.ErrUnreadableFailureMessage,
+ expectedDetails: &FailureDetails{
+ ErrorMessage: htlcswitch.ErrUnreadableFailureMessage.Error(),
+ Failure: &FailureDetails_UnreadableFailure{
+ UnreadableFailure: &UnreadableFailure{},
+ },
+ },
+ },
+
+ {
+ name: "clear text error",
+ err: mockLinkErr,
+ expectedDetails: &FailureDetails{
+ ErrorMessage: mockLinkErr.Error(),
+ Failure: &FailureDetails_LocalFailure{
+ LocalFailure: &LocalFailure{},
+ },
+ },
+ },
+ {
+ name: "forwarding error",
+ err: mockFwdErr,
+ expectedDetails: &FailureDetails{
+ ErrorMessage: mockFwdErr.Error(),
+ Failure: &FailureDetails_ForwardingFailure{
+ ForwardingFailure: &ForwardingFailure{
+ FailureSourceIndex: 1,
+ },
+ },
+ },
+ },
+ {
+ name: "internal error",
+ err: errors.New("some unexpected error"),
+ expectedDetails: &FailureDetails{
+ ErrorMessage: "some unexpected error",
+ Failure: &FailureDetails_SwitchError{
+ SwitchError: &SwitchError{},
+ },
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ details := marshallFailureDetails(tc.err)
+
+ require.Contains(t, details.ErrorMessage,
+ tc.expectedDetails.ErrorMessage)
+
+ if tc.expectedDetails.Failure == nil {
+ require.Nil(t, details.Failure)
+ return
+ }
+
+ // For clear text and forwarding errors, we expect the
+ // wire message to be encoded correctly.
+ switch failure := details.Failure.(type) {
+ case *FailureDetails_ForwardingFailure:
+ require.NotNil(t, failure.ForwardingFailure)
+ require.Equal(
+ t,
+ tc.expectedDetails.
+ GetForwardingFailure().
+ FailureSourceIndex,
+ failure.ForwardingFailure.
+ FailureSourceIndex,
+ )
+
+ decoded, err := UnmarshallFailureMessage(
+ failure.ForwardingFailure.WireMessage,
+ )
+ require.NoError(t, err)
+ require.Equal(t, mockWireMsg, decoded)
+
+ case *FailureDetails_LocalFailure:
+ require.NotNil(t, failure.LocalFailure)
+
+ decoded, err := UnmarshallFailureMessage(
+ failure.LocalFailure.WireMessage,
+ )
+ require.NoError(t, err)
+ require.Equal(t, mockWireMsg, decoded)
+
+ case *FailureDetails_UnreadableFailure:
+ require.NotNil(t, failure.UnreadableFailure)
+
+ case *FailureDetails_SwitchError:
+ require.NotNil(t, failure.SwitchError)
+
+ default:
+ t.Fatalf("unexpected failure type: %T",
+ details.Failure)
+ }
+ })
+ }
+}
+
+// TestUnmarshallFailureDetails tests the client helper for unmarshalling a
+// TrackOnion FailureDetails message. This is a round-trip test that ensures the
+// client helper can correctly decode the exact message that the server-side
+// logic produces.
+func TestUnmarshallFailureDetails(t *testing.T) {
+ t.Parallel()
+
+ // Create mock errors to be marshalled.
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ linkErr := htlcswitch.NewLinkError(wireMsg)
+ fwdErr := htlcswitch.NewForwardingError(wireMsg, 1)
+
+ testCases := []struct {
+ name string
+ originalErr error
+ }{
+ {
+ name: "forwarding failure",
+ originalErr: fwdErr,
+ },
+ {
+ name: "clear text failure",
+ originalErr: linkErr,
+ },
+ {
+ name: "unreadable failure",
+ originalErr: htlcswitch.ErrUnreadableFailureMessage,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ // Use the server-side helper to create the
+ // FailureDetails message.
+ details := marshallFailureDetails(tc.originalErr)
+
+ // Use the client-side helper to translate it back to a
+ // Go error.
+ translatedErr, err := UnmarshallFailureDetails(
+ details, nil,
+ )
+ require.NoError(t, err)
+
+ // Confirm that the final error is of the same type as
+ // the original.
+ require.IsType(t, tc.originalErr, translatedErr)
+ require.ErrorContains(
+ t, translatedErr, tc.originalErr.Error(),
+ )
+ })
+ }
+
+ // Test the fallback case where the oneof is not populated. This
+ // simulates a backward-compatibility scenario or a server-side bug.
+ // We expect the unmarshaller to return an error in this case which
+ // more clearly indicates to the rpc client that the htlc status is
+ // unknown.
+ t.Run("empty failure oneof", func(t *testing.T) {
+ details := &FailureDetails{
+ ErrorMessage: "simulated server bug",
+ Failure: nil,
+ }
+
+ translatedErr, err := UnmarshallFailureDetails(details, nil)
+ require.Error(t, err)
+ require.Nil(t, translatedErr)
+ })
+
+ // Add a test case for nil FailureDetails input.
+ t.Run("nil failure details", func(t *testing.T) {
+ t.Parallel()
+
+ _, err := UnmarshallFailureDetails(nil, nil)
+ require.Error(t, err)
+ require.EqualError(t, err,
+ "cannot unmarshall nil FailureDetails")
+ })
+
+ t.Run("generic error message fallback", func(t *testing.T) {
+ t.Parallel()
+
+ expectedMsg := "some generic error"
+ details := &FailureDetails{
+ Failure: &FailureDetails_SwitchError{
+ SwitchError: &SwitchError{},
+ },
+ ErrorMessage: expectedMsg,
+ }
+
+ translatedErr, err := UnmarshallFailureDetails(details, nil)
+ require.NoError(t, err)
+ require.EqualError(t, translatedErr, expectedMsg)
+ })
+
+ t.Run("encrypted error with decryptor", func(t *testing.T) {
+ t.Parallel()
+
+ expectedEncryptedData := []byte("some encrypted data")
+ details := &FailureDetails{
+ Failure: &FailureDetails_EncryptedErrorData{
+ EncryptedErrorData: expectedEncryptedData,
+ },
+ }
+
+ // Create a forwarding error to be returned by the mock
+ // decrypter. Mock error decrypter that always returns a
+ // specific error.
+ mockErrorDecrypter := &mockErrorDecrypter{
+ decryptedErr: *fwdErr,
+ }
+
+ translatedErr, err := UnmarshallFailureDetails(
+ details, mockErrorDecrypter,
+ )
+ require.NoError(t, err)
+ require.Equal(t, fwdErr, translatedErr)
+
+ // Assert that the original encrypted data was passed to the
+ // decryptor.
+ require.Equal(
+ t,
+ expectedEncryptedData,
+ []byte(mockErrorDecrypter.receivedData),
+ "decryptor did not receive the expected encrypted data",
+ )
+ })
+}
+
+// TestBuildErrorDecryptor tests the buildErrorDecryptor function.
+func TestBuildErrorDecryptor(t *testing.T) {
+ t.Parallel()
+
+ validSessionKey := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
+ 31, 32}
+ validPubKey := []byte{2, 153, 44, 150, 184, 220, 236, 177, 70, 240, 51,
+ 88, 154, 232, 72, 158, 23, 39, 58, 18, 201, 79, 200, 164, 48,
+ 103, 208, 148, 27, 216, 153, 206, 77}
+ invalidSessionKey := []byte{1, 2, 3}
+ invalidPubKey := []byte{1, 2, 3}
+
+ tests := []struct {
+ name string
+ sessionKey []byte
+ hopPubkeys [][]byte
+ expectsError bool
+ expectsDecrypt bool
+ }{
+ {
+ name: "Valid session key and pubkeys",
+ sessionKey: validSessionKey,
+ hopPubkeys: [][]byte{validPubKey, validPubKey},
+ expectsError: false,
+ expectsDecrypt: true,
+ },
+ {
+ name: "Empty session key",
+ sessionKey: []byte{},
+ hopPubkeys: [][]byte{validPubKey},
+ expectsError: true,
+ expectsDecrypt: false,
+ },
+ {
+ name: "Empty pubkeys",
+ sessionKey: validSessionKey,
+ hopPubkeys: [][]byte{},
+ expectsError: true,
+ expectsDecrypt: false,
+ },
+ {
+ name: "Empty session key and pubkeys",
+ sessionKey: []byte{},
+ hopPubkeys: [][]byte{},
+ expectsError: false,
+ expectsDecrypt: false,
+ },
+ {
+ name: "Invalid pubkey format",
+ sessionKey: validSessionKey,
+ hopPubkeys: [][]byte{invalidPubKey},
+ expectsError: true,
+ expectsDecrypt: false,
+ },
+ {
+ name: "Invalid session key format",
+ sessionKey: invalidSessionKey,
+ hopPubkeys: [][]byte{validPubKey},
+ expectsError: true,
+ expectsDecrypt: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ decryptor, err := buildErrorDecryptor(
+ tt.sessionKey, tt.hopPubkeys,
+ )
+
+ if tt.expectsError {
+ require.Error(t, err)
+ require.Nil(t, decryptor)
+ return
+ }
+
+ require.NoError(t, err)
+ if tt.expectsDecrypt {
+ require.NotNil(t, decryptor)
+ } else {
+ require.Nil(t, decryptor)
+ }
+ })
+ }
+}
+
+// TestMarshallDispatchFailure tests that the server-side marshalling of
+// internal htlcswitch errors into gRPC status errors with rich,
+// structurally-classified details is correct.
+func TestMarshallDispatchFailure(t *testing.T) {
+ t.Parallel()
+
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ linkErr := htlcswitch.NewLinkError(wireMsg)
+
+ //nolint:ll
+ testCases := []struct {
+ name string
+ err error
+ expectedGRPCCode codes.Code
+ checkDetails func(*testing.T, *SendOnionFailureDetails)
+ }{
+ {
+ name: "clear text error",
+ err: linkErr,
+ expectedGRPCCode: codes.FailedPrecondition,
+ checkDetails: func(t *testing.T, d *SendOnionFailureDetails) {
+ definite := d.GetDefiniteFailure()
+ require.NotNil(t, definite)
+ require.Nil(t, d.GetIndefiniteFailure())
+
+ ctf := definite.GetLocalFailure()
+ require.NotNil(t, ctf)
+
+ decoded, err := UnmarshallFailureMessage(
+ ctf.WireMessage,
+ )
+ require.NoError(t, err)
+ require.Equal(t, wireMsg, decoded)
+ },
+ },
+ {
+ name: "switch exiting",
+ err: htlcswitch.ErrSwitchExiting,
+ expectedGRPCCode: codes.Unavailable,
+ checkDetails: func(t *testing.T, d *SendOnionFailureDetails) {
+ indefinite := d.GetIndefiniteFailure()
+ require.NotNil(t, indefinite)
+ require.Nil(t, d.GetDefiniteFailure())
+ require.Equal(t,
+ IndefiniteFailureCode_SWITCH_EXITING,
+ indefinite.Reason,
+ )
+ },
+ },
+ {
+ name: "ambiguous init",
+ err: htlcswitch.ErrAmbiguousAttemptInit,
+ expectedGRPCCode: codes.Unavailable,
+ checkDetails: func(t *testing.T, d *SendOnionFailureDetails) {
+ indefinite := d.GetIndefiniteFailure()
+ require.NotNil(t, indefinite)
+ require.Nil(t, d.GetDefiniteFailure())
+ require.Equal(t,
+ IndefiniteFailureCode_HTLC_INIT_FAILED,
+ indefinite.Reason,
+ )
+ },
+ },
+ {
+ name: "generic internal error",
+ err: errors.New("generic error"),
+ expectedGRPCCode: codes.Unavailable,
+ checkDetails: func(t *testing.T, d *SendOnionFailureDetails) {
+ indefinite := d.GetIndefiniteFailure()
+ require.NotNil(t, indefinite)
+ require.Nil(t, d.GetDefiniteFailure())
+ require.Equal(t,
+ IndefiniteFailureCode_REASON_UNKNOWN,
+ indefinite.Reason,
+ )
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Marshall the error into a gRPC status error.
+ rpcErr := marshallDispatchFailure(tc.err)
+
+ // Assert the gRPC status code and extract the
+ // structured failure details.
+ details := requireSendOnionFailureDetails(
+ t, rpcErr, tc.expectedGRPCCode,
+ )
+ tc.checkDetails(t, details)
+ })
+ }
+}
+
+// TestGetSendOnionFailureDetails verifies the behavior of the
+// GetSendOnionFailureDetails helper.
+func TestGetSendOnionFailureDetails(t *testing.T) {
+ t.Parallel()
+
+ // Create a mock wire message and encode it.
+ wireMsg := lnwire.NewTemporaryChannelFailure(nil)
+ var buf bytes.Buffer
+ err := lnwire.EncodeFailure(&buf, wireMsg, 0)
+ require.NoError(t, err)
+
+ // Create mock SendOnionFailureDetails structs for expected outputs.
+ mockDefiniteDetails := &SendOnionFailureDetails{
+ ErrorMessage: "mock clear text error",
+ FailureClass: &SendOnionFailureDetails_DefiniteFailure{
+ DefiniteFailure: &DefiniteFailure{
+ LocalFailure: &LocalFailure{
+ WireMessage: buf.Bytes(),
+ },
+ },
+ },
+ }
+
+ mockIndefiniteDetails := &SendOnionFailureDetails{
+ ErrorMessage: "mock indefinite error",
+ FailureClass: &SendOnionFailureDetails_IndefiniteFailure{
+ IndefiniteFailure: &IndefiniteFailure{
+ Reason: IndefiniteFailureCode_REASON_UNKNOWN,
+ },
+ },
+ }
+
+ // Create gRPC status errors with the new mock details.
+ gRPCErrorWithDefiniteDetails, err := status.New(
+ codes.FailedPrecondition, "test error",
+ ).WithDetails(mockDefiniteDetails)
+ require.NoError(t, err)
+
+ gRPCErrorWithIndefiniteDetails, err := status.New(
+ codes.Internal, "test error",
+ ).WithDetails(mockIndefiniteDetails)
+ require.NoError(t, err)
+
+ // Create a gRPC status error without any details.
+ gRPCErrorWithoutDetails := status.Error(codes.Unavailable,
+ "generic gRPC error")
+
+ // Create a non-gRPC error.
+ nonGrpcError := errors.New("plain old error")
+
+ testCases := []struct {
+ name string
+ err error
+ expectedDetails *SendOnionFailureDetails
+ }{
+ {
+ name: "gRPC error with definite details",
+ err: gRPCErrorWithDefiniteDetails.Err(),
+ expectedDetails: mockDefiniteDetails,
+ },
+ {
+ name: "gRPC error with indefinite details",
+ err: gRPCErrorWithIndefiniteDetails.Err(),
+ expectedDetails: mockIndefiniteDetails,
+ },
+ {
+ name: "gRPC error without details",
+ err: gRPCErrorWithoutDetails,
+ expectedDetails: nil,
+ },
+ {
+ name: "non-gRPC error",
+ err: nonGrpcError,
+ expectedDetails: nil,
+ },
+ {
+ name: "nil error",
+ err: nil,
+ expectedDetails: nil,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result := GetSendOnionFailureDetails(tc.err)
+
+ // If no details were expected, assert nil and return.
+ if tc.expectedDetails == nil {
+ require.Nil(t, result)
+ return
+ }
+
+ // Otherwise, confirm the top-level error message.
+ require.NotNil(t, result)
+ require.Equal(t, tc.expectedDetails.ErrorMessage,
+ result.ErrorMessage)
+
+ // Now, validate the oneof FailureClass field.
+ switch expectedClass := tc.expectedDetails.
+ FailureClass.(type) {
+ case *SendOnionFailureDetails_DefiniteFailure:
+ actualDefinite := result.GetDefiniteFailure()
+ require.NotNil(t, actualDefinite)
+ require.Nil(t, result.GetIndefiniteFailure())
+
+ // Validate nested LocalFailure.
+ expectedErr := expectedClass.DefiniteFailure.
+ GetLocalFailure()
+ actualErr := actualDefinite.
+ GetLocalFailure()
+
+ require.NotNil(t, actualErr)
+ require.Equal(t, expectedErr.WireMessage,
+ actualErr.WireMessage)
+
+ case *SendOnionFailureDetails_IndefiniteFailure:
+ actualIndefinite := result.
+ GetIndefiniteFailure()
+
+ require.NotNil(t, actualIndefinite)
+ require.Nil(t, result.GetDefiniteFailure())
+
+ // Validate nested IndefiniteFailureCode reason.
+ require.Equal(t, expectedClass.
+ IndefiniteFailure.Reason,
+ actualIndefinite.Reason)
+
+ default:
+ t.Fatalf("unexpected failure class type: %T",
+ expectedClass)
+ }
+ })
+ }
+}
### lntest/rpc/harness_rpc.go
@@ -13,6 +13,7 @@ import (
"github.com/lightningnetwork/lnd/lnrpc/peersrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/switchrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnrpc/watchtowerrpc"
"github.com/lightningnetwork/lnd/lnrpc/wtclientrpc"
@@ -34,6 +35,7 @@ type HarnessRPC struct {
WalletUnlocker lnrpc.WalletUnlockerClient
Invoice invoicesrpc.InvoicesClient
Signer signrpc.SignerClient
+ Switch switchrpc.SwitchClient
Router routerrpc.RouterClient
WalletKit walletrpc.WalletKitClient
Watchtower watchtowerrpc.WatchtowerClient
@@ -71,6 +73,7 @@ func NewHarnessRPC(ctxt context.Context, t *testing.T, c *grpc.ClientConn,
WatchtowerClient: wtclientrpc.NewWatchtowerClientClient(c),
Signer: signrpc.NewSignerClient(c),
State: lnrpc.NewStateClient(c),
+ Switch: switchrpc.NewSwitchClient(c),
ChainClient: chainrpc.NewChainNotifierClient(c),
ChainKit: chainrpc.NewChainKitClient(c),
NeutrinoKit: neutrinorpc.NewNeutrinoKitClient(c),
### lntest/rpc/switch.go
@@ -0,0 +1,70 @@
+package rpc
+
+import (
+ "context"
+
+ "github.com/lightningnetwork/lnd/lnrpc/switchrpc"
+)
+
+// =====================
+// SwitchClient related RPCs.
+// =====================
+
+// SendOnion makes a RPC call to SendOnion and returns the error.
+//
+//nolint:lll
+func (h *HarnessRPC) SendOnion(
+ req *switchrpc.SendOnionRequest) error {
+
+ ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
+ defer cancel()
+
+ _, err := h.Switch.SendOnion(ctxt, req)
+
+ return err
+}
+
+// TrackOnion makes a RPC call to TrackOnion and asserts.
+//
+//nolint:lll
+func (h *HarnessRPC) TrackOnion(
+ req *switchrpc.TrackOnionRequest) *switchrpc.TrackOnionResponse {
+
+ ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
+ defer cancel()
+
+ resp, err := h.Switch.TrackOnion(ctxt, req)
+ h.NoError(err, "TrackOnion")
+
+ return resp
+}
+
+// BuildOnion makes a RPC call to BuildOnion and asserts.
+//
+//nolint:lll
+func (h *HarnessRPC) BuildOnion(
+ req *switchrpc.BuildOnionRequest) *switchrpc.BuildOnionResponse {
+
+ ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
+ defer cancel()
+
+ resp, err := h.Switch.BuildOnion(ctxt, req)
+ h.NoError(err, "BuildOnion")
+
+ return resp
+}
+
+// DeleteAttempts makes a RPC call to DeleteAttempts and asserts.
+//
+//nolint:ll
+func (h *HarnessRPC) DeleteAttempts(
+ req *switchrpc.DeleteAttemptsRequest) *switchrpc.DeleteAttemptsResponse {
+
+ ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout)
+ defer cancel()
+
+ resp, err := h.Switch.DeleteAttempts(ctxt, req)
+ h.NoError(err, "DeleteAttempts")
+
+ return resp
+}
### log.go
@@ -38,6 +38,7 @@ import (
"github.com/lightningnetwork/lnd/lnrpc/peersrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/switchrpc"
"github.com/lightningnetwork/lnd/lnrpc/verrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnwallet"
@@ -195,6 +196,7 @@ func SetupLoggers(root *build.SubLoggerManager, interceptor signal.Interceptor)
AddSubLogger(root, routing.Subsystem, interceptor, routing.UseLogger)
AddSubLogger(root, routerrpc.Subsystem, interceptor, routerrpc.UseLogger)
+ AddSubLogger(root, switchrpc.Subsystem, interceptor, switchrpc.UseLogger)
AddSubLogger(root, chanfitness.Subsystem, interceptor, chanfitness.UseLogger)
AddSubLogger(root, verrpc.Subsystem, interceptor, verrpc.UseLogger)
AddSubLogger(root, healthcheck.Subsystem, interceptor, healthcheck.UseLogger)
### make/testing_flags.mk
@@ -1,5 +1,5 @@
DEV_TAGS = dev
-RPC_TAGS = autopilotrpc chainrpc invoicesrpc neutrinorpc peersrpc signrpc walletrpc watchtowerrpc
+RPC_TAGS = autopilotrpc chainrpc invoicesrpc neutrinorpc peersrpc signrpc switchrpc walletrpc watchtowerrpc
LOG_TAGS =
TEST_FLAGS =
ITEST_FLAGS =
@@ -166,4 +166,4 @@ endif
ITEST_TAGS := $(DEV_TAGS) $(RPC_TAGS) integration $(backend)
# Construct the coverage test command with the added build flags.
-UNIT_COVER := $(GOTEST) $(COVER_FLAGS) -tags="$(DEV_TAGS) $(LOG_TAGS)" $(TEST_FLAGS) $(COVER_PKG)
+UNIT_COVER := $(GOTEST) $(COVER_FLAGS) -tags="$(DEV_TAGS) $(RPC_TAGS) $(LOG_TAGS)" $(TEST_FLAGS) $(COVER_PKG)
### payments/db/payment.go
@@ -216,7 +216,7 @@ func (h *HTLCAttemptInfo) Circuit() (*sphinx.Circuit, error) {
// attachOnionBlobAndCircuit creates a sphinx packet and caches the onion blob
// and circuit for this attempt.
func (h *HTLCAttemptInfo) attachOnionBlobAndCircuit() error {
- onionBlob, circuit, err := generateSphinxPacket(
+ onionBlob, circuit, err := GenerateSphinxPacket(
&h.Route, h.Hash[:], h.SessionKey(),
)
if err != nil {
@@ -661,11 +661,11 @@ func (m *MPPayment) AllowMoreAttempts() (bool, error) {
return true, nil
}
-// generateSphinxPacket generates then encodes a sphinx packet which encodes
+// GenerateSphinxPacket generates then encodes a sphinx packet which encodes
// the onion route specified by the passed layer 3 route. The blob returned
// from this function can immediately be included within an HTLC add packet to
// be sent to the first hop within the route.
-func generateSphinxPacket(rt *route.Route, paymentHash []byte,
+func GenerateSphinxPacket(rt *route.Route, paymentHash []byte,
sessionKey *btcec.PrivateKey) ([]byte, *sphinx.Circuit, error) {
// Now that we know we have an actual route, we'll map the route into a
### payments/db/payment_test.go
@@ -1572,7 +1572,7 @@ func TestEmptyRoutesGenerateSphinxPacket(t *testing.T) {
sessionKey, _ := btcec.NewPrivateKey()
emptyRoute := &route.Route{}
- _, _, err := generateSphinxPacket(emptyRoute, testHash[:], sessionKey)
+ _, _, err := GenerateSphinxPacket(emptyRoute, testHash[:], sessionKey)
require.ErrorIs(t, err, route.ErrNoRouteHopsProvided)
}
### peer/test_utils.go
@@ -427,6 +427,11 @@ func (m *mockUpdateHandler) HandleChannelUpdate(msg lnwire.Message) {}
// ChanID returns the mockUpdateHandler's cid.
func (m *mockUpdateHandler) ChanID() lnwire.ChannelID { return m.cid }
+// ShortChanID returns the mockUpdateHandler's cid.
+func (m *mockUpdateHandler) ShortChanID() lnwire.ShortChannelID {
+ return lnwire.NewShortChanIDFromInt(0)
+}
+
// Bandwidth currently returns a dummy value.
func (m *mockUpdateHandler) Bandwidth() lnwire.MilliSatoshi { return 0 }
### routing/graph.go
@@ -46,7 +46,9 @@ func FetchAmountPairCapacity(graph Graph, source, nodeFrom, nodeTo route.Vertex,
//
// Note: Inbound fees are not used here because this method is only used
// by a deprecated router rpc.
- u := newNodeEdgeUnifier(source, nodeTo, false, nil)
+ u := newNodeEdgeUnifier(
+ source, nodeTo, &singleOrigin{source: source}, false, nil,
+ )
err := u.addGraphPolicies(graph)
if err != nil {
### routing/pathfind.go
@@ -50,11 +50,46 @@ const (
fakeHopHintCapacity = btcutil.Amount(10 * btcutil.SatoshiPerBitcoin)
)
-// pathFinder defines the interface of a path finding algorithm.
+// RouteOrigin determines where routes can originate from. The backward
+// Dijkstra terminates when it reaches any origin vertex. This is the
+// source-end counterpart to AdditionalEdge, which extends the graph at the
+// destination end. Standard lnd uses singleOrigin (one source node). A
+// multi-backend payment service can provide a multi-source implementation
+// that terminates at any of its gateway nodes.
+//
+// NOTE: Only include vertices the caller can actually dispatch payments
+// from.
+type RouteOrigin interface {
+ // IsOrigin reports whether the given vertex is a valid route
+ // starting point.
+ //
+ // NOTE: Implementations should be O(1). findPath calls IsOrigin
+ // once per heap pop and once per edge relaxation, so any per-call
+ // cost directly contributes to path-finding latency.
+ IsOrigin(v route.Vertex) bool
+}
+
+// singleOrigin is the default RouteOrigin: a single source vertex.
+type singleOrigin struct {
+ source route.Vertex
+}
+
+// IsOrigin reports whether v is the source vertex.
+func (s *singleOrigin) IsOrigin(v route.Vertex) bool {
+ return v == s.source
+}
+
+// pathFinder defines the interface of a path finding algorithm. The
+// first return value is the source vertex of the computed path. This
+// is typically the node's own key, but it may be an arbitrary source
+// or, for multi-origin callers, whichever origin provides the
+// cheapest path.
type pathFinder = func(g *graphParams, r *RestrictParams,
- cfg *PathFindingConfig, self, source, target route.Vertex,
- amt lnwire.MilliSatoshi, timePref float64, finalHtlcExpiry int32) (
- []*unifiedEdge, float64, error)
+ cfg *PathFindingConfig, self route.Vertex,
+ origin RouteOrigin, target route.Vertex,
+ amt lnwire.MilliSatoshi, timePref float64,
+ finalHtlcExpiry int32) (
+ route.Vertex, []*unifiedEdge, float64, error)
var (
// DefaultEstimator is the default estimator used for computing
@@ -601,9 +636,9 @@ func getOutgoingBalance(node route.Vertex, outgoingChans map[uint64]struct{},
// path and accurately check the amount to forward at every node against the
// available bandwidth.
func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
- self, source, target route.Vertex, amt lnwire.MilliSatoshi,
- timePref float64, finalHtlcExpiry int32) ([]*unifiedEdge, float64,
- error) {
+ self route.Vertex, origin RouteOrigin, target route.Vertex,
+ amt lnwire.MilliSatoshi, timePref float64,
+ finalHtlcExpiry int32) (route.Vertex, []*unifiedEdge, float64, error) {
// Pathfinding can be a significant portion of the total payment
// latency, especially on low-powered devices. Log several metrics to
@@ -626,7 +661,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
context.TODO(), target,
)
if err != nil {
- return nil, 0, err
+ return route.Vertex{}, nil, 0, err
}
}
@@ -635,14 +670,14 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
err := feature.ValidateRequired(features)
if err != nil {
log.Warnf("Pathfinding destination node features: %v", err)
- return nil, 0, errUnknownRequiredFeature
+ return route.Vertex{}, nil, 0, errUnknownRequiredFeature
}
// Ensure that all transitive dependencies are set.
err = feature.ValidateDeps(features)
if err != nil {
log.Warnf("Pathfinding destination node features: %v", err)
- return nil, 0, errMissingDependentFeature
+ return route.Vertex{}, nil, 0, errMissingDependentFeature
}
// Now that we know the feature vector is well-formed, we'll proceed in
@@ -652,7 +687,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
if r.PaymentAddr.IsSome() &&
!features.HasFeature(lnwire.PaymentAddrOptional) {
- return nil, 0, errNoPaymentAddr
+ return route.Vertex{}, nil, 0, errNoPaymentAddr
}
// Set up outgoing channel map for quicker access.
@@ -664,30 +699,31 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
}
}
- // If we are routing from ourselves, check that we have enough local
- // balance available.
- if source == self {
+ // If we are routing from ourselves, check that we have enough
+ // local balance available.
+ if origin.IsOrigin(self) {
max, total, err := getOutgoingBalance(
self, outgoingChanMap, g.bandwidthHints, g.graph,
)
if err != nil {
- return nil, 0, err
+ return route.Vertex{}, nil, 0, err
}
// If the total outgoing balance isn't sufficient, it will be
// impossible to complete the payment.
if total < amt {
- log.Warnf("Not enough outbound balance to send "+
- "htlc of amount: %v, only have local "+
- "balance: %v", amt, total)
+ log.Warnf("Not enough outbound balance to "+
+ "send htlc of amount: %v, only have "+
+ "local balance: %v", amt, total)
- return nil, 0, errInsufficientBalance
+ return route.Vertex{}, nil, 0,
+ errInsufficientBalance
}
- // If there is only not enough capacity on a single route, it
- // may still be possible to complete the payment by splitting.
+ // If there is not enough capacity on a single route, it may
+ // still be possible to complete the payment by splitting.
if max < amt {
- return nil, 0, errNoPathFound
+ return route.Vertex{}, nil, 0, errNoPathFound
}
}
@@ -729,7 +765,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// and depends on whether the destination is blinded or not.
lastHopPayloadSize, err := lastHopPayloadSize(r, finalHtlcExpiry, amt)
if err != nil {
- return nil, 0, err
+ return route.Vertex{}, nil, 0, err
}
// We can't always assume that the end destination is publicly
@@ -763,8 +799,8 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// Validate time preference value.
if math.Abs(timePref) > 1 {
- return nil, 0, fmt.Errorf("time preference %v out of range "+
- "[-1, 1]", timePref)
+ return route.Vertex{}, nil, 0, fmt.Errorf("time preference %v "+
+ "out of range [-1, 1]", timePref)
}
// Scale to avoid the extremes -1 and 1 which run into infinity issues.
@@ -857,7 +893,11 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
outboundFee int64
)
- if fromVertex != source {
+ // The route origin is fee-exempt and doesn't add a
+ // payload hop.
+ fromIsOrigin := origin.IsOrigin(fromVertex)
+
+ if !fromIsOrigin {
outboundFee = int64(
edge.policy.ComputeFee(amountToSend),
)
@@ -956,7 +996,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// little inaccuracy here because we are over estimating by
// 1 hop.
var payloadSize uint64
- if fromVertex != source {
+ if !fromIsOrigin {
// In case the unifiedEdge does not have a payload size
// function supplied we request a graceful shutdown
// because this should never happen.
@@ -1051,7 +1091,11 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
return fromFeatures, nil
}
- routeToSelf := source == target
+ // Allow circular routes when the target is itself an origin.
+ // This lets path finding explore past the target on first visit
+ // rather than terminating immediately, enabling self-payments
+ // (e.g., rebalancing).
+ allowCircular := origin.IsOrigin(target)
for {
nodesVisited++
@@ -1061,12 +1105,12 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// Create unified policies for all incoming connections. Don't
// use inbound fees for the exit hop.
u := newNodeEdgeUnifier(
- self, pivot, !isExitHop, outgoingChanMap,
+ self, pivot, origin, !isExitHop, outgoingChanMap,
)
err := u.addGraphPolicies(g.graph)
if err != nil {
- return nil, 0, err
+ return route.Vertex{}, nil, 0, err
}
// We add hop hints that were supplied externally.
@@ -1101,10 +1145,10 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
for fromNode, edgeUnifier := range u.edgeUnifiers {
// The target node is not recorded in the distance map.
// Therefore we need to have this check to prevent
- // creating a cycle. Only when we intend to route to
- // self, we allow this cycle to form. In that case we'll
- // also break out of the search loop below.
- if !routeToSelf && fromNode == target {
+ // creating a cycle. When circular routes are
+ // permitted, we allow this cycle to form so
+ // Dijkstra can find the cheapest loop.
+ if !allowCircular && fromNode == target {
continue
}
@@ -1127,7 +1171,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// Get feature vector for fromNode.
fromFeatures, err := getGraphFeatures(fromNode)
if err != nil {
- return nil, 0, err
+ return route.Vertex{}, nil, 0, err
}
// If there are no valid features, skip this node.
@@ -1148,14 +1192,21 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
// from the heap.
partialPath = heap.Pop(&nodeHeap).(*nodeWithDist)
- // If we've reached our source (or we don't have any incoming
- // edges), then we're done here and can exit the graph
- // traversal early.
- if partialPath.node == source {
+ // If we've reached a valid origin (or we don't have any
+ // incoming edges), then we're done here and can exit the
+ // graph traversal early.
+ if origin.IsOrigin(partialPath.node) {
break
}
}
+ // The path finding loop exits either when it reaches a valid origin or
+ // when the heap empties. In the latter case, no path exists.
+ source := partialPath.node
+ if !origin.IsOrigin(source) {
+ return route.Vertex{}, nil, 0, errNoPathFound
+ }
+
// Use the distance map to unravel the forward path from source to
// target.
var pathEdges []*unifiedEdge
@@ -1166,7 +1217,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
if !ok {
// If the node doesn't have a next hop it means we
// didn't find a path.
- return nil, 0, errNoPathFound
+ return route.Vertex{}, nil, 0, errNoPathFound
}
// Add the next hop to the list of path edges.
@@ -1200,7 +1251,7 @@ func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
distance[source].probability, len(pathEdges),
distance[source].netAmountReceived-amt)
- return pathEdges, distance[source].probability, nil
+ return source, pathEdges, distance[source].probability, nil
}
// blindedPathRestrictions are a set of constraints to adhere to when
### routing/pathfind_test.go
@@ -887,6 +887,18 @@ func TestPathFinding(t *testing.T) {
}, {
name: "route to self",
fn: runRouteToSelf,
+ }, {
+ name: "multi origin",
+ fn: runMultiOrigin,
+ }, {
+ name: "multi origin cheapest path",
+ fn: runMultiOriginCheapestPath,
+ }, {
+ name: "multi origin circular route",
+ fn: runMultiOriginCircularRoute,
+ }, {
+ name: "multi origin outgoing restriction",
+ fn: runMultiOriginOutgoingRestriction,
}, {
name: "with metadata",
fn: runFindPathWithMetadata,
@@ -3073,6 +3085,522 @@ func runRouteToSelf(t *testing.T, useCache bool) {
ctx.assertPath(path, []uint64{1, 3, 2})
}
+// multiOrigin is a RouteOrigin that terminates at any vertex in the set. This
+// is the multi-source variant for external payment controllers that dispatch
+// from multiple gateway nodes.
+type multiOrigin struct {
+ sources map[route.Vertex]struct{}
+}
+
+func (m *multiOrigin) IsOrigin(v route.Vertex) bool {
+ _, ok := m.sources[v]
+
+ return ok
+}
+
+// findPathWithOrigin is a test helper that runs findPath with a given
+// RouteOrigin and returns the settled source vertex alongside the path.
+func findPathWithOrigin(t *testing.T, ctx *pathFindingTestContext,
+ origin RouteOrigin, target route.Vertex,
+ amt lnwire.MilliSatoshi) (route.Vertex, []*unifiedEdge, error) {
+
+ t.Helper()
+
+ sourceNode, err := ctx.v1Graph.SourceNode(t.Context())
+ require.NoError(t, err)
+
+ var (
+ source route.Vertex
+ path []*unifiedEdge
+ )
+
+ err = ctx.v1Graph.GraphSession(
+ t.Context(),
+ func(graph graphdb.NodeTraverser) error {
+ source, path, _, err = findPath(
+ &graphParams{
+ bandwidthHints: ctx.bandwidthHints,
+ graph: graph,
+ },
+ &ctx.restrictParams,
+ &ctx.pathFindingConfig,
+ sourceNode.PubKeyBytes,
+ origin, target,
+ amt, 0, 0,
+ )
+
+ return err
+ }, func() {
+ path = nil
+ },
+ )
+
+ return source, path, err
+}
+
+// runMultiOrigin tests that the pathfinder correctly terminates at the nearest
+// origin when given a RouteOrigin containing multiple valid source vertices.
+// This exercises the multi-source Dijkstra behavior needed by an external
+// payment controller that dispatches from multiple gateway nodes.
+func runMultiOrigin(t *testing.T, useCache bool) {
+ // Build a diamond-shaped network with two possible origins
+ // and a separate proxy node as self (no channels):
+ //
+ // proxy (self, no channels)
+ // gw1 ---- alice ---- dest
+ // gw2 ---- bob ------/
+ //
+ // Both gw1 and gw2 are valid origins. Since origins are fee-exempt
+ // (the sender doesn't pay its own forwarding fee), we differentiate
+ // the paths by the intermediate hop's fee: alice charges 500 msat
+ // while bob charges 2000 msat.
+ testChannels := []*testChannel{
+ symmetricTestChannel("gw1", "alice", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 1,
+ ),
+ symmetricTestChannel("gw2", "bob", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 2,
+ ),
+ // alice->dest is cheap (500 msat).
+ symmetricTestChannel("alice", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 3,
+ ),
+ // bob->dest is expensive (2000 msat).
+ symmetricTestChannel("bob", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 2000,
+ }, 4,
+ ),
+ }
+
+ ctx := newPathFindingTestContext(t, useCache, testChannels, "proxy")
+
+ gw1 := ctx.keyFromAlias("gw1")
+ gw2 := ctx.keyFromAlias("gw2")
+ target := ctx.keyFromAlias("dest")
+ paymentAmt := lnwire.NewMSatFromSatoshis(100)
+
+ // With both gateways available, the pathfinder should select
+ // gw1->alice->dest since alice charges less than bob.
+ bothOrigins := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw1: {},
+ gw2: {},
+ }}
+ source, path, err := findPathWithOrigin(
+ t, ctx, bothOrigins, target, paymentAmt,
+ )
+ require.NoError(t, err, "unable to find multi-origin path")
+ require.Equal(t, gw1, source, "expected gw1 as selected route source")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, path, "alice", "dest",
+ )
+
+ // Simulate gw1 going offline by removing it from the origin set.
+ // The pathfinder should fall back to gw2->bob->dest.
+ gw2Only := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw2: {},
+ }}
+ source, path, err = findPathWithOrigin(
+ t, ctx, gw2Only, target, paymentAmt,
+ )
+ require.NoError(t, err, "unable to find path via gw2")
+ require.Equal(t, gw2, source, "expected gw2 as selected route source")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, path, "bob", "dest",
+ )
+
+ // An empty origin set should return errNoPathFound, since the
+ // path-finding loop will exhaust the heap without reaching any origin.
+ emptyOrigin := &multiOrigin{sources: map[route.Vertex]struct{}{}}
+ _, _, err = findPathWithOrigin(
+ t, ctx, emptyOrigin, target, paymentAmt,
+ )
+ require.ErrorIs(t, err, errNoPathFound)
+}
+
+// runMultiOriginCircularRoute tests that when the target is in the origin
+// set and a circular route physically exists, the pathfinder can find it.
+// The topology extends the diamond with a direct dest→gw2 channel so that
+// gw2→bob→dest→gw2 forms a valid cycle. With origins={gw1, gw2} and
+// target=gw2, the pathfinder should pick whichever path is cheaper:
+// cross-gateway (gw1→alice→dest→gw2) or circular (gw2→bob→dest→gw2).
+func runMultiOriginCircularRoute(t *testing.T, useCache bool) {
+ // Extended diamond topology with a closing channel (chan 5):
+ //
+ // proxy (self, no channels)
+ // gw1 ---- alice ---- dest (chan 1, chan 3)
+ // gw2 ---- bob ------/ (chan 2, chan 4)
+ // gw2 --------- dest (chan 5, direct)
+ //
+ // Fee structure makes the circular path (gw2→bob→dest→gw2) cheaper
+ // than the cross-gateway path (gw1→alice→dest→gw2): bob charges
+ // 500 msat, alice charges 2000 msat. The dest→gw2 hop on chan 5
+ // is cheap (100 msat) for both paths.
+ testChannels := []*testChannel{
+ symmetricTestChannel("gw1", "alice", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 2000,
+ }, 1,
+ ),
+ symmetricTestChannel("gw2", "bob", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 2,
+ ),
+ symmetricTestChannel("alice", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 2000,
+ }, 3,
+ ),
+ symmetricTestChannel("bob", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 4,
+ ),
+ symmetricTestChannel("dest", "gw2", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 100,
+ }, 5,
+ ),
+ }
+
+ ctx := newPathFindingTestContext(t, useCache, testChannels, "proxy")
+
+ gw1 := ctx.keyFromAlias("gw1")
+ gw2 := ctx.keyFromAlias("gw2")
+ paymentAmt := lnwire.NewMSatFromSatoshis(100)
+
+ // With both gateways as origins and gw2 as target, the circular
+ // path through gw2 should win because it's cheaper.
+ bothOrigins := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw1: {},
+ gw2: {},
+ }}
+ source, path, err := findPathWithOrigin(
+ t, ctx, bothOrigins, gw2, paymentAmt,
+ )
+ require.NoError(t, err)
+ require.Equal(t, gw2, source,
+ "circular gw2→bob→dest→gw2 should win on cost")
+ require.Greater(t, len(path), 0,
+ "circular route should have real hops")
+
+ lastHop := path[len(path)-1].policy.ToNodePubKey()
+ require.Equal(t, gw2, lastHop,
+ "last hop should reach gw2")
+
+ // Cross-gateway path should be found when gw2 is removed from
+ // the origin set (only gw1 remains).
+ gw1Only := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw1: {},
+ }}
+ source, _, err = findPathWithOrigin(
+ t, ctx, gw1Only, gw2, paymentAmt,
+ )
+ require.NoError(t, err)
+ require.Equal(t, gw1, source,
+ "with only gw1, cross-gateway path should be found")
+}
+
+// runMultiOriginCheapestPath proves that multi-origin termination finds the
+// globally cheapest path by cross-validating against exhaustive single-origin
+// searches. This addresses the question: "is it enough to halt when you've
+// found one of the origin nodes?" The answer is yes, because Dijkstra's
+// min-heap ordering guarantees the first origin popped has the minimum cost.
+//
+// The test builds a network with three gateways at varying distances and fee
+// levels, runs findPath once with all three as a multi-origin set, then runs
+// findPath separately for each gateway as a single origin. The multi-origin
+// result must match the cheapest individual result.
+func runMultiOriginCheapestPath(t *testing.T, useCache bool) {
+ // Build a network where the cheapest origin is NOT the one with the
+ // fewest intermediate hops:
+ //
+ // gw1 ---- cheap1 ---- cheap2 ---- dest (2 intermediaries)
+ // gw2 ---- expensive ---- dest (1 intermediary)
+ // gw3 ---- medium1 ---- medium2 ---- dest (2 intermediaries)
+ //
+ // gw2's path has the fewest hops, but gw1's path is cheapest in fees.
+ // Origins are fee-exempt (the sender doesn't pay its own forwarding
+ // fee), so cost differentiation comes entirely from the intermediate
+ // hops. The cheap1/cheap2 edges each charge 100 msat base fee, the
+ // expensive edge charges 5000, and the medium edges charge 800 each.
+ testChannels := []*testChannel{
+ // gw1's path: cheap intermediaries.
+ symmetricTestChannel("gw1", "cheap1", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 100,
+ }, 1,
+ ),
+ symmetricTestChannel("cheap1", "cheap2", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 100,
+ }, 2,
+ ),
+ symmetricTestChannel("cheap2", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 100,
+ }, 3,
+ ),
+ // gw2's path: fewest hops but expensive intermediary.
+ symmetricTestChannel("gw2", "expensive", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 5000,
+ }, 4,
+ ),
+ symmetricTestChannel("expensive", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 5000,
+ }, 5,
+ ),
+ // gw3's path: medium-cost intermediaries.
+ symmetricTestChannel("gw3", "medium1", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 800,
+ }, 6,
+ ),
+ symmetricTestChannel("medium1", "medium2", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 800,
+ }, 7,
+ ),
+ symmetricTestChannel("medium2", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 800,
+ }, 8,
+ ),
+ }
+
+ ctx := newPathFindingTestContext(t, useCache, testChannels, "proxy")
+
+ gw1 := ctx.keyFromAlias("gw1")
+ gw2 := ctx.keyFromAlias("gw2")
+ gw3 := ctx.keyFromAlias("gw3")
+ target := ctx.keyFromAlias("dest")
+ paymentAmt := lnwire.NewMSatFromSatoshis(1000)
+
+ const (
+ startingHeight = 100
+ finalHopCLTV = 1
+ )
+
+ // buildRoute converts a findPath result into a route so we can
+ // compare TotalFees across origins.
+ buildRoute := func(source route.Vertex,
+ path []*unifiedEdge) *route.Route {
+
+ r, err := newRoute(
+ source, path, startingHeight,
+ finalHopParams{
+ amt: paymentAmt,
+ cltvDelta: finalHopCLTV,
+ records: nil,
+ }, nil,
+ )
+ require.NoError(t, err)
+
+ return r
+ }
+
+ // Run multi-origin search with all three gateways.
+ allOrigins := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw1: {},
+ gw2: {},
+ gw3: {},
+ }}
+ multiSource, multiPath, err := findPathWithOrigin(
+ t, ctx, allOrigins, target, paymentAmt,
+ )
+ require.NoError(t, err, "multi-origin findPath failed")
+ multiRoute := buildRoute(multiSource, multiPath)
+
+ // Run single-origin search for each gateway independently
+ // and record the total fees for each.
+ type singleResult struct {
+ name string
+ vertex route.Vertex
+ fees lnwire.MilliSatoshi
+ }
+ gateways := []struct {
+ name string
+ vertex route.Vertex
+ }{
+ {"gw1", gw1},
+ {"gw2", gw2},
+ {"gw3", gw3},
+ }
+
+ var results []singleResult
+ for _, gw := range gateways {
+ origin := &singleOrigin{source: gw.vertex}
+ src, path, err := findPathWithOrigin(
+ t, ctx, origin, target, paymentAmt,
+ )
+ require.NoError(t, err, "single-origin findPath failed for %s",
+ gw.name)
+
+ r := buildRoute(src, path)
+ results = append(results, singleResult{
+ name: gw.name,
+ vertex: gw.vertex,
+ fees: r.TotalFees(),
+ })
+ }
+
+ // Find the cheapest single-origin result.
+ cheapest := results[0]
+ for _, r := range results[1:] {
+ if r.fees < cheapest.fees {
+ cheapest = r
+ }
+ }
+
+ // Assert multi-origin picked the same gateway as the cheapest
+ // individual search. This is the core property: early termination in
+ // multi-origin Dijkstra finds the globally optimal origin.
+ require.Equal(t, cheapest.vertex, multiSource,
+ "multi-origin selected %s but cheapest individual origin is "+
+ "%s (fees: multi=%v, gw1=%v, gw2=%v, gw3=%v)",
+ multiSource, cheapest.name, multiRoute.TotalFees(),
+ results[0].fees, results[1].fees, results[2].fees,
+ )
+
+ // Assert the total fees match exactly.
+ require.Equal(t, cheapest.fees, multiRoute.TotalFees(),
+ "multi-origin fees should equal cheapest single-origin fees",
+ )
+
+ // Sanity check the expected winner and path.
+ require.Equal(t, gw1, multiSource,
+ "expected gw1 as cheapest origin")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, multiPath,
+ "cheap1", "cheap2", "dest",
+ )
+}
+
+// runMultiOriginOutgoingRestriction tests that OutgoingChannelIDs correctly
+// restricts which gateway is selected in a multi-origin setup. This verifies
+// the decoupled isOriginEdge predicate in nodeEdgeUnifier: the restriction
+// fires for any origin edge, while the selection algorithm (getEdgeLocal vs
+// getEdgeNetwork) remains gated on localChan (self only).
+func runMultiOriginOutgoingRestriction(t *testing.T, useCache bool) {
+ // Same diamond topology as runMultiOrigin.
+ //
+ // proxy (self, no channels)
+ // gw1 ---- alice ---- dest (chan 1, chan 3)
+ // gw2 ---- bob ------/ (chan 2, chan 4)
+ //
+ // gw1→alice→dest is cheaper (alice=500) than gw2→bob→dest (bob=2000).
+ testChannels := []*testChannel{
+ symmetricTestChannel("gw1", "alice", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 1,
+ ),
+ symmetricTestChannel("gw2", "bob", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 2,
+ ),
+ symmetricTestChannel("alice", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 500,
+ }, 3,
+ ),
+ symmetricTestChannel("bob", "dest", 100000,
+ &testChannelPolicy{
+ Expiry: 144,
+ FeeBaseMsat: 2000,
+ }, 4,
+ ),
+ }
+
+ ctx := newPathFindingTestContext(t, useCache, testChannels, "proxy")
+
+ gw1 := ctx.keyFromAlias("gw1")
+ gw2 := ctx.keyFromAlias("gw2")
+ target := ctx.keyFromAlias("dest")
+ paymentAmt := lnwire.NewMSatFromSatoshis(100)
+
+ bothOrigins := &multiOrigin{sources: map[route.Vertex]struct{}{
+ gw1: {},
+ gw2: {},
+ }}
+
+ // Subtest 1: No restriction — cheapest gateway (gw1) wins.
+ ctx.restrictParams.OutgoingChannelIDs = nil
+ source, path, err := findPathWithOrigin(
+ t, ctx, bothOrigins, target, paymentAmt,
+ )
+ require.NoError(t, err)
+ require.Equal(t, gw1, source,
+ "unrestricted should pick cheapest gateway")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, path, "alice", "dest",
+ )
+
+ // Subtest 2: Restrict to gw2's channel — forces the expensive path.
+ ctx.restrictParams.OutgoingChannelIDs = []uint64{2}
+ source, path, err = findPathWithOrigin(
+ t, ctx, bothOrigins, target, paymentAmt,
+ )
+ require.NoError(t, err)
+ require.Equal(t, gw2, source,
+ "restriction to chan 2 should force gw2")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, path, "bob", "dest",
+ )
+
+ // Subtest 3: Restrict to gw1's channel — picks gw1 explicitly.
+ ctx.restrictParams.OutgoingChannelIDs = []uint64{1}
+ source, path, err = findPathWithOrigin(
+ t, ctx, bothOrigins, target, paymentAmt,
+ )
+ require.NoError(t, err)
+ require.Equal(t, gw1, source,
+ "restriction to chan 1 should force gw1")
+ assertExpectedPath(
+ t, ctx.testGraphInstance.aliasMap, path, "alice", "dest",
+ )
+
+ // Subtest 4: Restrict to invalid channel — no path found.
+ ctx.restrictParams.OutgoingChannelIDs = []uint64{999}
+ _, _, err = findPathWithOrigin(
+ t, ctx, bothOrigins, target, paymentAmt,
+ )
+ require.ErrorIs(t, err, errNoPathFound)
+
+ // Reset for other tests.
+ ctx.restrictParams.OutgoingChannelIDs = nil
+}
+
// runInboundFees tests whether correct routes are built when inbound fees
// apply.
func runInboundFees(t *testing.T, useCache bool) {
@@ -3325,27 +3853,28 @@ func dbFindPath(graph *graphdb.VersionedGraph,
return nil, err
}
- var route []*unifiedEdge
+ var routeEdges []*unifiedEdge
err = graph.GraphSession(ctx, func(graph graphdb.NodeTraverser) error {
- route, _, err = findPath(
+ _, routeEdges, _, err = findPath(
&graphParams{
additionalEdges: additionalEdges,
bandwidthHints: bandwidthHints,
graph: graph,
},
- r, cfg, sourceNode.PubKeyBytes, source, target, amt,
+ r, cfg, sourceNode.PubKeyBytes,
+ &singleOrigin{source}, target, amt,
timePref, finalHtlcExpiry,
)
return err
}, func() {
- route = nil
+ routeEdges = nil
})
if err != nil {
return nil, err
}
- return route, nil
+ return routeEdges, nil
}
// dbFindBlindedPaths calls findBlindedPaths after getting a db transaction from
### routing/payment_lifecycle.go
@@ -637,7 +637,7 @@ func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
lastShard bool) (*paymentsdb.HTLCAttempt, error) {
// Generate a new key to be used for this attempt.
- sessionKey, err := generateNewSessionKey()
+ sessionKey, err := GenerateNewSessionKey()
if err != nil {
return nil, err
}
@@ -851,6 +851,11 @@ func (p *paymentLifecycle) failPaymentAndAttempt(ctx context.Context,
// the error type, the error is either the final outcome of the payment or we
// need to continue with an alternative route. A final outcome is indicated by
// a non-nil reason value.
+//
+// NOTE: Our Switch RPC server delivers the errors utilized here to callers
+// of SendOnion and TrackOnion rpcs. If the logic the router relies on to handle
+// errors changes, we should be careful to ensure that the Switch RPC server
+// logic for transporting errors to rpc callers is updated as well.
func (p *paymentLifecycle) handleSwitchErr(ctx context.Context,
attempt *paymentsdb.HTLCAttempt,
sendErr error) (*attemptResult, error) {
@@ -1155,6 +1160,18 @@ func (p *paymentLifecycle) reloadInflightAttempts(
// it's a legacy payment.
a = p.patchLegacyPaymentHash(a)
+ // Execute the configured reconciliation strategy.
+ if err := p.router.cfg.ReconcileAttempt(a); err != nil {
+ log.Warnf("Reconciliation failed for attempt "+
+ "%v in payment %v: %v. Skipping result "+
+ "collection; will retry on next restart.",
+ a.AttemptID, p.identifier, err)
+
+ continue
+ }
+
+ // Reconciliation succeeded (or was a no-op), so proceed
+ // to awaiting the attempt result.
p.resultCollector(&a)
}
### routing/payment_lifecycle_test.go
@@ -33,6 +33,7 @@ func createTestPaymentLifecycle() *paymentLifecycle {
TrafficShaper: fn.Some[htlcswitch.AuxTrafficShaper](
&mockTrafficShaper{},
),
+ ReconcileAttempt: noOpReconcile,
},
quit: quitChan,
}
@@ -86,6 +87,7 @@ func newTestPaymentLifecycle(t *testing.T) (*paymentLifecycle, *mockers) {
TrafficShaper: fn.Some[htlcswitch.AuxTrafficShaper](
&mockTrafficShaper{},
),
+ ReconcileAttempt: noOpReconcile,
},
quit: quitChan,
}
@@ -2015,3 +2017,230 @@ func TestReloadInflightAttemptsLegacy(t *testing.T) {
// Assert the result is received as expected.
require.Equal(t, result, r.result)
}
+
+// TestReloadInflightAttemptsWithReconciliation checks that when a
+// ReconcileFunc is configured, it is called for each in-flight attempt and
+// result collection proceeds on success.
+func TestReloadInflightAttemptsWithReconciliation(t *testing.T) {
+ t.Parallel()
+
+ p, m := newTestPaymentLifecycle(t)
+
+ // Create an attempt.
+ paymentAmt := 10_000
+ preimage := lntypes.Preimage{1}
+ attempt := makeSettledAttempt(t, paymentAmt, preimage)
+
+ // Track which attempts the callback receives.
+ var reconciledIDs []uint64
+ p.router.cfg.ReconcileAttempt = func(a paymentsdb.HTLCAttempt) error {
+ reconciledIDs = append(reconciledIDs, a.AttemptID)
+ return nil
+ }
+
+ // Mock FetchPayment and InFlightHTLCs.
+ m.control.On("FetchPayment", p.identifier).Return(m.payment, nil).Once()
+ m.payment.On("InFlightHTLCs").Return(
+ []paymentsdb.HTLCAttempt{*attempt},
+ ).Once()
+
+ // Call the method under test.
+ payment, err := p.reloadInflightAttempts(t.Context())
+ require.NoError(t, err)
+ require.Equal(t, m.payment, payment)
+
+ // The callback should have been invoked with the attempt.
+ require.Len(t, reconciledIDs, 1)
+ require.Equal(t, attempt.AttemptID, reconciledIDs[0])
+
+ // Result collection should have proceeded.
+ require.Equal(t, 1, m.collectResultsCount)
+}
+
+// TestReloadInflightAttemptsReconciliationError checks that when
+// ReconcileFunc returns an error, result collection is skipped for that
+// attempt.
+func TestReloadInflightAttemptsReconciliationError(t *testing.T) {
+ t.Parallel()
+
+ p, m := newTestPaymentLifecycle(t)
+
+ // Create an attempt.
+ paymentAmt := 10_000
+ preimage := lntypes.Preimage{1}
+ attempt := makeSettledAttempt(t, paymentAmt, preimage)
+
+ // Configure a ReconcileFunc that always fails, simulating
+ // the case where the htlc's in-flight status cannot be
+ // confirmed.
+ p.router.cfg.ReconcileAttempt = func(a paymentsdb.HTLCAttempt) error {
+ return errors.New("htlc status unknown: dispatch unavailable")
+ }
+
+ // Mock FetchPayment and InFlightHTLCs.
+ m.control.On("FetchPayment", p.identifier).Return(m.payment, nil).Once()
+ m.payment.On("InFlightHTLCs").Return(
+ []paymentsdb.HTLCAttempt{*attempt},
+ ).Once()
+
+ // Call the method under test.
+ payment, err := p.reloadInflightAttempts(t.Context())
+ require.NoError(t, err)
+ require.Equal(t, m.payment, payment)
+
+ // Result collection should NOT have been called — the attempt was
+ // skipped because reconciliation failed.
+ require.Equal(t, 0, m.collectResultsCount)
+}
+
+// makeInflightAttempt creates an in-flight HTLCAttempt with the given ID and
+// amount. Unlike makeSettledAttempt, Settle and Failure are nil, matching
+// production in-flight state.
+func makeInflightAttempt(t *testing.T, id uint64,
+ amt int) paymentsdb.HTLCAttempt {
+
+ info := makeAttemptInfo(t, amt)
+ info.AttemptID = id
+
+ return paymentsdb.HTLCAttempt{
+ HTLCAttemptInfo: info,
+ }
+}
+
+// TestReloadInflightAttemptsPartialReconciliation verifies that when a payment
+// has multiple in-flight attempts and reconciliation fails for a subset, only
+// the successfully reconciled attempts get result collectors. The failed
+// attempts are skipped.
+func TestReloadInflightAttemptsPartialReconciliation(t *testing.T) {
+ t.Parallel()
+
+ p, m := newTestPaymentLifecycle(t)
+
+ // Create three in-flight attempts.
+ a1 := makeInflightAttempt(t, 1, 5_000)
+ a2 := makeInflightAttempt(t, 2, 3_000)
+ a3 := makeInflightAttempt(t, 3, 2_000)
+
+ // Configure reconciliation to fail for attempt 2 only,
+ // simulating one unreachable Switch RPC backend.
+ var reconciledIDs []uint64
+ p.router.cfg.ReconcileAttempt = func(a paymentsdb.HTLCAttempt) error {
+ reconciledIDs = append(reconciledIDs, a.AttemptID)
+
+ if a.AttemptID == 2 {
+ return errors.New("backend unreachable")
+ }
+
+ return nil
+ }
+
+ // Mock FetchPayment and InFlightHTLCs.
+ m.control.On("FetchPayment", p.identifier).Return(m.payment, nil).Once()
+ m.payment.On("InFlightHTLCs").Return(
+ []paymentsdb.HTLCAttempt{a1, a2, a3},
+ ).Once()
+
+ // Call the method under test.
+ payment, err := p.reloadInflightAttempts(t.Context())
+ require.NoError(t, err)
+ require.Equal(t, m.payment, payment)
+
+ // All three attempts should have been presented to the callback.
+ require.Equal(t, []uint64{1, 2, 3}, reconciledIDs)
+
+ // Result collectors should have been started for attempts 1 and 3
+ // only. Attempt 2 was skipped.
+ require.Equal(t, 2, m.collectResultsCount)
+}
+
+// TestReloadInflightAttemptsSettlementDespiteSkip exercises the key safety
+// property of the continue-on-error design: when one MPP shard fails
+// reconciliation, the lifecycle remains responsive and collects settlement
+// results for healthy shards. This test uses the real collectResultAsync
+// path (not the counting mock) to prove the preimage arrives on
+// p.resultCollected.
+func TestReloadInflightAttemptsSettlementDespiteSkip(t *testing.T) {
+ t.Parallel()
+
+ p, m := newTestPaymentLifecycle(t)
+
+ // Use the real result collector so we can observe the settlement
+ // arriving on p.resultCollected.
+ p.resultCollector = p.collectResultAsync
+
+ // Create two in-flight attempts with valid session keys so that
+ // Circuit() succeeds inside collectResult.
+ sessionKey1, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ rt1 := createDummyRoute(t, 5_000)
+ hash := lntypes.Hash{1, 2, 3}
+ a1, err := paymentsdb.NewHtlcAttempt(
+ 1, sessionKey1, *rt1, time.Now(), &hash,
+ )
+ require.NoError(t, err)
+
+ sessionKey2, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+
+ rt2 := createDummyRoute(t, 5_000)
+ a2, err := paymentsdb.NewHtlcAttempt(
+ 2, sessionKey2, *rt2, time.Now(), &hash,
+ )
+ require.NoError(t, err)
+
+ // Reconciliation succeeds for attempt 1, fails for attempt 2
+ // (simulating one unreachable Switch RPC backend).
+ p.router.cfg.ReconcileAttempt = func(a paymentsdb.HTLCAttempt) error {
+ if a.AttemptID == 2 {
+ return errors.New("backend unreachable")
+ }
+
+ return nil
+ }
+
+ // Mock FetchPayment and InFlightHTLCs.
+ m.control.On("FetchPayment", p.identifier).Return(
+ m.payment, nil,
+ ).Once()
+ m.payment.On("InFlightHTLCs").Return(
+ []paymentsdb.HTLCAttempt{*a1, *a2},
+ ).Once()
+
+ // Create a preimage result for attempt 1.
+ preimage := lntypes.Preimage{4, 5, 6}
+ result := &htlcswitch.PaymentResult{Preimage: preimage}
+
+ // Mock GetAttemptResult for attempt 1 to deliver a preimage
+ // settlement. The Run callback sends the result immediately,
+ // simulating the switch resolving the HTLC.
+ resultChan := make(chan *htlcswitch.PaymentResult, 1)
+ m.payer.On("GetAttemptResult",
+ a1.AttemptID, p.identifier, mock.Anything,
+ ).Return(resultChan, nil).Once().Run(func(args mock.Arguments) {
+ resultChan <- result
+ })
+
+ // No GetAttemptResult mock for attempt 2 — its reconciliation
+ // fails so collectResultAsync is never called for it.
+
+ // Call the method under test.
+ payment, reloadErr := p.reloadInflightAttempts(t.Context())
+ require.NoError(t, reloadErr)
+ require.Equal(t, m.payment, payment)
+
+ // The settlement for attempt 1 should arrive on resultCollected,
+ // proving the lifecycle remains responsive to healthy shards
+ // despite attempt 2's reconciliation failure.
+ var r *switchResult
+
+ waitErr := wait.NoError(func() error {
+ r = <-p.resultCollected
+
+ return nil
+ }, testTimeout)
+ require.NoError(t, waitErr, "timeout waiting for settlement")
+
+ require.Equal(t, result, r.result)
+ require.Equal(t, a1.AttemptID, r.attempt.AttemptID)
+}
### routing/payment_session.go
@@ -6,6 +6,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btclog/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
graphdb "github.com/lightningnetwork/lnd/graph/db"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/lnutils"
@@ -195,14 +196,44 @@ type paymentSession struct {
// log is a payment session-specific logger.
log btclog.Logger
+
+ // opts holds optional configuration for the payment session.
+ opts sessionOptions
+}
+
+// sessionOptions holds optional configuration for a payment session.
+type sessionOptions struct {
+ // origin is an optional RouteOrigin that determines where routes can
+ // start. When set, the pathfinder terminates at any vertex for which
+ // IsOrigin returns true.
+ origin fn.Option[RouteOrigin]
+}
+
+// defaultSessionOptions returns sessionOptions with default values.
+func defaultSessionOptions() sessionOptions {
+ return sessionOptions{}
+}
+
+// sessionOption is a functional option for configuring a payment session.
+type sessionOption func(*sessionOptions)
+
+// withOrigin sets the RouteOrigin for this payment session.
+func withOrigin(o RouteOrigin) sessionOption {
+ return func(opts *sessionOptions) {
+ if o == nil {
+ return
+ }
+ opts.origin = fn.Some(o)
+ }
}
// newPaymentSession instantiates a new payment session.
func newPaymentSession(p *LightningPayment, selfNode route.Vertex,
getBandwidthHints func(Graph) (bandwidthHints, error),
graphSessFactory GraphSessionFactory,
missionControl MissionControlQuerier,
- pathFindingConfig PathFindingConfig) (*paymentSession, error) {
+ pathFindingConfig PathFindingConfig,
+ options ...sessionOption) (*paymentSession, error) {
edges, err := RouteHintsToEdges(p.RouteHints, p.Target)
if err != nil {
@@ -223,6 +254,11 @@ func newPaymentSession(p *LightningPayment, selfNode route.Vertex,
logPrefix := fmt.Sprintf("PaymentSession(%x):", p.Identifier())
+ opts := defaultSessionOptions()
+ for _, o := range options {
+ o(&opts)
+ }
+
return &paymentSession{
selfNode: selfNode,
additionalEdges: edges,
@@ -234,6 +270,7 @@ func newPaymentSession(p *LightningPayment, selfNode route.Vertex,
missionControl: missionControl,
minShardAmt: DefaultShardMinAmt,
log: log.WithPrefix(logPrefix),
+ opts: opts,
}, nil
}
@@ -308,7 +345,10 @@ func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
maxAmt = *p.payment.MaxShardAmt
}
- var path []*unifiedEdge
+ var (
+ sourceVertex route.Vertex
+ path []*unifiedEdge
+ )
findPath := func(graph graphdb.NodeTraverser) error {
// We'll also obtain a set of bandwidthHints from the lower
// layer for each of our outbound channels. This will allow the
@@ -323,15 +363,21 @@ func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
p.log.Debugf("pathfinding for amt=%v", maxAmt)
+ // Use the configured origin if one was provided,
+ // otherwise default to the session's own node.
+ origin := p.opts.origin.UnwrapOr(
+ &singleOrigin{p.selfNode},
+ )
+
// Find a route for the current amount.
- path, _, err = p.pathFinder(
+ sourceVertex, path, _, err = p.pathFinder(
&graphParams{
additionalEdges: p.additionalEdges,
bandwidthHints: bandwidthHints,
graph: graph,
},
restrictions, &p.pathFindingConfig,
- p.selfNode, p.selfNode, p.payment.Target,
+ p.selfNode, origin, p.payment.Target,
maxAmt, p.payment.TimePref, finalHtlcExpiry,
)
if err != nil {
@@ -347,6 +393,7 @@ func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
err := p.graphSessFactory.GraphSession(
context.TODO(),
findPath, func() {
+ sourceVertex = route.Vertex{}
path = nil
},
)
@@ -440,7 +487,7 @@ func (p *paymentSession) RequestRoute(maxAmt, feeLimit lnwire.MilliSatoshi,
// this into a route by applying the time-lock and fee
// requirements.
route, err := newRoute(
- p.selfNode, path, height,
+ sourceVertex, path, height,
finalHopParams{
amt: maxAmt,
totalAmt: p.payment.Amount,
### routing/payment_session_source.go
@@ -44,6 +44,11 @@ type SessionSource struct {
// PathFindingConfig defines global parameters that control the
// trade-off in path finding between fees and probability.
PathFindingConfig PathFindingConfig
+
+ // Origin is an optional RouteOrigin that determines where routes can
+ // start. When set, the pathfinder terminates at any vertex for which
+ // IsOrigin returns true. When unset, routes originate from SourceNode.
+ Origin fn.Option[RouteOrigin]
}
// NewPaymentSession creates a new payment session backed by the latest prune
@@ -62,9 +67,15 @@ func (m *SessionSource) NewPaymentSession(p *LightningPayment,
)
}
+ var options []sessionOption
+ m.Origin.WhenSome(func(o RouteOrigin) {
+ options = append(options, withOrigin(o))
+ })
+
session, err := newPaymentSession(
p, m.SourceNode.PubKeyBytes, getBandwidthHints,
m.GraphSessionFactory, m.MissionControl, m.PathFindingConfig,
+ options...,
)
if err != nil {
return nil, err
### routing/payment_session_test.go
@@ -208,9 +208,10 @@ func TestRequestRoute(t *testing.T) {
// Override pathfinder with a mock.
session.pathFinder = func(_ *graphParams, r *RestrictParams,
- _ *PathFindingConfig, _, _, _ route.Vertex,
- _ lnwire.MilliSatoshi, _ float64, _ int32) ([]*unifiedEdge,
- float64, error) {
+ _ *PathFindingConfig, self route.Vertex,
+ _ RouteOrigin, _ route.Vertex,
+ _ lnwire.MilliSatoshi, _ float64,
+ _ int32) (route.Vertex, []*unifiedEdge, float64, error) {
// We expect find path to receive a cltv limit excluding the
// final cltv delta (including the block padding).
@@ -231,7 +232,7 @@ func TestRequestRoute(t *testing.T) {
},
}
- return path, 1.0, nil
+ return self, path, 1.0, nil
}
route, err := session.RequestRoute(
@@ -252,6 +253,98 @@ func TestRequestRoute(t *testing.T) {
}
}
+// TestRequestRouteWithOrigin verifies that a custom IsRouteOrigin provided via
+// the withOrigin option is forwarded to the pathfinder and that the source
+// vertex it returns is used as the route's SourcePubKey.
+func TestRequestRouteWithOrigin(t *testing.T) {
+ t.Parallel()
+
+ // selfNode is the local coordinator node. It is deliberately different
+ // from the gateway vertex that the custom origin will select, so we
+ // can verify the returned route uses the gateway, not self.
+ selfNode := route.Vertex{0xaa}
+ gatewayNode := route.Vertex{0xbb}
+
+ payment := &LightningPayment{
+ Amount: 1000,
+ FeeLimit: 1000,
+ }
+
+ var paymentHash [32]byte
+ err := payment.SetPaymentHash(paymentHash)
+ require.NoError(t, err, "unable to set payment hash")
+
+ // Build a trivial one-hop path for the mock to return.
+ mockPath := []*unifiedEdge{
+ {
+ policy: &models.CachedEdgePolicy{
+ ToNodePubKey: func() route.Vertex {
+ return route.Vertex{0xcc}
+ },
+ ToNodeFeatures: lnwire.NewFeatureVector(
+ nil, nil,
+ ),
+ },
+ },
+ }
+
+ // Create a custom origin that only accepts gatewayNode.
+ customOrigin := &singleOrigin{source: gatewayNode}
+
+ // Create a session with the withOrigin option.
+ session, err := newPaymentSession(
+ payment, selfNode,
+ func(Graph) (bandwidthHints, error) {
+ return &mockBandwidthHints{}, nil
+ },
+ &sessionGraph{},
+ &MissionControl{},
+ PathFindingConfig{},
+ withOrigin(customOrigin),
+ )
+ require.NoError(t, err, "unable to create payment session")
+
+ // Override the pathfinder with a mock that asserts the origin it
+ // receives is the custom one (not the default singleOrigin{selfNode})
+ // and returns gatewayNode as the settled source.
+ session.pathFinder = func(_ *graphParams, _ *RestrictParams,
+ _ *PathFindingConfig, self route.Vertex,
+ origin RouteOrigin, _ route.Vertex,
+ _ lnwire.MilliSatoshi, _ float64,
+ _ int32) (route.Vertex, []*unifiedEdge, float64, error) {
+
+ // The self parameter should still be the session's own node.
+ require.Equal(t, selfNode, self, "self should be selfNode")
+
+ // The origin must accept gatewayNode and reject selfNode.
+ require.True(
+ t, origin.IsOrigin(gatewayNode),
+ "origin should accept gatewayNode",
+ )
+ require.False(
+ t, origin.IsOrigin(selfNode),
+ "origin should reject selfNode",
+ )
+
+ return gatewayNode, mockPath, 1.0, nil
+ }
+
+ rt, err := session.RequestRoute(
+ payment.Amount, payment.FeeLimit, 0, 10,
+ lnwire.CustomRecords{
+ lnwire.MinCustomRecordsTlvType + 123: []byte{1, 2, 3},
+ },
+ )
+ require.NoError(t, err)
+
+ // The route's SourcePubKey must be the gateway returned by the
+ // pathfinder, not the session's selfNode.
+ require.Equal(
+ t, gatewayNode, rt.SourcePubKey,
+ "SourcePubKey should be the gateway, not selfNode",
+ )
+}
+
type sessionGraph struct {
Graph
}
### routing/router.go
@@ -185,6 +185,34 @@ type MissionControlQuerier interface {
amt lnwire.MilliSatoshi, capacity btcutil.Amount) float64
}
+// ReconcileFunc defines the callback invoked for each in-flight HTLC attempt
+// during startup before result collection begins.
+//
+// When the ChannelRouter runs in a separate process from the Switch, a crash
+// can occur after the router persists an attempt but before the dispatch call
+// is confirmed by the switch. On restart, the router cannot tell whether the
+// HTLC is actually in-flight. This callback resolves that ambiguity by letting
+// the caller re-dispatch the attempt idempotently: the switch either accepts
+// the HTLC (newly dispatched) or returns a duplicate error (already in-flight).
+// Either outcome confirms the attempt is live and result collection can
+// proceed safely.
+//
+// Implementations should handle transient failures internally (e.g. retry with
+// backoff) and only return an error when reconciliation cannot be completed. A
+// returned error causes the lifecycle to skip result collection for that
+// attempt; it will be retried on the next restart.
+type ReconcileFunc func(a paymentsdb.HTLCAttempt) error
+
+// noOpReconcile is the default ReconcileFunc used in standard lnd where the
+// ChannelRouter and Switch run in the same process. Because they share a crash
+// domain — if lnd crashes, both restart together — the dispatch hand-off
+// (RegisterAttempt to CommitCircuits) is synchronous and in-process. On
+// restart, result collection from the Switch unambiguously reveals whether
+// each attempt was dispatched, so no reconciliation is needed.
+func noOpReconcile(_ paymentsdb.HTLCAttempt) error {
+ return nil
+}
+
// FeeSchema is the set fee configuration for a Lightning Node on the network.
// Using the coefficients described within the schema, the required fee to
// forward outgoing payments can be derived.
@@ -299,6 +327,22 @@ type Config struct {
// KeepFailedPaymentAttempts indicates whether to keep failed payment
// attempts in the database.
KeepFailedPaymentAttempts bool
+
+ // ReconcileAttempt is the strategy executed for each in-flight
+ // HTLC attempt during startup before result collection begins.
+ // Callers running the ChannelRouter in a separate process from
+ // the Switch should provide an implementation that idempotently
+ // confirms dispatch status for each attempt (e.g. via SendOnion).
+ // See ReconcileFunc for the full contract.
+ //
+ // Defaults to noOpReconcile when not set, preserving standard
+ // lnd behavior where the router and switch share a crash domain.
+ ReconcileAttempt ReconcileFunc
+
+ // ExternalPaymentLifecycle indicates that the payment lifecycle is
+ // managed by an external entity, and the dispatcher's payment store
+ // should not be cleaned on startup.
+ ExternalPaymentLifecycle bool
}
// EdgeLocator is a struct used to identify a specific edge.
@@ -342,6 +386,13 @@ type ChannelRouter struct {
// channel graph is a subset of the UTXO set) set, then the router will proceed
// to fully sync to the latest state of the UTXO set.
func New(cfg Config) (*ChannelRouter, error) {
+ // Default to a no-op reconciliation callback, preserving
+ // standard lnd behavior where the router and switch share a
+ // crash domain.
+ if cfg.ReconcileAttempt == nil {
+ cfg.ReconcileAttempt = noOpReconcile
+ }
+
return &ChannelRouter{
cfg: &cfg,
quit: make(chan struct{}),
@@ -426,6 +477,11 @@ type RouteRequest struct {
// parameters used to reach a target node blinded paths. This field is
// mutually exclusive with the Target field.
BlindedPathSet *BlindedPaymentPathSet
+
+ // Origin is an optional RouteOrigin that determines where the
+ // route can start. When set, it overrides Source for path-finding
+ // termination. When nil, a singleOrigin wrapping Source is used.
+ Origin RouteOrigin
}
// RouteHints is an alias type for a set of route hints, with the source node
@@ -549,23 +605,28 @@ func (r *ChannelRouter) FindRoute(req *RouteRequest) (*route.Route, float64,
return nil, 0, errors.New("time preference out of range")
}
- path, probability, err := findPath(
+ origin := RouteOrigin(&singleOrigin{req.Source})
+ if req.Origin != nil {
+ origin = req.Origin
+ }
+
+ source, path, probability, err := findPath(
&graphParams{
additionalEdges: req.RouteHints,
bandwidthHints: bandwidthHints,
graph: r.cfg.RoutingGraph,
},
req.Restrictions, &r.cfg.PathFindingConfig,
- r.cfg.SelfNode, req.Source, req.Target, req.Amount,
- req.TimePreference, finalHtlcExpiry,
+ r.cfg.SelfNode, origin, req.Target,
+ req.Amount, req.TimePreference, finalHtlcExpiry,
)
if err != nil {
return nil, 0, err
}
// Create the route with absolute time lock values.
route, err := newRoute(
- req.Source, path, uint32(currentHeight),
+ source, path, uint32(currentHeight),
finalHopParams{
amt: req.Amount,
totalAmt: req.Amount,
@@ -729,9 +790,9 @@ func (r *ChannelRouter) FindBlindedPaths(destination route.Vertex,
return bestRoutes, nil
}
-// generateNewSessionKey generates a new ephemeral private key to be used for a
+// GenerateNewSessionKey generates a new ephemeral private key to be used for a
// payment attempt.
-func generateNewSessionKey() (*btcec.PrivateKey, error) {
+func GenerateNewSessionKey() (*btcec.PrivateKey, error) {
// Generate a new random session key to ensure that we don't trigger
// any replay.
//
@@ -1338,15 +1399,18 @@ func (e ErrNoChannel) Error() string {
"node index %v", e.position)
}
-// BuildRoute returns a fully specified route based on a list of pubkeys. If
-// amount is nil, the minimum routable amount is used. To force a specific
-// outgoing channel, use the outgoingChan parameter.
-func (r *ChannelRouter) BuildRoute(amt fn.Option[lnwire.MilliSatoshi],
- hops []route.Vertex, outgoingChan *uint64, finalCltvDelta int32,
+// BuildRoute builds a fully specified route based on a list of pubkeys from
+// the perspective of the provided source node. If amount is nil, the minimum
+// routable amount is used. To force a specific outgoing channel, use the
+// outgoingChan parameter.
+func (r *ChannelRouter) BuildRoute(sourceNode route.Vertex,
+ amt fn.Option[lnwire.MilliSatoshi], hops []route.Vertex,
+ outgoingChan *uint64, finalCltvDelta int32,
payAddr fn.Option[[32]byte], firstHopBlob fn.Option[[]byte]) (
*route.Route, error) {
- log.Tracef("BuildRoute called: hopsCount=%v, amt=%v", len(hops), amt)
+ log.Tracef("BuildRoute called: sourceNode=%v, hopsCount=%v, amt=%v",
+ sourceNode, len(hops), amt)
var outgoingChans map[uint64]struct{}
if outgoingChan != nil {
@@ -1365,12 +1429,10 @@ func (r *ChannelRouter) BuildRoute(amt fn.Option[lnwire.MilliSatoshi],
return nil, err
}
- sourceNode := r.cfg.SelfNode
-
// We check that each node in the route has a connection to others that
// can forward in principle.
unifiers, err := getEdgeUnifiers(
- r.cfg.SelfNode, hops, outgoingChans, r.cfg.RoutingGraph,
+ sourceNode, hops, outgoingChans, r.cfg.RoutingGraph,
)
if err != nil {
return nil, err
@@ -1464,9 +1526,19 @@ func (r *ChannelRouter) resumePayments() error {
}
}
- log.Debugf("Cleaning network result store.")
- if err := r.cfg.Payer.CleanStore(toKeep); err != nil {
- return err
+ // When the payment life-cycle is managed by an external entity, we
+ // must not clean the attempt store on startup. The external controller
+ // relies on HTLC attempt information persisted by the dispatcher to
+ // resume its payment lifecycle and will need to coordinate all cleanup
+ // operations itself.
+ if !r.cfg.ExternalPaymentLifecycle {
+ log.Debugf("Cleaning network result store.")
+ if err := r.cfg.Payer.CleanStore(toKeep); err != nil {
+ return err
+ }
+ } else {
+ log.Infof("Dispatcher attempt store cleanup disabled. " +
+ "Attempt information must be cleaned remotely.")
}
// launchPayment is a helper closure that handles resuming the payment.
@@ -1662,7 +1734,8 @@ func getEdgeUnifiers(source route.Vertex, hops []route.Vertex,
// is not the last hop.
isExitHop := i == len(hops)-1
u := newNodeEdgeUnifier(
- source, toNode, !isExitHop, outgoingChans,
+ source, toNode, &singleOrigin{source: source},
+ !isExitHop, outgoingChans,
)
err := u.addGraphPolicies(graph)
### routing/router_test.go
@@ -1667,17 +1667,21 @@ func TestBuildRoute(t *testing.T) {
noAmt := fn.None[lnwire.MilliSatoshi]()
+ selfNode := ctx.router.cfg.SelfNode
+
// Test that we can't build a route when no hops are given.
hops = []route.Vertex{}
_, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.None[[32]byte](), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.None[[32]byte](), fn.None[[]byte](),
)
require.Error(t, err)
// Create hop list for an unknown destination.
hops := []route.Vertex{ctx.aliases["b"], ctx.aliases["y"]}
_, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.Some(payAddr), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
noChanErr := ErrNoChannel{}
require.ErrorAs(t, err, &noChanErr)
@@ -1689,8 +1693,8 @@ func TestBuildRoute(t *testing.T) {
// Build the route for the given amount.
rt, err := ctx.router.BuildRoute(
- fn.Some(amt), hops, nil, 40, fn.Some(payAddr),
- fn.None[[]byte](),
+ selfNode, fn.Some(amt), hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
require.NoError(t, err)
@@ -1702,7 +1706,8 @@ func TestBuildRoute(t *testing.T) {
// Build the route for the minimum amount.
rt, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.Some(payAddr), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
require.NoError(t, err)
@@ -1720,7 +1725,8 @@ func TestBuildRoute(t *testing.T) {
// There is no amount that can pass through both channel 5 and 4.
hops = []route.Vertex{ctx.aliases["e"], ctx.aliases["c"]}
_, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.None[[32]byte](), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.None[[32]byte](), fn.None[[]byte](),
)
require.Error(t, err)
noChanErr = ErrNoChannel{}
@@ -1740,7 +1746,8 @@ func TestBuildRoute(t *testing.T) {
// policy of channel 3.
hops = []route.Vertex{ctx.aliases["b"], ctx.aliases["z"]}
rt, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.Some(payAddr), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
require.NoError(t, err)
checkHops(rt, []uint64{1, 8}, payAddr)
@@ -1754,8 +1761,8 @@ func TestBuildRoute(t *testing.T) {
hops = []route.Vertex{ctx.aliases["d"], ctx.aliases["f"]}
amt = lnwire.NewMSatFromSatoshis(100)
rt, err = ctx.router.BuildRoute(
- fn.Some(amt), hops, nil, 40, fn.Some(payAddr),
- fn.None[[]byte](),
+ selfNode, fn.Some(amt), hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
require.NoError(t, err)
checkHops(rt, []uint64{9, 10}, payAddr)
@@ -1771,11 +1778,24 @@ func TestBuildRoute(t *testing.T) {
// is a third pass through newRoute in which this gets corrected to end
hops = []route.Vertex{ctx.aliases["d"], ctx.aliases["f"]}
rt, err = ctx.router.BuildRoute(
- noAmt, hops, nil, 40, fn.Some(payAddr), fn.None[[]byte](),
+ selfNode, noAmt, hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
)
require.NoError(t, err)
checkHops(rt, []uint64{9, 10}, payAddr)
require.EqualValues(t, 20180, rt.TotalAmount, "%v", rt.TotalAmount)
+
+ // Test a route built from an alternate source node (d --> f).
+ hops = []route.Vertex{ctx.aliases["f"]}
+ rt, err = ctx.router.BuildRoute(
+ ctx.aliases["d"], fn.Some(amt), hops, nil, 40,
+ fn.Some(payAddr), fn.None[[]byte](),
+ )
+ require.NoError(t, err)
+ require.Equal(t, ctx.aliases["d"], rt.SourcePubKey,
+ "expected 'd' as source")
+ checkHops(rt, []uint64{10}, payAddr)
+
}
// TestReceiverAmtForwardPass tests that the forward pass returns the expected
@@ -3303,3 +3323,40 @@ func TestFindBlindedPathsWithMC(t *testing.T) {
"alice,bob,dave",
})
}
+
+// TestResumePaymentsSkipsCleanStoreInExternalMode verifies that when
+// ExternalPaymentLifecycle is true, CleanStore is not called during
+// resumePayments. The external controller is responsible for cleaning the
+// attempt store.
+func TestResumePaymentsSkipsCleanStoreInExternalMode(t *testing.T) {
+ t.Parallel()
+
+ mockControl := &mockControlTower{}
+ mockPayer := &mockPaymentAttemptDispatcher{}
+
+ // resumePayments calls FetchInFlightPayments before deciding
+ // whether to run CleanStore. Return an empty slice so no payment
+ // goroutines are launched.
+ mockControl.On("FetchInFlightPayments").Return(
+ []*paymentsdb.MPPayment{}, nil,
+ )
+
+ rt := &ChannelRouter{
+ cfg: &Config{
+ Control: mockControl,
+ Payer: mockPayer,
+
+ // This is the key: external mode is active.
+ ExternalPaymentLifecycle: true,
+ },
+ quit: make(chan struct{}),
+ }
+
+ err := rt.resumePayments()
+ require.NoError(t, err)
+
+ // CleanStore should NOT have been called.
+ mockPayer.AssertNotCalled(t, "CleanStore", mock.Anything)
+
+ mockControl.AssertExpectations(t)
+}
### routing/unified_edges.go
@@ -20,6 +20,11 @@ type nodeEdgeUnifier struct {
// policy are different for local channels.
sourceNode route.Vertex
+ // origin identifies the set of vertices that are valid route
+ // starting points. Used to gate the outgoing channel restriction
+ // independently of the local-channel selection algorithm.
+ origin RouteOrigin
+
// toNode is the node for which the edge unifiers are instantiated.
toNode route.Vertex
@@ -33,14 +38,16 @@ type nodeEdgeUnifier struct {
// newNodeEdgeUnifier instantiates a new nodeEdgeUnifier object. Channel
// policies can be added to this object.
-func newNodeEdgeUnifier(sourceNode, toNode route.Vertex, useInboundFees bool,
+func newNodeEdgeUnifier(sourceNode, toNode route.Vertex,
+ origin RouteOrigin, useInboundFees bool,
outChanRestr map[uint64]struct{}) *nodeEdgeUnifier {
return &nodeEdgeUnifier{
edgeUnifiers: make(map[route.Vertex]*edgeUnifier),
toNode: toNode,
useInboundFees: useInboundFees,
sourceNode: sourceNode,
+ origin: origin,
outChanRestr: outChanRestr,
}
}
@@ -54,10 +61,23 @@ func (u *nodeEdgeUnifier) addPolicy(fromNode route.Vertex,
capacity btcutil.Amount, hopPayloadSizeFn PayloadSizeFunc,
blindedPayment *BlindedPayment) {
+ // localChan indicates whether we have out-of-band knowledge
+ // about this channel's state (self's channels, where
+ // bandwidthHints has real-time data). Controls the selection
+ // algorithm: getEdgeLocal (bandwidth-aware) vs getEdgeNetwork
+ // (gossip heuristics).
localChan := fromNode == u.sourceNode
+ // isOriginEdge indicates whether this edge originates from a
+ // vertex in the RouteOrigin set. Controls the outgoing channel
+ // restriction. For vanilla lnd these coincide (self is the
+ // only origin), but for multi-origin routing they diverge:
+ // gateway edges are origin edges (restriction applies) but
+ // not local channels (no bandwidth data).
+ isOriginEdge := u.origin.IsOrigin(fromNode)
+
// Skip channels if there is an outgoing channel restriction.
- if localChan && u.outChanRestr != nil {
+ if isOriginEdge && u.outChanRestr != nil {
if _, ok := u.outChanRestr[edge.ChannelID]; !ok {
log.Debugf("Skipped adding policy for restricted edge "+
"%v", edge.ChannelID)
### routing/unified_edges_test.go
@@ -56,7 +56,11 @@ func TestNodeEdgeUnifier(t *testing.T) {
Rate: 10000,
}
- unifierFilled := newNodeEdgeUnifier(source, toNode, false, nil)
+ sourceOrigin := &singleOrigin{source: source}
+
+ unifierFilled := newNodeEdgeUnifier(
+ source, toNode, sourceOrigin, false, nil,
+ )
unifierFilled.addPolicy(
fromNode, &p1, inboundFee1, c1, defaultHopPayloadSize, nil,
@@ -65,29 +69,37 @@ func TestNodeEdgeUnifier(t *testing.T) {
fromNode, &p2, inboundFee2, c2, defaultHopPayloadSize, nil,
)
- unifierNoCapacity := newNodeEdgeUnifier(source, toNode, false, nil)
+ unifierNoCapacity := newNodeEdgeUnifier(
+ source, toNode, sourceOrigin, false, nil,
+ )
unifierNoCapacity.addPolicy(
fromNode, &p1, inboundFee1, 0, defaultHopPayloadSize, nil,
)
unifierNoCapacity.addPolicy(
fromNode, &p2, inboundFee2, 0, defaultHopPayloadSize, nil,
)
- unifierNoInfo := newNodeEdgeUnifier(source, toNode, false, nil)
+ unifierNoInfo := newNodeEdgeUnifier(
+ source, toNode, sourceOrigin, false, nil,
+ )
unifierNoInfo.addPolicy(
fromNode, &models.CachedEdgePolicy{}, models.InboundFee{},
0, defaultHopPayloadSize, nil,
)
- unifierInboundFee := newNodeEdgeUnifier(source, toNode, true, nil)
+ unifierInboundFee := newNodeEdgeUnifier(
+ source, toNode, sourceOrigin, true, nil,
+ )
unifierInboundFee.addPolicy(
fromNode, &p1, inboundFee1, c1, defaultHopPayloadSize, nil,
)
unifierInboundFee.addPolicy(
fromNode, &p2, inboundFee2, c2, defaultHopPayloadSize, nil,
)
- unifierLocal := newNodeEdgeUnifier(fromNode, toNode, true, nil)
+ unifierLocal := newNodeEdgeUnifier(
+ fromNode, toNode, &singleOrigin{source: fromNode}, true, nil,
+ )
unifierLocal.addPolicy(
fromNode, &p1, inboundFee1, c1, defaultHopPayloadSize, nil,
)
@@ -96,7 +108,9 @@ func TestNodeEdgeUnifier(t *testing.T) {
inboundFeeNegative := models.InboundFee{
Base: -150,
}
- unifierNegInboundFee := newNodeEdgeUnifier(source, toNode, true, nil)
+ unifierNegInboundFee := newNodeEdgeUnifier(
+ source, toNode, sourceOrigin, true, nil,
+ )
unifierNegInboundFee.addPolicy(
fromNode, &p1, inboundFeeZero, c1, defaultHopPayloadSize, nil,
)
### server.go
@@ -31,6 +31,7 @@ import (
"github.com/lightningnetwork/lnd/aliasmgr"
"github.com/lightningnetwork/lnd/autopilot"
"github.com/lightningnetwork/lnd/brontide"
+ "github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/chainio"
"github.com/lightningnetwork/lnd/chainreg"
"github.com/lightningnetwork/lnd/chanacceptor"
@@ -935,6 +936,7 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
)
}
+ //nolint:ll
s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
DB: dbs.ChanStateDB,
FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
@@ -957,23 +959,24 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
peer.HandleLocalCloseChanReqs(request)
},
- FwdingLog: dbs.ChanStateDB.ForwardingLog(),
- SwitchPackager: channeldb.NewSwitchPackager(),
- ExtractErrorEncrypter: s.sphinxPayment.ExtractErrorEncrypter,
- FetchLastChannelUpdate: s.fetchLastChanUpdate(),
- Notifier: s.cc.ChainNotifier,
- HtlcNotifier: s.htlcNotifier,
- ReputationManager: repMgrIface,
- FwdEventTicker: ticker.New(htlcswitch.DefaultFwdEventInterval),
- LogEventTicker: ticker.New(htlcswitch.DefaultLogInterval),
- AckEventTicker: ticker.New(htlcswitch.DefaultAckInterval),
- AllowCircularRoute: cfg.AllowCircularRoute,
- RejectHTLC: cfg.RejectHTLC,
- Clock: clock.NewDefaultClock(),
- MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
- MaxFeeExposure: thresholdMSats,
- SignAliasUpdate: s.signAliasUpdate,
- IsAlias: aliasmgr.IsAlias,
+ FwdingLog: dbs.ChanStateDB.ForwardingLog(),
+ SwitchPackager: channeldb.NewSwitchPackager(),
+ ExtractErrorEncrypter: s.sphinxPayment.ExtractErrorEncrypter,
+ FetchLastChannelUpdate: s.fetchLastChanUpdate(),
+ Notifier: s.cc.ChainNotifier,
+ HtlcNotifier: s.htlcNotifier,
+ ReputationManager: repMgrIface,
+ FwdEventTicker: ticker.New(htlcswitch.DefaultFwdEventInterval),
+ LogEventTicker: ticker.New(htlcswitch.DefaultLogInterval),
+ AckEventTicker: ticker.New(htlcswitch.DefaultAckInterval),
+ AllowCircularRoute: cfg.AllowCircularRoute,
+ RejectHTLC: cfg.RejectHTLC,
+ Clock: clock.NewDefaultClock(),
+ MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
+ MaxFeeExposure: thresholdMSats,
+ SignAliasUpdate: s.signAliasUpdate,
+ IsAlias: aliasmgr.IsAlias,
+ ExternalPaymentLifecycle: build.SwitchRPC,
}, uint32(currentHeight))
if err != nil {
return nil, err
@@ -1205,6 +1208,7 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
ClosedSCIDs: s.fetchClosedChannelSCIDs(),
TrafficShaper: implCfg.TrafficShaper,
KeepFailedPaymentAttempts: cfg.KeepFailedPaymentAttempts,
+ ExternalPaymentLifecycle: build.SwitchRPC,
})
if err != nil {
return nil, fmt.Errorf("can't create router: %w", err)
### subrpcserver_config.go
@@ -25,6 +25,7 @@ import (
"github.com/lightningnetwork/lnd/lnrpc/peersrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/switchrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnrpc/watchtowerrpc"
"github.com/lightningnetwork/lnd/lnrpc/wtclientrpc"
@@ -82,6 +83,11 @@ type subRPCServerConfigs struct {
// fees.
RouterRPC *routerrpc.Config `group:"routerrpc" namespace:"routerrpc"`
+ // SwitchRPC is a sub-RPC server that allows clients to directly
+ // interact with the forwarding system (Switch) of the daemon to send
+ // onion attempts (HTLCs) and manipulate the Switch result store.
+ SwitchRPC *switchrpc.Config `group:"switchrpc" namespace:"switchrpc"`
+
// WatchtowerRPC is a sub-RPC server that exposes functionality allowing
// clients to monitor and control their embedded watchtower.
WatchtowerRPC *watchtowerrpc.Config `group:"watchtowerrpc" namespace:"watchtowerrpc"`
@@ -312,6 +318,36 @@ func (s *subRPCServerConfigs) PopulateDependencies(cfg *Config,
reflect.ValueOf(aliasMgr),
)
+ case *switchrpc.Config:
+ subCfgValue := extractReflectValue(subCfg)
+
+ subCfgValue.FieldByName("NetworkDir").Set(
+ reflect.ValueOf(networkDir),
+ )
+ subCfgValue.FieldByName("MacService").Set(
+ reflect.ValueOf(macService),
+ )
+
+ subCfgValue.FieldByName("HtlcDispatcher").Set(
+ reflect.ValueOf(htlcSwitch),
+ )
+
+ subCfgValue.FieldByName("ChannelInfoAccessor").Set(
+ reflect.ValueOf(htlcSwitch),
+ )
+
+ subCfgValue.FieldByName("RouteProcessor").Set(
+ reflect.ValueOf(routerBackend),
+ )
+
+ subCfgValue.FieldByName("AttemptStore").Set(
+ reflect.ValueOf(htlcSwitch.AttemptStore()),
+ )
+
+ subCfgValue.FieldByName("RemoteRouterController").Set(
+ reflect.ValueOf(htlcSwitch),
+ )
+
case *watchtowerrpc.Config:
subCfgValue := extractReflectValue(subCfg)
Why this scored 59/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.