From 5b570d8919cdab2dfe39f94f255da48e4ad3b67a Mon Sep 17 00:00:00 2001 From: claudell Date: Fri, 30 Oct 2026 19:24:24 +0000 Subject: [PATCH 1/2] loopd: track lnd connection ownership, don't close borrowed conns When running as a subserver inside lightning-terminal, the loop daemon receives an lnd connection that is created and owned by the parent process and shared among all subservers. On shutdown, both graceful and after a runtime error, the daemon unconditionally closed that connection, tearing down lnd access for LiT itself and all other integrated subservers (pool, faraday, tapd, accounts and the LiT macaroon service). Track the connection ownership like faraday already does: the standalone Start path marks the connection as owned, StartAsSubserver marks it as borrowed and stop only closes owned connections. Add a regression test that starts an embedded daemon against a mock lnd with a real injected grpc.ClientConn and asserts the connection survives both a graceful Stop and a runtime-error shutdown, plus a test that an owned connection is still closed on stop. Refs lightninglabs/lightning-terminal#1381 (comment 6530026672). --- docs/release-notes/release-notes-next.md | 7 + loopd/daemon.go | 24 +- loopd/daemon_ownership_test.go | 443 +++++++++++++++++++++++ 3 files changed, 472 insertions(+), 2 deletions(-) create mode 100644 loopd/daemon_ownership_test.go diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 7ebced4870..f2603317ab 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -11,6 +11,13 @@ #### Bug Fixes +* Fix a connection ownership bug where an embedded loop daemon closed the + shared lnd connection on shutdown. When running as a subserver of + lightning-terminal, a graceful stop or a runtime error in the loop daemon + tore down the lnd connection owned by the parent process, breaking lnd + access for LiT and all other integrated subservers. The daemon now tracks + whether it created the connection itself and only closes owned connections. + * Bound the static Loop In risk decision replay cache to prevent unbounded memory growth from swap server notifications for unknown swaps. Cached decisions retain only a copy of the validated swap hash, without unknown diff --git a/loopd/daemon.go b/loopd/daemon.go index 530514d307..7c96f51469 100644 --- a/loopd/daemon.go +++ b/loopd/daemon.go @@ -94,6 +94,13 @@ type Daemon struct { assetClient *assets.TapdClient clientCleanup func() + // lndOwned indicates whether the daemon created the lnd connection + // itself (standalone mode via Start) and therefore owns its + // lifecycle. When the daemon is started as a subserver + // (StartAsSubserver), the lnd connection is shared with and owned + // by the parent process (e.g. LiT) and must not be closed here. + lndOwned bool + wg sync.WaitGroup quit chan struct{} stopOnce sync.Once @@ -152,6 +159,10 @@ func (d *Daemon) Start() error { return err } + // We created the lnd connection ourselves, so we own it and are + // responsible for closing it on shutdown. + d.lndOwned = true + // Initialize the assets client. if d.cfg.Tapd.Activate { d.assetClient, err = assets.NewTapdClient(d.cfg.Tapd) @@ -219,6 +230,11 @@ func (d *Daemon) StartAsSubserver(lndGrpc *lndclient.GrpcLndServices, // connection to lnd that might be shared among other subservers. d.lnd = lndGrpc + // The lnd connection is owned by the parent process (e.g. LiT) and + // potentially shared with other subservers, so we must never close + // it ourselves. + d.lndOwned = false + // With lnd already pre-connected, initialize everything else, such as // the swap server client, the RPC server instance and our main swap // handlers. If this fails, then nothing has been started yet, and we @@ -1148,8 +1164,12 @@ func (d *Daemon) stop() { } } - // Next, shut down the connections to lnd and the swap server. - if d.lnd != nil { + // Next, shut down the connections to lnd and the swap server. We + // only close the lnd connection if we created it ourselves + // (standalone mode). In subserver mode the connection is owned by + // the parent process and shared with other subservers, closing it + // here would tear down their lnd access as well. + if d.lnd != nil && d.lndOwned { d.lnd.Close() } if d.clientCleanup != nil { diff --git a/loopd/daemon_ownership_test.go b/loopd/daemon_ownership_test.go new file mode 100644 index 0000000000..1005b1d6d0 --- /dev/null +++ b/loopd/daemon_ownership_test.go @@ -0,0 +1,443 @@ +package loopd + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "errors" + "math/big" + "net" + "path/filepath" + "testing" + "time" + + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/loop/loopdb" + "github.com/lightningnetwork/lnd/lnrpc" + "github.com/lightningnetwork/lnd/lnrpc/chainrpc" + "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc" + "github.com/lightningnetwork/lnd/lnrpc/routerrpc" + "github.com/lightningnetwork/lnd/lnrpc/signrpc" + "github.com/lightningnetwork/lnd/lnrpc/verrpc" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/test/bufconn" +) + +const ( + // testMockLndHeight is the block height the mock lnd node reports. + testMockLndHeight = 600 + + // testMockLndPubkey is the identity pubkey the mock lnd node + // reports. + testMockLndPubkey = "03f5374b16f0b1f1b49101de1b9d89e0b460bc57ce9c2f9" + + "132b73dfc76d3704daa" + + // testMacaroonHex is a pre-baked macaroon (root key + // "dummy-root-key", id "42", location "lnd") that is used as the + // macaroon for all lnd services. The mock lnd server does not + // validate macaroons, the hex only needs to parse. + testMacaroonHex = "0201036c6e6402023432000006205a6adf86f5fef1c3738c7" + + "c299da15c0bb5e2c3d3f84e89090bbad9e070ee6663" + + // testTimeout is the maximum time we wait for the daemon to shut + // down. + testTimeout = time.Second * 30 + + // testMockLndName is the alias and TLS common name of the mock lnd + // node. + testMockLndName = "mock-lnd" +) + +// The following mock servers implement the minimal subset of lnd's gRPC +// services that is required to create an lndclient.GrpcLndServices and to +// start an embedded loop daemon. They are used to verify that the injected +// lnd connection is not closed by the subserver on shutdown. Each service +// gets its own struct because the embedded Unimplemented types have +// overlapping method names. + +// mockLightningServer implements lnd's main Lightning gRPC service. +type mockLightningServer struct { + lnrpc.UnimplementedLightningServer +} + +// GetInfo returns static node information. +func (m *mockLightningServer) GetInfo(_ context.Context, + _ *lnrpc.GetInfoRequest) (*lnrpc.GetInfoResponse, error) { + + return &lnrpc.GetInfoResponse{ + IdentityPubkey: testMockLndPubkey, + Alias: testMockLndName, + Color: "#3399ff", + Version: "0.21.0-beta", + BlockHeight: testMockLndHeight, + BlockHash: "00000000000000000000000000000000" + + "00000000000000000000000000000000", + SyncedToChain: true, + SyncedToGraph: true, + Chains: []*lnrpc.Chain{ + { + Chain: "bitcoin", + Network: "testnet", + }, + }, + }, nil +} + +// ListPayments returns an empty payment list. +func (m *mockLightningServer) ListPayments(_ context.Context, + _ *lnrpc.ListPaymentsRequest) (*lnrpc.ListPaymentsResponse, error) { + + return &lnrpc.ListPaymentsResponse{}, nil +} + +// mockStateServer implements lnd's State gRPC service. +type mockStateServer struct { + lnrpc.UnimplementedStateServer +} + +// SubscribeState reports the wallet as unlocked and then blocks. +func (m *mockStateServer) SubscribeState(_ *lnrpc.SubscribeStateRequest, + stream lnrpc.State_SubscribeStateServer) error { + + err := stream.Send(&lnrpc.SubscribeStateResponse{ + State: lnrpc.WalletState_RPC_ACTIVE, + }) + if err != nil { + return err + } + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// GetState reports the wallet as unlocked. +func (m *mockStateServer) GetState(_ context.Context, + _ *lnrpc.GetStateRequest) (*lnrpc.GetStateResponse, error) { + + return &lnrpc.GetStateResponse{ + State: lnrpc.WalletState_RPC_ACTIVE, + }, nil +} + +// mockVersionerServer implements lnd's verrpc gRPC service. +type mockVersionerServer struct { + verrpc.UnimplementedVersionerServer +} + +// GetVersion returns a version that satisfies the minimum required lnd +// version of the loop daemon. +func (m *mockVersionerServer) GetVersion(_ context.Context, + _ *verrpc.VersionRequest) (*verrpc.Version, error) { + + return &verrpc.Version{ + AppMajor: 0, + AppMinor: 21, + AppPatch: 0, + BuildTags: []string{ + "signrpc", "walletrpc", "chainrpc", + "invoicesrpc", + }, + }, nil +} + +// mockChainNotifierServer implements lnd's chainrpc gRPC service. +type mockChainNotifierServer struct { + chainrpc.UnimplementedChainNotifierServer +} + +// RegisterBlockEpochNtfn sends the current block height once (like lnd +// does on registration) and then blocks until the subscription is +// canceled. +func (m *mockChainNotifierServer) RegisterBlockEpochNtfn( + _ *chainrpc.BlockEpoch, + stream chainrpc.ChainNotifier_RegisterBlockEpochNtfnServer) error { + + err := stream.Send(&chainrpc.BlockEpoch{ + Height: testMockLndHeight, + }) + if err != nil { + return err + } + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// RegisterConfirmationsNtfn blocks until the subscription is canceled. +func (m *mockChainNotifierServer) RegisterConfirmationsNtfn( + _ *chainrpc.ConfRequest, + stream chainrpc.ChainNotifier_RegisterConfirmationsNtfnServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// RegisterSpendNtfn blocks until the subscription is canceled. +func (m *mockChainNotifierServer) RegisterSpendNtfn( + _ *chainrpc.SpendRequest, + stream chainrpc.ChainNotifier_RegisterSpendNtfnServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// mockWalletKitServer implements lnd's walletrpc gRPC service. +type mockWalletKitServer struct { + walletrpc.UnimplementedWalletKitServer +} + +// ListUnspent returns an empty UTXO list. +func (m *mockWalletKitServer) ListUnspent(_ context.Context, + _ *walletrpc.ListUnspentRequest) (*walletrpc.ListUnspentResponse, + error) { + + return &walletrpc.ListUnspentResponse{}, nil +} + +// mockInvoicesServer implements lnd's invoicesrpc gRPC service. +type mockInvoicesServer struct { + invoicesrpc.UnimplementedInvoicesServer +} + +// SubscribeSingleInvoice blocks until the subscription is canceled. +func (m *mockInvoicesServer) SubscribeSingleInvoice( + _ *invoicesrpc.SubscribeSingleInvoiceRequest, + stream invoicesrpc.Invoices_SubscribeSingleInvoiceServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// startMockLnd starts the mock lnd gRPC server on an in-memory listener and +// returns the listener to dial. +func startMockLnd(t *testing.T) *bufconn.Listener { + t.Helper() + + lis := bufconn.Listen(1024 * 1024) + server := grpc.NewServer(grpc.Creds( + credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{testTLSCert(t)}, + }), + )) + + lnrpc.RegisterLightningServer(server, &mockLightningServer{}) + lnrpc.RegisterStateServer(server, &mockStateServer{}) + verrpc.RegisterVersionerServer(server, &mockVersionerServer{}) + chainrpc.RegisterChainNotifierServer( + server, &mockChainNotifierServer{}, + ) + walletrpc.RegisterWalletKitServer(server, &mockWalletKitServer{}) + invoicesrpc.RegisterInvoicesServer(server, &mockInvoicesServer{}) + routerrpc.RegisterRouterServer( + server, &routerrpc.UnimplementedRouterServer{}, + ) + signrpc.RegisterSignerServer( + server, &signrpc.UnimplementedSignerServer{}, + ) + + go func() { + _ = server.Serve(lis) + }() + + t.Cleanup(func() { + server.Stop() + _ = lis.Close() + }) + + return lis +} + +// newInjectedLndServices creates a real lndclient.GrpcLndServices backed by +// a real gRPC connection to the mock lnd server. This mirrors exactly what +// LiT creates once and then injects into its subservers. +func newInjectedLndServices(t *testing.T, + lis *bufconn.Listener) *lndclient.GrpcLndServices { + + t.Helper() + + services, err := lndclient.NewLndServices(&lndclient.LndServicesConfig{ + LndAddress: "bufnet", + Network: lndclient.NetworkTestnet, + CustomMacaroonHex: testMacaroonHex, + Insecure: true, + Dialer: func(ctx context.Context, _ string) (net.Conn, error) { + return lis.DialContext(ctx) + }, + CheckVersion: LoopMinRequiredLndVersion, + }) + require.NoError(t, err) + + return services +} + +// newTestDaemon creates a loop daemon that uses only temporary directories +// and connects to a swap server address that nothing listens on (the swap +// server connection is established lazily and is not needed for this test). +func newTestDaemon(t *testing.T) *Daemon { + t.Helper() + + tmpDir := t.TempDir() + + cfg := DefaultConfig() + cfg.Network = "testnet" + cfg.LoopDir = tmpDir + cfg.DataDir = tmpDir + cfg.LogDir = tmpDir + cfg.MacaroonPath = filepath.Join(tmpDir, "loop.macaroon") + cfg.Sqlite = &loopdb.SqliteConfig{ + DatabaseFileName: filepath.Join(tmpDir, "loop.db"), + } + cfg.Server = &loopServerConfig{ + Host: "127.0.0.1:1", + NoTLS: true, + } + + return New(&cfg, &ListenerCfg{}) +} + +// TestSubserverDoesNotCloseSharedLndConn is a regression test for the +// connection ownership bug that caused an embedded loop daemon to close the +// lnd connection that LiT shares among all its subservers. Stopping the +// embedded daemon (either gracefully or after a runtime error) must not +// close the injected lnd connection. +func TestSubserverDoesNotCloseSharedLndConn(t *testing.T) { + setLogger(btclog.Disabled) + + testCases := []struct { + name string + + // triggerShutdown initiates the daemon shutdown and returns + // the error the daemon is expected to report on its main + // error channel. + triggerShutdown func(d *Daemon) error + }{ + { + name: "graceful stop", + triggerShutdown: func(d *Daemon) error { + d.Stop() + + return nil + }, + }, + { + name: "runtime error", + triggerShutdown: func(d *Daemon) error { + runtimeErr := errors.New("mock runtime error") + d.internalErrChan <- runtimeErr + + return runtimeErr + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Start the mock lnd node and create the shared lnd + // connection, exactly like LiT does before starting + // its subservers. + lis := startMockLnd(t) + services := newInjectedLndServices(t, lis) + conn := services.ClientConn + + // Start the daemon as a subserver with the shared + // (borrowed) lnd connection. + d := newTestDaemon(t) + err := d.StartAsSubserver(services, false) + require.NoError(t, err) + + // Trigger the shutdown and wait for the daemon to + // report completion on its main error channel. + expectedErr := tc.triggerShutdown(d) + + select { + case err := <-d.ErrChan: + require.Equal(t, expectedErr, err) + + case <-time.After(testTimeout): + t.Fatal("timeout waiting for daemon shutdown") + } + + // The shared lnd connection must still be usable, it + // must NOT be closed by the subserver. + require.NotEqual( + t, connectivity.Shutdown, conn.GetState(), + "subserver closed the shared lnd connection", + ) + + // The owner of the connection (the test, acting as + // the parent process) cleans up. + services.Close() + require.Equal( + t, connectivity.Shutdown, conn.GetState(), + ) + }) + } +} + +// TestOwnedLndConnClosedOnStop verifies that the daemon still closes the lnd +// connection when it owns it (standalone mode), i.e. that the ownership +// guard does not leak connections that the daemon created itself. +func TestOwnedLndConnClosedOnStop(t *testing.T) { + setLogger(btclog.Disabled) + + lis := startMockLnd(t) + services := newInjectedLndServices(t, lis) + conn := services.ClientConn + + // Simulate a daemon that created its own lnd connection (standalone + // mode via Start) by marking the connection as owned. + d := newTestDaemon(t) + d.lnd = services + d.lndOwned = true + + // Stopping the daemon must close the connection it owns. + d.stop() + require.Equal(t, connectivity.Shutdown, conn.GetState()) +} + +// testTLSCert creates an ephemeral self-signed TLS certificate for the mock +// lnd server. The lndclient is configured with Insecure=true, which skips +// certificate verification but still requires the server to speak TLS. +func testTLSCert(t *testing.T) tls.Certificate { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{ + CommonName: testMockLndName, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | + x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{testMockLndName}, + } + + der, err := x509.CreateCertificate( + rand.Reader, template, template, &key.PublicKey, key, + ) + require.NoError(t, err) + + return tls.Certificate{ + Certificate: [][]byte{der}, + PrivateKey: key, + } +} From c5b31d11c50632068ad400b282c56ccf39d27df4 Mon Sep 17 00:00:00 2001 From: claudell Date: Fri, 30 Oct 2026 20:02:48 +0000 Subject: [PATCH 2/2] loopd: make borrowed lnd connections unrepresentable Strengthen the ownership fix from a runtime flag to type-level prevention: StartAsSubserver now accepts the non-closable *lndclient.LndServices view instead of the *lndclient.GrpcLndServices wrapper, so a subserver cannot call Close on the shared connection even if it tries. The closable wrapper is only held in the new lndOwner field, which is only set when the daemon creates the connection itself (standalone Start and the view command). Add a mechanically enforced guard test that fails CI if any code in the package closes an lnd connection handle outside the whitelisted owner sites, or if StartAsSubserver ever accepts the closable wrapper again. The guard was verified to fail against master (flagging the original d.lnd.Close() bug site and the wrapper-typed signature) and to pass with this change. --- loopd/daemon.go | 64 ++++++++------ loopd/daemon_ownership_test.go | 12 +-- loopd/ownership_guard_test.go | 157 +++++++++++++++++++++++++++++++++ loopd/view.go | 9 +- loopout.go | 4 +- 5 files changed, 207 insertions(+), 39 deletions(-) create mode 100644 loopd/ownership_guard_test.go diff --git a/loopd/daemon.go b/loopd/daemon.go index 7c96f51469..02f3d589e7 100644 --- a/loopd/daemon.go +++ b/loopd/daemon.go @@ -90,16 +90,21 @@ type Daemon struct { listenerCfg *ListenerCfg internalErrChan chan error - lnd *lndclient.GrpcLndServices + // lnd is the set of lnd services the daemon uses. It is a + // non-closable view: the closeable connection wrapper is only ever + // held in lndOwner, and only when the daemon created the connection + // itself (standalone mode). + lnd *lndclient.LndServices assetClient *assets.TapdClient clientCleanup func() - // lndOwned indicates whether the daemon created the lnd connection - // itself (standalone mode via Start) and therefore owns its - // lifecycle. When the daemon is started as a subserver - // (StartAsSubserver), the lnd connection is shared with and owned - // by the parent process (e.g. LiT) and must not be closed here. - lndOwned bool + // lndOwner holds the full lnd services wrapper, including its Close + // method, if and only if the daemon created the lnd connection + // itself (standalone mode via Start). When the daemon is started as + // a subserver (StartAsSubserver), the lnd connection is shared with + // and owned by the parent process (e.g. LiT) and lndOwner is nil, + // so there is no closable handle to the borrowed connection. + lndOwner *lndclient.GrpcLndServices wg sync.WaitGroup quit chan struct{} @@ -154,14 +159,16 @@ func (d *Daemon) Start() error { network := lndclient.Network(d.cfg.Network) var err error - d.lnd, err = d.listenerCfg.getLnd(network, d.cfg.Lnd) + lndGrpc, err := d.listenerCfg.getLnd(network, d.cfg.Lnd) if err != nil { return err } // We created the lnd connection ourselves, so we own it and are - // responsible for closing it on shutdown. - d.lndOwned = true + // responsible for closing it on shutdown. The rest of the daemon + // only ever sees the non-closable services view. + d.lndOwner = lndGrpc + d.lnd = &lndGrpc.LndServices // Initialize the assets client. if d.cfg.Tapd.Activate { @@ -216,7 +223,7 @@ func (d *Daemon) Start() error { // create its own gRPC server but registers to an existing one. The same goes // for REST (if enabled), instead of creating an own mux and HTTP server, we // register to an existing one. -func (d *Daemon) StartAsSubserver(lndGrpc *lndclient.GrpcLndServices, +func (d *Daemon) StartAsSubserver(lndServices *lndclient.LndServices, withMacaroonService bool) error { // There should be no reason to start the daemon twice. Therefore, @@ -227,13 +234,11 @@ func (d *Daemon) StartAsSubserver(lndGrpc *lndclient.GrpcLndServices, } // When starting as a subserver, we get passed in an already established - // connection to lnd that might be shared among other subservers. - d.lnd = lndGrpc - - // The lnd connection is owned by the parent process (e.g. LiT) and - // potentially shared with other subservers, so we must never close - // it ourselves. - d.lndOwned = false + // connection to lnd that might be shared among other subservers. We + // only receive the non-closable services view: the connection is + // owned by the parent process (e.g. LiT) and it is not possible for + // us to close it. + d.lnd = lndServices // With lnd already pre-connected, initialize everything else, such as // the swap server client, the RPC server instance and our main swap @@ -462,7 +467,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Run the cost migration. err = loop.MigrateLoopOutCosts( - d.mainCtx, d.lnd.LndServices, d.cfg.MigrationRPCBatchSize, + d.mainCtx, *d.lnd, d.cfg.MigrationRPCBatchSize, swapDb, ) if err != nil { @@ -507,7 +512,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { // Create an instance of the loop client library. swapClient, clientCleanup, err := getClient( - d.cfg, swapDb, sweeperDb, &d.lnd.LndServices, d.assetClient, + d.cfg, swapDb, sweeperDb, d.lnd, d.assetClient, ) if err != nil { return err @@ -564,7 +569,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { }, RequiredPerms: loop_looprpc.RequiredPermissions, DBPassword: macDbDefaultPw, - LndClient: &d.lnd.LndServices, + LndClient: d.lnd, EphemeralKey: lndclient.SharedKeyNUMS, KeyLocator: lndclient.SharedKeyLocator, }, @@ -817,7 +822,7 @@ func (d *Daemon) initialize(withMacaroonService bool) error { impl: swapClient, loopInQuoter: swapClient, liquidityMgr: liquidityMgr, - lnd: &d.lnd.LndServices, + lnd: d.lnd, swaps: make(map[lntypes.Hash]loop.SwapInfo), subscribers: make(map[int]chan<- any), statusChan: statusChan, @@ -1164,13 +1169,14 @@ func (d *Daemon) stop() { } } - // Next, shut down the connections to lnd and the swap server. We - // only close the lnd connection if we created it ourselves - // (standalone mode). In subserver mode the connection is owned by - // the parent process and shared with other subservers, closing it - // here would tear down their lnd access as well. - if d.lnd != nil && d.lndOwned { - d.lnd.Close() + // Next, shut down the connections to lnd and the swap server. The + // lnd connection is only closed if we created it ourselves + // (standalone mode), in which case lndOwner holds the closable + // wrapper. In subserver mode the connection is owned by the parent + // process and shared with other subservers, closing it here would + // tear down their lnd access as well. + if d.lndOwner != nil { + d.lndOwner.Close() } if d.clientCleanup != nil { d.clientCleanup() diff --git a/loopd/daemon_ownership_test.go b/loopd/daemon_ownership_test.go index 1005b1d6d0..f4173c0cc3 100644 --- a/loopd/daemon_ownership_test.go +++ b/loopd/daemon_ownership_test.go @@ -354,9 +354,10 @@ func TestSubserverDoesNotCloseSharedLndConn(t *testing.T) { conn := services.ClientConn // Start the daemon as a subserver with the shared - // (borrowed) lnd connection. + // (borrowed) lnd services. Note that the daemon only + // receives the non-closable view of the connection. d := newTestDaemon(t) - err := d.StartAsSubserver(services, false) + err := d.StartAsSubserver(&services.LndServices, false) require.NoError(t, err) // Trigger the shutdown and wait for the daemon to @@ -399,10 +400,11 @@ func TestOwnedLndConnClosedOnStop(t *testing.T) { conn := services.ClientConn // Simulate a daemon that created its own lnd connection (standalone - // mode via Start) by marking the connection as owned. + // mode via Start): it keeps the closable wrapper in lndOwner while + // the rest of the daemon only sees the non-closable services view. d := newTestDaemon(t) - d.lnd = services - d.lndOwned = true + d.lnd = &services.LndServices + d.lndOwner = services // Stopping the daemon must close the connection it owns. d.stop() diff --git a/loopd/ownership_guard_test.go b/loopd/ownership_guard_test.go new file mode 100644 index 0000000000..b6d8463ae7 --- /dev/null +++ b/loopd/ownership_guard_test.go @@ -0,0 +1,157 @@ +package loopd + +import ( + "bytes" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestLndConnectionOwnershipGuard is a mechanically enforced invariant +// (running as part of the unit tests in CI) that makes sure the lnd +// connection ownership model cannot silently regress: +// +// - StartAsSubserver must never again accept the closable +// *lndclient.GrpcLndServices wrapper, only the non-closable +// *lndclient.LndServices view. +// - No code in this package may call .Close() on an lnd connection +// handle (the services view, the raw client connection or the +// wrapper), except through the designated owner handle lndOwner, +// which is only set in standalone mode. +func TestLndConnectionOwnershipGuard(t *testing.T) { + // allowedCloseReceivers is the exhaustive whitelist of receiver + // expressions on which .Close() may be called on an lnd connection + // handle in this package. The lndOwner field is only non-nil when + // the daemon created the connection itself. + allowedCloseReceivers := map[string]bool{ + // The daemon's owner handle, only set in standalone mode. + "d.lndOwner": true, + + // The view command's own connection, created and owned by + // the command itself. + "ownedLnd": true, + } + + // forbiddenReceiverComponents are the components (split on '.') + // that no .Close() receiver expression may contain, unless the + // whole expression is whitelisted above. + forbiddenReceiverComponents := []string{ + "lnd", "lndServices", "lndGrpc", "lndClient", "lndOwner", + "ClientConn", + } + + fset := token.NewFileSet() + err := filepath.WalkDir(".", func(path string, d os.DirEntry, + err error) error { + + if err != nil { + return err + } + + if d.IsDir() || !strings.HasSuffix(path, ".go") || + strings.HasSuffix(path, "_test.go") { + + return nil + } + + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + + checkFileOwnershipGuard( + t, fset, path, file, allowedCloseReceivers, + forbiddenReceiverComponents, + ) + + return nil + }) + require.NoError(t, err) +} + +// checkFileOwnershipGuard inspects a single parsed file for violations of +// the lnd connection ownership invariant. +func checkFileOwnershipGuard(t *testing.T, fset *token.FileSet, path string, + file *ast.File, allowedCloseReceivers map[string]bool, + forbiddenReceiverComponents []string) { + + ast.Inspect(file, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.FuncDecl: + // The subserver entry point must only accept the + // non-closable services view. + if node.Name.Name != "StartAsSubserver" { + return true + } + + for _, field := range node.Type.Params.List { + typeStr := renderNode(fset, field.Type) + if strings.Contains( + typeStr, "GrpcLndServices", + ) { + + t.Errorf( + "%v: StartAsSubserver must "+ + "not accept the closable "+ + "wrapper type %v", + fset.Position(node.Pos()), + typeStr, + ) + } + } + + case *ast.CallExpr: + sel, ok := node.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Close" { + return true + } + + receiver := renderNode(fset, sel.X) + if allowedCloseReceivers[receiver] { + return true + } + + components := strings.FieldsFunc( + receiver, func(r rune) bool { + return r == '.' || r == '(' || + r == ')' || r == '&' || + r == '*' + }, + ) + for _, component := range components { + for _, forbidden := range forbiddenReceiverComponents { //nolint:lll + if component != forbidden { + continue + } + + t.Errorf( + "%v: %v: forbidden .Close() "+ + "call on lnd connection "+ + "receiver %q, only the "+ + "owner handle lndOwner "+ + "may be closed", + fset.Position(node.Pos()), + path, receiver, + ) + } + } + } + + return true + }) +} + +// renderNode renders an AST node back to its source string. +func renderNode(fset *token.FileSet, n ast.Node) string { + var buf bytes.Buffer + _ = printer.Fprint(&buf, fset, n) + + return buf.String() +} diff --git a/loopd/view.go b/loopd/view.go index 86b9604a1f..776d9cd3c8 100644 --- a/loopd/view.go +++ b/loopd/view.go @@ -17,11 +17,14 @@ import ( func view(config *Config, lisCfg *ListenerCfg) error { network := lndclient.Network(config.Network) - lnd, err := lisCfg.getLnd(network, config.Lnd) + // The view command creates its own lnd connection and therefore owns + // (and closes) it. The variable is deliberately named ownedLnd so the + // ownership guard test can whitelist this legitimate close site. + ownedLnd, err := lisCfg.getLnd(network, config.Lnd) if err != nil { return err } - defer lnd.Close() + defer ownedLnd.Close() chainParams, err := network.ChainParams() if err != nil { @@ -48,7 +51,7 @@ func view(config *Config, lisCfg *ListenerCfg) error { } swapClient, cleanup, err := getClient( - config, swapDb, sweeperDb, &lnd.LndServices, assetClient, + config, swapDb, sweeperDb, &ownedLnd.LndServices, assetClient, ) if err != nil { return err diff --git a/loopout.go b/loopout.go index 59fa6f74a8..32ef1f45d5 100644 --- a/loopout.go +++ b/loopout.go @@ -1555,7 +1555,7 @@ type resumeManager struct { ntfnManager NotificationManager swapStore loopdb.SwapStore swapClient swapserverrpc.SwapServerClient - lnd *lndclient.GrpcLndServices + lnd *lndclient.LndServices clock clock.Clock reqChan chan *swapserverrpc.ServerUnfinishedSwapNotification @@ -1566,7 +1566,7 @@ type resumeManager struct { func Resume(ctx context.Context, ntfnManager NotificationManager, swapStore loopdb.SwapStore, swapClientConn *grpc.ClientConn, - lnd *lndclient.GrpcLndServices, clock clock.Clock) { + lnd *lndclient.LndServices, clock clock.Clock) { resumeManager := &resumeManager{ ntfnManager: ntfnManager,