From 0df363e1607503dbdcfed4c96e0a6a8b41f57de6 Mon Sep 17 00:00:00 2001 From: claudell Date: Fri, 30 Oct 2026 19:24:32 +0000 Subject: [PATCH 1/2] pool: track lnd connection ownership, don't close borrowed conns When running as a subserver inside lightning-terminal, the pool trader server receives an lnd connection that is created and owned by the parent process and shared among all subservers. On Stop, the server unconditionally closed that connection, tearing down lnd access for LiT itself and all other integrated subservers (loop, 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 trader server against a mock lnd with a real injected grpc.ClientConn and asserts the connection survives Stop, 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 | 9 + server.go | 28 +- server_ownership_test.go | 372 +++++++++++++++++++++++ 3 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 server_ownership_test.go diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 4af54cbb..c88e2950 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -1,5 +1,14 @@ # Next release +## Bug Fixes + +* Fix a connection ownership bug where an embedded pool trader server closed + the shared lnd connection on shutdown. When running as a subserver of + lightning-terminal, stopping the pool daemon tore down the lnd connection + owned by the parent process, breaking lnd access for LiT and all other + integrated subservers. The server now tracks whether it created the + connection itself and only closes owned connections. + ## Breaking Changes * Migrate exported Bitcoin types and dependencies to the btcd v2 modules. diff --git a/server.go b/server.go index cccca4cd..a54fd625 100644 --- a/server.go +++ b/server.go @@ -113,6 +113,13 @@ type Server struct { l402Store *l402.FileStore lndServices *lndclient.GrpcLndServices lndClient lnrpc.LightningClient + + // lndOwned indicates whether the server created the lnd connection + // itself (standalone mode via Start) and therefore owns its + // lifecycle. When the server 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 grpcServer *grpc.Server restProxy *http.Server grpcListener net.Listener @@ -160,6 +167,10 @@ func (s *Server) Start() error { if err != nil { return err } + + // We created the lnd connection ourselves, so we own it and are + // responsible for closing it on shutdown. + s.lndOwned = true shutdownFuncs["lnd"] = func() error { // nolint:unparam s.lndServices.Close() return nil @@ -388,6 +399,11 @@ func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient, s.lndClient = lndClient s.lndServices = 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. + s.lndOwned = false + // Print the version before executing either primary directive. log.Infof("Version: %v", Version()) @@ -719,7 +735,7 @@ func (s *Server) Stop() error { } } - s.lndServices.Close() + s.stopLnd() s.wg.Wait() if shutdownErr != nil { @@ -728,6 +744,16 @@ func (s *Server) Stop() error { return nil } +// stopLnd closes the connection to lnd, but only if the server created the +// connection itself (standalone mode). In subserver mode the connection is +// owned by the parent process (e.g. LiT) and shared with other subservers, +// closing it here would tear down their lnd access as well. +func (s *Server) stopLnd() { + if s.lndServices != nil && s.lndOwned { + s.lndServices.Close() + } +} + // getLnd returns an instance of the lnd services proxy. func getLnd(network string, cfg *LndConfig, interceptor signal.Interceptor) (*lndclient.GrpcLndServices, error) { diff --git a/server_ownership_test.go b/server_ownership_test.go new file mode 100644 index 00000000..da233776 --- /dev/null +++ b/server_ownership_test.go @@ -0,0 +1,372 @@ +package pool + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "testing" + "time" + + "github.com/lightninglabs/lndclient" + "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" +) + +// 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 pool trader server. 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: "mock-lnd", + Color: "#3399ff", + Version: "0.21.0-beta", + BlockHeight: testMockLndHeight, + BlockHash: "00000000000000000000000000000000" + + "00000000000000000000000000000000", + SyncedToChain: true, + SyncedToGraph: true, + Chains: []*lnrpc.Chain{ + { + Chain: "bitcoin", + Network: "testnet", + }, + }, + }, nil +} + +// SubscribeChannelEvents blocks until the subscription is canceled. +func (m *mockLightningServer) SubscribeChannelEvents( + _ *lnrpc.ChannelEventSubscription, + stream lnrpc.Lightning_SubscribeChannelEventsServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// ChannelAcceptor blocks until the stream is canceled. +func (m *mockLightningServer) ChannelAcceptor( + stream lnrpc.Lightning_ChannelAcceptorServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// 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() +} + +// 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 pool 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 +} + +// EstimateFee returns a static fee estimate. +func (m *mockWalletKitServer) EstimateFee(_ context.Context, + _ *walletrpc.EstimateFeeRequest) (*walletrpc.EstimateFeeResponse, + error) { + + return &walletrpc.EstimateFeeResponse{ + SatPerKw: 12500, + }, nil +} + +// 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, &invoicesrpc.UnimplementedInvoicesServer{}, + ) + 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: minimalCompatibleVersion, + }) + require.NoError(t, err) + + return services +} + +// 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: "mock-lnd", + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | + x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{"mock-lnd"}, + } + + der, err := x509.CreateCertificate( + rand.Reader, template, template, &key.PublicKey, key, + ) + require.NoError(t, err) + + return tls.Certificate{ + Certificate: [][]byte{der}, + PrivateKey: key, + } +} + +// TestSubserverDoesNotCloseSharedLndConn is a regression test for the +// connection ownership bug that caused an embedded pool trader server to +// close the lnd connection that LiT shares among all its subservers. +// Stopping the embedded server must not close the injected lnd connection. +func TestSubserverDoesNotCloseSharedLndConn(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 + + cfg := DefaultConfig() + cfg.Network = "testnet" + cfg.BaseDir = t.TempDir() + cfg.LogDir = cfg.BaseDir + cfg.AuctionServer = "127.0.0.1:1" + cfg.Insecure = true + cfg.FakeAuth = true + + // Start the trader as a subserver with the shared (borrowed) lnd + // connection and a basic client on the same connection, exactly like + // LiT passes them. + server := NewServer(&cfg) + basicClient := lnrpc.NewLightningClient(conn) + err := server.StartAsSubserver(basicClient, services, false) + require.NoError(t, err) + + // Stopping the trader server must not close the shared lnd + // connection, it is owned by the parent process. + require.NoError(t, server.Stop()) + 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 trader server still closes +// the lnd connection when it owns it (standalone mode), i.e. that the +// ownership guard does not leak connections that the server created itself. +func TestOwnedLndConnClosedOnStop(t *testing.T) { + lis := startMockLnd(t) + services := newInjectedLndServices(t, lis) + conn := services.ClientConn + + // Simulate a server that created its own lnd connection (standalone + // mode via Start) by marking the connection as owned. + cfg := DefaultConfig() + cfg.Network = "testnet" + cfg.BaseDir = t.TempDir() + + server := NewServer(&cfg) + server.lndServices = services + server.lndOwned = true + + // Stopping the server must close the connection it owns. We call the + // relevant part of the shutdown logic directly as the rest of the + // server was never started. + server.stopLnd() + require.Equal(t, connectivity.Shutdown, conn.GetState()) +} From fd581ca67e8030702746db27d123675de0bf1782 Mon Sep 17 00:00:00 2001 From: claudell Date: Fri, 30 Oct 2026 20:02:59 +0000 Subject: [PATCH 2/2] pool: 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 server creates the connection itself (standalone Start). 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 s.lndServices.Close() bug site in Stop and the wrapper-typed signature) and to pass with this change. --- rpcserver.go | 2 +- rpcserver_test.go | 4 +- server.go | 64 ++++++++------ server_ownership_guard_test.go | 153 +++++++++++++++++++++++++++++++++ server_ownership_test.go | 15 ++-- 5 files changed, 201 insertions(+), 37 deletions(-) create mode 100644 server_ownership_guard_test.go diff --git a/rpcserver.go b/rpcserver.go index 085a92bc..2b837c47 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -132,7 +132,7 @@ func (s *accountStore) PendingBatch() error { // database is created in `serverDir` if it does not yet exist. func newRPCServer(server *Server) (*rpcServer, error) { accountStore := &accountStore{server.db} - lndServices := &server.lndServices.LndServices + lndServices := server.lndServices batchVersion, err := server.determineBatchVersion() if err != nil { return nil, err diff --git a/rpcserver_test.go b/rpcserver_test.go index a78e6498..43ba56e0 100644 --- a/rpcserver_test.go +++ b/rpcserver_test.go @@ -197,9 +197,7 @@ func TestRenewAccount(t *testing.T) { orderManager: orderMgr, marshaler: marshaler, server: &Server{ - lndServices: &lndclient.GrpcLndServices{ - LndServices: lndServices, - }, + lndServices: &lndServices, }, } srv.bestHeight = 100 diff --git a/server.go b/server.go index a54fd625..2e03b581 100644 --- a/server.go +++ b/server.go @@ -111,15 +111,21 @@ type Server struct { fundingManager *funding.Manager sidecarAcceptor *SidecarAcceptor l402Store *l402.FileStore - lndServices *lndclient.GrpcLndServices - lndClient lnrpc.LightningClient - - // lndOwned indicates whether the server created the lnd connection - // itself (standalone mode via Start) and therefore owns its - // lifecycle. When the server 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 + + // lndServices is the set of lnd services the server uses. It is a + // non-closable view: the closeable connection wrapper is only ever + // held in lndOwner, and only when the server created the connection + // itself (standalone mode). + lndServices *lndclient.LndServices + lndClient lnrpc.LightningClient + + // lndOwner holds the full lnd services wrapper, including its Close + // method, if and only if the server created the lnd connection + // itself (standalone mode via Start). When the server 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 grpcServer *grpc.Server restProxy *http.Server grpcListener net.Listener @@ -161,7 +167,7 @@ func (s *Server) Start() error { }() var err error - s.lndServices, err = getLnd( + lndGrpc, err := getLnd( s.cfg.Network, s.cfg.Lnd, s.cfg.ShutdownInterceptor, ) if err != nil { @@ -169,10 +175,12 @@ func (s *Server) Start() error { } // We created the lnd connection ourselves, so we own it and are - // responsible for closing it on shutdown. - s.lndOwned = true + // responsible for closing it on shutdown. The rest of the server + // only ever sees the non-closable services view. + s.lndOwner = lndGrpc + s.lndServices = &lndGrpc.LndServices shutdownFuncs["lnd"] = func() error { // nolint:unparam - s.lndServices.Close() + s.lndOwner.Close() return nil } @@ -212,7 +220,7 @@ func (s *Server) Start() error { }, RequiredPerms: poolrpc.RequiredPermissions, DBPassword: macDbDefaultPw, - LndClient: &s.lndServices.LndServices, + LndClient: s.lndServices, EphemeralKey: lndclient.SharedKeyNUMS, KeyLocator: lndclient.SharedKeyLocator, }, @@ -390,19 +398,20 @@ func (s *Server) Start() error { // StartAsSubserver is an alternative start method where the RPC server does not // create its own gRPC server but registers on an existing one. func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient, - lndGrpc *lndclient.GrpcLndServices, withMacaroonService bool) error { + lndServices *lndclient.LndServices, withMacaroonService bool) error { if atomic.AddInt32(&s.started, 1) != 1 { return fmt.Errorf("trader can only be started once") } s.lndClient = lndClient - s.lndServices = 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. - s.lndOwned = false + // When starting as a subserver, we get passed in an already + // established 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. + s.lndServices = lndServices // Print the version before executing either primary directive. log.Infof("Version: %v", Version()) @@ -443,7 +452,7 @@ func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient, }, RequiredPerms: poolrpc.RequiredPermissions, DBPassword: macDbDefaultPw, - LndClient: &s.lndServices.LndServices, + LndClient: s.lndServices, EphemeralKey: lndclient.SharedKeyNUMS, KeyLocator: lndclient.SharedKeyLocator, }, @@ -566,7 +575,7 @@ func (s *Server) setupClient() error { // create a fixed identity that is used for the whole runtime of the // trader instead. var interceptor Interceptor = l402.NewInterceptor( - &s.lndServices.LndServices, s.l402Store, defaultRPCTimeout, + s.lndServices, s.l402Store, defaultRPCTimeout, defaultL402MaxCost, s.cfg.L402MaxRoutingFee, false, ) if s.cfg.FakeAuth && s.cfg.Network == "mainnet" { @@ -745,12 +754,13 @@ func (s *Server) Stop() error { } // stopLnd closes the connection to lnd, but only if the server created the -// connection itself (standalone mode). In subserver mode the connection is -// owned by the parent process (e.g. LiT) and shared with other subservers, -// closing it here would tear down their lnd access as well. +// connection itself (standalone mode), in which case lndOwner holds the +// closable wrapper. In subserver mode the connection is owned by the parent +// process (e.g. LiT) and shared with other subservers, closing it here +// would tear down their lnd access as well. func (s *Server) stopLnd() { - if s.lndServices != nil && s.lndOwned { - s.lndServices.Close() + if s.lndOwner != nil { + s.lndOwner.Close() } } diff --git a/server_ownership_guard_test.go b/server_ownership_guard_test.go new file mode 100644 index 00000000..7ddae91e --- /dev/null +++ b/server_ownership_guard_test.go @@ -0,0 +1,153 @@ +package pool + +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 server created the connection itself. + allowedCloseReceivers := map[string]bool{ + // The server's owner handle, only set in standalone mode. + "s.lndOwner": 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/server_ownership_test.go b/server_ownership_test.go index da233776..55066daf 100644 --- a/server_ownership_test.go +++ b/server_ownership_test.go @@ -325,11 +325,13 @@ func TestSubserverDoesNotCloseSharedLndConn(t *testing.T) { cfg.FakeAuth = true // Start the trader as a subserver with the shared (borrowed) lnd - // connection and a basic client on the same connection, exactly like - // LiT passes them. + // services and a basic client on the same connection, exactly like + // LiT passes them. Note that the trader only receives the + // non-closable view of the connection. server := NewServer(&cfg) basicClient := lnrpc.NewLightningClient(conn) - err := server.StartAsSubserver(basicClient, services, false) + err := server.StartAsSubserver(basicClient, &services.LndServices, + false) require.NoError(t, err) // Stopping the trader server must not close the shared lnd @@ -355,14 +357,15 @@ func TestOwnedLndConnClosedOnStop(t *testing.T) { conn := services.ClientConn // Simulate a server 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 server only sees the non-closable services view. cfg := DefaultConfig() cfg.Network = "testnet" cfg.BaseDir = t.TempDir() server := NewServer(&cfg) - server.lndServices = services - server.lndOwned = true + server.lndServices = &services.LndServices + server.lndOwner = services // Stopping the server must close the connection it owns. We call the // relevant part of the shutdown logic directly as the rest of the