forked from lightninglabs/lightning-terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terminal.go
1920 lines (1640 loc) · 58 KB
/
terminal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package terminal
import (
"context"
"crypto/tls"
"embed"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
restProxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/jessevdk/go-flags"
"github.com/lightninglabs/lightning-terminal/accounts"
"github.com/lightninglabs/lightning-terminal/autopilotserver"
"github.com/lightninglabs/lightning-terminal/firewall"
"github.com/lightninglabs/lightning-terminal/firewalldb"
"github.com/lightninglabs/lightning-terminal/litrpc"
"github.com/lightninglabs/lightning-terminal/perms"
"github.com/lightninglabs/lightning-terminal/queue"
mid "github.com/lightninglabs/lightning-terminal/rpcmiddleware"
"github.com/lightninglabs/lightning-terminal/rules"
"github.com/lightninglabs/lightning-terminal/session"
"github.com/lightninglabs/lightning-terminal/status"
"github.com/lightninglabs/lightning-terminal/subservers"
"github.com/lightninglabs/lndclient"
"github.com/lightningnetwork/lnd"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/chainreg"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/lncfg"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/autopilotrpc"
"github.com/lightningnetwork/lnd/lnrpc/chainrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
"github.com/lightningnetwork/lnd/lnrpc/verrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnrpc/watchtowerrpc"
"github.com/lightningnetwork/lnd/lnrpc/wtclientrpc"
"github.com/lightningnetwork/lnd/lnwallet/btcwallet"
"github.com/lightningnetwork/lnd/macaroons"
"github.com/lightningnetwork/lnd/rpcperms"
"github.com/lightningnetwork/lnd/signal"
grpcProxy "github.com/mwitkow/grpc-proxy/proxy"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/test/bufconn"
"google.golang.org/protobuf/encoding/protojson"
"gopkg.in/macaroon-bakery.v2/bakery"
"gopkg.in/macaroon.v2"
)
const (
MainnetServer = "autopilot.lightning.finance:12010"
TestnetServer = "test.autopilot.lightning.finance:12010"
// lndWalletReadyStatus is a custom status that will be used with the
// LND subserver. If the subserver is in this state then it will allow
// certain wallet calls through while denying other calls that require
// LND to be fully started.
lndWalletReadyStatus = "Wallet Ready"
defaultServerTimeout = 10 * time.Second
defaultConnectTimeout = 15 * time.Second
defaultStartupTimeout = 5 * time.Second
)
// restRegistration is a function type that represents a REST proxy
// registration.
type restRegistration func(context.Context, *restProxy.ServeMux, string,
[]grpc.DialOption) error
var (
// maxMsgRecvSize is the largest message our REST proxy will receive. We
// set this to 200MiB atm.
maxMsgRecvSize = grpc.MaxCallRecvMsgSize(1 * 1024 * 1024 * 200)
// macDatabaseOpenTimeout is how long we wait for acquiring the lock on
// the macaroon database before we give up with an error.
macDatabaseOpenTimeout = time.Second * 5
// appBuildFS is an in-memory file system that contains all the static
// HTML/CSS/JS files of the UI. It is compiled into the binary with the
// go 1.16 embed directive below. Because the path is relative to the
// root package, all assets will have a path prefix of /app/build/ which
// we'll strip by giving a sub directory to the HTTP server.
//
//go:embed app/build/*
appBuildFS embed.FS
// appFilesDir is the sub directory of the above build directory which
// we pass to the HTTP server.
appFilesDir = "app/build"
// appFilesPrefix is the path prefix the static assets of the UI are
// exposed under. This variable can be overwritten during build time if
// a different deployment path should be used.
appFilesPrefix = ""
// patternRESTRequest is the regular expression that matches all REST
// URIs that are currently used by lnd, faraday, loop and pool.
patternRESTRequest = regexp.MustCompile(`^/v\d/.*`)
// lndRESTRegistrations is the list of all lnd REST handler registration
// functions we want to call when creating our REST proxy. We include
// all lnd subserver packages here, even though some might not be active
// in a remote lnd node. That will result in an "UNIMPLEMENTED" error
// instead of a 404 which should be an okay tradeoff vs. connecting
// first and querying all enabled subservers to dynamically populate
// this list.
lndRESTRegistrations = []restRegistration{
lnrpc.RegisterLightningHandlerFromEndpoint,
lnrpc.RegisterWalletUnlockerHandlerFromEndpoint,
lnrpc.RegisterStateHandlerFromEndpoint,
autopilotrpc.RegisterAutopilotHandlerFromEndpoint,
chainrpc.RegisterChainNotifierHandlerFromEndpoint,
invoicesrpc.RegisterInvoicesHandlerFromEndpoint,
routerrpc.RegisterRouterHandlerFromEndpoint,
signrpc.RegisterSignerHandlerFromEndpoint,
verrpc.RegisterVersionerHandlerFromEndpoint,
walletrpc.RegisterWalletKitHandlerFromEndpoint,
watchtowerrpc.RegisterWatchtowerHandlerFromEndpoint,
wtclientrpc.RegisterWatchtowerClientHandlerFromEndpoint,
}
// minimalCompatibleVersion is the minimal lnd version that is required
// to run LiT in remote mode.
minimalCompatibleVersion = &verrpc.Version{
AppMajor: 0,
AppMinor: 17,
AppPatch: 0,
BuildTags: []string{
"signrpc", "walletrpc", "chainrpc", "invoicesrpc",
},
}
)
// LightningTerminal is the main grand unified binary instance. Its task is to
// start an lnd node then start and register external subservers to it.
type LightningTerminal struct {
cfg *Config
defaultImplCfg *lnd.ImplementationCfg
permsMgr *perms.Manager
// lndInterceptorChain is a reference to lnd's interceptor chain that
// guards all incoming calls. This is only set in integrated mode!
lndInterceptorChain *rpcperms.InterceptorChain
wg sync.WaitGroup
errQueue *queue.ConcurrentQueue[error]
lndConnID string
lndConn *grpc.ClientConn
lndClient *lndclient.GrpcLndServices
basicClient lnrpc.LightningClient
subServerMgr *subservers.Manager
statusMgr *status.Manager
autopilotClient autopilotserver.Autopilot
ruleMgrs rules.ManagerSet
rpcProxy *rpcProxy
httpServer *http.Server
sessionRpcServer *sessionRpcServer
sessionRpcServerStarted bool
macaroonService *lndclient.MacaroonService
macaroonServiceStarted bool
macaroonDB kvdb.Backend
middleware *mid.Manager
middlewareStarted bool
accountService *accounts.InterceptorService
accountServiceStarted bool
accountRpcServer *accounts.RPCServer
firewallDB *firewalldb.DB
sessionDB *session.DB
restHandler http.Handler
restCancel func()
}
// New creates a new instance of the lightning-terminal daemon.
func New() *LightningTerminal {
return &LightningTerminal{
statusMgr: status.NewStatusManager(),
}
}
// Run starts everything and then blocks until either the application is shut
// down or a critical error happens.
func (g *LightningTerminal) Run() error {
// Hook interceptor for os signals.
shutdownInterceptor, err := signal.Intercept()
if err != nil {
return fmt.Errorf("could not intercept signals: %v", err)
}
cfg, err := loadAndValidateConfig(shutdownInterceptor)
if err != nil {
return fmt.Errorf("could not load config: %w", err)
}
g.cfg = cfg
g.defaultImplCfg = g.cfg.Lnd.ImplementationConfig(shutdownInterceptor)
// Show version at startup.
log.Infof("LiT version: %s", Version())
// This concurrent error queue can be used by every component that can
// raise runtime errors. Using a queue will prevent us from blocking on
// sending errors to it, as long as the queue is running.
g.errQueue = queue.NewConcurrentQueue[error](queue.DefaultQueueSize)
g.errQueue.Start()
defer g.errQueue.Stop()
// Construct a new Manager.
g.permsMgr, err = perms.NewManager(false)
if err != nil {
return fmt.Errorf("could not create permissions manager")
}
// The litcli status command will call the "/lnrpc.State/GetState" RPC.
// As the status command is available to the user before the macaroons
// have been loaded/created, and before the lnd clients have been
// set up, we need to override the isReady check for this specific
// URI as soon as LND can accept the call, i.e. when the lnd sub-server
// is in the "Wallet Ready" state.
lndOverride := func(uri, manualStatus string) (bool, bool) {
if uri != "/lnrpc.State/GetState" {
return false, false
}
return manualStatus == lndWalletReadyStatus, true
}
// Register LND, LiT and Accounts with the status manager.
g.statusMgr.RegisterAndEnableSubServer(
subservers.LND, status.WithIsReadyOverride(lndOverride),
)
g.statusMgr.RegisterAndEnableSubServer(subservers.LIT)
g.statusMgr.RegisterSubServer(subservers.ACCOUNTS)
// Also enable the accounts subserver if it's not disabled.
if !g.cfg.Accounts.Disable {
g.statusMgr.SetEnabled(subservers.ACCOUNTS)
}
// Create the instances of our subservers now so we can hook them up to
// lnd once it's fully started.
g.subServerMgr = subservers.NewManager(g.permsMgr, g.statusMgr)
// Register our sub-servers. This must be done before the REST proxy is
// set up so that the correct REST handlers are registered.
g.initSubServers()
// Construct the rpcProxy. It must be initialised before the main web
// server is started.
g.rpcProxy = newRpcProxy(
g.cfg, g, g.validateSuperMacaroon, g.permsMgr, g.subServerMgr,
g.statusMgr,
)
// Register any gRPC services that should be served using LiT's
// gRPC server regardless of the LND mode being used.
litrpc.RegisterProxyServer(g.rpcProxy.grpcServer, g.rpcProxy)
litrpc.RegisterStatusServer(g.rpcProxy.grpcServer, g.statusMgr)
// Start the main web server that dispatches requests either to the
// static UI file server or the RPC proxy. This makes it possible to
// unlock lnd through the UI.
if err := g.startMainWebServer(); err != nil {
return fmt.Errorf("error starting main proxy HTTP server: %v",
err)
}
// We'll also create a REST proxy that'll convert any REST calls to gRPC
// calls and forward them to the internal listener.
if g.cfg.EnableREST {
if err := g.createRESTProxy(); err != nil {
return fmt.Errorf("error creating REST proxy: %v", err)
}
}
// Attempt to start Lit and all of its sub-servers. If an error is
// returned, it means that either one of Lit's internal sub-servers
// could not start or LND could not start or be connected to.
startErr := g.start()
if startErr != nil {
g.statusMgr.SetErrored(
subservers.LIT, "could not start Lit: %v", startErr,
)
}
// Now block until we receive an error or the main shutdown
// signal.
<-shutdownInterceptor.ShutdownChannel()
log.Infof("Shutdown signal received")
err = g.shutdownSubServers()
if err != nil {
log.Errorf("Error shutting down: %v", err)
}
g.wg.Wait()
return startErr
}
// start attempts to start all the various components of Litd. Only Litd and
// LND errors are considered fatal and will result in an error being returned.
// If any of the sub-servers managed by the subServerMgr error while starting
// up, these are considered non-fatal and will not result in an error being
// returned.
func (g *LightningTerminal) start() error {
var err error
accountServiceErrCallback := func(err error) {
g.statusMgr.SetErrored(
subservers.ACCOUNTS,
err.Error(),
)
log.Errorf("Error thrown in the accounts service, keeping "+
"litd running: %v", err,
)
}
g.accountService, err = accounts.NewService(
filepath.Dir(g.cfg.MacaroonPath), accountServiceErrCallback,
)
if err != nil {
return fmt.Errorf("error creating account service: %v", err)
}
superMacBaker := func(ctx context.Context, rootKeyID uint64,
recipe *session.MacaroonRecipe) (string, error) {
return BakeSuperMacaroon(
ctx, g.basicClient, rootKeyID,
recipe.Permissions, recipe.Caveats,
)
}
g.accountRpcServer = accounts.NewRPCServer(
g.accountService, superMacBaker,
)
g.ruleMgrs = rules.NewRuleManagerSet()
// Create an instance of the local Terminal Connect session store DB.
networkDir := filepath.Join(g.cfg.LitDir, g.cfg.Network)
g.sessionDB, err = session.NewDB(networkDir, session.DBFilename)
if err != nil {
return fmt.Errorf("error creating session DB: %v", err)
}
g.firewallDB, err = firewalldb.NewDB(
networkDir, firewalldb.DBFilename, g.sessionDB,
)
if err != nil {
return fmt.Errorf("error creating firewall DB: %v", err)
}
if !g.cfg.Autopilot.Disable {
if g.cfg.Autopilot.Address == "" &&
len(g.cfg.Autopilot.DialOpts) == 0 {
switch g.cfg.Network {
case "mainnet":
g.cfg.Autopilot.Address = MainnetServer
case "testnet":
g.cfg.Autopilot.Address = TestnetServer
default:
return errors.New("no autopilot server " +
"address specified")
}
}
g.cfg.Autopilot.LitVersion = autopilotserver.Version{
Major: uint32(appMajor),
Minor: uint32(appMinor),
Patch: uint32(appPatch),
}
g.autopilotClient, err = autopilotserver.NewClient(
g.cfg.Autopilot,
)
if err != nil {
return err
}
}
g.sessionRpcServer, err = newSessionRPCServer(&sessionRpcServerConfig{
db: g.sessionDB,
basicAuth: g.rpcProxy.basicAuth,
grpcOptions: []grpc.ServerOption{
grpc.CustomCodec(grpcProxy.Codec()), // nolint: staticcheck,
grpc.ChainStreamInterceptor(
g.rpcProxy.StreamServerInterceptor,
),
grpc.ChainUnaryInterceptor(
g.rpcProxy.UnaryServerInterceptor,
),
grpc.UnknownServiceHandler(
grpcProxy.TransparentHandler(
// Don't allow calls to litrpc.
g.rpcProxy.makeDirector(false),
),
),
},
registerGrpcServers: func(server *grpc.Server) {
g.registerSubDaemonGrpcServers(server, true)
},
superMacBaker: superMacBaker,
firstConnectionDeadline: g.cfg.FirstLNCConnDeadline,
permMgr: g.permsMgr,
actionsDB: g.firewallDB,
autopilot: g.autopilotClient,
ruleMgrs: g.ruleMgrs,
privMap: g.firewallDB.PrivacyDB,
})
if err != nil {
return fmt.Errorf("could not create new session rpc "+
"server: %v", err)
}
// Call the "real" main in a nested manner so the defers will properly
// be executed in the case of a graceful shutdown.
var (
bufRpcListener = bufconn.Listen(100)
readyChan = make(chan struct{})
bufReadyChan = make(chan struct{})
unlockChan = make(chan struct{})
lndQuit = make(chan struct{})
macChan = make(chan []byte, 1)
)
if g.cfg.LndMode == ModeIntegrated {
lisCfg := lnd.ListenerCfg{
RPCListeners: []*lnd.ListenerWithSignal{{
Listener: &onDemandListener{
addr: g.cfg.Lnd.RPCListeners[0],
},
Ready: readyChan,
}, {
Listener: bufRpcListener,
Ready: bufReadyChan,
MacChan: macChan,
}},
}
implCfg := &lnd.ImplementationCfg{
GrpcRegistrar: g,
RestRegistrar: g,
ExternalValidator: g,
DatabaseBuilder: g.defaultImplCfg.DatabaseBuilder,
WalletConfigBuilder: g,
ChainControlBuilder: g.defaultImplCfg.ChainControlBuilder,
}
g.wg.Add(1)
go func() {
defer g.wg.Done()
err := lnd.Main(g.cfg.Lnd, lisCfg, implCfg, interceptor)
if e, ok := err.(*flags.Error); err != nil &&
(!ok || e.Type != flags.ErrHelp) {
errStr := fmt.Sprintf("Error running main "+
"lnd: %v", err)
log.Errorf(errStr)
g.statusMgr.SetErrored(subservers.LND, errStr)
g.errQueue.ChanIn() <- err
return
}
close(lndQuit)
}()
} else {
close(unlockChan)
close(readyChan)
close(bufReadyChan)
_ = g.RegisterGrpcSubserver(g.rpcProxy.grpcServer)
}
// Wait for lnd to be started up so we know we have a TLS cert.
select {
// If lnd needs to be unlocked we get the signal that it's ready to do
// so. We then go ahead and start the UI so we can unlock it there as
// well.
case <-unlockChan:
// If lnd is running with --noseedbackup and doesn't need unlocking, we
// get the ready signal immediately.
case <-readyChan:
case err := <-g.errQueue.ChanOut():
g.statusMgr.SetErrored(
subservers.LND, "error from errQueue channel",
)
return fmt.Errorf("could not start LND: %v", err)
case <-lndQuit:
g.statusMgr.SetErrored(
subservers.LND, "lndQuit channel closed",
)
return fmt.Errorf("LND has stopped")
case <-interceptor.ShutdownChannel():
return fmt.Errorf("received the shutdown signal")
}
// Connect to LND.
g.lndConn, err = connectLND(g.cfg, bufRpcListener)
if err != nil {
g.statusMgr.SetErrored(
subservers.LND, "could not connect to LND: %v", err,
)
return fmt.Errorf("could not connect to LND")
}
// In order to be able to create unique middleware request identifiers,
// we set a new unique connection ID. This should be refreshed every
// time we (re)connect to LND.
// TODO: This assumes that litd needs to be restarted when the
// connection to LND is interrupted, leading to a unique connection ID.
// When automatic reconnection is implemented, we need to make sure that
// the connection ID is refreshed when the connection is re-established.
g.lndConnID = randId(rules.LndConnIdLen)
// Initialise any connections to sub-servers that we are running in
// remote mode.
g.subServerMgr.ConnectRemoteSubServers()
// bakeSuperMac is a closure that can be used to bake a new super
// macaroon that contains all active permissions.
bakeSuperMac := func(ctx context.Context, rootKeyIDSuffix uint32) (
string, error) {
var suffixBytes [4]byte
binary.BigEndian.PutUint32(suffixBytes[:], rootKeyIDSuffix)
rootKeyID := session.NewSuperMacaroonRootKeyID(suffixBytes)
return BakeSuperMacaroon(
ctx, g.basicClient, rootKeyID,
g.permsMgr.ActivePermissions(false), nil,
)
}
// Now start the RPC proxy that will handle all incoming gRPC, grpc-web
// and REST requests.
if err := g.rpcProxy.Start(g.lndConn, bakeSuperMac); err != nil {
return fmt.Errorf("error starting lnd gRPC proxy server: %v",
err)
}
// We now set a custom status for the LND sub-server to indicate that
// the wallet is ready.
// This is done _before_ we have set up the lnd clients so that the
// litcli status command won't error before the lnd sub-server has
// been marked as running.
g.statusMgr.SetCustomStatus(subservers.LND, lndWalletReadyStatus)
// Now that we have started the main UI web server, show some useful
// information to the user so they can access the web UI easily.
if err := g.showStartupInfo(); err != nil {
return fmt.Errorf("error displaying startup info: %v", err)
}
// waitForSignal is a helper closure that can be used to wait on the
// given channel for a signal while also being responsive to an error
// from the error Queue, LND quiting or the interceptor receiving a
// shutdown signal.
waitForSignal := func(c chan struct{}) error {
select {
case <-c:
return nil
case err := <-g.errQueue.ChanOut():
return err
case <-lndQuit:
g.statusMgr.SetErrored(
subservers.LND, "lndQuit channel closed",
)
return fmt.Errorf("LND has stopped")
case <-interceptor.ShutdownChannel():
return fmt.Errorf("received the shutdown signal")
}
}
// Wait for lnd to be unlocked, then start all clients.
if err = waitForSignal(readyChan); err != nil {
return err
}
// If we're in integrated mode, we'll need to wait for lnd to send the
// macaroon after unlock before going any further.
if g.cfg.LndMode == ModeIntegrated {
if err = waitForSignal(bufReadyChan); err != nil {
return err
}
// Create a new macReady channel that will serve to signal that
// the LND macaroon is ready. Spin off a goroutine that will
// close this channel when the macaroon has been received.
macReady := make(chan struct{})
go func() {
g.cfg.lndAdminMacaroon = <-macChan
close(macReady)
}()
if err = waitForSignal(macReady); err != nil {
return err
}
}
// Set up all the LND clients required by LiT.
err = g.setUpLNDClients(lndQuit)
if err != nil {
g.statusMgr.SetErrored(
subservers.LND, "could not set up LND clients: %v", err,
)
return fmt.Errorf("could not start LND")
}
// Mark that lnd is now completely running after connecting the
// lnd clients.
g.statusMgr.SetRunning(subservers.LND)
// If we're in integrated and stateless init mode, we won't create
// macaroon files in any of the subserver daemons.
createDefaultMacaroons := true
if g.cfg.LndMode == ModeIntegrated && g.lndInterceptorChain != nil &&
g.lndInterceptorChain.MacaroonService() != nil {
// If the wallet was initialized in stateless mode, we don't
// want any macaroons lying around on the filesystem. In that
// case only the UI will be able to access any of the integrated
// daemons. In all other cases we want default macaroons so we
// can use the CLI tools to interact with loop/pool/faraday.
macService := g.lndInterceptorChain.MacaroonService()
createDefaultMacaroons = !macService.StatelessInit
}
// Both connection types are ready now, let's start our sub-servers if
// they should be started locally as an integrated service.
g.subServerMgr.StartIntegratedServers(
g.basicClient, g.lndClient, createDefaultMacaroons,
)
err = g.startInternalSubServers(createDefaultMacaroons)
if err != nil {
return fmt.Errorf("could not start litd sub-servers: %v", err)
}
// We can now set the status of LiT as running.
g.statusMgr.SetRunning(subservers.LIT)
// Now block until we receive an error or the main shutdown signal.
select {
case err := <-g.errQueue.ChanOut():
if err != nil {
return fmt.Errorf("received critical error from "+
"subsystem, shutting down: %v", err)
}
case <-lndQuit:
g.statusMgr.SetErrored(
subservers.LND, "lndQuit channel closed",
)
return fmt.Errorf("LND is not running")
case <-interceptor.ShutdownChannel():
log.Infof("Shutdown signal received")
}
return nil
}
// setUpLNDClients sets up the various LND clients required by LiT.
func (g *LightningTerminal) setUpLNDClients(lndQuit chan struct{}) error {
var (
err error
insecure bool
clientOptions []lndclient.BasicClientOption
)
host, network, tlsPath, macPath, macData := g.cfg.lndConnectParams()
clientOptions = append(clientOptions, lndclient.MacaroonData(
hex.EncodeToString(macData),
))
clientOptions = append(
clientOptions, lndclient.MacFilename(filepath.Base(macPath)),
)
// If we're in integrated mode, we can retrieve the macaroon string
// from lnd directly, rather than grabbing it from disk.
if g.cfg.LndMode == ModeIntegrated {
// Set to true in integrated mode, since we will not require tls
// when communicating with lnd via a bufconn.
insecure = true
clientOptions = append(clientOptions, lndclient.Insecure())
}
// checkRunning checks if we should continue running for the duration of
// the defaultStartupTimeout, or else returns an error indicating why
// a shut-down is needed.
checkRunning := func() error {
select {
case err := <-g.errQueue.ChanOut():
return fmt.Errorf("error from subsystem: %v", err)
case <-lndQuit:
return fmt.Errorf("LND has stopped")
case <-interceptor.ShutdownChannel():
return fmt.Errorf("received the shutdown signal")
case <-time.After(defaultStartupTimeout):
return nil
}
}
// The main RPC listener of lnd might need some time to start, it could
// be that we run into a connection refused a few times. We use the
// basic client connection to find out if the RPC server is started yet
// because that doesn't do anything else than just connect. We'll check
// if lnd is also ready to be used in the next step.
log.Infof("Connecting basic lnd client")
for {
// Create an lnd client now that we have the full configuration.
// We'll need a basic client and a full client because not all
// subservers have the same requirements.
g.basicClient, err = lndclient.NewBasicClient(
host, tlsPath, filepath.Dir(macPath),
string(network), clientOptions...,
)
if err == nil {
log.Infof("Basic lnd client connected")
break
}
g.statusMgr.SetErrored(
subservers.LIT,
"Error when setting up basic LND Client: %v", err,
)
err = checkRunning()
if err != nil {
return err
}
log.Infof("Retrying to connect basic lnd client")
}
// Now we know that the connection itself is ready. But we also need to
// wait for two things: The chain notifier to be ready and the lnd
// wallet being fully synced to its chain backend. The chain notifier
// will always be ready first so if we instruct the lndclient to wait
// for the wallet sync, we should be fully ready to start all our
// subservers. This will just block until lnd signals readiness. But we
// still want to react to shutdown requests, so we need to listen for
// those.
ctxc, cancel := context.WithCancel(context.Background())
defer cancel()
// Make sure the context is canceled if the user requests shutdown.
go func() {
select {
// Client requests shutdown, cancel the wait.
case <-interceptor.ShutdownChannel():
cancel()
// The check was completed and the above defer canceled the
// context. We can just exit the goroutine, nothing more to do.
case <-ctxc.Done():
}
}()
log.Infof("Connecting full lnd client")
for {
g.lndClient, err = lndclient.NewLndServices(
&lndclient.LndServicesConfig{
LndAddress: host,
Network: network,
TLSPath: tlsPath,
Insecure: insecure,
CustomMacaroonPath: macPath,
CustomMacaroonHex: hex.EncodeToString(macData),
BlockUntilChainSynced: true,
BlockUntilUnlocked: true,
CallerCtx: ctxc,
CheckVersion: minimalCompatibleVersion,
},
)
if err == nil {
log.Infof("Full lnd client connected")
break
}
g.statusMgr.SetErrored(
subservers.LIT,
"Error when creating LND Services client: %v",
err,
)
err = checkRunning()
if err != nil {
return err
}
log.Infof("Retrying to create LND Services client")
}
// Pass LND's build tags to the permission manager so that it can
// filter the available permissions accordingly.
g.permsMgr.OnLNDBuildTags(g.lndClient.Version.BuildTags)
// In the integrated mode, we received an admin macaroon once lnd was
// ready. We can now bake a "super macaroon" that contains all
// permissions of all daemons that we can use for any internal calls.
if g.cfg.LndMode == ModeIntegrated {
// Create a super macaroon that can be used to control lnd,
// faraday, loop, and pool, all at the same time.
log.Infof("Baking internal super macaroon")
ctx := context.Background()
superMacaroon, err := BakeSuperMacaroon(
ctx, g.basicClient, session.NewSuperMacaroonRootKeyID(
[4]byte{},
),
g.permsMgr.ActivePermissions(false), nil,
)
if err != nil {
return err
}
g.rpcProxy.superMacaroon = superMacaroon
}
return nil
}
// startInternalSubServers starts all Litd specific sub-servers.
func (g *LightningTerminal) startInternalSubServers(
createDefaultMacaroons bool) error {
log.Infof("Starting LiT macaroon service")
// Set up the macaroon service.
rks, db, err := lndclient.NewBoltMacaroonStore(
filepath.Join(g.cfg.LitDir, g.cfg.Network),
lncfg.MacaroonDBName, macDatabaseOpenTimeout,
)
if err != nil {
return err
}
g.macaroonDB = db
g.macaroonService, err = lndclient.NewMacaroonService(
&lndclient.MacaroonServiceConfig{
RootKeyStore: rks,
MacaroonLocation: "litd",
StatelessInit: !createDefaultMacaroons,
RequiredPerms: perms.RequiredPermissions,
LndClient: &g.lndClient.LndServices,
EphemeralKey: lndclient.SharedKeyNUMS,
KeyLocator: lndclient.SharedKeyLocator,
MacaroonPath: g.cfg.MacaroonPath,
},
)
if err != nil {
log.Errorf("Could not create a new macaroon service: %v", err)
return err
}
if err := g.macaroonService.Start(); err != nil {
return fmt.Errorf("could not start macaroon service: %v", err)
}
g.macaroonServiceStarted = true
if !g.cfg.Autopilot.Disable {
withLndVersion := func(cfg *autopilotserver.Config) {
cfg.LndVersion = autopilotserver.Version{
Major: g.lndClient.Version.AppMajor,
Minor: g.lndClient.Version.AppMinor,
Patch: g.lndClient.Version.AppPatch,
}
}
if err = g.autopilotClient.Start(withLndVersion); err != nil {
return fmt.Errorf("could not start the autopilot "+
"client: %v", err)
}
}
log.Infof("Starting LiT session server")
if err = g.sessionRpcServer.start(); err != nil {
return err
}
g.sessionRpcServerStarted = true
// The rest of the function only applies if the rpc middleware
// interceptor has been enabled.
if g.cfg.RPCMiddleware.Disabled {
log.Infof("Internal sub server startup complete")
return nil
}
// Even if the accounts service fails on the Start function, or the
// accounts service is disabled, we still want to call Stop function as
// this closes the contexts and the db store which were opened with the
// accounts.NewService function call in the LightningTerminal start
// function above.
closeAccountService := func() {
if err := g.accountService.Stop(); err != nil {
// We only log the error if we fail to stop the service,
// as it's not critical that this succeeds in order to
// keep litd running
log.Errorf("Error stopping account service: %v", err)
}
}
log.Infof("Starting LiT account service")
if !g.cfg.Accounts.Disable {
err = g.accountService.Start(
g.lndClient.Client, g.lndClient.Router,
g.lndClient.ChainParams,
)
if err != nil {
log.Errorf("error starting account service: %v, "+
"disabling account service", err)
g.statusMgr.SetErrored(subservers.ACCOUNTS, err.Error())
closeAccountService()
} else {
g.statusMgr.SetRunning(subservers.ACCOUNTS)
g.accountServiceStarted = true
}
} else {
closeAccountService()
}
requestLogger, err := firewall.NewRequestLogger(
g.cfg.Firewall.RequestLogger, g.firewallDB,
)
if err != nil {
return fmt.Errorf("error creating new request logger")
}
privacyMapper := firewall.NewPrivacyMapper(
g.firewallDB.PrivacyDB, firewall.CryptoRandIntn,
g.sessionDB,
)
mw := []mid.RequestInterceptor{
privacyMapper,
g.accountService,
requestLogger,
}
if !g.cfg.Autopilot.Disable {
ruleEnforcer := firewall.NewRuleEnforcer(
g.firewallDB, g.firewallDB, g.sessionDB,