This repository has been archived by the owner on May 23, 2021. It is now read-only.
forked from BTCGPU/lnd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lnd.go
1139 lines (992 loc) · 32.3 KB
/
lnd.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
// Copyright (c) 2013-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Copyright (C) 2015-2017 The Lightning Network Developers
package lnd
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net"
"net/http"
"os"
"path/filepath"
"runtime/pprof"
"strings"
"sync"
"time"
// Blank import to set up profiling HTTP handlers.
_ "net/http/pprof"
"gopkg.in/macaroon-bakery.v2/bakery"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/BTCGPU/neutrino"
"github.com/btgsuite/btgd/btcec"
btcutil "github.com/btgsuite/btgutil"
"github.com/btgsuite/btgwallet/wallet"
proxy "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/BTCGPU/lnd/autopilot"
"github.com/BTCGPU/lnd/build"
"github.com/BTCGPU/lnd/chanacceptor"
"github.com/BTCGPU/lnd/channeldb"
"github.com/BTCGPU/lnd/keychain"
"github.com/BTCGPU/lnd/lncfg"
"github.com/BTCGPU/lnd/lnrpc"
"github.com/BTCGPU/lnd/lnwallet"
"github.com/BTCGPU/lnd/lnwallet/btcwallet"
"github.com/BTCGPU/lnd/macaroons"
"github.com/BTCGPU/lnd/signal"
"github.com/BTCGPU/lnd/walletunlocker"
"github.com/BTCGPU/lnd/watchtower"
"github.com/BTCGPU/lnd/watchtower/wtdb"
)
const (
// Make certificate valid for 14 months.
autogenCertValidity = 14 /*months*/ * 30 /*days*/ * 24 * time.Hour
)
var (
cfg *config
registeredChains = newChainRegistry()
// networkDir is the path to the directory of the currently active
// network. This path will hold the files related to each different
// network.
networkDir string
// End of ASN.1 time.
endOfTime = time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
// Max serial number.
serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
/*
* These cipher suites fit the following criteria:
* - Don't use outdated algorithms like SHA-1 and 3DES
* - Don't use ECB mode or other insecure symmetric methods
* - Included in the TLS v1.2 suite
* - Are available in the Go 1.7.6 standard library (more are
* available in 1.8.3 and will be added after lnd no longer
* supports 1.7, including suites that support CBC mode)
**/
tlsCipherSuites = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
}
)
// ListenerCfg is a wrapper around custom listeners that can be passed to lnd
// when calling its main method.
type ListenerCfg struct {
// WalletUnlocker can be set to the listener to use for the wallet
// unlocker. If nil a regular network listener will be created.
WalletUnlocker net.Listener
// RPCListener can be set to the listener to use for the RPC server. If
// nil a regular network listener will be created.
RPCListener net.Listener
}
// rpcListeners is a function type used for closures that fetches a set of RPC
// listeners for the current configuration, and the GRPC server options to use
// with these listeners. If no custom listeners are present, this should return
// normal listeners from the RPC endpoints defined in the config, and server
// options specifying TLS.
type rpcListeners func() ([]net.Listener, func(), []grpc.ServerOption, error)
// Main is the true entry point for lnd. This function is required since defers
// created in the top-level scope of a main method aren't executed if os.Exit()
// is called.
func Main(lisCfg ListenerCfg) error {
// Load the configuration, and parse any command line options. This
// function will also set up logging properly.
loadedConfig, err := loadConfig()
if err != nil {
return err
}
cfg = loadedConfig
defer func() {
if logRotator != nil {
ltndLog.Info("Shutdown complete")
logRotator.Close()
}
}()
// Show version at startup.
ltndLog.Infof("Version: %s, build=%s, logging=%s",
build.Version(), build.Deployment, build.LoggingType)
var network string
switch {
case cfg.Bitcoin.TestNet3 || cfg.Litecoin.TestNet3:
network = "testnet"
case cfg.Bitcoin.MainNet || cfg.Litecoin.MainNet:
network = "mainnet"
case cfg.Bitcoin.SimNet || cfg.Litecoin.SimNet:
network = "simnet"
case cfg.Bitcoin.RegTest || cfg.Litecoin.RegTest:
network = "regtest"
}
ltndLog.Infof("Active chain: %v (network=%v)",
strings.Title(registeredChains.PrimaryChain().String()),
network,
)
// Enable http profiling server if requested.
if cfg.Profile != "" {
go func() {
listenAddr := net.JoinHostPort("", cfg.Profile)
profileRedirect := http.RedirectHandler("/debug/pprof",
http.StatusSeeOther)
http.Handle("/", profileRedirect)
fmt.Println(http.ListenAndServe(listenAddr, nil))
}()
}
// Write cpu profile if requested.
if cfg.CPUProfile != "" {
f, err := os.Create(cfg.CPUProfile)
if err != nil {
err := fmt.Errorf("Unable to create CPU profile: %v",
err)
ltndLog.Error(err)
return err
}
pprof.StartCPUProfile(f)
defer f.Close()
defer pprof.StopCPUProfile()
}
// Create the network-segmented directory for the channel database.
graphDir := filepath.Join(cfg.DataDir,
defaultGraphSubDirname,
normalizeNetwork(activeNetParams.Name))
// Open the channeldb, which is dedicated to storing channel, and
// network related metadata.
chanDB, err := channeldb.Open(
graphDir,
channeldb.OptionSetRejectCacheSize(cfg.Caches.RejectCacheSize),
channeldb.OptionSetChannelCacheSize(cfg.Caches.ChannelCacheSize),
channeldb.OptionSetSyncFreelist(cfg.SyncFreelist),
)
if err != nil {
err := fmt.Errorf("Unable to open channeldb: %v", err)
ltndLog.Error(err)
return err
}
defer chanDB.Close()
// Only process macaroons if --no-macaroons isn't set.
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
tlsCfg, restCreds, restProxyDest, err := getTLSConfig(
cfg.TLSCertPath, cfg.TLSKeyPath, cfg.TLSExtraIPs,
cfg.TLSExtraDomains, cfg.RPCListeners,
)
if err != nil {
err := fmt.Errorf("Unable to load TLS credentials: %v", err)
ltndLog.Error(err)
return err
}
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.
restDialOpts := []grpc.DialOption{
grpc.WithTransportCredentials(*restCreds),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(1 * 1024 * 1024 * 50),
),
}
// 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.
mainChain := cfg.Bitcoin
if registeredChains.PrimaryChain() == litecoinChain {
mainChain = cfg.Litecoin
}
var neutrinoCS *neutrino.ChainService
if mainChain.Node == "neutrino" {
neutrinoBackend, neutrinoCleanUp, err := initNeutrinoBackend(
mainChain.ChainDir,
)
if err != nil {
err := fmt.Errorf("Unable to initialize neutrino "+
"backend: %v", err)
ltndLog.Error(err)
return err
}
defer neutrinoCleanUp()
neutrinoCS = neutrinoBackend
}
var (
walletInitParams WalletUnlockParams
privateWalletPw = lnwallet.DefaultPrivatePassphrase
publicWalletPw = lnwallet.DefaultPublicPassphrase
)
// 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()
// getListeners is a closure that creates listeners from the
// RPCListeners defined in the config. It also returns a cleanup
// closure and the server options to use for the GRPC server.
getListeners := func() ([]net.Listener, func(), []grpc.ServerOption,
error) {
var grpcListeners []net.Listener
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)
return nil, nil, nil, err
}
grpcListeners = append(grpcListeners, lis)
}
cleanup := func() {
for _, lis := range grpcListeners {
lis.Close()
}
}
return grpcListeners, cleanup, serverOpts, nil
}
// walletUnlockerListeners is a closure we'll hand to the wallet
// unlocker, that will be called when it needs listeners for its GPRC
// server.
walletUnlockerListeners := func() ([]net.Listener, func(),
[]grpc.ServerOption, error) {
// If we have chosen to start with a dedicated listener for the
// wallet unlocker, we return it directly, and empty server
// options to deactivate TLS.
// TODO(halseth): any point in adding TLS support for custom
// listeners?
if lisCfg.WalletUnlocker != nil {
return []net.Listener{lisCfg.WalletUnlocker}, func() {},
[]grpc.ServerOption{}, nil
}
// Otherwise we'll return the regular listeners.
return getListeners()
}
// We wait until the user provides a password over RPC. In case lnd is
// started with the --noseedbackup flag, we use the default password
// for wallet encryption.
if !cfg.NoSeedBackup {
params, err := waitForWalletPassword(
cfg.RESTListeners, restDialOpts, restProxyDest, tlsCfg,
walletUnlockerListeners,
)
if err != nil {
err := fmt.Errorf("Unable to set up wallet password "+
"listeners: %v", err)
ltndLog.Error(err)
return err
}
walletInitParams = *params
privateWalletPw = walletInitParams.Password
publicWalletPw = walletInitParams.Password
if walletInitParams.RecoveryWindow > 0 {
ltndLog.Infof("Wallet recovery mode enabled with "+
"address lookahead of %d addresses",
walletInitParams.RecoveryWindow)
}
}
var macaroonService *macaroons.Service
if !cfg.NoMacaroons {
// Create the macaroon authentication/authorization service.
macaroonService, err = macaroons.NewService(
networkDir, macaroons.IPLockChecker,
)
if err != nil {
err := fmt.Errorf("Unable to set up macaroon "+
"authentication: %v", err)
ltndLog.Error(err)
return err
}
defer macaroonService.Close()
// Try to unlock the macaroon store with the private password.
err = macaroonService.CreateUnlock(&privateWalletPw)
if err != nil {
err := fmt.Errorf("Unable to unlock macaroons: %v", err)
ltndLog.Error(err)
return err
}
// Create macaroon files for lncli to use if they don't exist.
if !fileExists(cfg.AdminMacPath) && !fileExists(cfg.ReadMacPath) &&
!fileExists(cfg.InvoiceMacPath) {
err = genMacaroons(
ctx, macaroonService, cfg.AdminMacPath,
cfg.ReadMacPath, cfg.InvoiceMacPath,
)
if err != nil {
err := fmt.Errorf("Unable to create macaroons "+
"%v", err)
ltndLog.Error(err)
return err
}
}
}
// With the information parsed from the configuration, create valid
// instances of the pertinent interfaces required to operate the
// Lightning Network Daemon.
activeChainControl, err := newChainControlFromConfig(
cfg, chanDB, privateWalletPw, publicWalletPw,
walletInitParams.Birthday, walletInitParams.RecoveryWindow,
walletInitParams.Wallet, neutrinoCS,
)
if err != nil {
err := fmt.Errorf("Unable to create chain control: %v", err)
ltndLog.Error(err)
return err
}
// Finally before we start the server, we'll register the "holy
// trinity" of interface for our current "home chain" with the active
// chainRegistry interface.
primaryChain := registeredChains.PrimaryChain()
registeredChains.RegisterChain(primaryChain, activeChainControl)
// TODO(roasbeef): add rotation
idPrivKey, err := activeChainControl.wallet.DerivePrivKey(keychain.KeyDescriptor{
KeyLocator: keychain.KeyLocator{
Family: keychain.KeyFamilyNodeKey,
Index: 0,
},
})
if err != nil {
err := fmt.Errorf("Unable to derive node private key: %v", err)
ltndLog.Error(err)
return err
}
idPrivKey.Curve = btcec.S256()
if cfg.Tor.Active {
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)
}
// If the watchtower client should be active, open the client database.
// This is done here so that Close always executes when lndMain returns.
var towerClientDB *wtdb.ClientDB
if cfg.WtClient.Active {
var err error
towerClientDB, err = wtdb.OpenClientDB(graphDir)
if err != nil {
err := fmt.Errorf("Unable to open watchtower client "+
"database: %v", err)
ltndLog.Error(err)
return err
}
defer towerClientDB.Close()
}
var tower *watchtower.Standalone
if cfg.Watchtower.Active {
// Segment the watchtower directory by chain and network.
towerDBDir := filepath.Join(
cfg.Watchtower.TowerDir,
registeredChains.PrimaryChain().String(),
normalizeNetwork(activeNetParams.Name),
)
towerDB, err := wtdb.OpenTowerDB(towerDBDir)
if err != nil {
err := fmt.Errorf("Unable to open watchtower "+
"database: %v", err)
ltndLog.Error(err)
return err
}
defer towerDB.Close()
towerPrivKey, err := activeChainControl.wallet.DerivePrivKey(
keychain.KeyDescriptor{
KeyLocator: keychain.KeyLocator{
Family: keychain.KeyFamilyTowerID,
Index: 0,
},
},
)
if err != nil {
err := fmt.Errorf("Unable to derive watchtower "+
"private key: %v", err)
ltndLog.Error(err)
return err
}
wtConfig, err := cfg.Watchtower.Apply(&watchtower.Config{
BlockFetcher: activeChainControl.chainIO,
DB: towerDB,
EpochRegistrar: activeChainControl.chainNotifier,
Net: cfg.net,
NewAddress: func() (btcutil.Address, error) {
return activeChainControl.wallet.NewAddress(
lnwallet.WitnessPubKey, false,
)
},
NodePrivKey: towerPrivKey,
PublishTx: activeChainControl.wallet.PublishTransaction,
ChainHash: *activeNetParams.GenesisHash,
}, lncfg.NormalizeAddresses)
if err != nil {
err := fmt.Errorf("Unable to configure watchtower: %v",
err)
ltndLog.Error(err)
return err
}
tower, err = watchtower.New(wtConfig)
if err != nil {
err := fmt.Errorf("Unable to create watchtower: %v", err)
ltndLog.Error(err)
return err
}
}
// Initialize the ChainedAcceptor.
chainedAcceptor := chanacceptor.NewChainedAcceptor()
// Set up the core server which will listen for incoming peer
// connections.
server, err := newServer(
cfg.Listeners, chanDB, towerClientDB, activeChainControl,
idPrivKey, walletInitParams.ChansToRestore, chainedAcceptor,
)
if err != nil {
err := fmt.Errorf("Unable to create server: %v", err)
ltndLog.Error(err)
return err
}
// Set up an autopilot manager from the current config. This will be
// used to manage the underlying autopilot agent, starting and stopping
// it at will.
atplCfg, err := initAutoPilot(server, cfg.Autopilot)
if err != nil {
err := fmt.Errorf("Unable to initialize autopilot: %v", err)
ltndLog.Error(err)
return err
}
atplManager, err := autopilot.NewManager(atplCfg)
if err != nil {
err := fmt.Errorf("Unable to create autopilot manager: %v", err)
ltndLog.Error(err)
return err
}
if err := atplManager.Start(); err != nil {
err := fmt.Errorf("Unable to start autopilot manager: %v", err)
ltndLog.Error(err)
return err
}
defer atplManager.Stop()
// rpcListeners is a closure we'll hand to the rpc server, that will be
// called when it needs listeners for its GPRC server.
rpcListeners := func() ([]net.Listener, func(), []grpc.ServerOption,
error) {
// If we have chosen to start with a dedicated listener for the
// rpc server, we return it directly, and empty server options
// to deactivate TLS.
// TODO(halseth): any point in adding TLS support for custom
// listeners?
if lisCfg.RPCListener != nil {
return []net.Listener{lisCfg.RPCListener}, func() {},
[]grpc.ServerOption{}, nil
}
// Otherwise we'll return the regular listeners.
return getListeners()
}
// Initialize, and register our implementation of the gRPC interface
// exported by the rpcServer.
rpcServer, err := newRPCServer(
server, macaroonService, cfg.SubRPCServers, restDialOpts,
restProxyDest, atplManager, server.invoices, tower, tlsCfg,
rpcListeners, chainedAcceptor,
)
if err != nil {
err := fmt.Errorf("Unable to create RPC server: %v", err)
ltndLog.Error(err)
return err
}
if err := rpcServer.Start(); err != nil {
err := fmt.Errorf("Unable to start RPC server: %v", err)
ltndLog.Error(err)
return err
}
defer rpcServer.Stop()
// If we're not in regtest or simnet mode, 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.
if !(cfg.Bitcoin.RegTest || cfg.Bitcoin.SimNet ||
cfg.Litecoin.RegTest || cfg.Litecoin.SimNet) {
_, 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("Waiting for chain backend to finish sync, "+
"start_height=%v", bestHeight)
for {
if !signal.Alive() {
return nil
}
synced, _, err := activeChainControl.wallet.IsSynced()
if err != nil {
err := fmt.Errorf("Unable to determine if "+
"wallet is synced: %v", err)
ltndLog.Error(err)
return err
}
if synced {
break
}
time.Sleep(time.Second * 1)
}
_, 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)
}
// With all the relevant chains initialized, we can finally start the
// server itself.
if err := server.Start(); err != nil {
err := fmt.Errorf("Unable to start server: %v", err)
ltndLog.Error(err)
return err
}
defer server.Stop()
// Now that the server has started, if the autopilot mode is currently
// active, then we'll start the autopilot agent immediately. It will be
// stopped together with the autopilot service.
if cfg.Autopilot.Active {
if err := atplManager.StartAgent(); err != nil {
err := fmt.Errorf("Unable to start autopilot agent: %v",
err)
ltndLog.Error(err)
return err
}
}
if cfg.Watchtower.Active {
if err := tower.Start(); err != nil {
err := fmt.Errorf("Unable to start watchtower: %v", err)
ltndLog.Error(err)
return err
}
defer tower.Stop()
}
// Wait for shutdown signal from either a graceful server stop or from
// the interrupt handler.
<-signal.ShutdownChannel()
return nil
}
// getTLSConfig returns a TLS configuration for the gRPC server and credentials
// and a proxy destination for the REST reverse proxy.
func getTLSConfig(tlsCertPath string, tlsKeyPath string, tlsExtraIPs,
tlsExtraDomains []string, rpcListeners []net.Addr) (*tls.Config,
*credentials.TransportCredentials, string, error) {
// Ensure we create TLS key and certificate if they don't exist
if !fileExists(tlsCertPath) && !fileExists(tlsKeyPath) {
err := genCertPair(
tlsCertPath, tlsKeyPath, tlsExtraIPs, tlsExtraDomains,
)
if err != nil {
return nil, nil, "", err
}
}
certData, err := tls.LoadX509KeyPair(tlsCertPath, tlsKeyPath)
if err != nil {
return nil, nil, "", err
}
cert, err := x509.ParseCertificate(certData.Certificate[0])
if err != nil {
return nil, nil, "", err
}
// If the certificate expired, delete it and the TLS key and generate a new pair
if time.Now().After(cert.NotAfter) {
ltndLog.Info("TLS certificate is expired, generating a new one")
err := os.Remove(tlsCertPath)
if err != nil {
return nil, nil, "", err
}
err = os.Remove(tlsKeyPath)
if err != nil {
return nil, nil, "", err
}
err = genCertPair(
tlsCertPath, tlsKeyPath, tlsExtraIPs, tlsExtraDomains,
)
if err != nil {
return nil, nil, "", err
}
}
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{certData},
CipherSuites: tlsCipherSuites,
MinVersion: tls.VersionTLS12,
}
restCreds, err := credentials.NewClientTLSFromFile(tlsCertPath, "")
if err != nil {
return nil, nil, "", err
}
restProxyDest := 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,
)
}
return tlsCfg, &restCreds, restProxyDest, nil
}
// fileExists reports whether the named file or directory exists.
// This function is taken from https://github.com/btgsuite/btgd
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// genCertPair generates a key/cert pair to the paths provided. The
// auto-generated certificates should *not* be used in production for public
// access as they're self-signed and don't necessarily contain all of the
// desired hostnames for the service. For production/public use, consider a
// real PKI.
//
// This function is adapted from https://github.com/btgsuite/btgd and
// https://github.com/btgsuite/btgutil
func genCertPair(certFile, keyFile string, tlsExtraIPs,
tlsExtraDomains []string) error {
rpcsLog.Infof("Generating TLS certificates...")
org := "lnd autogenerated cert"
now := time.Now()
validUntil := now.Add(autogenCertValidity)
// Check that the certificate validity isn't past the ASN.1 end of time.
if validUntil.After(endOfTime) {
validUntil = endOfTime
}
// Generate a serial number that's below the serialNumberLimit.
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %s", err)
}
// Collect the host's IP addresses, including loopback, in a slice.
ipAddresses := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
// addIP appends an IP address only if it isn't already in the slice.
addIP := func(ipAddr net.IP) {
for _, ip := range ipAddresses {
if bytes.Equal(ip, ipAddr) {
return
}
}
ipAddresses = append(ipAddresses, ipAddr)
}
// Add all the interface IPs that aren't already in the slice.
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, a := range addrs {
ipAddr, _, err := net.ParseCIDR(a.String())
if err == nil {
addIP(ipAddr)
}
}
// Add extra IPs to the slice.
for _, ip := range tlsExtraIPs {
ipAddr := net.ParseIP(ip)
if ipAddr != nil {
addIP(ipAddr)
}
}
// Collect the host's names into a slice.
host, err := os.Hostname()
if err != nil {
rpcsLog.Errorf("Failed getting hostname, falling back to "+
"localhost: %v", err)
host = "localhost"
}
dnsNames := []string{host}
if host != "localhost" {
dnsNames = append(dnsNames, "localhost")
}
dnsNames = append(dnsNames, tlsExtraDomains...)
// Also add fake hostnames for unix sockets, otherwise hostname
// verification will fail in the client.
dnsNames = append(dnsNames, "unix", "unixpacket")
// Generate a private key for the certificate.
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
// Construct the certificate template.
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{org},
CommonName: host,
},
NotBefore: now.Add(-time.Hour * 24),
NotAfter: validUntil,
KeyUsage: x509.KeyUsageKeyEncipherment |
x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
IsCA: true, // so can sign self.
BasicConstraintsValid: true,
DNSNames: dnsNames,
IPAddresses: ipAddresses,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template,
&template, &priv.PublicKey, priv)
if err != nil {
return fmt.Errorf("failed to create certificate: %v", err)
}
certBuf := &bytes.Buffer{}
err = pem.Encode(certBuf, &pem.Block{Type: "CERTIFICATE",
Bytes: derBytes})
if err != nil {
return fmt.Errorf("failed to encode certificate: %v", err)
}
keybytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return fmt.Errorf("unable to encode privkey: %v", err)
}
keyBuf := &bytes.Buffer{}
err = pem.Encode(keyBuf, &pem.Block{Type: "EC PRIVATE KEY",
Bytes: keybytes})
if err != nil {
return fmt.Errorf("failed to encode private key: %v", err)
}
// Write cert and key files.
if err = ioutil.WriteFile(certFile, certBuf.Bytes(), 0644); err != nil {
return err
}
if err = ioutil.WriteFile(keyFile, keyBuf.Bytes(), 0600); err != nil {
os.Remove(certFile)
return err
}
rpcsLog.Infof("Done generating TLS certificates")
return nil
}
// 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.
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.
invoiceMac, err := svc.Oven.NewMacaroon(
ctx, bakery.LatestVersion, nil, invoicePermissions...,
)
if err != nil {
return err
}
invoiceMacBytes, err := invoiceMac.M().MarshalBinary()
if err != nil {
return err
}
err = ioutil.WriteFile(invoiceFile, invoiceMacBytes, 0644)
if err != nil {
os.Remove(invoiceFile)
return err
}
// Generate the read-only macaroon and write it to a file.
roMacaroon, err := svc.Oven.NewMacaroon(
ctx, bakery.LatestVersion, nil, readPermissions...,
)
if err != nil {
return err
}
roBytes, err := roMacaroon.M().MarshalBinary()
if err != nil {
return err
}
if err = ioutil.WriteFile(roFile, roBytes, 0644); err != nil {
os.Remove(admFile)
return err
}
// Generate the admin macaroon and write it to a file.
adminPermissions := append(readPermissions, writePermissions...)
admMacaroon, err := svc.Oven.NewMacaroon(
ctx, bakery.LatestVersion, nil, adminPermissions...,
)
if err != nil {
return err
}
admBytes, err := admMacaroon.M().MarshalBinary()
if err != nil {
return err
}
if err = ioutil.WriteFile(admFile, admBytes, 0600); err != nil {
return err
}
return nil
}
// 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
// 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
// ChansToRestore a set of static channel backups that should be
// restored before the main server instance starts up.
ChansToRestore walletunlocker.ChannelsToRecover
}
// waitForWalletPassword will spin up gRPC and REST endpoints for the
// WalletUnlocker server, and block until a password is provided by
// the user to this RPC server.
func waitForWalletPassword(restEndpoints []net.Addr,
restDialOpts []grpc.DialOption, restProxyDest string,
tlsConf *tls.Config, getListeners rpcListeners) (
*WalletUnlockParams, error) {
// Start a gRPC server listening for HTTP/2 connections, solely used
// for getting the encryption password from the client.
listeners, cleanup, serverOpts, err := getListeners()
if err != nil {
return nil, err
}
defer cleanup()
// Set up a new PasswordService, which will listen for passwords
// provided over RPC.
grpcServer := grpc.NewServer(serverOpts...)
defer grpcServer.GracefulStop()
chainConfig := cfg.Bitcoin
if registeredChains.PrimaryChain() == litecoinChain {
chainConfig = cfg.Litecoin
}
// The macaroon files are passed to the wallet unlocker since they are
// also encrypted with the wallet's password. These files will be
// deleted within it and recreated when successfully changing the
// wallet's password.
macaroonFiles := []string{
filepath.Join(networkDir, macaroons.DBFilename),