2017-11-28 01:12:09 +01:00
|
|
|
// Copyright (c) 2013-2017 The btcsuite developers
|
|
|
|
// Copyright (c) 2015-2016 The Decred developers
|
|
|
|
// Copyright (C) 2015-2017 The Lightning Network Developers
|
|
|
|
|
2019-01-24 14:28:25 +01:00
|
|
|
package lnd
|
2015-12-17 01:42:52 +01:00
|
|
|
|
2015-12-30 01:23:27 +01:00
|
|
|
import (
|
2021-04-16 14:28:49 +02:00
|
|
|
"bytes"
|
2019-09-29 01:07:37 +02:00
|
|
|
"context"
|
2017-08-14 22:54:06 +02:00
|
|
|
"crypto/tls"
|
2021-06-20 11:16:03 +02:00
|
|
|
"errors"
|
2015-12-30 01:23:27 +01:00
|
|
|
"fmt"
|
2017-07-26 01:22:06 +02:00
|
|
|
"io/ioutil"
|
2015-12-30 01:23:27 +01:00
|
|
|
"net"
|
2016-01-17 04:09:41 +01:00
|
|
|
"net/http"
|
2020-09-14 13:19:32 +02:00
|
|
|
_ "net/http/pprof" // Blank import to set up profiling HTTP handlers.
|
2015-12-30 03:59:16 +01:00
|
|
|
"os"
|
2018-01-05 22:43:47 +01:00
|
|
|
"path/filepath"
|
2017-10-15 02:08:27 +02:00
|
|
|
"runtime/pprof"
|
2020-10-08 15:10:27 +02:00
|
|
|
"strconv"
|
2018-03-15 10:04:17 +01:00
|
|
|
"strings"
|
2017-12-17 18:28:38 +01:00
|
|
|
"sync"
|
2017-06-06 00:18:06 +02:00
|
|
|
"time"
|
2015-12-30 01:23:27 +01:00
|
|
|
|
2021-09-21 19:18:25 +02:00
|
|
|
"github.com/btcsuite/btcd/chaincfg"
|
2020-10-08 15:10:27 +02:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2019-06-14 02:31:55 +02:00
|
|
|
"github.com/btcsuite/btcutil"
|
2018-08-02 01:02:47 +02:00
|
|
|
"github.com/btcsuite/btcwallet/wallet"
|
2020-10-08 15:10:27 +02:00
|
|
|
"github.com/btcsuite/btcwallet/walletdb"
|
2021-07-27 12:59:59 +02:00
|
|
|
proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
|
2019-02-12 03:35:45 +01:00
|
|
|
"github.com/lightninglabs/neutrino"
|
2020-10-08 15:10:27 +02:00
|
|
|
"github.com/lightninglabs/neutrino/headerfs"
|
2019-01-07 18:48:02 +01:00
|
|
|
"golang.org/x/crypto/acme/autocert"
|
2020-09-14 13:19:32 +02:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/credentials"
|
2021-07-27 12:59:59 +02:00
|
|
|
"google.golang.org/protobuf/encoding/protojson"
|
2020-09-14 13:19:32 +02:00
|
|
|
"gopkg.in/macaroon-bakery.v2/bakery"
|
|
|
|
"gopkg.in/macaroon.v2"
|
2018-09-20 12:26:58 +02:00
|
|
|
|
2018-12-13 12:26:29 +01:00
|
|
|
"github.com/lightningnetwork/lnd/autopilot"
|
2021-03-24 07:48:33 +01:00
|
|
|
"github.com/lightningnetwork/lnd/blockcache"
|
2018-09-20 12:26:58 +02:00
|
|
|
"github.com/lightningnetwork/lnd/build"
|
2019-11-13 14:03:10 +01:00
|
|
|
"github.com/lightningnetwork/lnd/cert"
|
2020-09-29 17:56:18 +02:00
|
|
|
"github.com/lightningnetwork/lnd/chainreg"
|
2019-08-08 04:17:50 +02:00
|
|
|
"github.com/lightningnetwork/lnd/chanacceptor"
|
2016-03-23 02:50:11 +01:00
|
|
|
"github.com/lightningnetwork/lnd/channeldb"
|
2018-02-18 00:40:10 +01:00
|
|
|
"github.com/lightningnetwork/lnd/keychain"
|
2021-08-03 09:57:27 +02:00
|
|
|
"github.com/lightningnetwork/lnd/kvdb"
|
2018-05-23 15:41:16 +02:00
|
|
|
"github.com/lightningnetwork/lnd/lncfg"
|
2016-01-16 19:38:48 +01:00
|
|
|
"github.com/lightningnetwork/lnd/lnrpc"
|
2017-06-06 00:18:06 +02:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet"
|
2018-02-02 05:49:34 +01:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/btcwallet"
|
2017-08-18 03:50:57 +02:00
|
|
|
"github.com/lightningnetwork/lnd/macaroons"
|
2021-02-02 13:45:29 +01:00
|
|
|
"github.com/lightningnetwork/lnd/monitoring"
|
2020-10-13 11:24:40 +02:00
|
|
|
"github.com/lightningnetwork/lnd/rpcperms"
|
2018-06-15 05:16:20 +02:00
|
|
|
"github.com/lightningnetwork/lnd/signal"
|
2020-03-17 15:58:36 +01:00
|
|
|
"github.com/lightningnetwork/lnd/tor"
|
2017-10-12 11:37:37 +02:00
|
|
|
"github.com/lightningnetwork/lnd/walletunlocker"
|
2019-06-14 02:31:55 +02:00
|
|
|
"github.com/lightningnetwork/lnd/watchtower"
|
2021-08-03 09:57:33 +02:00
|
|
|
"github.com/lightningnetwork/lnd/watchtower/wtclient"
|
2019-06-14 02:29:47 +02:00
|
|
|
"github.com/lightningnetwork/lnd/watchtower/wtdb"
|
2015-12-30 01:23:27 +01:00
|
|
|
)
|
|
|
|
|
2021-07-17 10:45:17 +02:00
|
|
|
const (
|
|
|
|
// adminMacaroonFilePermissions is the file permission that is used for
|
|
|
|
// creating the admin macaroon file.
|
|
|
|
//
|
|
|
|
// Why 640 is safe:
|
|
|
|
// Assuming a reasonably secure Linux system, it will have a
|
|
|
|
// separate group for each user. E.g. a new user lnd gets assigned group
|
|
|
|
// lnd which nothing else belongs to. A system that does not do this is
|
|
|
|
// inherently broken already.
|
|
|
|
//
|
|
|
|
// Since there is no other user in the group, no other user can read
|
|
|
|
// admin macaroon unless the administrator explicitly allowed it. Thus
|
|
|
|
// there's no harm allowing group read.
|
|
|
|
adminMacaroonFilePermissions = 0640
|
|
|
|
)
|
|
|
|
|
2019-12-02 13:23:20 +01:00
|
|
|
// AdminAuthOptions returns a list of DialOptions that can be used to
|
|
|
|
// authenticate with the RPC server with admin capabilities.
|
2021-02-11 13:53:30 +01:00
|
|
|
// skipMacaroons=true should be set if we don't want to include macaroons with
|
|
|
|
// the auth options. This is needed for instance for the WalletUnlocker
|
|
|
|
// service, which must be usable also before macaroons are created.
|
2019-12-02 13:23:20 +01:00
|
|
|
//
|
|
|
|
// NOTE: This should only be called after the RPCListener has signaled it is
|
|
|
|
// ready.
|
2021-02-11 13:53:30 +01:00
|
|
|
func AdminAuthOptions(cfg *Config, skipMacaroons bool) ([]grpc.DialOption, error) {
|
2019-12-02 13:23:20 +01:00
|
|
|
creds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "")
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to read TLS cert: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a dial options array.
|
|
|
|
opts := []grpc.DialOption{
|
|
|
|
grpc.WithTransportCredentials(creds),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the admin macaroon if macaroons are active.
|
2021-02-11 13:53:30 +01:00
|
|
|
if !skipMacaroons && !cfg.NoMacaroons {
|
2019-12-02 13:23:20 +01:00
|
|
|
// Load the adming macaroon file.
|
|
|
|
macBytes, err := ioutil.ReadFile(cfg.AdminMacPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to read macaroon "+
|
|
|
|
"path (check the network setting!): %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
mac := &macaroon.Macaroon{}
|
|
|
|
if err = mac.UnmarshalBinary(macBytes); err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to decode macaroon: %v",
|
|
|
|
err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now we append the macaroon credentials to the dial options.
|
2021-08-12 16:07:18 +02:00
|
|
|
cred, err := macaroons.NewMacaroonCredential(mac)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error cloning mac: %v", err)
|
|
|
|
}
|
2019-12-02 13:23:20 +01:00
|
|
|
opts = append(opts, grpc.WithPerRPCCredentials(cred))
|
|
|
|
}
|
|
|
|
|
|
|
|
return opts, nil
|
|
|
|
}
|
|
|
|
|
2020-05-04 18:15:03 +02:00
|
|
|
// GrpcRegistrar is an interface that must be satisfied by an external subserver
|
|
|
|
// that wants to be able to register its own gRPC server onto lnd's main
|
|
|
|
// grpc.Server instance.
|
|
|
|
type GrpcRegistrar interface {
|
|
|
|
// RegisterGrpcSubserver is called for each net.Listener on which lnd
|
|
|
|
// creates a grpc.Server instance. External subservers implementing this
|
|
|
|
// method can then register their own gRPC server structs to the main
|
|
|
|
// server instance.
|
|
|
|
RegisterGrpcSubserver(*grpc.Server) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// RestRegistrar is an interface that must be satisfied by an external subserver
|
|
|
|
// that wants to be able to register its own REST mux onto lnd's main
|
|
|
|
// proxy.ServeMux instance.
|
|
|
|
type RestRegistrar interface {
|
|
|
|
// RegisterRestSubserver is called after lnd creates the main
|
|
|
|
// proxy.ServeMux instance. External subservers implementing this method
|
|
|
|
// can then register their own REST proxy stubs to the main server
|
|
|
|
// instance.
|
|
|
|
RegisterRestSubserver(context.Context, *proxy.ServeMux, string,
|
|
|
|
[]grpc.DialOption) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// RPCSubserverConfig is a struct that can be used to register an external
|
|
|
|
// subserver with the custom permissions that map to the gRPC server that is
|
|
|
|
// going to be registered with the GrpcRegistrar.
|
|
|
|
type RPCSubserverConfig struct {
|
|
|
|
// Registrar is a callback that is invoked for each net.Listener on
|
|
|
|
// which lnd creates a grpc.Server instance.
|
|
|
|
Registrar GrpcRegistrar
|
|
|
|
|
|
|
|
// Permissions is the permissions required for the external subserver.
|
|
|
|
// It is a map between the full HTTP URI of each RPC and its required
|
|
|
|
// macaroon permissions. If multiple action/entity tuples are specified
|
|
|
|
// per URI, they are all required. See rpcserver.go for a list of valid
|
|
|
|
// action and entity values.
|
|
|
|
Permissions map[string][]bakery.Op
|
2020-07-13 17:06:51 +02:00
|
|
|
|
|
|
|
// MacaroonValidator is a custom macaroon validator that should be used
|
|
|
|
// instead of the default lnd validator. If specified, the custom
|
|
|
|
// validator is used for all URIs specified in the above Permissions
|
|
|
|
// map.
|
|
|
|
MacaroonValidator macaroons.MacaroonValidator
|
2020-05-04 18:15:03 +02:00
|
|
|
}
|
|
|
|
|
2020-03-19 05:43:49 +01:00
|
|
|
// ListenerWithSignal is a net.Listener that has an additional Ready channel that
|
2019-11-29 11:35:37 +01:00
|
|
|
// will be closed when a server starts listening.
|
|
|
|
type ListenerWithSignal struct {
|
|
|
|
net.Listener
|
|
|
|
|
|
|
|
// Ready will be closed by the server listening on Listener.
|
|
|
|
Ready chan struct{}
|
2021-09-22 21:31:39 +02:00
|
|
|
|
|
|
|
// MacChan is an optional way to pass the admin macaroon to the program
|
|
|
|
// that started lnd. The channel should be buffered to avoid lnd being
|
|
|
|
// blocked on sending to the channel.
|
|
|
|
MacChan chan []byte
|
2019-11-29 11:35:37 +01:00
|
|
|
}
|
|
|
|
|
2019-07-09 14:04:51 +02:00
|
|
|
// ListenerCfg is a wrapper around custom listeners that can be passed to lnd
|
|
|
|
// when calling its main method.
|
|
|
|
type ListenerCfg struct {
|
2021-09-22 21:31:39 +02:00
|
|
|
// RPCListeners can be set to the listeners to use for the RPC server.
|
|
|
|
// If empty a regular network listener will be created.
|
|
|
|
RPCListeners []*ListenerWithSignal
|
2020-10-14 11:52:18 +02:00
|
|
|
|
|
|
|
// ExternalRPCSubserverCfg is optional and specifies the registration
|
|
|
|
// callback and permissions to register external gRPC subservers.
|
|
|
|
ExternalRPCSubserverCfg *RPCSubserverConfig
|
|
|
|
|
|
|
|
// ExternalRestRegistrar is optional and specifies the registration
|
|
|
|
// callback to register external REST subservers.
|
|
|
|
ExternalRestRegistrar RestRegistrar
|
2019-07-09 14:04:51 +02:00
|
|
|
}
|
|
|
|
|
2021-08-01 14:28:32 +02:00
|
|
|
var errStreamIsolationWithProxySkip = errors.New(
|
|
|
|
"while stream isolation is enabled, the TOR proxy may not be skipped",
|
2021-06-20 11:16:03 +02:00
|
|
|
)
|
|
|
|
|
2020-04-30 09:42:28 +02:00
|
|
|
// Main is the true entry point for lnd. It accepts a fully populated and
|
|
|
|
// validated main configuration struct and an optional listener config struct.
|
|
|
|
// This function starts all main system components then blocks until a signal
|
|
|
|
// is received on the shutdownChan at which point everything is shut down again.
|
2020-08-28 11:18:15 +02:00
|
|
|
func Main(cfg *Config, lisCfg ListenerCfg, interceptor signal.Interceptor) error {
|
2017-06-21 17:07:44 +02:00
|
|
|
defer func() {
|
2020-11-23 14:37:42 +01:00
|
|
|
ltndLog.Info("Shutdown complete\n")
|
2020-05-25 18:22:41 +02:00
|
|
|
err := cfg.LogWriter.Close()
|
2019-09-20 16:22:02 +02:00
|
|
|
if err != nil {
|
|
|
|
ltndLog.Errorf("Could not close log rotator: %v", err)
|
|
|
|
}
|
2017-06-21 17:07:44 +02:00
|
|
|
}()
|
2016-03-23 02:50:11 +01:00
|
|
|
|
|
|
|
// Show version at startup.
|
2020-10-02 00:02:16 +02:00
|
|
|
ltndLog.Infof("Version: %s commit=%s, build=%s, logging=%s, debuglevel=%s",
|
2020-04-14 11:13:11 +02:00
|
|
|
build.Version(), build.Commit, build.Deployment,
|
2020-09-27 18:39:20 +02:00
|
|
|
build.LoggingType, cfg.DebugLevel)
|
2016-02-23 03:24:56 +01:00
|
|
|
|
2018-03-15 10:04:17 +01:00
|
|
|
var network string
|
|
|
|
switch {
|
|
|
|
case cfg.Bitcoin.TestNet3 || cfg.Litecoin.TestNet3:
|
|
|
|
network = "testnet"
|
|
|
|
|
|
|
|
case cfg.Bitcoin.MainNet || cfg.Litecoin.MainNet:
|
|
|
|
network = "mainnet"
|
|
|
|
|
2018-09-14 08:03:09 +02:00
|
|
|
case cfg.Bitcoin.SimNet || cfg.Litecoin.SimNet:
|
2018-05-24 03:24:01 +02:00
|
|
|
network = "simnet"
|
2018-03-15 10:04:17 +01:00
|
|
|
|
2018-11-29 22:53:01 +01:00
|
|
|
case cfg.Bitcoin.RegTest || cfg.Litecoin.RegTest:
|
2018-03-15 10:04:17 +01:00
|
|
|
network = "regtest"
|
2020-12-24 16:46:13 +01:00
|
|
|
|
|
|
|
case cfg.Bitcoin.SigNet:
|
|
|
|
network = "signet"
|
2018-03-15 10:04:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
ltndLog.Infof("Active chain: %v (network=%v)",
|
2020-05-14 13:37:32 +02:00
|
|
|
strings.Title(cfg.registeredChains.PrimaryChain().String()),
|
2018-03-15 10:04:17 +01:00
|
|
|
network,
|
|
|
|
)
|
|
|
|
|
2016-06-21 06:42:07 +02:00
|
|
|
// Enable http profiling server if requested.
|
|
|
|
if cfg.Profile != "" {
|
|
|
|
go func() {
|
|
|
|
profileRedirect := http.RedirectHandler("/debug/pprof",
|
|
|
|
http.StatusSeeOther)
|
|
|
|
http.Handle("/", profileRedirect)
|
2021-03-02 23:08:31 +01:00
|
|
|
ltndLog.Infof("Pprof listening on %v", cfg.Profile)
|
|
|
|
fmt.Println(http.ListenAndServe(cfg.Profile, nil))
|
2016-06-21 06:42:07 +02:00
|
|
|
}()
|
|
|
|
}
|
2016-01-17 04:01:06 +01:00
|
|
|
|
2017-10-15 02:08:27 +02:00
|
|
|
// Write cpu profile if requested.
|
|
|
|
if cfg.CPUProfile != "" {
|
|
|
|
f, err := os.Create(cfg.CPUProfile)
|
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create CPU profile: %v",
|
2019-07-17 23:21:19 +02:00
|
|
|
err)
|
|
|
|
ltndLog.Error(err)
|
2017-10-15 02:08:27 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
pprof.StartCPUProfile(f)
|
|
|
|
defer f.Close()
|
|
|
|
defer pprof.StopCPUProfile()
|
|
|
|
}
|
|
|
|
|
2020-05-25 18:08:58 +02:00
|
|
|
ctx := context.Background()
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
|
2021-02-09 17:44:43 +01:00
|
|
|
// Run configuration dependent DB pre-initialization. Note that this
|
|
|
|
// needs to be done early and once during the startup process, before
|
|
|
|
// any DB access.
|
2021-08-03 09:57:26 +02:00
|
|
|
if err := cfg.DB.Init(ctx, cfg.graphDatabaseDir()); err != nil {
|
2021-02-09 17:44:43 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-08-18 03:50:57 +02:00
|
|
|
// Only process macaroons if --no-macaroons isn't set.
|
2020-09-24 13:14:43 +02:00
|
|
|
serverOpts, restDialOpts, restListen, cleanUp, err := getTLSConfig(cfg)
|
2017-10-12 11:37:37 +02:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to load TLS credentials: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2017-10-12 11:37:37 +02:00
|
|
|
return err
|
|
|
|
}
|
2019-01-30 09:09:57 +01:00
|
|
|
|
2019-01-07 18:48:02 +01:00
|
|
|
defer cleanUp()
|
|
|
|
|
2021-03-24 07:48:33 +01:00
|
|
|
// Initialize a new block cache.
|
|
|
|
blockCache := blockcache.NewBlockCache(cfg.BlockCacheSize)
|
|
|
|
|
2019-03-14 01:20:29 +01:00
|
|
|
// Before starting the wallet, we'll create and start our Neutrino
|
|
|
|
// light client instance, if enabled, in order to allow it to sync
|
|
|
|
// while the rest of the daemon continues startup.
|
2019-02-12 03:35:45 +01:00
|
|
|
mainChain := cfg.Bitcoin
|
2020-09-29 17:56:18 +02:00
|
|
|
if cfg.registeredChains.PrimaryChain() == chainreg.LitecoinChain {
|
2019-02-12 03:35:45 +01:00
|
|
|
mainChain = cfg.Litecoin
|
|
|
|
}
|
|
|
|
var neutrinoCS *neutrino.ChainService
|
|
|
|
if mainChain.Node == "neutrino" {
|
2019-03-14 01:20:29 +01:00
|
|
|
neutrinoBackend, neutrinoCleanUp, err := initNeutrinoBackend(
|
2021-03-24 07:48:33 +01:00
|
|
|
cfg, mainChain.ChainDir, blockCache,
|
2019-02-12 03:35:45 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to initialize neutrino "+
|
2019-07-17 23:21:19 +02:00
|
|
|
"backend: %v", err)
|
|
|
|
ltndLog.Error(err)
|
2019-03-14 01:20:29 +01:00
|
|
|
return err
|
2019-02-12 03:35:45 +01:00
|
|
|
}
|
2019-07-15 22:32:37 +02:00
|
|
|
defer neutrinoCleanUp()
|
2019-03-14 01:20:29 +01:00
|
|
|
neutrinoCS = neutrinoBackend
|
2019-02-12 03:35:45 +01:00
|
|
|
}
|
|
|
|
|
2018-03-26 23:12:17 +02:00
|
|
|
var (
|
2021-03-16 14:41:21 +01:00
|
|
|
walletInitParams = WalletUnlockParams{
|
2021-04-16 14:28:49 +02:00
|
|
|
// In case we do auto-unlock, we need to be able to send
|
|
|
|
// into the channel without blocking so we buffer it.
|
|
|
|
MacResponseChan: make(chan []byte, 1),
|
2021-03-16 14:41:21 +01:00
|
|
|
}
|
|
|
|
privateWalletPw = lnwallet.DefaultPrivatePassphrase
|
|
|
|
publicWalletPw = lnwallet.DefaultPublicPassphrase
|
2018-03-26 23:12:17 +02:00
|
|
|
)
|
|
|
|
|
2018-12-10 05:08:32 +01:00
|
|
|
// If the user didn't request a seed, then we'll manually assume a
|
|
|
|
// wallet birthday of now, as otherwise the seed would've specified
|
|
|
|
// this information.
|
|
|
|
walletInitParams.Birthday = time.Now()
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// If we have chosen to start with a dedicated listener for the
|
|
|
|
// rpc server, we set it directly.
|
|
|
|
var grpcListeners []*ListenerWithSignal
|
2021-09-22 21:31:39 +02:00
|
|
|
if len(lisCfg.RPCListeners) > 0 {
|
|
|
|
grpcListeners = append(grpcListeners, lisCfg.RPCListeners...)
|
2021-02-02 13:45:29 +01:00
|
|
|
} else {
|
|
|
|
// Otherwise we create listeners from the RPCListeners defined
|
|
|
|
// in the config.
|
2019-07-09 11:09:19 +02:00
|
|
|
for _, grpcEndpoint := range cfg.RPCListeners {
|
|
|
|
// Start a gRPC server listening for HTTP/2
|
|
|
|
// connections.
|
|
|
|
lis, err := lncfg.ListenOnAddress(grpcEndpoint)
|
|
|
|
if err != nil {
|
|
|
|
ltndLog.Errorf("unable to listen on %s",
|
|
|
|
grpcEndpoint)
|
2021-02-02 13:45:29 +01:00
|
|
|
return err
|
2019-07-09 11:09:19 +02:00
|
|
|
}
|
2021-02-02 13:45:29 +01:00
|
|
|
defer lis.Close()
|
|
|
|
|
2019-11-29 11:35:37 +01:00
|
|
|
grpcListeners = append(
|
|
|
|
grpcListeners, &ListenerWithSignal{
|
|
|
|
Listener: lis,
|
|
|
|
Ready: make(chan struct{}),
|
|
|
|
})
|
2019-07-09 11:09:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-19 15:53:06 +01:00
|
|
|
// Create a new RPC interceptor that we'll add to the GRPC server. This
|
|
|
|
// will be used to log the API calls invoked on the GRPC server.
|
|
|
|
interceptorChain := rpcperms.NewInterceptorChain(
|
2021-08-12 16:07:24 +02:00
|
|
|
rpcsLog, cfg.NoMacaroons, cfg.RPCMiddleware.Mandatory,
|
2021-03-19 15:53:06 +01:00
|
|
|
)
|
|
|
|
if err := interceptorChain.Start(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
err := interceptorChain.Stop()
|
|
|
|
if err != nil {
|
|
|
|
ltndLog.Warnf("error stopping RPC interceptor "+
|
|
|
|
"chain: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
rpcServerOpts := interceptorChain.CreateServerOpts()
|
|
|
|
serverOpts = append(serverOpts, rpcServerOpts...)
|
|
|
|
|
|
|
|
grpcServer := grpc.NewServer(serverOpts...)
|
|
|
|
defer grpcServer.Stop()
|
|
|
|
|
|
|
|
// We'll also register the RPC interceptor chain as the StateServer, as
|
|
|
|
// it can be used to query for the current state of the wallet.
|
|
|
|
lnrpc.RegisterStateServer(grpcServer, interceptorChain)
|
|
|
|
|
|
|
|
// Register the WalletUnlockerService with the GRPC server.
|
|
|
|
pwService := createWalletUnlockerService(cfg)
|
|
|
|
lnrpc.RegisterWalletUnlockerServer(grpcServer, pwService)
|
|
|
|
|
|
|
|
// Initialize, and register our implementation of the gRPC interface
|
|
|
|
// exported by the rpcServer.
|
|
|
|
rpcServer := newRPCServer(
|
|
|
|
cfg, interceptorChain, lisCfg.ExternalRPCSubserverCfg,
|
|
|
|
lisCfg.ExternalRestRegistrar,
|
|
|
|
interceptor,
|
|
|
|
)
|
|
|
|
|
|
|
|
err = rpcServer.RegisterWithGrpcServer(grpcServer)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that both the WalletUnlocker and LightningService have been
|
|
|
|
// registered with the GRPC server, we can start listening.
|
|
|
|
err = startGrpcListen(cfg, grpcServer, grpcListeners)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now start the REST proxy for our gRPC server above. We'll ensure
|
|
|
|
// we direct LND to connect to its loopback address rather than a
|
|
|
|
// wildcard to prevent certificate issues when accessing the proxy
|
|
|
|
// externally.
|
|
|
|
stopProxy, err := startRestProxy(
|
|
|
|
cfg, rpcServer, restDialOpts, restListen,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer stopProxy()
|
|
|
|
|
2021-02-08 21:56:27 +01:00
|
|
|
// Start leader election if we're running on etcd. Continuation will be
|
|
|
|
// blocked until this instance is elected as the current leader or
|
|
|
|
// shutting down.
|
|
|
|
elected := false
|
|
|
|
if cfg.Cluster.EnableLeaderElection {
|
|
|
|
electionCtx, cancelElection := context.WithCancel(ctx)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-interceptor.ShutdownChannel()
|
|
|
|
cancelElection()
|
|
|
|
}()
|
|
|
|
|
|
|
|
ltndLog.Infof("Using %v leader elector",
|
|
|
|
cfg.Cluster.LeaderElector)
|
|
|
|
|
|
|
|
leaderElector, err := cfg.Cluster.MakeLeaderElector(
|
|
|
|
electionCtx, cfg.DB,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if !elected {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ltndLog.Infof("Attempting to resign from leader role "+
|
|
|
|
"(%v)", cfg.Cluster.ID)
|
|
|
|
|
|
|
|
if err := leaderElector.Resign(); err != nil {
|
|
|
|
ltndLog.Errorf("Leader elector failed to "+
|
|
|
|
"resign: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
ltndLog.Infof("Starting leadership campaign (%v)",
|
|
|
|
cfg.Cluster.ID)
|
|
|
|
|
|
|
|
if err := leaderElector.Campaign(electionCtx); err != nil {
|
|
|
|
ltndLog.Errorf("Leadership campaign failed: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
elected = true
|
|
|
|
ltndLog.Infof("Elected as leader (%v)", cfg.Cluster.ID)
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:57:24 +02:00
|
|
|
dbs, cleanUp, err := initializeDatabases(ctx, cfg)
|
2021-02-08 21:56:27 +01:00
|
|
|
switch {
|
|
|
|
case err == channeldb.ErrDryRunMigrationOK:
|
|
|
|
ltndLog.Infof("%v, exiting", err)
|
|
|
|
return nil
|
|
|
|
case err != nil:
|
|
|
|
return fmt.Errorf("unable to open databases: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer cleanUp()
|
|
|
|
|
2021-08-03 09:57:35 +02:00
|
|
|
pwService.SetLoaderOpts([]btcwallet.LoaderOption{dbs.walletDB})
|
2021-08-03 09:57:30 +02:00
|
|
|
pwService.SetMacaroonDB(dbs.macaroonDB)
|
2021-02-05 13:33:01 +01:00
|
|
|
walletExists, err := pwService.WalletExists()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-03-19 15:53:06 +01:00
|
|
|
if !walletExists {
|
|
|
|
interceptorChain.SetWalletNotCreated()
|
|
|
|
} else {
|
|
|
|
interceptorChain.SetWalletLocked()
|
2021-02-02 13:45:29 +01:00
|
|
|
}
|
|
|
|
|
2021-07-01 11:00:40 +02:00
|
|
|
// If we've started in auto unlock mode, then a wallet should already
|
|
|
|
// exist because we don't want to enable the RPC unlocker in that case
|
|
|
|
// for security reasons (an attacker could inject their seed since the
|
|
|
|
// RPC is unauthenticated). Only if the user explicitly wants to allow
|
|
|
|
// wallet creation we don't error out here.
|
|
|
|
if cfg.WalletUnlockPasswordFile != "" && !walletExists &&
|
|
|
|
!cfg.WalletUnlockAllowCreate {
|
|
|
|
|
2021-04-16 14:28:49 +02:00
|
|
|
return fmt.Errorf("wallet unlock password file was specified " +
|
|
|
|
"but wallet does not exist; initialize the wallet " +
|
|
|
|
"before using auto unlocking")
|
|
|
|
}
|
|
|
|
|
|
|
|
// What wallet mode are we running in? We've already made sure the no
|
|
|
|
// seed backup and auto unlock aren't both set during config parsing.
|
|
|
|
switch {
|
|
|
|
// No seed backup means we're also using the default password.
|
|
|
|
case cfg.NoSeedBackup:
|
|
|
|
// We continue normally, the default password has already been
|
|
|
|
// set above.
|
|
|
|
|
|
|
|
// A password for unlocking is provided in a file.
|
2021-07-01 11:00:40 +02:00
|
|
|
case cfg.WalletUnlockPasswordFile != "" && walletExists:
|
2021-04-16 14:28:49 +02:00
|
|
|
ltndLog.Infof("Attempting automatic wallet unlock with " +
|
|
|
|
"password provided in file")
|
|
|
|
pwBytes, err := ioutil.ReadFile(cfg.WalletUnlockPasswordFile)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error reading password from file "+
|
|
|
|
"%s: %v", cfg.WalletUnlockPasswordFile, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove any newlines at the end of the file. The lndinit tool
|
|
|
|
// won't ever write a newline but maybe the file was provisioned
|
|
|
|
// by another process or user.
|
|
|
|
pwBytes = bytes.TrimRight(pwBytes, "\r\n")
|
|
|
|
|
|
|
|
// We have the password now, we can ask the unlocker service to
|
|
|
|
// do the unlock for us.
|
|
|
|
unlockedWallet, unloadWalletFn, err := pwService.LoadAndUnlock(
|
|
|
|
pwBytes, 0,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error unlocking wallet with "+
|
|
|
|
"password from file: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if err := unloadWalletFn(); err != nil {
|
|
|
|
ltndLog.Errorf("Could not unload wallet: %v",
|
|
|
|
err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
privateWalletPw = pwBytes
|
|
|
|
publicWalletPw = pwBytes
|
|
|
|
walletInitParams.Wallet = unlockedWallet
|
|
|
|
walletInitParams.UnloadWallet = unloadWalletFn
|
|
|
|
|
|
|
|
// If none of the automatic startup options are selected, we fall back
|
|
|
|
// to the default behavior of waiting for the wallet creation/unlocking
|
|
|
|
// over RPC.
|
|
|
|
default:
|
2021-07-17 13:54:41 +02:00
|
|
|
if err := interceptor.Notifier.NotifyReady(false); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-03-04 23:13:06 +01:00
|
|
|
params, err := waitForWalletPassword(
|
2021-08-03 09:57:35 +02:00
|
|
|
cfg, pwService, []btcwallet.LoaderOption{dbs.walletDB},
|
2021-03-04 23:13:06 +01:00
|
|
|
interceptor.ShutdownChannel(),
|
|
|
|
)
|
2017-10-12 11:37:37 +02:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to set up wallet password "+
|
2019-07-17 23:21:19 +02:00
|
|
|
"listeners: %v", err)
|
|
|
|
ltndLog.Error(err)
|
2017-10-12 11:37:37 +02:00
|
|
|
return err
|
|
|
|
}
|
2018-03-26 23:12:17 +02:00
|
|
|
|
2018-12-10 05:08:32 +01:00
|
|
|
walletInitParams = *params
|
2018-03-26 23:12:17 +02:00
|
|
|
privateWalletPw = walletInitParams.Password
|
|
|
|
publicWalletPw = walletInitParams.Password
|
2020-09-03 18:10:30 +02:00
|
|
|
defer func() {
|
|
|
|
if err := walletInitParams.UnloadWallet(); err != nil {
|
|
|
|
ltndLog.Errorf("Could not unload wallet: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
2018-03-26 23:12:17 +02:00
|
|
|
|
2018-12-10 05:08:32 +01:00
|
|
|
if walletInitParams.RecoveryWindow > 0 {
|
2018-03-26 23:12:17 +02:00
|
|
|
ltndLog.Infof("Wallet recovery mode enabled with "+
|
|
|
|
"address lookahead of %d addresses",
|
2018-12-10 05:08:32 +01:00
|
|
|
walletInitParams.RecoveryWindow)
|
2018-03-26 23:12:17 +02:00
|
|
|
}
|
2017-10-12 11:37:37 +02:00
|
|
|
}
|
|
|
|
|
2018-04-20 09:06:06 +02:00
|
|
|
var macaroonService *macaroons.Service
|
2018-02-01 01:04:56 +01:00
|
|
|
if !cfg.NoMacaroons {
|
2018-04-20 09:06:06 +02:00
|
|
|
// Create the macaroon authentication/authorization service.
|
2018-08-22 21:27:16 +02:00
|
|
|
macaroonService, err = macaroons.NewService(
|
2021-08-03 09:57:30 +02:00
|
|
|
dbs.macaroonDB, "lnd", walletInitParams.StatelessInit,
|
|
|
|
macaroons.IPLockChecker,
|
2021-08-12 16:07:24 +02:00
|
|
|
macaroons.CustomChecker(interceptorChain),
|
2018-08-22 21:27:16 +02:00
|
|
|
)
|
2018-04-20 09:06:06 +02:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to set up macaroon "+
|
2019-07-17 23:21:19 +02:00
|
|
|
"authentication: %v", err)
|
|
|
|
ltndLog.Error(err)
|
2018-04-20 09:06:06 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer macaroonService.Close()
|
|
|
|
|
2018-02-01 01:04:56 +01:00
|
|
|
// Try to unlock the macaroon store with the private password.
|
2020-10-06 17:23:38 +02:00
|
|
|
// Ignore ErrAlreadyUnlocked since it could be unlocked by the
|
|
|
|
// wallet unlocker.
|
2018-02-01 01:04:56 +01:00
|
|
|
err = macaroonService.CreateUnlock(&privateWalletPw)
|
2020-10-06 17:23:38 +02:00
|
|
|
if err != nil && err != macaroons.ErrAlreadyUnlocked {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to unlock macaroons: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2018-02-01 01:04:56 +01:00
|
|
|
return err
|
|
|
|
}
|
2018-03-21 00:50:08 +01:00
|
|
|
|
2020-10-06 17:23:38 +02:00
|
|
|
// In case we actually needed to unlock the wallet, we now need
|
|
|
|
// to create an instance of the admin macaroon and send it to
|
|
|
|
// the unlocker so it can forward it to the user. In no seed
|
|
|
|
// backup mode, there's nobody listening on the channel and we'd
|
|
|
|
// block here forever.
|
|
|
|
if !cfg.NoSeedBackup {
|
|
|
|
adminMacBytes, err := bakeMacaroon(
|
|
|
|
ctx, macaroonService, adminPermissions(),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// The channel is buffered by one element so writing
|
|
|
|
// should not block here.
|
|
|
|
walletInitParams.MacResponseChan <- adminMacBytes
|
2021-09-22 21:31:39 +02:00
|
|
|
|
|
|
|
for _, lis := range grpcListeners {
|
|
|
|
if lis.MacChan != nil {
|
|
|
|
lis.MacChan <- adminMacBytes
|
|
|
|
}
|
|
|
|
}
|
2020-10-06 17:23:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// If the user requested a stateless initialization, no macaroon
|
|
|
|
// files should be created.
|
|
|
|
if !walletInitParams.StatelessInit &&
|
|
|
|
!fileExists(cfg.AdminMacPath) &&
|
|
|
|
!fileExists(cfg.ReadMacPath) &&
|
2018-03-21 00:50:08 +01:00
|
|
|
!fileExists(cfg.InvoiceMacPath) {
|
|
|
|
|
2020-10-06 17:23:38 +02:00
|
|
|
// Create macaroon files for lncli to use if they don't
|
|
|
|
// exist.
|
2018-03-21 00:50:08 +01:00
|
|
|
err = genMacaroons(
|
|
|
|
ctx, macaroonService, cfg.AdminMacPath,
|
|
|
|
cfg.ReadMacPath, cfg.InvoiceMacPath,
|
|
|
|
)
|
2018-02-01 01:04:56 +01:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create macaroons "+
|
2019-07-17 23:21:19 +02:00
|
|
|
"%v", err)
|
|
|
|
ltndLog.Error(err)
|
2018-02-01 01:04:56 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-10-06 17:23:38 +02:00
|
|
|
|
|
|
|
// As a security service to the user, if they requested
|
|
|
|
// stateless initialization and there are macaroon files on disk
|
|
|
|
// we log a warning.
|
|
|
|
if walletInitParams.StatelessInit {
|
|
|
|
msg := "Found %s macaroon on disk (%s) even though " +
|
|
|
|
"--stateless_init was requested. Unencrypted " +
|
|
|
|
"state is accessible by the host system. You " +
|
|
|
|
"should change the password and use " +
|
|
|
|
"--new_mac_root_key with --stateless_init to " +
|
|
|
|
"clean up and invalidate old macaroons."
|
|
|
|
|
|
|
|
if fileExists(cfg.AdminMacPath) {
|
|
|
|
ltndLog.Warnf(msg, "admin", cfg.AdminMacPath)
|
|
|
|
}
|
|
|
|
if fileExists(cfg.ReadMacPath) {
|
|
|
|
ltndLog.Warnf(msg, "readonly", cfg.ReadMacPath)
|
|
|
|
}
|
|
|
|
if fileExists(cfg.InvoiceMacPath) {
|
|
|
|
ltndLog.Warnf(msg, "invoice", cfg.InvoiceMacPath)
|
|
|
|
}
|
|
|
|
}
|
2020-10-13 11:24:40 +02:00
|
|
|
|
|
|
|
// We add the macaroon service to our RPC interceptor. This
|
|
|
|
// will start checking macaroons against permissions on every
|
|
|
|
// RPC invocation.
|
|
|
|
interceptorChain.AddMacaroonService(macaroonService)
|
2018-02-01 01:04:56 +01:00
|
|
|
}
|
|
|
|
|
2021-03-16 14:41:21 +01:00
|
|
|
// Now that the wallet password has been provided, transition the RPC
|
|
|
|
// state into Unlocked.
|
|
|
|
interceptorChain.SetWalletUnlocked()
|
|
|
|
|
|
|
|
// Since calls to the WalletUnlocker service wait for a response on the
|
|
|
|
// macaroon channel, we close it here to make sure they return in case
|
|
|
|
// we did not return the admin macaroon above. This will be the case if
|
|
|
|
// --no-macaroons is used.
|
|
|
|
close(walletInitParams.MacResponseChan)
|
|
|
|
|
2021-09-22 21:31:39 +02:00
|
|
|
// We'll also close all the macaroon channels since lnd is done sending
|
|
|
|
// macaroon data over it.
|
|
|
|
for _, lis := range grpcListeners {
|
|
|
|
if lis.MacChan != nil {
|
|
|
|
close(lis.MacChan)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-18 20:49:32 +02:00
|
|
|
// With the information parsed from the configuration, create valid
|
2017-08-22 09:03:03 +02:00
|
|
|
// instances of the pertinent interfaces required to operate the
|
2017-05-18 20:49:32 +02:00
|
|
|
// Lightning Network Daemon.
|
2020-05-07 05:49:36 +02:00
|
|
|
//
|
|
|
|
// When we create the chain control, we need storage for the height
|
|
|
|
// hints and also the wallet itself, for these two we want them to be
|
|
|
|
// replicated, so we'll pass in the remote channel DB instance.
|
2020-09-29 19:00:19 +02:00
|
|
|
chainControlCfg := &chainreg.Config{
|
|
|
|
Bitcoin: cfg.Bitcoin,
|
|
|
|
Litecoin: cfg.Litecoin,
|
|
|
|
PrimaryChain: cfg.registeredChains.PrimaryChain,
|
|
|
|
HeightHintCacheQueryDisable: cfg.HeightHintCacheQueryDisable,
|
|
|
|
NeutrinoMode: cfg.NeutrinoMode,
|
|
|
|
BitcoindMode: cfg.BitcoindMode,
|
|
|
|
LitecoindMode: cfg.LitecoindMode,
|
|
|
|
BtcdMode: cfg.BtcdMode,
|
|
|
|
LtcdMode: cfg.LtcdMode,
|
2021-08-03 09:57:27 +02:00
|
|
|
HeightHintDB: dbs.heightHintDB,
|
2021-09-21 19:18:17 +02:00
|
|
|
ChanStateDB: dbs.chanStateDB.ChannelStateDB(),
|
2020-09-29 19:00:19 +02:00
|
|
|
PrivateWalletPw: privateWalletPw,
|
|
|
|
PublicWalletPw: publicWalletPw,
|
|
|
|
Birthday: walletInitParams.Birthday,
|
|
|
|
RecoveryWindow: walletInitParams.RecoveryWindow,
|
|
|
|
Wallet: walletInitParams.Wallet,
|
|
|
|
NeutrinoCS: neutrinoCS,
|
|
|
|
ActiveNetParams: cfg.ActiveNetParams,
|
|
|
|
FeeURL: cfg.FeeURL,
|
2021-03-09 23:12:26 +01:00
|
|
|
Dialer: func(addr string) (net.Conn, error) {
|
|
|
|
return cfg.net.Dial("tcp", addr, cfg.ConnectionTimeout)
|
|
|
|
},
|
2021-03-18 12:40:53 +01:00
|
|
|
BlockCacheSize: cfg.BlockCacheSize,
|
2021-08-03 09:57:35 +02:00
|
|
|
LoaderOptions: []btcwallet.LoaderOption{dbs.walletDB},
|
2020-09-29 19:00:19 +02:00
|
|
|
}
|
|
|
|
|
2021-03-29 15:23:46 +02:00
|
|
|
// Parse coin selection strategy.
|
|
|
|
switch cfg.CoinSelectionStrategy {
|
|
|
|
case "largest":
|
|
|
|
chainControlCfg.CoinSelectionStrategy = wallet.CoinSelectionLargest
|
|
|
|
|
|
|
|
case "random":
|
|
|
|
chainControlCfg.CoinSelectionStrategy = wallet.CoinSelectionRandom
|
|
|
|
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("unknown coin selection strategy %v",
|
|
|
|
cfg.CoinSelectionStrategy)
|
|
|
|
}
|
|
|
|
|
2021-03-24 07:48:33 +01:00
|
|
|
activeChainControl, cleanup, err := chainreg.NewChainControl(
|
|
|
|
chainControlCfg, blockCache,
|
|
|
|
)
|
2021-04-08 11:58:32 +02:00
|
|
|
if cleanup != nil {
|
|
|
|
defer cleanup()
|
|
|
|
}
|
2015-12-30 01:23:27 +01:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create chain control: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2016-07-13 02:03:29 +02:00
|
|
|
return err
|
2015-12-30 01:23:27 +01:00
|
|
|
}
|
2017-03-27 19:25:44 +02:00
|
|
|
|
2017-05-03 04:49:14 +02:00
|
|
|
// Finally before we start the server, we'll register the "holy
|
|
|
|
// trinity" of interface for our current "home chain" with the active
|
|
|
|
// chainRegistry interface.
|
2020-05-14 13:37:32 +02:00
|
|
|
primaryChain := cfg.registeredChains.PrimaryChain()
|
|
|
|
cfg.registeredChains.RegisterChain(primaryChain, activeChainControl)
|
2017-05-03 04:49:14 +02:00
|
|
|
|
2018-02-18 00:40:10 +01:00
|
|
|
// TODO(roasbeef): add rotation
|
2020-10-06 17:03:42 +02:00
|
|
|
idKeyDesc, err := activeChainControl.KeyRing.DeriveKey(
|
2020-04-28 10:06:27 +02:00
|
|
|
keychain.KeyLocator{
|
|
|
|
Family: keychain.KeyFamilyNodeKey,
|
|
|
|
Index: 0,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("error deriving node key: %v", err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-01 14:28:32 +02:00
|
|
|
if cfg.Tor.StreamIsolation && cfg.Tor.SkipProxyForClearNetTargets {
|
|
|
|
return errStreamIsolationWithProxySkip
|
2021-06-20 11:16:03 +02:00
|
|
|
}
|
|
|
|
|
2018-04-27 22:54:35 +02:00
|
|
|
if cfg.Tor.Active {
|
2021-08-01 14:28:32 +02:00
|
|
|
if cfg.Tor.SkipProxyForClearNetTargets {
|
2021-06-20 11:16:03 +02:00
|
|
|
srvrLog.Info("Onion services are accessible via Tor! NOTE: " +
|
|
|
|
"Traffic to clearnet services is not routed via Tor.")
|
|
|
|
} else {
|
|
|
|
srvrLog.Infof("Proxying all network traffic via Tor "+
|
|
|
|
"(stream_isolation=%v)! NOTE: Ensure the backend node "+
|
|
|
|
"is proxying over Tor as well", cfg.Tor.StreamIsolation)
|
|
|
|
}
|
2018-02-06 03:36:11 +01:00
|
|
|
}
|
|
|
|
|
2020-03-17 15:58:36 +01:00
|
|
|
// If tor is active and either v2 or v3 onion services have been specified,
|
|
|
|
// make a tor controller and pass it into both the watchtower server and
|
|
|
|
// the regular lnd server.
|
|
|
|
var torController *tor.Controller
|
|
|
|
if cfg.Tor.Active && (cfg.Tor.V2 || cfg.Tor.V3) {
|
|
|
|
torController = tor.NewController(
|
|
|
|
cfg.Tor.Control, cfg.Tor.TargetIPAddress, cfg.Tor.Password,
|
|
|
|
)
|
|
|
|
|
|
|
|
// Start the tor controller before giving it to any other subsystems.
|
|
|
|
if err := torController.Start(); err != nil {
|
|
|
|
err := fmt.Errorf("unable to initialize tor controller: %v", err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err := torController.Stop(); err != nil {
|
|
|
|
ltndLog.Errorf("error stopping tor controller: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2019-06-14 02:31:55 +02:00
|
|
|
var tower *watchtower.Standalone
|
|
|
|
if cfg.Watchtower.Active {
|
2020-10-06 17:03:42 +02:00
|
|
|
towerKeyDesc, err := activeChainControl.KeyRing.DeriveKey(
|
2020-04-28 10:06:31 +02:00
|
|
|
keychain.KeyLocator{
|
|
|
|
Family: keychain.KeyFamilyTowerID,
|
|
|
|
Index: 0,
|
2019-06-21 01:55:52 +02:00
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
2020-04-28 10:06:31 +02:00
|
|
|
err := fmt.Errorf("error deriving tower key: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2019-06-21 01:55:52 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-03-17 15:58:36 +01:00
|
|
|
wtCfg := &watchtower.Config{
|
2020-10-06 17:03:42 +02:00
|
|
|
BlockFetcher: activeChainControl.ChainIO,
|
2021-08-03 09:57:33 +02:00
|
|
|
DB: dbs.towerServerDB,
|
2020-10-06 17:03:42 +02:00
|
|
|
EpochRegistrar: activeChainControl.ChainNotifier,
|
2019-06-14 02:31:55 +02:00
|
|
|
Net: cfg.net,
|
|
|
|
NewAddress: func() (btcutil.Address, error) {
|
2020-10-06 17:03:42 +02:00
|
|
|
return activeChainControl.Wallet.NewAddress(
|
2019-06-14 02:31:55 +02:00
|
|
|
lnwallet.WitnessPubKey, false,
|
2021-02-20 02:41:45 +01:00
|
|
|
lnwallet.DefaultAccountName,
|
2019-06-14 02:31:55 +02:00
|
|
|
)
|
|
|
|
},
|
2020-04-28 10:06:31 +02:00
|
|
|
NodeKeyECDH: keychain.NewPubKeyECDH(
|
2020-10-06 17:03:42 +02:00
|
|
|
towerKeyDesc, activeChainControl.KeyRing,
|
2020-04-28 10:06:31 +02:00
|
|
|
),
|
2020-10-06 17:03:42 +02:00
|
|
|
PublishTx: activeChainControl.Wallet.PublishTransaction,
|
2020-08-04 20:56:31 +02:00
|
|
|
ChainHash: *cfg.ActiveNetParams.GenesisHash,
|
2020-03-17 15:58:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// If there is a tor controller (user wants auto hidden services), then
|
|
|
|
// store a pointer in the watchtower config.
|
|
|
|
if torController != nil {
|
|
|
|
wtCfg.TorController = torController
|
|
|
|
wtCfg.WatchtowerKeyPath = cfg.Tor.WatchtowerKeyPath
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case cfg.Tor.V2:
|
|
|
|
wtCfg.Type = tor.V2
|
|
|
|
case cfg.Tor.V3:
|
|
|
|
wtCfg.Type = tor.V3
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
wtConfig, err := cfg.Watchtower.Apply(wtCfg, lncfg.NormalizeAddresses)
|
2019-06-14 02:31:55 +02:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to configure watchtower: %v",
|
2019-07-17 23:21:19 +02:00
|
|
|
err)
|
|
|
|
ltndLog.Error(err)
|
2019-06-14 02:31:55 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
tower, err = watchtower.New(wtConfig)
|
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create watchtower: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2019-06-14 02:31:55 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-08 04:17:50 +02:00
|
|
|
// Initialize the ChainedAcceptor.
|
|
|
|
chainedAcceptor := chanacceptor.NewChainedAcceptor()
|
|
|
|
|
2017-05-18 20:49:32 +02:00
|
|
|
// Set up the core server which will listen for incoming peer
|
|
|
|
// connections.
|
2018-02-18 00:40:10 +01:00
|
|
|
server, err := newServer(
|
2021-08-03 09:57:33 +02:00
|
|
|
cfg, cfg.Listeners, dbs, activeChainControl, &idKeyDesc,
|
|
|
|
walletInitParams.ChansToRestore, chainedAcceptor, torController,
|
2018-02-18 00:40:10 +01:00
|
|
|
)
|
2016-01-17 04:09:41 +01:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create server: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2016-07-13 02:03:29 +02:00
|
|
|
return err
|
2016-01-17 04:09:41 +01:00
|
|
|
}
|
2017-06-06 00:18:06 +02:00
|
|
|
|
2019-01-09 09:14:45 +01:00
|
|
|
// Set up an autopilot manager from the current config. This will be
|
2018-12-13 12:26:29 +01:00
|
|
|
// used to manage the underlying autopilot agent, starting and stopping
|
|
|
|
// it at will.
|
2020-08-04 20:56:31 +02:00
|
|
|
atplCfg, err := initAutoPilot(server, cfg.Autopilot, mainChain, cfg.ActiveNetParams)
|
2019-01-09 09:14:45 +01:00
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to initialize autopilot: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2019-01-09 09:14:45 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-12-13 12:26:29 +01:00
|
|
|
atplManager, err := autopilot.NewManager(atplCfg)
|
|
|
|
if err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to create autopilot manager: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2018-12-13 12:26:29 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := atplManager.Start(); err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to start autopilot manager: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2018-12-13 12:26:29 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer atplManager.Stop()
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// Now we have created all dependencies necessary to populate and
|
|
|
|
// start the RPC server.
|
|
|
|
err = rpcServer.addDeps(
|
|
|
|
server, macaroonService, cfg.SubRPCServers, atplManager,
|
|
|
|
server.invoices, tower, chainedAcceptor,
|
2018-05-23 15:38:19 +02:00
|
|
|
)
|
2016-10-15 23:38:47 +02:00
|
|
|
if err != nil {
|
2021-02-02 13:45:29 +01:00
|
|
|
err := fmt.Errorf("unable to add deps to RPC server: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2016-10-15 23:38:47 +02:00
|
|
|
return err
|
|
|
|
}
|
lnd+rpc: modify rpcServer to fully manaage listeners and gRPC, handle sub-servers
In this commit, we modify the existing rpcServer to fully manage the
macaroons, gRPC server, and also seek out and create all sub-servers.
With this change, the RPC server gains more responsibility, as it
becomes the "root" server in the hierarchy of gRPC sub-servers.
In addition to creating each sub-server, it will also merge the set of
macaroon permissions for each sub-server, with the permissions of the
rest of the RPC infra. As a result, each sub-server is able to
independently specify what it needs w.r.t macaroon permissions and have
that taken care of by the RPC server. In order to achieve this, we need
to unify the creation of the RPC interceptors, and also fully manage the
gRPC server ourselves.
Some examples with various build configs:
```
⛰i make build
Building debug lnd and lncli.
go build -v -tags="dev" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
unknown flag `signrpc.signermacaroonpath'
unknown flag `signrpc.signermacaroonpath'
⛰i make build tags=signerrpc
Building debug lnd and lncli.
go build -v -tags="dev signerrpc" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev signerrpc" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
2018-10-22 17:31:01.132 [INF] LTND: Version: 0.5.0-beta commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty, build=development, logging=default
2018-10-22 17:31:01.133 [INF] LTND: Active chain: Bitcoin (network=simnet)
2018-10-22 17:31:01.140 [INF] CHDB: Checking for schema update: latest_version=6, db_version=6
2018-10-22 17:31:01.236 [INF] LTND: Primary chain is set to: bitcoin
2018-10-22 17:31:02.391 [INF] LNWL: Opened wallet
2018-10-22 17:31:03.315 [INF] LNWL: The wallet has been unlocked without a time limit
2018-10-22 17:31:03.315 [INF] LTND: LightningWallet opened
2018-10-22 17:31:03.319 [INF] LNWL: Catching up block hashes to height 3060, this will take a while...
2018-10-22 17:31:03.320 [INF] HSWC: Restoring in-memory circuit state from disk
2018-10-22 17:31:03.320 [INF] LNWL: Done catching up block hashes
2018-10-22 17:31:03.320 [INF] HSWC: Payment circuits loaded: num_pending=0, num_open=0
2018-10-22 17:31:03.322 [DBG] LTND: Populating dependencies for sub RPC server: Signrpc
```
As for the config, an example is:
```
[signrpc]
signrpc.signermacaroonpath=~/signer.macaroon
```
2018-10-23 03:03:07 +02:00
|
|
|
if err := rpcServer.Start(); err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to start RPC server: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
lnd+rpc: modify rpcServer to fully manaage listeners and gRPC, handle sub-servers
In this commit, we modify the existing rpcServer to fully manage the
macaroons, gRPC server, and also seek out and create all sub-servers.
With this change, the RPC server gains more responsibility, as it
becomes the "root" server in the hierarchy of gRPC sub-servers.
In addition to creating each sub-server, it will also merge the set of
macaroon permissions for each sub-server, with the permissions of the
rest of the RPC infra. As a result, each sub-server is able to
independently specify what it needs w.r.t macaroon permissions and have
that taken care of by the RPC server. In order to achieve this, we need
to unify the creation of the RPC interceptors, and also fully manage the
gRPC server ourselves.
Some examples with various build configs:
```
⛰i make build
Building debug lnd and lncli.
go build -v -tags="dev" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
unknown flag `signrpc.signermacaroonpath'
unknown flag `signrpc.signermacaroonpath'
⛰i make build tags=signerrpc
Building debug lnd and lncli.
go build -v -tags="dev signerrpc" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev signerrpc" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
2018-10-22 17:31:01.132 [INF] LTND: Version: 0.5.0-beta commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty, build=development, logging=default
2018-10-22 17:31:01.133 [INF] LTND: Active chain: Bitcoin (network=simnet)
2018-10-22 17:31:01.140 [INF] CHDB: Checking for schema update: latest_version=6, db_version=6
2018-10-22 17:31:01.236 [INF] LTND: Primary chain is set to: bitcoin
2018-10-22 17:31:02.391 [INF] LNWL: Opened wallet
2018-10-22 17:31:03.315 [INF] LNWL: The wallet has been unlocked without a time limit
2018-10-22 17:31:03.315 [INF] LTND: LightningWallet opened
2018-10-22 17:31:03.319 [INF] LNWL: Catching up block hashes to height 3060, this will take a while...
2018-10-22 17:31:03.320 [INF] HSWC: Restoring in-memory circuit state from disk
2018-10-22 17:31:03.320 [INF] LNWL: Done catching up block hashes
2018-10-22 17:31:03.320 [INF] HSWC: Payment circuits loaded: num_pending=0, num_open=0
2018-10-22 17:31:03.322 [DBG] LTND: Populating dependencies for sub RPC server: Signrpc
```
As for the config, an example is:
```
[signrpc]
signrpc.signermacaroonpath=~/signer.macaroon
```
2018-10-23 03:03:07 +02:00
|
|
|
return err
|
2017-12-17 18:28:38 +01:00
|
|
|
}
|
lnd+rpc: modify rpcServer to fully manaage listeners and gRPC, handle sub-servers
In this commit, we modify the existing rpcServer to fully manage the
macaroons, gRPC server, and also seek out and create all sub-servers.
With this change, the RPC server gains more responsibility, as it
becomes the "root" server in the hierarchy of gRPC sub-servers.
In addition to creating each sub-server, it will also merge the set of
macaroon permissions for each sub-server, with the permissions of the
rest of the RPC infra. As a result, each sub-server is able to
independently specify what it needs w.r.t macaroon permissions and have
that taken care of by the RPC server. In order to achieve this, we need
to unify the creation of the RPC interceptors, and also fully manage the
gRPC server ourselves.
Some examples with various build configs:
```
⛰i make build
Building debug lnd and lncli.
go build -v -tags="dev" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
unknown flag `signrpc.signermacaroonpath'
unknown flag `signrpc.signermacaroonpath'
⛰i make build tags=signerrpc
Building debug lnd and lncli.
go build -v -tags="dev signerrpc" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev signerrpc" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
2018-10-22 17:31:01.132 [INF] LTND: Version: 0.5.0-beta commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty, build=development, logging=default
2018-10-22 17:31:01.133 [INF] LTND: Active chain: Bitcoin (network=simnet)
2018-10-22 17:31:01.140 [INF] CHDB: Checking for schema update: latest_version=6, db_version=6
2018-10-22 17:31:01.236 [INF] LTND: Primary chain is set to: bitcoin
2018-10-22 17:31:02.391 [INF] LNWL: Opened wallet
2018-10-22 17:31:03.315 [INF] LNWL: The wallet has been unlocked without a time limit
2018-10-22 17:31:03.315 [INF] LTND: LightningWallet opened
2018-10-22 17:31:03.319 [INF] LNWL: Catching up block hashes to height 3060, this will take a while...
2018-10-22 17:31:03.320 [INF] HSWC: Restoring in-memory circuit state from disk
2018-10-22 17:31:03.320 [INF] LNWL: Done catching up block hashes
2018-10-22 17:31:03.320 [INF] HSWC: Payment circuits loaded: num_pending=0, num_open=0
2018-10-22 17:31:03.322 [DBG] LTND: Populating dependencies for sub RPC server: Signrpc
```
As for the config, an example is:
```
[signrpc]
signrpc.signermacaroonpath=~/signer.macaroon
```
2018-10-23 03:03:07 +02:00
|
|
|
defer rpcServer.Stop()
|
2016-10-15 23:38:47 +02:00
|
|
|
|
2021-02-05 13:33:01 +01:00
|
|
|
// We transition the RPC state to Active, as the RPC server is up.
|
|
|
|
interceptorChain.SetRPCActive()
|
|
|
|
|
2021-07-17 13:54:41 +02:00
|
|
|
if err := interceptor.Notifier.NotifyReady(true); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
// We'll wait until we're fully synced to continue the start up of the
|
|
|
|
// remainder of the daemon. This ensures that we don't accept any
|
|
|
|
// possibly invalid state transitions, or accept channels with spent
|
|
|
|
// funds.
|
|
|
|
_, bestHeight, err := activeChainControl.ChainIO.GetBestBlock()
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("unable to determine chain tip: %v",
|
|
|
|
err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return err
|
|
|
|
}
|
2017-06-06 00:18:06 +02:00
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
ltndLog.Infof("Waiting for chain backend to finish sync, "+
|
|
|
|
"start_height=%v", bestHeight)
|
2017-06-06 00:18:06 +02:00
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
for {
|
|
|
|
if !interceptor.Alive() {
|
|
|
|
return nil
|
2017-06-06 00:18:06 +02:00
|
|
|
}
|
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
synced, _, err := activeChainControl.Wallet.IsSynced()
|
2017-06-06 00:18:06 +02:00
|
|
|
if err != nil {
|
2021-08-17 20:55:00 +02:00
|
|
|
err := fmt.Errorf("unable to determine if "+
|
|
|
|
"wallet is synced: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2017-06-06 00:18:06 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
if synced {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
time.Sleep(time.Second * 1)
|
2017-06-06 00:18:06 +02:00
|
|
|
}
|
|
|
|
|
2021-08-17 20:55:00 +02:00
|
|
|
_, bestHeight, err = activeChainControl.ChainIO.GetBestBlock()
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("unable to determine chain tip: %v",
|
|
|
|
err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
ltndLog.Infof("Chain backend is fully synced (end_height=%v)!",
|
|
|
|
bestHeight)
|
|
|
|
|
2017-06-06 00:18:06 +02:00
|
|
|
// With all the relevant chains initialized, we can finally start the
|
|
|
|
// server itself.
|
|
|
|
if err := server.Start(); err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to start server: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2017-06-06 00:18:06 +02:00
|
|
|
return err
|
|
|
|
}
|
2018-06-15 05:16:20 +02:00
|
|
|
defer server.Stop()
|
2017-06-06 00:18:06 +02:00
|
|
|
|
2021-09-11 19:26:43 +02:00
|
|
|
// We transition the server state to Active, as the server is up.
|
|
|
|
interceptorChain.SetServerActive()
|
|
|
|
|
2017-08-11 06:40:15 +02:00
|
|
|
// Now that the server has started, if the autopilot mode is currently
|
2018-12-13 12:26:29 +01:00
|
|
|
// active, then we'll start the autopilot agent immediately. It will be
|
|
|
|
// stopped together with the autopilot service.
|
2017-08-11 06:40:15 +02:00
|
|
|
if cfg.Autopilot.Active {
|
2018-12-13 12:26:29 +01:00
|
|
|
if err := atplManager.StartAgent(); err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to start autopilot agent: %v",
|
2017-08-11 06:40:15 +02:00
|
|
|
err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2017-08-11 06:40:15 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-14 02:31:55 +02:00
|
|
|
if cfg.Watchtower.Active {
|
|
|
|
if err := tower.Start(); err != nil {
|
2020-04-14 19:56:05 +02:00
|
|
|
err := fmt.Errorf("unable to start watchtower: %v", err)
|
2019-07-17 23:21:19 +02:00
|
|
|
ltndLog.Error(err)
|
2019-06-14 02:31:55 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer tower.Stop()
|
|
|
|
}
|
|
|
|
|
2016-03-23 02:50:11 +01:00
|
|
|
// Wait for shutdown signal from either a graceful server stop or from
|
|
|
|
// the interrupt handler.
|
2020-08-28 11:18:15 +02:00
|
|
|
<-interceptor.ShutdownChannel()
|
2016-07-13 02:03:29 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-01-30 09:09:57 +01:00
|
|
|
// getTLSConfig returns a TLS configuration for the gRPC server and credentials
|
|
|
|
// and a proxy destination for the REST reverse proxy.
|
2020-09-24 13:14:43 +02:00
|
|
|
func getTLSConfig(cfg *Config) ([]grpc.ServerOption, []grpc.DialOption,
|
|
|
|
func(net.Addr) (net.Listener, error), func(), error) {
|
2019-01-30 09:09:57 +01:00
|
|
|
|
2019-11-14 09:34:47 +01:00
|
|
|
// Ensure we create TLS key and certificate if they don't exist.
|
2020-05-14 14:35:11 +02:00
|
|
|
if !fileExists(cfg.TLSCertPath) && !fileExists(cfg.TLSKeyPath) {
|
2019-11-14 09:34:47 +01:00
|
|
|
rpcsLog.Infof("Generating TLS certificates...")
|
2019-11-13 14:03:10 +01:00
|
|
|
err := cert.GenCertPair(
|
2020-05-14 14:35:11 +02:00
|
|
|
"lnd autogenerated cert", cfg.TLSCertPath,
|
|
|
|
cfg.TLSKeyPath, cfg.TLSExtraIPs, cfg.TLSExtraDomains,
|
2021-04-06 05:23:33 +02:00
|
|
|
cfg.TLSDisableAutofill, cfg.TLSCertDuration,
|
2019-07-22 09:26:25 +02:00
|
|
|
)
|
2019-01-30 09:09:57 +01:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
2019-11-14 09:34:47 +01:00
|
|
|
rpcsLog.Infof("Done generating TLS certificates")
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
|
|
|
|
2020-05-14 14:35:11 +02:00
|
|
|
certData, parsedCert, err := cert.LoadCert(
|
|
|
|
cfg.TLSCertPath, cfg.TLSKeyPath,
|
|
|
|
)
|
2019-01-30 09:09:57 +01:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
|
|
|
|
2020-02-05 13:51:48 +01:00
|
|
|
// We check whether the certifcate we have on disk match the IPs and
|
|
|
|
// domains specified by the config. If the extra IPs or domains have
|
|
|
|
// changed from when the certificate was created, we will refresh the
|
|
|
|
// certificate if auto refresh is active.
|
|
|
|
refresh := false
|
|
|
|
if cfg.TLSAutoRefresh {
|
|
|
|
refresh, err = cert.IsOutdated(
|
2020-06-26 19:53:05 +02:00
|
|
|
parsedCert, cfg.TLSExtraIPs,
|
|
|
|
cfg.TLSExtraDomains, cfg.TLSDisableAutofill,
|
2020-02-05 13:51:48 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2020-02-05 13:51:48 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the certificate expired or it was outdated, delete it and the TLS
|
|
|
|
// key and generate a new pair.
|
|
|
|
if time.Now().After(parsedCert.NotAfter) || refresh {
|
|
|
|
ltndLog.Info("TLS certificate is expired or outdated, " +
|
|
|
|
"generating a new one")
|
2019-04-25 09:09:45 +02:00
|
|
|
|
2020-05-14 14:35:11 +02:00
|
|
|
err := os.Remove(cfg.TLSCertPath)
|
2019-04-25 09:09:45 +02:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-04-25 09:09:45 +02:00
|
|
|
}
|
|
|
|
|
2020-05-14 14:35:11 +02:00
|
|
|
err = os.Remove(cfg.TLSKeyPath)
|
2019-04-25 09:09:45 +02:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-04-25 09:09:45 +02:00
|
|
|
}
|
|
|
|
|
2019-11-13 14:03:10 +01:00
|
|
|
rpcsLog.Infof("Renewing TLS certificates...")
|
|
|
|
err = cert.GenCertPair(
|
2020-05-14 14:35:11 +02:00
|
|
|
"lnd autogenerated cert", cfg.TLSCertPath,
|
|
|
|
cfg.TLSKeyPath, cfg.TLSExtraIPs, cfg.TLSExtraDomains,
|
2021-04-06 05:23:33 +02:00
|
|
|
cfg.TLSDisableAutofill, cfg.TLSCertDuration,
|
2019-07-22 09:26:25 +02:00
|
|
|
)
|
2019-04-25 09:09:45 +02:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-04-25 09:09:45 +02:00
|
|
|
}
|
2019-11-13 14:03:10 +01:00
|
|
|
rpcsLog.Infof("Done renewing TLS certificates")
|
2020-02-05 13:51:48 +01:00
|
|
|
|
|
|
|
// Reload the certificate data.
|
2020-05-14 14:35:11 +02:00
|
|
|
certData, _, err = cert.LoadCert(
|
|
|
|
cfg.TLSCertPath, cfg.TLSKeyPath,
|
|
|
|
)
|
2020-02-05 13:51:48 +01:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2020-02-05 13:51:48 +01:00
|
|
|
}
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
|
|
|
|
2019-11-13 14:03:10 +01:00
|
|
|
tlsCfg := cert.TLSConfFromCert(certData)
|
2019-01-07 18:48:02 +01:00
|
|
|
|
2020-05-14 14:35:11 +02:00
|
|
|
restCreds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "")
|
2019-01-30 09:09:57 +01:00
|
|
|
if err != nil {
|
2020-09-24 13:14:43 +02:00
|
|
|
return nil, nil, nil, nil, err
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
|
|
|
|
2019-01-07 18:48:02 +01:00
|
|
|
// If Let's Encrypt is enabled, instantiate autocert to request/renew
|
|
|
|
// the certificates.
|
|
|
|
cleanUp := func() {}
|
|
|
|
if cfg.LetsEncryptDomain != "" {
|
|
|
|
ltndLog.Infof("Using Let's Encrypt certificate for domain %v",
|
|
|
|
cfg.LetsEncryptDomain)
|
|
|
|
|
|
|
|
manager := autocert.Manager{
|
|
|
|
Cache: autocert.DirCache(cfg.LetsEncryptDir),
|
|
|
|
Prompt: autocert.AcceptTOS,
|
|
|
|
HostPolicy: autocert.HostWhitelist(cfg.LetsEncryptDomain),
|
|
|
|
}
|
|
|
|
|
|
|
|
srv := &http.Server{
|
2020-09-17 09:54:23 +02:00
|
|
|
Addr: cfg.LetsEncryptListen,
|
2019-01-07 18:48:02 +01:00
|
|
|
Handler: manager.HTTPHandler(nil),
|
|
|
|
}
|
|
|
|
shutdownCompleted := make(chan struct{})
|
|
|
|
cleanUp = func() {
|
|
|
|
err := srv.Shutdown(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
ltndLog.Errorf("Autocert listener shutdown "+
|
|
|
|
" error: %v", err)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
<-shutdownCompleted
|
|
|
|
ltndLog.Infof("Autocert challenge listener stopped")
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
ltndLog.Infof("Autocert challenge listener started "+
|
2020-09-17 09:54:23 +02:00
|
|
|
"at %v", cfg.LetsEncryptListen)
|
2019-01-07 18:48:02 +01:00
|
|
|
|
|
|
|
err := srv.ListenAndServe()
|
|
|
|
if err != http.ErrServerClosed {
|
|
|
|
ltndLog.Errorf("autocert http: %v", err)
|
|
|
|
}
|
|
|
|
close(shutdownCompleted)
|
|
|
|
}()
|
|
|
|
|
|
|
|
getCertificate := func(h *tls.ClientHelloInfo) (
|
|
|
|
*tls.Certificate, error) {
|
|
|
|
|
|
|
|
lecert, err := manager.GetCertificate(h)
|
|
|
|
if err != nil {
|
|
|
|
ltndLog.Errorf("GetCertificate: %v", err)
|
|
|
|
return &certData, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return lecert, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// The self-signed tls.cert remains available as fallback.
|
|
|
|
tlsCfg.GetCertificate = getCertificate
|
|
|
|
}
|
|
|
|
|
2020-09-24 13:14:43 +02:00
|
|
|
serverCreds := credentials.NewTLS(tlsCfg)
|
|
|
|
serverOpts := []grpc.ServerOption{grpc.Creds(serverCreds)}
|
|
|
|
|
|
|
|
// For our REST dial options, we'll still use TLS, but also increase
|
|
|
|
// the max message size that we'll decode to allow clients to hit
|
|
|
|
// endpoints which return more data such as the DescribeGraph call.
|
|
|
|
// We set this to 200MiB atm. Should be the same value as maxMsgRecvSize
|
|
|
|
// in cmd/lncli/main.go.
|
|
|
|
restDialOpts := []grpc.DialOption{
|
|
|
|
grpc.WithTransportCredentials(restCreds),
|
|
|
|
grpc.WithDefaultCallOptions(
|
|
|
|
grpc.MaxCallRecvMsgSize(1 * 1024 * 1024 * 200),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return a function closure that can be used to listen on a given
|
|
|
|
// address with the current TLS config.
|
|
|
|
restListen := func(addr net.Addr) (net.Listener, error) {
|
2020-09-24 13:34:24 +02:00
|
|
|
// For restListen we will call ListenOnAddress if TLS is
|
|
|
|
// disabled.
|
|
|
|
if cfg.DisableRestTLS {
|
|
|
|
return lncfg.ListenOnAddress(addr)
|
|
|
|
}
|
|
|
|
|
2020-09-24 13:14:43 +02:00
|
|
|
return lncfg.TLSListenOnAddress(addr, tlsCfg)
|
|
|
|
}
|
|
|
|
|
|
|
|
return serverOpts, restDialOpts, restListen, cleanUp, nil
|
2019-01-30 09:09:57 +01:00
|
|
|
}
|
|
|
|
|
2017-07-26 01:22:06 +02:00
|
|
|
// fileExists reports whether the named file or directory exists.
|
|
|
|
// This function is taken from https://github.com/btcsuite/btcd
|
|
|
|
func fileExists(name string) bool {
|
|
|
|
if _, err := os.Stat(name); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-10-06 17:23:38 +02:00
|
|
|
// bakeMacaroon creates a new macaroon with newest version and the given
|
|
|
|
// permissions then returns it binary serialized.
|
|
|
|
func bakeMacaroon(ctx context.Context, svc *macaroons.Service,
|
|
|
|
permissions []bakery.Op) ([]byte, error) {
|
|
|
|
|
|
|
|
mac, err := svc.NewMacaroon(
|
|
|
|
ctx, macaroons.DefaultRootKeyID, permissions...,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return mac.M().MarshalBinary()
|
|
|
|
}
|
|
|
|
|
lnd+rpc: modify rpcServer to fully manaage listeners and gRPC, handle sub-servers
In this commit, we modify the existing rpcServer to fully manage the
macaroons, gRPC server, and also seek out and create all sub-servers.
With this change, the RPC server gains more responsibility, as it
becomes the "root" server in the hierarchy of gRPC sub-servers.
In addition to creating each sub-server, it will also merge the set of
macaroon permissions for each sub-server, with the permissions of the
rest of the RPC infra. As a result, each sub-server is able to
independently specify what it needs w.r.t macaroon permissions and have
that taken care of by the RPC server. In order to achieve this, we need
to unify the creation of the RPC interceptors, and also fully manage the
gRPC server ourselves.
Some examples with various build configs:
```
⛰i make build
Building debug lnd and lncli.
go build -v -tags="dev" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
unknown flag `signrpc.signermacaroonpath'
unknown flag `signrpc.signermacaroonpath'
⛰i make build tags=signerrpc
Building debug lnd and lncli.
go build -v -tags="dev signerrpc" -o lnd-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd
go build -v -tags="dev signerrpc" -o lncli-debug -ldflags "-X github.com/lightningnetwork/lnd/build.Commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty" github.com/lightningnetwork/lnd/cmd/lncli
⛰i ./lnd-debug --debuglevel=debug --signrpc.signermacaroonpath=~/sign.macaroon
2018-10-22 17:31:01.132 [INF] LTND: Version: 0.5.0-beta commit=v0.5-beta-143-gb2069914c4b76109b7c59320dc48f8a5f30deb75-dirty, build=development, logging=default
2018-10-22 17:31:01.133 [INF] LTND: Active chain: Bitcoin (network=simnet)
2018-10-22 17:31:01.140 [INF] CHDB: Checking for schema update: latest_version=6, db_version=6
2018-10-22 17:31:01.236 [INF] LTND: Primary chain is set to: bitcoin
2018-10-22 17:31:02.391 [INF] LNWL: Opened wallet
2018-10-22 17:31:03.315 [INF] LNWL: The wallet has been unlocked without a time limit
2018-10-22 17:31:03.315 [INF] LTND: LightningWallet opened
2018-10-22 17:31:03.319 [INF] LNWL: Catching up block hashes to height 3060, this will take a while...
2018-10-22 17:31:03.320 [INF] HSWC: Restoring in-memory circuit state from disk
2018-10-22 17:31:03.320 [INF] LNWL: Done catching up block hashes
2018-10-22 17:31:03.320 [INF] HSWC: Payment circuits loaded: num_pending=0, num_open=0
2018-10-22 17:31:03.322 [DBG] LTND: Populating dependencies for sub RPC server: Signrpc
```
As for the config, an example is:
```
[signrpc]
signrpc.signermacaroonpath=~/signer.macaroon
```
2018-10-23 03:03:07 +02:00
|
|
|
// genMacaroons generates three macaroon files; one admin-level, one for
|
|
|
|
// invoice access and one read-only. These can also be used to generate more
|
|
|
|
// granular macaroons.
|
2018-03-21 00:50:08 +01:00
|
|
|
func genMacaroons(ctx context.Context, svc *macaroons.Service,
|
|
|
|
admFile, roFile, invoiceFile string) error {
|
|
|
|
|
|
|
|
// First, we'll generate a macaroon that only allows the caller to
|
|
|
|
// access invoice related calls. This is useful for merchants and other
|
|
|
|
// services to allow an isolated instance that can only query and
|
|
|
|
// modify invoices.
|
2020-10-06 17:23:38 +02:00
|
|
|
invoiceMacBytes, err := bakeMacaroon(ctx, svc, invoicePermissions)
|
2018-03-21 00:50:08 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = ioutil.WriteFile(invoiceFile, invoiceMacBytes, 0644)
|
|
|
|
if err != nil {
|
2020-10-06 17:23:38 +02:00
|
|
|
_ = os.Remove(invoiceFile)
|
2018-03-21 00:50:08 +01:00
|
|
|
return err
|
|
|
|
}
|
2018-01-16 17:18:41 +01:00
|
|
|
|
|
|
|
// Generate the read-only macaroon and write it to a file.
|
2020-10-06 17:23:38 +02:00
|
|
|
roBytes, err := bakeMacaroon(ctx, svc, readPermissions)
|
2017-08-18 03:50:57 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-01-16 17:18:41 +01:00
|
|
|
if err = ioutil.WriteFile(roFile, roBytes, 0644); err != nil {
|
2020-10-06 17:23:38 +02:00
|
|
|
_ = os.Remove(roFile)
|
2017-08-18 03:50:57 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-01-16 17:18:41 +01:00
|
|
|
// Generate the admin macaroon and write it to a file.
|
2020-10-06 17:23:38 +02:00
|
|
|
admBytes, err := bakeMacaroon(ctx, svc, adminPermissions())
|
2017-08-18 03:50:57 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-07-17 10:45:17 +02:00
|
|
|
|
|
|
|
err = ioutil.WriteFile(admFile, admBytes, adminMacaroonFilePermissions)
|
|
|
|
if err != nil {
|
2020-10-06 17:23:38 +02:00
|
|
|
_ = os.Remove(admFile)
|
2017-08-18 03:50:57 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2020-10-06 17:23:38 +02:00
|
|
|
// adminPermissions returns a list of all permissions in a safe way that doesn't
|
|
|
|
// modify any of the source lists.
|
|
|
|
func adminPermissions() []bakery.Op {
|
|
|
|
admin := make([]bakery.Op, len(readPermissions)+len(writePermissions))
|
|
|
|
copy(admin[:len(readPermissions)], readPermissions)
|
|
|
|
copy(admin[len(readPermissions):], writePermissions)
|
|
|
|
return admin
|
|
|
|
}
|
|
|
|
|
2018-03-26 23:12:17 +02:00
|
|
|
// WalletUnlockParams holds the variables used to parameterize the unlocking of
|
|
|
|
// lnd's wallet after it has already been created.
|
|
|
|
type WalletUnlockParams struct {
|
|
|
|
// Password is the public and private wallet passphrase.
|
|
|
|
Password []byte
|
|
|
|
|
|
|
|
// Birthday specifies the approximate time that this wallet was created.
|
|
|
|
// This is used to bound any rescans on startup.
|
|
|
|
Birthday time.Time
|
|
|
|
|
|
|
|
// RecoveryWindow specifies the address lookahead when entering recovery
|
|
|
|
// mode. A recovery will be attempted if this value is non-zero.
|
|
|
|
RecoveryWindow uint32
|
2018-05-22 09:31:02 +02:00
|
|
|
|
|
|
|
// Wallet is the loaded and unlocked Wallet. This is returned
|
|
|
|
// from the unlocker service to avoid it being unlocked twice (once in
|
|
|
|
// the unlocker service to check if the password is correct and again
|
|
|
|
// later when lnd actually uses it). Because unlocking involves scrypt
|
|
|
|
// which is resource intensive, we want to avoid doing it twice.
|
|
|
|
Wallet *wallet.Wallet
|
2018-12-10 05:08:32 +01:00
|
|
|
|
|
|
|
// ChansToRestore a set of static channel backups that should be
|
|
|
|
// restored before the main server instance starts up.
|
|
|
|
ChansToRestore walletunlocker.ChannelsToRecover
|
2020-09-03 18:10:30 +02:00
|
|
|
|
|
|
|
// UnloadWallet is a function for unloading the wallet, which should
|
|
|
|
// be called on shutdown.
|
|
|
|
UnloadWallet func() error
|
2020-10-06 17:23:38 +02:00
|
|
|
|
|
|
|
// StatelessInit signals that the user requested the daemon to be
|
|
|
|
// initialized stateless, which means no unencrypted macaroons should be
|
|
|
|
// written to disk.
|
|
|
|
StatelessInit bool
|
|
|
|
|
|
|
|
// MacResponseChan is the channel for sending back the admin macaroon to
|
|
|
|
// the WalletUnlocker service.
|
|
|
|
MacResponseChan chan []byte
|
2018-03-26 23:12:17 +02:00
|
|
|
}
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// createWalletUnlockerService creates a WalletUnlockerService from the passed
|
|
|
|
// config.
|
2021-03-19 15:53:06 +01:00
|
|
|
func createWalletUnlockerService(cfg *Config) *walletunlocker.UnlockerService {
|
2020-10-06 17:23:38 +02:00
|
|
|
// The macaroonFiles are passed to the wallet unlocker so they can be
|
|
|
|
// deleted and recreated in case the root macaroon key is also changed
|
|
|
|
// during the change password operation.
|
2018-04-20 09:14:41 +02:00
|
|
|
macaroonFiles := []string{
|
|
|
|
cfg.AdminMacPath, cfg.ReadMacPath, cfg.InvoiceMacPath,
|
|
|
|
}
|
2021-03-04 23:13:06 +01:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
return walletunlocker.New(
|
2021-08-03 09:57:30 +02:00
|
|
|
cfg.ActiveNetParams.Params, macaroonFiles,
|
2021-03-19 15:53:06 +01:00
|
|
|
cfg.ResetWalletTransactions, nil,
|
2018-04-20 09:06:06 +02:00
|
|
|
)
|
2021-02-02 13:45:29 +01:00
|
|
|
}
|
2020-10-06 17:23:34 +02:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// startGrpcListen starts the GRPC server on the passed listeners.
|
|
|
|
func startGrpcListen(cfg *Config, grpcServer *grpc.Server,
|
|
|
|
listeners []*ListenerWithSignal) error {
|
2020-10-06 17:23:34 +02:00
|
|
|
|
2017-12-17 18:28:38 +01:00
|
|
|
// Use a WaitGroup so we can be sure the instructions on how to input the
|
|
|
|
// password is the last thing to be printed to the console.
|
|
|
|
var wg sync.WaitGroup
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2019-07-09 11:09:19 +02:00
|
|
|
for _, lis := range listeners {
|
2017-12-17 18:28:38 +01:00
|
|
|
wg.Add(1)
|
2019-11-29 11:35:37 +01:00
|
|
|
go func(lis *ListenerWithSignal) {
|
2021-02-02 13:45:29 +01:00
|
|
|
rpcsLog.Infof("RPC server listening on %s", lis.Addr())
|
2019-11-29 11:35:37 +01:00
|
|
|
|
|
|
|
// Close the ready chan to indicate we are listening.
|
|
|
|
close(lis.Ready)
|
|
|
|
|
2017-12-17 18:28:38 +01:00
|
|
|
wg.Done()
|
2020-10-06 17:23:36 +02:00
|
|
|
_ = grpcServer.Serve(lis)
|
2019-07-09 11:09:19 +02:00
|
|
|
}(lis)
|
2017-12-17 18:28:38 +01:00
|
|
|
}
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// If Prometheus monitoring is enabled, start the Prometheus exporter.
|
|
|
|
if cfg.Prometheus.Enabled() {
|
|
|
|
err := monitoring.ExportPrometheusMetrics(
|
|
|
|
grpcServer, cfg.Prometheus,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for gRPC servers to be up running.
|
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// startRestProxy starts the given REST proxy on the listeners found in the
|
|
|
|
// config.
|
|
|
|
func startRestProxy(cfg *Config, rpcServer *rpcServer, restDialOpts []grpc.DialOption,
|
|
|
|
restListen func(net.Addr) (net.Listener, error)) (func(), error) {
|
|
|
|
|
|
|
|
// We use the first RPC listener as the destination for our REST proxy.
|
|
|
|
// If the listener is set to listen on all interfaces, we replace it
|
|
|
|
// with localhost, as we cannot dial it directly.
|
|
|
|
restProxyDest := cfg.RPCListeners[0].String()
|
|
|
|
switch {
|
|
|
|
case strings.Contains(restProxyDest, "0.0.0.0"):
|
|
|
|
restProxyDest = strings.Replace(
|
|
|
|
restProxyDest, "0.0.0.0", "127.0.0.1", 1,
|
|
|
|
)
|
|
|
|
|
|
|
|
case strings.Contains(restProxyDest, "[::]"):
|
|
|
|
restProxyDest = strings.Replace(
|
|
|
|
restProxyDest, "[::]", "[::1]", 1,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
var shutdownFuncs []func()
|
|
|
|
shutdown := func() {
|
|
|
|
for _, shutdownFn := range shutdownFuncs {
|
|
|
|
shutdownFn()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start a REST proxy for our gRPC server.
|
2017-10-12 11:37:37 +02:00
|
|
|
ctx := context.Background()
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
2020-10-06 17:23:36 +02:00
|
|
|
shutdownFuncs = append(shutdownFuncs, cancel)
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// We'll set up a proxy that will forward REST calls to the GRPC
|
|
|
|
// server.
|
|
|
|
//
|
|
|
|
// The default JSON marshaler of the REST proxy only sets OrigName to
|
|
|
|
// true, which instructs it to use the same field names as specified in
|
|
|
|
// the proto file and not switch to camel case. What we also want is
|
|
|
|
// that the marshaler prints all values, even if they are falsey.
|
|
|
|
customMarshalerOption := proxy.WithMarshalerOption(
|
|
|
|
proxy.MIMEWildcard, &proxy.JSONPb{
|
2021-07-27 12:59:59 +02:00
|
|
|
MarshalOptions: protojson.MarshalOptions{
|
|
|
|
UseProtoNames: true,
|
|
|
|
EmitUnpopulated: true,
|
|
|
|
},
|
2021-02-02 13:45:29 +01:00
|
|
|
},
|
|
|
|
)
|
|
|
|
mux := proxy.NewServeMux(customMarshalerOption)
|
2017-12-17 18:28:38 +01:00
|
|
|
|
2021-02-09 15:12:21 +01:00
|
|
|
// Register our services with the REST proxy.
|
2021-02-02 13:45:29 +01:00
|
|
|
err := lnrpc.RegisterWalletUnlockerHandlerFromEndpoint(
|
2019-01-30 09:09:57 +01:00
|
|
|
ctx, mux, restProxyDest, restDialOpts,
|
2018-05-23 15:38:19 +02:00
|
|
|
)
|
2017-10-12 11:37:37 +02:00
|
|
|
if err != nil {
|
2021-02-02 13:45:29 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-02-09 15:12:21 +01:00
|
|
|
err = lnrpc.RegisterStateHandlerFromEndpoint(
|
|
|
|
ctx, mux, restProxyDest, restDialOpts,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
err = rpcServer.RegisterWithRestProxy(
|
|
|
|
ctx, mux, restDialOpts, restProxyDest,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-10-12 11:37:37 +02:00
|
|
|
}
|
2017-12-17 18:28:38 +01:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// Wrap the default grpc-gateway handler with the WebSocket handler.
|
2021-04-27 15:47:30 +02:00
|
|
|
restHandler := lnrpc.NewWebSocketProxy(
|
2021-04-27 15:47:34 +02:00
|
|
|
mux, rpcsLog, cfg.WSPingInterval, cfg.WSPongWait,
|
2021-04-27 15:47:32 +02:00
|
|
|
lnrpc.LndClientStreamingURIs,
|
2021-04-27 15:47:30 +02:00
|
|
|
)
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// Use a WaitGroup so we can be sure the instructions on how to input the
|
|
|
|
// password is the last thing to be printed to the console.
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
// Now spin up a network listener for each requested port and start a
|
|
|
|
// goroutine that serves REST with the created mux there.
|
|
|
|
for _, restEndpoint := range cfg.RESTListeners {
|
2020-09-24 13:14:43 +02:00
|
|
|
lis, err := restListen(restEndpoint)
|
2017-10-12 11:37:37 +02:00
|
|
|
if err != nil {
|
2021-02-02 13:45:29 +01:00
|
|
|
ltndLog.Errorf("gRPC proxy unable to listen on %s",
|
|
|
|
restEndpoint)
|
|
|
|
return nil, err
|
2017-10-12 11:37:37 +02:00
|
|
|
}
|
2021-02-02 13:45:29 +01:00
|
|
|
|
2020-10-06 17:23:36 +02:00
|
|
|
shutdownFuncs = append(shutdownFuncs, func() {
|
|
|
|
err := lis.Close()
|
|
|
|
if err != nil {
|
|
|
|
rpcsLog.Errorf("Error closing listener: %v",
|
|
|
|
err)
|
|
|
|
}
|
|
|
|
})
|
2017-12-17 18:28:38 +01:00
|
|
|
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
2021-02-02 13:45:29 +01:00
|
|
|
rpcsLog.Infof("gRPC proxy started at %s", lis.Addr())
|
|
|
|
|
|
|
|
// Create our proxy chain now. A request will pass
|
|
|
|
// through the following chain:
|
|
|
|
// req ---> CORS handler --> WS proxy --->
|
|
|
|
// REST proxy --> gRPC endpoint
|
|
|
|
corsHandler := allowCORS(restHandler, cfg.RestCORS)
|
|
|
|
|
2017-12-17 18:28:38 +01:00
|
|
|
wg.Done()
|
2021-02-02 13:45:29 +01:00
|
|
|
err := http.Serve(lis, corsHandler)
|
|
|
|
if err != nil && !lnrpc.IsClosedConnError(err) {
|
|
|
|
rpcsLog.Error(err)
|
|
|
|
}
|
2017-12-17 18:28:38 +01:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
// Wait for REST servers to be up running.
|
2017-12-17 18:28:38 +01:00
|
|
|
wg.Wait()
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
return shutdown, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// waitForWalletPassword blocks until a password is provided by the user to
|
|
|
|
// this RPC server.
|
|
|
|
func waitForWalletPassword(cfg *Config,
|
2020-08-28 11:18:15 +02:00
|
|
|
pwService *walletunlocker.UnlockerService,
|
2021-03-04 23:13:06 +01:00
|
|
|
loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
|
|
|
|
*WalletUnlockParams, error) {
|
2021-02-02 13:45:29 +01:00
|
|
|
|
2017-10-12 11:37:37 +02:00
|
|
|
// Wait for user to provide the password.
|
2018-04-20 09:14:41 +02:00
|
|
|
ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
|
|
|
|
"create` to create a wallet, `lncli unlock` to unlock an " +
|
|
|
|
"existing wallet, or `lncli changepassword` to change the " +
|
|
|
|
"password of an existing wallet and unlock it.")
|
2017-10-12 11:37:37 +02:00
|
|
|
|
2018-02-02 05:49:34 +01:00
|
|
|
// We currently don't distinguish between getting a password to be used
|
|
|
|
// for creation or unlocking, as a new wallet db will be created if
|
|
|
|
// none exists when creating the chain control.
|
2017-10-12 11:37:37 +02:00
|
|
|
select {
|
2018-02-02 05:49:34 +01:00
|
|
|
|
|
|
|
// The wallet is being created for the first time, we'll check to see
|
|
|
|
// if the user provided any entropy for seed creation. If so, then
|
|
|
|
// we'll create the wallet early to load the seed.
|
|
|
|
case initMsg := <-pwService.InitMsgs:
|
|
|
|
password := initMsg.Passphrase
|
|
|
|
cipherSeed := initMsg.WalletSeed
|
2020-10-24 23:18:50 +02:00
|
|
|
extendedKey := initMsg.WalletExtendedKey
|
2018-03-26 23:12:17 +02:00
|
|
|
recoveryWindow := initMsg.RecoveryWindow
|
2018-02-02 05:49:34 +01:00
|
|
|
|
2018-03-06 17:55:10 +01:00
|
|
|
// Before we proceed, we'll check the internal version of the
|
|
|
|
// seed. If it's greater than the current key derivation
|
|
|
|
// version, then we'll return an error as we don't understand
|
|
|
|
// this.
|
2020-10-24 23:18:50 +02:00
|
|
|
const latestVersion = keychain.KeyDerivationVersion
|
|
|
|
if cipherSeed != nil &&
|
|
|
|
cipherSeed.InternalVersion != latestVersion {
|
|
|
|
|
2021-02-02 13:45:29 +01:00
|
|
|
return nil, fmt.Errorf("invalid internal "+
|
2020-10-06 17:23:36 +02:00
|
|
|
"seed version %v, current version is %v",
|
2018-03-06 17:55:10 +01:00
|
|
|
cipherSeed.InternalVersion,
|
|
|
|
keychain.KeyDerivationVersion)
|
|
|
|
}
|
|
|
|
|
2021-03-04 23:13:06 +01:00
|
|
|
loader, err := btcwallet.NewWalletLoader(
|
|
|
|
cfg.ActiveNetParams.Params, recoveryWindow,
|
|
|
|
loaderOpts...,
|
2018-03-26 23:12:17 +02:00
|
|
|
)
|
2021-03-04 23:13:06 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-02-02 05:49:34 +01:00
|
|
|
|
|
|
|
// With the seed, we can now use the wallet loader to create
|
2018-05-22 09:31:02 +02:00
|
|
|
// the wallet, then pass it back to avoid unlocking it again.
|
2020-10-24 23:18:50 +02:00
|
|
|
var (
|
|
|
|
birthday time.Time
|
|
|
|
newWallet *wallet.Wallet
|
2018-02-02 05:49:34 +01:00
|
|
|
)
|
2020-10-24 23:18:50 +02:00
|
|
|
switch {
|
|
|
|
// A normal cipher seed was given, use the birthday encoded in
|
|
|
|
// it and create the wallet from that.
|
|
|
|
case cipherSeed != nil:
|
|
|
|
birthday = cipherSeed.BirthdayTime()
|
|
|
|
newWallet, err = loader.CreateNewWallet(
|
|
|
|
password, password, cipherSeed.Entropy[:],
|
|
|
|
birthday,
|
|
|
|
)
|
|
|
|
|
|
|
|
// No seed was given, we're importing a wallet from its extended
|
|
|
|
// private key.
|
|
|
|
case extendedKey != nil:
|
|
|
|
birthday = initMsg.ExtendedKeyBirthday
|
|
|
|
newWallet, err = loader.CreateNewWalletExtendedKey(
|
|
|
|
password, password, extendedKey, birthday,
|
|
|
|
)
|
|
|
|
|
|
|
|
default:
|
|
|
|
// The unlocker service made sure either the cipher seed
|
|
|
|
// or the extended key is set so, we shouldn't get here.
|
|
|
|
// The default case is just here for readability and
|
|
|
|
// completeness.
|
|
|
|
err = fmt.Errorf("cannot create wallet, neither seed " +
|
|
|
|
"nor extended key was given")
|
|
|
|
}
|
2018-02-02 05:49:34 +01:00
|
|
|
if err != nil {
|
2018-05-22 09:31:02 +02:00
|
|
|
// Don't leave the file open in case the new wallet
|
|
|
|
// could not be created for whatever reason.
|
|
|
|
if err := loader.UnloadWallet(); err != nil {
|
2018-06-15 05:16:20 +02:00
|
|
|
ltndLog.Errorf("Could not unload new "+
|
2018-05-22 09:31:02 +02:00
|
|
|
"wallet: %v", err)
|
|
|
|
}
|
2021-02-02 13:45:29 +01:00
|
|
|
return nil, err
|
2018-02-02 05:49:34 +01:00
|
|
|
}
|
|
|
|
|
2020-10-24 16:34:53 +02:00
|
|
|
// For new wallets, the ResetWalletTransactions flag is a no-op.
|
|
|
|
if cfg.ResetWalletTransactions {
|
|
|
|
ltndLog.Warnf("Ignoring reset-wallet-transactions " +
|
|
|
|
"flag for new wallet as it has no effect")
|
|
|
|
}
|
|
|
|
|
2018-12-10 05:08:32 +01:00
|
|
|
return &WalletUnlockParams{
|
2020-10-06 17:23:38 +02:00
|
|
|
Password: password,
|
|
|
|
Birthday: birthday,
|
|
|
|
RecoveryWindow: recoveryWindow,
|
|
|
|
Wallet: newWallet,
|
|
|
|
ChansToRestore: initMsg.ChanBackups,
|
|
|
|
UnloadWallet: loader.UnloadWallet,
|
|
|
|
StatelessInit: initMsg.StatelessInit,
|
|
|
|
MacResponseChan: pwService.MacResponseChan,
|
2021-02-02 13:45:29 +01:00
|
|
|
}, nil
|
2018-02-02 05:49:34 +01:00
|
|
|
|
|
|
|
// The wallet has already been created in the past, and is simply being
|
|
|
|
// unlocked. So we'll just return these passphrases.
|
2018-03-26 23:12:17 +02:00
|
|
|
case unlockMsg := <-pwService.UnlockMsgs:
|
2020-10-24 16:34:53 +02:00
|
|
|
// Resetting the transactions is something the user likely only
|
|
|
|
// wants to do once so we add a prominent warning to the log to
|
|
|
|
// remind the user to turn off the setting again after
|
|
|
|
// successful completion.
|
|
|
|
if cfg.ResetWalletTransactions {
|
2020-12-15 21:19:32 +01:00
|
|
|
ltndLog.Warnf("Dropped all transaction history from " +
|
2020-10-24 16:34:53 +02:00
|
|
|
"on-chain wallet. Remember to disable " +
|
|
|
|
"reset-wallet-transactions flag for next " +
|
|
|
|
"start of lnd")
|
|
|
|
}
|
|
|
|
|
2018-12-10 05:08:32 +01:00
|
|
|
return &WalletUnlockParams{
|
2020-10-06 17:23:38 +02:00
|
|
|
Password: unlockMsg.Passphrase,
|
|
|
|
RecoveryWindow: unlockMsg.RecoveryWindow,
|
|
|
|
Wallet: unlockMsg.Wallet,
|
|
|
|
ChansToRestore: unlockMsg.ChanBackups,
|
|
|
|
UnloadWallet: unlockMsg.UnloadWallet,
|
|
|
|
StatelessInit: unlockMsg.StatelessInit,
|
|
|
|
MacResponseChan: pwService.MacResponseChan,
|
2021-02-02 13:45:29 +01:00
|
|
|
}, nil
|
2018-02-02 05:49:34 +01:00
|
|
|
|
2020-08-28 11:18:15 +02:00
|
|
|
// If we got a shutdown signal we just return with an error immediately
|
|
|
|
case <-shutdownChan:
|
2021-02-02 13:45:29 +01:00
|
|
|
return nil, fmt.Errorf("shutting down")
|
2017-10-12 11:37:37 +02:00
|
|
|
}
|
|
|
|
}
|
2020-05-07 05:49:36 +02:00
|
|
|
|
2021-08-03 09:57:24 +02:00
|
|
|
// databaseInstances is a struct that holds all instances to the actual
|
|
|
|
// databases that are used in lnd.
|
|
|
|
type databaseInstances struct {
|
2021-08-03 09:57:33 +02:00
|
|
|
graphDB *channeldb.DB
|
|
|
|
chanStateDB *channeldb.DB
|
|
|
|
heightHintDB kvdb.Backend
|
|
|
|
macaroonDB kvdb.Backend
|
|
|
|
decayedLogDB kvdb.Backend
|
|
|
|
towerClientDB wtclient.DB
|
|
|
|
towerServerDB watchtower.DB
|
2021-08-03 09:57:35 +02:00
|
|
|
walletDB btcwallet.LoaderOption
|
2021-08-03 09:57:24 +02:00
|
|
|
}
|
|
|
|
|
2020-05-07 05:49:36 +02:00
|
|
|
// initializeDatabases extracts the current databases that we'll use for normal
|
2021-08-03 09:57:26 +02:00
|
|
|
// operation in the daemon. A function closure that closes all opened databases
|
|
|
|
// is also returned.
|
2020-05-07 05:49:36 +02:00
|
|
|
func initializeDatabases(ctx context.Context,
|
2021-08-03 09:57:24 +02:00
|
|
|
cfg *Config) (*databaseInstances, func(), error) {
|
2020-05-07 05:49:36 +02:00
|
|
|
|
|
|
|
ltndLog.Infof("Opening the main database, this might take a few " +
|
|
|
|
"minutes...")
|
|
|
|
|
|
|
|
if cfg.DB.Backend == lncfg.BoltBackend {
|
2020-11-09 10:21:25 +01:00
|
|
|
ltndLog.Infof("Opening bbolt database, sync_freelist=%v, "+
|
2021-07-15 21:42:05 +02:00
|
|
|
"auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
|
2020-11-09 10:21:25 +01:00
|
|
|
cfg.DB.Bolt.AutoCompact)
|
2020-05-07 05:49:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
startOpenTime := time.Now()
|
|
|
|
|
2021-08-03 09:57:30 +02:00
|
|
|
databaseBackends, err := cfg.DB.GetBackends(
|
2021-08-03 09:57:33 +02:00
|
|
|
ctx, cfg.graphDatabaseDir(), cfg.networkDir, filepath.Join(
|
|
|
|
cfg.Watchtower.TowerDir,
|
|
|
|
cfg.registeredChains.PrimaryChain().String(),
|
|
|
|
lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
|
|
|
|
), cfg.WtClient.Active, cfg.Watchtower.Active,
|
2021-08-03 09:57:30 +02:00
|
|
|
)
|
2020-05-07 05:49:36 +02:00
|
|
|
if err != nil {
|
2021-08-03 09:57:24 +02:00
|
|
|
return nil, nil, fmt.Errorf("unable to obtain database "+
|
2020-05-07 05:49:36 +02:00
|
|
|
"backends: %v", err)
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:57:28 +02:00
|
|
|
// With the full remote mode we made sure both the graph and channel
|
|
|
|
// state DB point to the same local or remote DB and the same namespace
|
|
|
|
// within that DB.
|
|
|
|
dbs := &databaseInstances{
|
|
|
|
heightHintDB: databaseBackends.HeightHintDB,
|
2021-08-03 09:57:30 +02:00
|
|
|
macaroonDB: databaseBackends.MacaroonDB,
|
2021-08-03 09:57:32 +02:00
|
|
|
decayedLogDB: databaseBackends.DecayedLogDB,
|
2021-08-03 09:57:35 +02:00
|
|
|
walletDB: databaseBackends.WalletDB,
|
2021-08-03 09:57:28 +02:00
|
|
|
}
|
|
|
|
cleanUp := func() {
|
|
|
|
// We can just close the returned close functions directly. Even
|
|
|
|
// if we decorate the channel DB with an additional struct, its
|
|
|
|
// close function still just points to the kvdb backend.
|
|
|
|
for name, closeFunc := range databaseBackends.CloseFuncs {
|
|
|
|
if err := closeFunc(); err != nil {
|
|
|
|
ltndLog.Errorf("Error closing %s "+
|
|
|
|
"database: %v", name, err)
|
|
|
|
}
|
2020-05-07 05:49:36 +02:00
|
|
|
}
|
2021-08-03 09:57:28 +02:00
|
|
|
}
|
|
|
|
if databaseBackends.Remote {
|
|
|
|
ltndLog.Infof("Using remote %v database! Creating "+
|
|
|
|
"graph and channel state DB instances", cfg.DB.Backend)
|
2020-05-07 05:49:36 +02:00
|
|
|
} else {
|
2021-08-03 09:57:28 +02:00
|
|
|
ltndLog.Infof("Creating local graph and channel state DB " +
|
|
|
|
"instances")
|
|
|
|
}
|
|
|
|
|
2021-09-21 19:18:25 +02:00
|
|
|
dbOptions := []channeldb.OptionModifier{
|
2021-08-03 09:57:28 +02:00
|
|
|
channeldb.OptionSetRejectCacheSize(cfg.Caches.RejectCacheSize),
|
|
|
|
channeldb.OptionSetChannelCacheSize(cfg.Caches.ChannelCacheSize),
|
|
|
|
channeldb.OptionSetBatchCommitInterval(cfg.DB.BatchCommitInterval),
|
|
|
|
channeldb.OptionDryRunMigration(cfg.DryRunMigration),
|
2021-09-21 19:18:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// We want to pre-allocate the channel graph cache according to what we
|
|
|
|
// expect for mainnet to speed up memory allocation.
|
|
|
|
if cfg.ActiveNetParams.Name == chaincfg.MainNetParams.Name {
|
|
|
|
dbOptions = append(
|
|
|
|
dbOptions, channeldb.OptionSetPreAllocCacheNumNodes(
|
|
|
|
channeldb.DefaultPreAllocCacheNumNodes,
|
|
|
|
),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, we'll open two instances, one for the state we only need
|
|
|
|
// locally, and the other for things we want to ensure are replicated.
|
|
|
|
dbs.graphDB, err = channeldb.CreateWithBackend(
|
|
|
|
databaseBackends.GraphDB, dbOptions...,
|
2021-08-03 09:57:28 +02:00
|
|
|
)
|
|
|
|
switch {
|
|
|
|
// Give the DB a chance to dry run the migration. Since we know that
|
|
|
|
// both the channel state and graph DBs are still always behind the same
|
|
|
|
// backend, we know this would be applied to both of those DBs.
|
|
|
|
case err == channeldb.ErrDryRunMigrationOK:
|
|
|
|
ltndLog.Infof("Graph DB dry run migration successful")
|
|
|
|
return nil, nil, err
|
2020-05-07 05:49:36 +02:00
|
|
|
|
2021-08-03 09:57:28 +02:00
|
|
|
case err != nil:
|
|
|
|
cleanUp()
|
2020-05-07 05:49:36 +02:00
|
|
|
|
2021-08-03 09:57:28 +02:00
|
|
|
err := fmt.Errorf("unable to open graph DB: %v", err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return nil, nil, err
|
2020-05-07 05:49:36 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 09:57:28 +02:00
|
|
|
// For now, we don't _actually_ split the graph and channel state DBs on
|
|
|
|
// the code level. Since they both are based upon the *channeldb.DB
|
|
|
|
// struct it will require more refactoring to fully separate them. With
|
|
|
|
// the full remote mode we at least know for now that they both point to
|
|
|
|
// the same DB backend (and also namespace within that) so we only need
|
|
|
|
// to apply any migration once.
|
|
|
|
//
|
|
|
|
// TODO(guggero): Once the full separation of anything graph related
|
|
|
|
// from the channeldb.DB is complete, the decorated instance of the
|
|
|
|
// channel state DB should be created here individually instead of just
|
|
|
|
// using the same struct (and DB backend) instance.
|
|
|
|
dbs.chanStateDB = dbs.graphDB
|
2020-05-07 05:49:36 +02:00
|
|
|
|
2021-08-03 09:57:33 +02:00
|
|
|
// Wrap the watchtower client DB and make sure we clean up.
|
|
|
|
if cfg.WtClient.Active {
|
|
|
|
dbs.towerClientDB, err = wtdb.OpenClientDB(
|
|
|
|
databaseBackends.TowerClientDB,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
cleanUp()
|
|
|
|
|
|
|
|
err := fmt.Errorf("unable to open %s database: %v",
|
|
|
|
lncfg.NSTowerClientDB, err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wrap the watchtower server DB and make sure we clean up.
|
|
|
|
if cfg.Watchtower.Active {
|
|
|
|
dbs.towerServerDB, err = wtdb.OpenTowerDB(
|
|
|
|
databaseBackends.TowerServerDB,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
cleanUp()
|
|
|
|
|
|
|
|
err := fmt.Errorf("unable to open %s database: %v",
|
|
|
|
lncfg.NSTowerServerDB, err)
|
|
|
|
ltndLog.Error(err)
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:57:28 +02:00
|
|
|
openTime := time.Since(startOpenTime)
|
|
|
|
ltndLog.Infof("Database(s) now open (time_to_open=%v)!", openTime)
|
2020-05-07 05:49:36 +02:00
|
|
|
|
2021-08-03 09:57:24 +02:00
|
|
|
return dbs, cleanUp, nil
|
2020-05-07 05:49:36 +02:00
|
|
|
}
|
2020-10-08 15:10:27 +02:00
|
|
|
|
|
|
|
// initNeutrinoBackend inits a new instance of the neutrino light client
|
|
|
|
// backend given a target chain directory to store the chain state.
|
2021-03-24 07:48:33 +01:00
|
|
|
func initNeutrinoBackend(cfg *Config, chainDir string,
|
|
|
|
blockCache *blockcache.BlockCache) (*neutrino.ChainService,
|
2020-10-08 15:10:27 +02:00
|
|
|
func(), error) {
|
|
|
|
|
2021-03-29 10:23:26 +02:00
|
|
|
// Both channel validation flags are false by default but their meaning
|
|
|
|
// is the inverse of each other. Therefore both cannot be true. For
|
|
|
|
// every other case, the neutrino.validatechannels overwrites the
|
|
|
|
// routing.assumechanvalid value.
|
|
|
|
if cfg.NeutrinoMode.ValidateChannels && cfg.Routing.AssumeChannelValid {
|
|
|
|
return nil, nil, fmt.Errorf("can't set both " +
|
|
|
|
"neutrino.validatechannels and routing." +
|
|
|
|
"assumechanvalid to true at the same time")
|
|
|
|
}
|
|
|
|
cfg.Routing.AssumeChannelValid = !cfg.NeutrinoMode.ValidateChannels
|
|
|
|
|
2020-10-08 15:10:27 +02:00
|
|
|
// First we'll open the database file for neutrino, creating the
|
|
|
|
// database if needed. We append the normalized network name here to
|
|
|
|
// match the behavior of btcwallet.
|
|
|
|
dbPath := filepath.Join(
|
2020-10-06 20:17:14 +02:00
|
|
|
chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
|
2020-10-08 15:10:27 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// Ensure that the neutrino db path exists.
|
|
|
|
if err := os.MkdirAll(dbPath, 0700); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
dbName := filepath.Join(dbPath, "neutrino.db")
|
kvdb: add timeout options for bbolt (#4787)
* mod: bump btcwallet version to accept db timeout
* btcwallet: add DBTimeOut in config
* kvdb: add database timeout option for bbolt
This commit adds a DBTimeout option in bbolt config. The relevant
functions walletdb.Open/Create are updated to use this config. In
addition, the bolt compacter also applies the new timeout option.
* channeldb: add DBTimeout in db options
This commit adds the DBTimeout option for channeldb. A new unit
test file is created to test the default options. In addition,
the params used in kvdb.Create inside channeldb_test is updated
with a DefaultDBTimeout value.
* contractcourt+routing: use DBTimeout in kvdb
This commit touches multiple test files in contractcourt and routing.
The call of function kvdb.Create and kvdb.Open are now updated with
the new param DBTimeout, using the default value kvdb.DefaultDBTimeout.
* lncfg: add DBTimeout option in db config
The DBTimeout option is added to db config. A new unit test is
added to check the default DB config is created as expected.
* migration: add DBTimeout param in kvdb.Create/kvdb.Open
* keychain: update tests to use DBTimeout param
* htlcswitch+chainreg: add DBTimeout option
* macaroons: support DBTimeout config in creation
This commit adds the DBTimeout during the creation of macaroons.db.
The usage of kvdb.Create and kvdb.Open in its tests are updated with
a timeout value using kvdb.DefaultDBTimeout.
* walletunlocker: add dbTimeout option in UnlockerService
This commit adds a new param, dbTimeout, during the creation of
UnlockerService. This param is then passed to wallet.NewLoader
inside various service calls, specifying a timeout value to be
used when opening the bbolt. In addition, the macaroonService
is also called with this dbTimeout param.
* watchtower/wtdb: add dbTimeout param during creation
This commit adds the dbTimeout param for the creation of both
watchtower.db and wtclient.db.
* multi: add db timeout param for walletdb.Create
This commit adds the db timeout param for the function call
walletdb.Create. It touches only the test files found in chainntnfs,
lnwallet, and routing.
* lnd: pass DBTimeout config to relevant services
This commit enables lnd to pass the DBTimeout config to the following
services/config/functions,
- chainControlConfig
- walletunlocker
- wallet.NewLoader
- macaroons
- watchtower
In addition, the usage of wallet.Create is updated too.
* sample-config: add dbtimeout option
2020-12-08 00:31:49 +01:00
|
|
|
db, err := walletdb.Create(
|
|
|
|
"bdb", dbName, !cfg.SyncFreelist, cfg.DB.Bolt.DBTimeout,
|
|
|
|
)
|
2020-10-08 15:10:27 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("unable to create neutrino "+
|
|
|
|
"database: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
headerStateAssertion, err := parseHeaderStateAssertion(
|
|
|
|
cfg.NeutrinoMode.AssertFilterHeader,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
db.Close()
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// With the database open, we can now create an instance of the
|
|
|
|
// neutrino light client. We pass in relevant configuration parameters
|
|
|
|
// required.
|
|
|
|
config := neutrino.Config{
|
|
|
|
DataDir: dbPath,
|
|
|
|
Database: db,
|
|
|
|
ChainParams: *cfg.ActiveNetParams.Params,
|
|
|
|
AddPeers: cfg.NeutrinoMode.AddPeers,
|
|
|
|
ConnectPeers: cfg.NeutrinoMode.ConnectPeers,
|
|
|
|
Dialer: func(addr net.Addr) (net.Conn, error) {
|
2020-11-26 15:49:45 +01:00
|
|
|
dialAddr := addr
|
|
|
|
if tor.IsOnionFakeIP(addr) {
|
|
|
|
// Because the Neutrino address manager only
|
|
|
|
// knows IP addresses, we need to turn any fake
|
|
|
|
// tcp6 address that actually encodes an Onion
|
|
|
|
// v2 address back into the hostname
|
|
|
|
// representation before we can pass it to the
|
|
|
|
// dialer.
|
|
|
|
var err error
|
|
|
|
dialAddr, err = tor.FakeIPToOnionHost(addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 15:10:27 +02:00
|
|
|
return cfg.net.Dial(
|
2020-11-26 15:49:45 +01:00
|
|
|
dialAddr.Network(), dialAddr.String(),
|
2020-10-08 15:10:27 +02:00
|
|
|
cfg.ConnectionTimeout,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
NameResolver: func(host string) ([]net.IP, error) {
|
2020-11-26 15:49:45 +01:00
|
|
|
if tor.IsOnionHost(host) {
|
|
|
|
// Neutrino internally uses btcd's address
|
|
|
|
// manager which only operates on an IP level
|
|
|
|
// and does not understand onion hosts. We need
|
|
|
|
// to turn an onion host into a fake
|
|
|
|
// representation of an IP address to make it
|
|
|
|
// possible to connect to a block filter backend
|
|
|
|
// that serves on an Onion v2 hidden service.
|
|
|
|
fakeIP, err := tor.OnionHostToFakeIP(host)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return []net.IP{fakeIP}, nil
|
|
|
|
}
|
|
|
|
|
2020-10-08 15:10:27 +02:00
|
|
|
addrs, err := cfg.net.LookupHost(host)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ips := make([]net.IP, 0, len(addrs))
|
|
|
|
for _, strIP := range addrs {
|
|
|
|
ip := net.ParseIP(strIP)
|
|
|
|
if ip == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
ips = append(ips, ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ips, nil
|
|
|
|
},
|
|
|
|
AssertFilterHeader: headerStateAssertion,
|
2021-03-24 07:48:33 +01:00
|
|
|
BlockCache: blockCache.Cache,
|
2021-04-29 01:16:34 +02:00
|
|
|
BroadcastTimeout: cfg.NeutrinoMode.BroadcastTimeout,
|
|
|
|
PersistToDisk: cfg.NeutrinoMode.PersistFilters,
|
2020-10-08 15:10:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
neutrino.MaxPeers = 8
|
|
|
|
neutrino.BanDuration = time.Hour * 48
|
|
|
|
neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
|
|
|
|
neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
|
|
|
|
|
|
|
|
neutrinoCS, err := neutrino.NewChainService(config)
|
|
|
|
if err != nil {
|
|
|
|
db.Close()
|
|
|
|
return nil, nil, fmt.Errorf("unable to create neutrino light "+
|
|
|
|
"client: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := neutrinoCS.Start(); err != nil {
|
|
|
|
db.Close()
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
cleanUp := func() {
|
|
|
|
if err := neutrinoCS.Stop(); err != nil {
|
|
|
|
ltndLog.Infof("Unable to stop neutrino light client: %v", err)
|
|
|
|
}
|
|
|
|
db.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return neutrinoCS, cleanUp, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseHeaderStateAssertion parses the user-specified neutrino header state
|
|
|
|
// into a headerfs.FilterHeader.
|
|
|
|
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
|
|
|
|
if len(state) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
split := strings.Split(state, ":")
|
|
|
|
if len(split) != 2 {
|
|
|
|
return nil, fmt.Errorf("header state assertion %v in "+
|
|
|
|
"unexpected format, expected format height:hash", state)
|
|
|
|
}
|
|
|
|
|
|
|
|
height, err := strconv.ParseUint(split[0], 10, 32)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid filter header height: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
hash, err := chainhash.NewHashFromStr(split[1])
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid filter header hash: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &headerfs.FilterHeader{
|
|
|
|
Height: uint32(height),
|
|
|
|
FilterHash: *hash,
|
|
|
|
}, nil
|
|
|
|
}
|