Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/release-notes/release-notes-next.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions rpcserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 46 additions & 10 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,21 @@ type Server struct {
fundingManager *funding.Manager
sidecarAcceptor *SidecarAcceptor
l402Store *l402.FileStore
lndServices *lndclient.GrpcLndServices
lndClient lnrpc.LightningClient

// 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
Expand Down Expand Up @@ -154,14 +167,20 @@ 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 {
return err
}

// We created the lnd connection ourselves, so we own it and are
// 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
}

Expand Down Expand Up @@ -201,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,
},
Expand Down Expand Up @@ -379,14 +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

// 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())
Expand Down Expand Up @@ -427,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,
},
Expand Down Expand Up @@ -550,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" {
Expand Down Expand Up @@ -719,7 +744,7 @@ func (s *Server) Stop() error {
}
}

s.lndServices.Close()
s.stopLnd()
s.wg.Wait()

if shutdownErr != nil {
Expand All @@ -728,6 +753,17 @@ 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 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.lndOwner != nil {
s.lndOwner.Close()
}
}

// getLnd returns an instance of the lnd services proxy.
func getLnd(network string, cfg *LndConfig,
interceptor signal.Interceptor) (*lndclient.GrpcLndServices, error) {
Expand Down
153 changes: 153 additions & 0 deletions server_ownership_guard_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
Loading
Loading