-
Notifications
You must be signed in to change notification settings - Fork 82
/
litd_node.go
2060 lines (1727 loc) · 56.3 KB
/
litd_node.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 itest
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/faraday/frdrpc"
terminal "github.com/lightninglabs/lightning-terminal"
"github.com/lightninglabs/lightning-terminal/litrpc"
"github.com/lightninglabs/lightning-terminal/subservers"
"github.com/lightninglabs/loop/looprpc"
"github.com/lightninglabs/pool/poolrpc"
"github.com/lightninglabs/taproot-assets/taprpc"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnrpc/watchtowerrpc"
"github.com/lightningnetwork/lnd/lnrpc/wtclientrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
"github.com/lightningnetwork/lnd/lntest/wait"
"github.com/lightningnetwork/lnd/macaroons"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/macaroon.v2"
)
const (
// logPubKeyBytes is the number of bytes of the node's PubKey that will
// be appended to the log file name. The whole PubKey is too long and
// not really necessary to quickly identify what node produced which
// log file.
logPubKeyBytes = 4
)
var (
// numActiveNodes is the number of active nodes within the test network.
numActiveNodes = 0
numActiveNodesMtx sync.Mutex
defaultLndPassphrase = []byte("default-wallet-password")
)
type LitNodeConfig struct {
*node.BaseNodeConfig
LitArgs []string
ActiveArgs *litArgs
RemoteMode bool
HasSeed bool
FaradayMacPath string
LoopMacPath string
PoolMacPath string
TapMacPath string
LitTLSCertPath string
LitMacPath string
UIPassword string
LitDir string
FaradayDir string
LoopDir string
PoolDir string
TapdDir string
LitPort int
LitRESTPort int
}
func (cfg *LitNodeConfig) LitAddr() string {
return fmt.Sprintf(node.ListenerFormat, cfg.LitPort)
}
func (cfg *LitNodeConfig) LitRESTAddr() string {
return fmt.Sprintf(node.ListenerFormat, cfg.LitRESTPort)
}
func (cfg *LitNodeConfig) GenerateListeningPorts() {
cfg.BaseNodeConfig.GenerateListeningPorts()
if cfg.LitPort == 0 {
cfg.LitPort = node.NextAvailablePort()
}
if cfg.LitRESTPort == 0 {
cfg.LitRESTPort = node.NextAvailablePort()
}
}
// litArgs holds a key-value map of config option to config value. An empty
// string value means that the config option is a boolean.
type litArgs struct {
args map[string]string
mu sync.Mutex
}
// deleteArg deletes the argument with the given name from the set if it is
// present.
func (l *litArgs) deleteArg(argName string) {
l.mu.Lock()
defer l.mu.Unlock()
delete(l.args, argName)
}
// addArg adds a new argument to the set. An empty value string will mean that
// the key will be added as a boolean flag.
func (l *litArgs) addArg(name, value string) {
l.mu.Lock()
defer l.mu.Unlock()
l.args[name] = value
}
// getArg gets the arg with the given name from the set and returns the value.
// The boolean returned will be true if the argument is in the set. If the
// boolean is true but the string is empty, it means it is a boolean config
// flag.
func (l *litArgs) getArg(name string) (string, bool) {
l.mu.Lock()
defer l.mu.Unlock()
value, ok := l.args[name]
return value, ok
}
// toArgList converts the litArgs map to an arguments string slice.
func (l *litArgs) toArgList() []string {
l.mu.Lock()
defer l.mu.Unlock()
args := make([]string, 0, len(l.args))
for arg, setting := range l.args {
if setting == "" {
args = append(args, fmt.Sprintf("--%s", arg))
continue
}
args = append(args, fmt.Sprintf("--%s=%s", arg, setting))
}
return args
}
// LitArgOption defines the signature of a functional option that can be used
// to tweak the default arguments of a Litd node.
type LitArgOption func(args *litArgs)
// WithoutLitArg can be used to delete a litd config option.
func WithoutLitArg(arg string) LitArgOption {
return func(args *litArgs) {
args.deleteArg(arg)
}
}
// WithLitArg can be used to set a Litd config option. An empty value string
// will mean that the key will be added as a boolean flag.
func WithLitArg(key, value string) LitArgOption {
return func(args *litArgs) {
args.addArg(key, value)
}
}
// GenArgs generates a slice of command line arguments from the lightning node
// config struct.
func (cfg *LitNodeConfig) GenArgs(opts ...LitArgOption) []string {
args := cfg.defaultLitdArgs()
for _, opt := range opts {
opt(args)
}
cfg.ActiveArgs = args
return args.toArgList()
}
// defaultLitArgs generates the default arguments to be used with a Litd node.
func (cfg *LitNodeConfig) defaultLitdArgs() *litArgs {
var (
args = map[string]string{
"httpslisten": cfg.LitAddr(),
"insecure-httplisten": cfg.LitRESTAddr(),
"lit-dir": cfg.LitDir,
"faraday.faradaydir": cfg.FaradayDir,
"loop.loopdir": cfg.LoopDir,
"pool.basedir": cfg.PoolDir,
"taproot-assets.tapddir": cfg.TapdDir,
"taproot-assets-mode": "integrated",
"uipassword": cfg.UIPassword,
"enablerest": "",
"restcors": "*",
}
)
for _, arg := range cfg.LitArgs {
parts := strings.Split(arg, "=")
option := strings.TrimLeft(parts[0], "--")
switch len(parts) {
case 1:
args[option] = ""
case 2:
args[option] = parts[1]
}
}
switch cfg.NetParams {
case &chaincfg.TestNet3Params:
args["network"] = "testnet"
case &chaincfg.SimNetParams:
args["network"] = "simnet"
case &chaincfg.RegressionNetParams:
args["network"] = "regtest"
}
// In remote mode, we don't need any lnd specific arguments other than
// those we need to connect.
if cfg.RemoteMode {
args["lnd-mode"] = "remote"
args["remote.lnd.rpcserver"] = cfg.RPCAddr()
args["remote.lnd.tlscertpath"] = cfg.TLSCertPath
args["remote.lnd.macaroonpath"] = cfg.AdminMacPath
return &litArgs{args: args}
}
// All arguments so far were for lnd. Let's namespace them now so we can
// add args for the other daemons and LiT itself afterwards.
args["lnd-mode"] = "integrated"
lndArgs := cfg.BaseNodeConfig.GenArgs()
for idx := range lndArgs {
arg := strings.ReplaceAll(lndArgs[idx], "--", "--lnd.")
parts := strings.Split(arg, "=")
option := strings.TrimLeft(parts[0], "--")
switch len(parts) {
case 1:
args[option] = ""
case 2:
args[option] = parts[1]
}
}
return &litArgs{args: args}
}
// policyUpdateMap defines a type to store channel policy updates. It has the
// format,
//
// {
// "chanPoint1": {
// "advertisingNode1": [
// policy1, policy2, ...
// ],
// "advertisingNode2": [
// policy1, policy2, ...
// ]
// },
// "chanPoint2": ...
// }
type policyUpdateMap map[string]map[string][]*lnrpc.RoutingPolicy
// HarnessNode represents an instance of lnd running within our test network
// harness. Each HarnessNode instance also fully embeds an RPC client in
// order to pragmatically drive the node.
type HarnessNode struct {
Cfg *LitNodeConfig
// NodeID is a unique identifier for the node within a NetworkHarness.
NodeID int
RemoteLnd *node.HarnessNode
// PubKey is the serialized compressed identity public key of the node.
// This field will only be populated once the node itself has been
// started via the start() method.
PubKey [33]byte
PubKeyStr string
cmd *exec.Cmd
pidFile string
logFile *os.File
// processExit is a channel that's closed once it's detected that the
// process this instance of HarnessNode is bound to has exited.
processExit chan struct{}
chanWatchRequests chan *chanWatchRequest
// For each outpoint, we'll track an integer which denotes the number of
// edges seen for that channel within the network. When this number
// reaches 2, then it means that both edge advertisements has propagated
// through the network.
openChans map[wire.OutPoint]int
openChanWatchers map[wire.OutPoint][]chan struct{}
closedChans map[wire.OutPoint]struct{}
closeChanWatchers map[wire.OutPoint][]chan struct{}
// policyUpdates stores a slice of seen polices by each advertising
// node and the outpoint.
policyUpdates policyUpdateMap
quit chan struct{}
wg sync.WaitGroup
lnrpc.LightningClient
lnrpc.WalletUnlockerClient
invoicesrpc.InvoicesClient
// SignerClient cannot be embedded because the name collisions of the
// methods SignMessage and VerifyMessage.
SignerClient signrpc.SignerClient
// conn is the underlying connection to the lnd grpc endpoint of the
// node.
conn *grpc.ClientConn
// litConn is the underlying connection to Lit's grpc endpoint.
litConn *grpc.ClientConn
// RouterClient, WalletKitClient, WatchtowerClient cannot be embedded,
// because a name collision would occur with LightningClient.
RouterClient routerrpc.RouterClient
WalletKitClient walletrpc.WalletKitClient
Watchtower watchtowerrpc.WatchtowerClient
WatchtowerClient wtclientrpc.WatchtowerClientClient
StateClient lnrpc.StateClient
// backupDbDir is the path where a database backup is stored, if any.
backupDbDir string
}
// Assert *HarnessNode implements the lnrpc.LightningClient interface.
var _ lnrpc.LightningClient = (*HarnessNode)(nil)
var _ lnrpc.WalletUnlockerClient = (*HarnessNode)(nil)
var _ invoicesrpc.InvoicesClient = (*HarnessNode)(nil)
// NewNode creates a new test lightning node instance from the passed config.
func NewNode(t *testing.T, cfg *LitNodeConfig,
harness *lntest.HarnessTest) (*HarnessNode, error) {
if cfg.BaseDir == "" {
var err error
cfg.BaseDir, err = os.MkdirTemp("", "litdtest-node")
if err != nil {
return nil, err
}
}
cfg.DataDir = filepath.Join(cfg.BaseDir, "data")
cfg.LogDir = filepath.Join(cfg.BaseDir, "log")
cfg.LitDir = filepath.Join(cfg.BaseDir, "lit")
cfg.FaradayDir = filepath.Join(cfg.LitDir, "faraday")
cfg.LoopDir = filepath.Join(cfg.LitDir, "loop")
cfg.PoolDir = filepath.Join(cfg.LitDir, "pool")
cfg.TapdDir = filepath.Join(cfg.LitDir, "tapd")
cfg.TLSCertPath = filepath.Join(cfg.BaseDir, "tls.cert")
cfg.TLSKeyPath = filepath.Join(cfg.BaseDir, "tls.key")
networkDir := filepath.Join(
cfg.DataDir, "chain", "bitcoin", cfg.NetParams.Name,
)
cfg.AdminMacPath = filepath.Join(networkDir, "admin.macaroon")
cfg.ReadMacPath = filepath.Join(networkDir, "readonly.macaroon")
cfg.InvoiceMacPath = filepath.Join(networkDir, "invoice.macaroon")
cfg.FaradayMacPath = filepath.Join(
cfg.FaradayDir, cfg.NetParams.Name, "faraday.macaroon",
)
cfg.LoopMacPath = filepath.Join(
cfg.LoopDir, cfg.NetParams.Name, "loop.macaroon",
)
cfg.PoolMacPath = filepath.Join(
cfg.PoolDir, cfg.NetParams.Name, "pool.macaroon",
)
cfg.TapMacPath = filepath.Join(
cfg.TapdDir, "data", cfg.NetParams.Name, "admin.macaroon",
)
cfg.LitMacPath = filepath.Join(
cfg.LitDir, cfg.NetParams.Name, "lit.macaroon",
)
cfg.LitTLSCertPath = filepath.Join(cfg.LitDir, "tls.cert")
cfg.GenerateListeningPorts()
// Generate a random UI password by reading 16 random bytes and base64
// encoding them.
var randomBytes [16]byte
_, _ = rand.Read(randomBytes[:])
cfg.UIPassword = base64.URLEncoding.EncodeToString(randomBytes[:])
numActiveNodesMtx.Lock()
nodeNum := numActiveNodes
numActiveNodes++
numActiveNodesMtx.Unlock()
var remoteNode *node.HarnessNode
if cfg.RemoteMode {
lndHarness := harness
remoteNode = lndHarness.NewNode("bob-custom", cfg.ExtraArgs)
tenBTC := btcutil.Amount(10 * btcutil.SatoshiPerBitcoin)
lndHarness.FundCoins(tenBTC, remoteNode)
cfg.RPCPort = remoteNode.Cfg.RPCPort
cfg.P2PPort = remoteNode.Cfg.P2PPort
cfg.TLSCertPath = remoteNode.Cfg.TLSCertPath
cfg.AdminMacPath = remoteNode.Cfg.AdminMacPath
}
t.Logf("Created new node %s with p2p port %d", cfg.Name, cfg.P2PPort)
return &HarnessNode{
Cfg: cfg,
NodeID: nodeNum,
RemoteLnd: remoteNode,
chanWatchRequests: make(chan *chanWatchRequest),
openChans: make(map[wire.OutPoint]int),
openChanWatchers: make(map[wire.OutPoint][]chan struct{}),
closedChans: make(map[wire.OutPoint]struct{}),
closeChanWatchers: make(map[wire.OutPoint][]chan struct{}),
policyUpdates: policyUpdateMap{},
}, nil
}
// String gives the internal state of the node which is useful for debugging.
func (hn *HarnessNode) String() string {
type nodeCfg struct {
LogFilenamePrefix string
ExtraArgs []string
HasSeed bool
P2PPort int
RPCPort int
RESTPort int
ProfilePort int
AcceptKeySend bool
AcceptAMP bool
FeeURL string
}
nodeState := struct {
NodeID int
Name string
PubKey string
OpenChans map[string]int
ClosedChans map[string]struct{}
NodeCfg nodeCfg
}{
NodeID: hn.NodeID,
Name: hn.Cfg.Name,
PubKey: hn.PubKeyStr,
OpenChans: make(map[string]int),
ClosedChans: make(map[string]struct{}),
NodeCfg: nodeCfg{
LogFilenamePrefix: hn.Cfg.LogFilenamePrefix,
ExtraArgs: hn.Cfg.ExtraArgs,
HasSeed: hn.Cfg.HasSeed,
P2PPort: hn.Cfg.P2PPort,
RPCPort: hn.Cfg.RPCPort,
RESTPort: hn.Cfg.RESTPort,
FeeURL: hn.Cfg.FeeURL,
},
}
for outpoint, count := range hn.openChans {
nodeState.OpenChans[outpoint.String()] = count
}
for outpoint, count := range hn.closedChans {
nodeState.ClosedChans[outpoint.String()] = count
}
b, err := json.MarshalIndent(nodeState, "", "\t")
if err != nil {
return fmt.Sprintf("\n encode node state with err: %v", err)
}
return fmt.Sprintf("\nnode state: %s", b)
}
// DBPath returns the filepath to the channeldb database file for this node.
func (hn *HarnessNode) DBPath() string {
return hn.Cfg.DBPath()
}
// DBDir returns the path for the directory holding channeldb file(s).
func (hn *HarnessNode) DBDir() string {
return hn.Cfg.DBDir()
}
// Name returns the name of this node set during initialization.
func (hn *HarnessNode) Name() string {
return hn.Cfg.Name
}
// TLSCertStr returns the path where the TLS certificate is stored.
func (hn *HarnessNode) TLSCertStr() string {
return hn.Cfg.TLSCertPath
}
// TLSKeyStr returns the path where the TLS key is stored.
func (hn *HarnessNode) TLSKeyStr() string {
return hn.Cfg.TLSKeyPath
}
// ChanBackupPath returns the fielpath to the on-disk channel.backup file for
// this node.
func (hn *HarnessNode) ChanBackupPath() string {
return hn.Cfg.ChanBackupPath()
}
// AdminMacPath returns the filepath to the admin.macaroon file for this node.
func (hn *HarnessNode) AdminMacPath() string {
return hn.Cfg.AdminMacPath
}
// ReadMacPath returns the filepath to the readonly.macaroon file for this node.
func (hn *HarnessNode) ReadMacPath() string {
return hn.Cfg.ReadMacPath
}
// InvoiceMacPath returns the filepath to the invoice.macaroon file for this
// node.
func (hn *HarnessNode) InvoiceMacPath() string {
return hn.Cfg.InvoiceMacPath
}
// renameFile is a helper to rename (log) files created during integration tests.
func renameFile(fromFileName, toFileName string) {
err := os.Rename(fromFileName, toFileName)
if err != nil {
fmt.Printf("could not rename %s to %s: %v\n",
fromFileName, toFileName, err)
}
}
// Start launches a new process running lnd. Additionally, the PID of the
// launched process is saved in order to possibly kill the process forcibly
// later.
//
// This may not clean up properly if an error is returned, so the caller should
// call shutdown() regardless of the return value.
func (hn *HarnessNode) Start(litdBinary string, litdError chan<- error,
waitForStart bool, litArgOpts ...LitArgOption) error {
hn.quit = make(chan struct{})
args := hn.Cfg.GenArgs(litArgOpts...)
hn.cmd = exec.Command(litdBinary, args...)
// Redirect stderr output to buffer
var errb bytes.Buffer
hn.cmd.Stderr = &errb
// Make sure the log file cleanup function is initialized, even
// if no log file is created.
var finalizeLogfile = func() {
if hn.logFile != nil {
_ = hn.logFile.Close()
}
}
getFinalizedLogFilePrefix := func() string {
pubKeyHex := hex.EncodeToString(hn.PubKey[:logPubKeyBytes])
return fmt.Sprintf("%s/%d-%s-%s-%s", node.GetLogDir(),
hn.NodeID, hn.Cfg.LogFilenamePrefix, hn.Cfg.Name,
pubKeyHex)
}
// If the logoutput flag is passed, redirect output from the nodes to
// log files.
dir := node.GetLogDir()
fileName := fmt.Sprintf("%s/%d-%s-%s-%s.log", dir, hn.NodeID,
hn.Cfg.LogFilenamePrefix, hn.Cfg.Name,
hex.EncodeToString(hn.PubKey[:logPubKeyBytes]))
// If the node's PubKey is not yet initialized, create a
// temporary file name. Later, after the PubKey has been
// initialized, the file can be moved to its final name with
// the PubKey included.
if bytes.Equal(hn.PubKey[:4], []byte{0, 0, 0, 0}) {
fileName = fmt.Sprintf("%s/%d-%s-%s-tmp__.log", dir,
hn.NodeID, hn.Cfg.LogFilenamePrefix, hn.Cfg.Name)
}
// Once the node has done its work, the log file can be
// renamed.
finalizeLogfile = func() {
if hn.logFile != nil {
_ = hn.logFile.Close()
newFileName := fmt.Sprintf("%v.log",
getFinalizedLogFilePrefix(),
)
renameFile(fileName, newFileName)
}
}
// Create file if not exists, otherwise append.
file, err := os.OpenFile(fileName,
os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666,
)
if err != nil {
return err
}
// Pass node's stderr to both errb and the file.
w := io.MultiWriter(&errb, file)
hn.cmd.Stderr = w
// Pass the node's stdout only to the file.
hn.cmd.Stdout = file
// Let the node keep a reference to this file, such
// that we can add to it if necessary.
hn.logFile = file
if err := hn.cmd.Start(); err != nil {
return err
}
// Launch a new goroutine which that bubbles up any potential fatal
// process errors to the goroutine running the tests.
hn.processExit = make(chan struct{})
hn.wg.Add(1)
go func() {
defer hn.wg.Done()
err := hn.cmd.Wait()
if err != nil {
litdError <- fmt.Errorf("%v\n%v\n", err, errb.String())
}
// Signal any onlookers that this process has exited.
close(hn.processExit)
// Make sure log file is closed and renamed if necessary.
finalizeLogfile()
}()
// We may want to skip waiting for the node to come up (eg. the node
// is waiting to become the leader).
if !waitForStart {
return nil
}
// Since Stop uses the LightningClient to stop the node, if we fail to get a
// connected client, we have to kill the process.
useMacaroons := !hn.Cfg.HasSeed
conn, err := hn.ConnectRPC(useMacaroons)
if err != nil {
_ = hn.cmd.Process.Kill()
return err
}
if err := hn.WaitUntilStarted(conn, lntest.DefaultTimeout); err != nil {
return err
}
// If the node was created with a seed, we will need to perform an
// additional step to unlock the wallet. The connection returned will
// only use the TLS certs, and can only perform operations necessary to
// unlock the daemon.
if hn.Cfg.HasSeed {
hn.WalletUnlockerClient = lnrpc.NewWalletUnlockerClient(conn)
return nil
}
err = hn.initLightningClient(conn)
if err != nil {
return fmt.Errorf("could not init Lightning Client: %w", err)
}
// Also connect to Lit's RPC port for any Litd specific calls.
litConn, err := connectLitRPC(
context.Background(), hn.Cfg.LitAddr(), hn.Cfg.LitTLSCertPath,
hn.Cfg.LitMacPath,
)
if err != nil {
return fmt.Errorf("could not connect to Lit RPC: %w", err)
}
hn.litConn = litConn
ctxt, cancel := context.WithTimeout(
context.Background(), lntest.DefaultTimeout,
)
defer cancel()
return wait.NoError(func() error {
litConn := litrpc.NewProxyClient(hn.litConn)
_, err = litConn.GetInfo(ctxt, &litrpc.GetInfoRequest{})
return err
}, lntest.DefaultTimeout)
}
// WaitUntilStarted waits until the wallet state flips from "WAITING_TO_START".
func (hn *HarnessNode) WaitUntilStarted(conn grpc.ClientConnInterface,
timeout time.Duration) error {
// First wait for Litd status server to show that LND has started.
ctx := context.Background()
rawConn, err := connectLitRPC(
ctx, hn.Cfg.LitAddr(), hn.Cfg.LitTLSCertPath, "",
)
if err != nil {
return err
}
litConn := litrpc.NewStatusClient(rawConn)
err = wait.NoError(func() error {
states, err := litConn.SubServerStatus(
ctx, &litrpc.SubServerStatusReq{},
)
if err != nil {
return err
}
lndStatus, ok := states.SubServers[subservers.LND]
if !ok || !lndStatus.Running {
return fmt.Errorf("LND has not yet started")
}
return nil
}, lntest.DefaultTimeout)
if err != nil {
return err
}
err = hn.waitForState(conn, timeout, func(s lnrpc.WalletState) bool {
return s >= lnrpc.WalletState_SERVER_ACTIVE
})
if err != nil {
return err
}
faradayMode, _ := hn.Cfg.ActiveArgs.getArg("faraday-mode")
loopMode, _ := hn.Cfg.ActiveArgs.getArg("loop-mode")
poolMode, _ := hn.Cfg.ActiveArgs.getArg("pool-mode")
tapMode, _ := hn.Cfg.ActiveArgs.getArg("taproot-assets-mode")
ctxt, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return wait.NoError(func() error {
if faradayMode != terminal.ModeDisable {
faradayClient, err := hn.faradayClient()
if err != nil {
return err
}
_, err = faradayClient.RevenueReport(
ctxt, &frdrpc.RevenueReportRequest{},
)
if err != nil {
return err
}
}
if loopMode != terminal.ModeDisable {
loopClient, err := hn.loopClient()
if err != nil {
return err
}
_, err = loopClient.ListSwaps(
ctxt, &looprpc.ListSwapsRequest{},
)
if err != nil {
return err
}
}
if poolMode != terminal.ModeDisable {
poolClient, err := hn.poolClient()
if err != nil {
return err
}
_, err = poolClient.GetInfo(
ctxt, &poolrpc.GetInfoRequest{},
)
if err != nil {
return err
}
}
if tapMode != terminal.ModeDisable {
tapClient, err := hn.tapClient()
if err != nil {
return err
}
_, err = tapClient.ListAssets(
ctxt, &taprpc.ListAssetRequest{},
)
if err != nil {
return err
}
}
return nil
}, timeout)
}
func (hn *HarnessNode) faradayClient() (frdrpc.FaradayServerClient, error) {
mac, err := hn.ReadMacaroon(
hn.Cfg.FaradayMacPath, lntest.DefaultTimeout,
)
if err != nil {
return nil, err
}
conn, err := hn.ConnectRPCWithMacaroon(mac)
if err != nil {
return nil, err
}
return frdrpc.NewFaradayServerClient(conn), nil
}
func (hn *HarnessNode) loopClient() (looprpc.SwapClientClient, error) {
mac, err := hn.ReadMacaroon(hn.Cfg.LoopMacPath, lntest.DefaultTimeout)
if err != nil {
return nil, err
}
conn, err := hn.ConnectRPCWithMacaroon(mac)
if err != nil {
return nil, err
}
return looprpc.NewSwapClientClient(conn), nil
}
func (hn *HarnessNode) poolClient() (poolrpc.TraderClient, error) {
mac, err := hn.ReadMacaroon(hn.Cfg.PoolMacPath, lntest.DefaultTimeout)
if err != nil {
return nil, err
}
conn, err := hn.ConnectRPCWithMacaroon(mac)
if err != nil {
return nil, err
}
return poolrpc.NewTraderClient(conn), nil
}
func (hn *HarnessNode) tapClient() (taprpc.TaprootAssetsClient, error) {
mac, err := hn.ReadMacaroon(hn.Cfg.TapMacPath, lntest.DefaultTimeout)
if err != nil {
return nil, err
}
conn, err := hn.ConnectRPCWithMacaroon(mac)
if err != nil {
return nil, err
}
return taprpc.NewTaprootAssetsClient(conn), nil
}
// waitForState waits until the current node state fulfills the given
// predicate.
func (hn *HarnessNode) waitForState(conn grpc.ClientConnInterface,
timeout time.Duration,
predicate func(state lnrpc.WalletState) bool) error {
stateClient := lnrpc.NewStateClient(conn)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var (
stateStream lnrpc.State_SubscribeStateClient
err error
)
subscribeFunc := func() error {
stateStream, err = stateClient.SubscribeState(
ctx, &lnrpc.SubscribeStateRequest{},
)
return err
}
err = wait.NoError(subscribeFunc, lntest.DefaultTimeout)
if err != nil {
return err
}
errChan := make(chan error, 1)
started := make(chan struct{})
go func() {
for {
resp, err := stateStream.Recv()
if err != nil {
errChan <- err
return
}
if predicate(resp.State) {
close(started)
return
}
}
}()
select {
case <-started:
case err = <-errChan:
case <-time.After(timeout):
return fmt.Errorf("WaitUntilLeader timed out")
}
return err
}
// initClientWhenReady waits until the main gRPC server is detected as active,
// then complete the normal HarnessNode gRPC connection creation. This can be
// used it a node has just been unlocked, or has its wallet state initialized.
func (hn *HarnessNode) initClientWhenReady(timeout time.Duration) error {
var (
conn *grpc.ClientConn
connErr error
)
if err := wait.NoError(func() error {
conn, connErr = hn.ConnectRPC(true)
return connErr
}, timeout); err != nil {
return err
}
return hn.initLightningClient(conn)
}
// Init initializes a harness node by passing the init request via rpc. After
// the request is submitted, this method will block until a
// macaroon-authenticated RPC connection can be established to the harness node.
// Once established, the new connection is used to initialize the
// LightningClient and subscribes the HarnessNode to topology changes.
func (hn *HarnessNode) Init(ctx context.Context,
initReq *lnrpc.InitWalletRequest) (*lnrpc.InitWalletResponse, error) {
ctxt, cancel := context.WithTimeout(ctx, lntest.DefaultTimeout)
defer cancel()
response, err := hn.InitWallet(ctxt, initReq)
if err != nil {
return nil, err
}
// Wait for the wallet to finish unlocking, such that we can connect to
// it via a macaroon-authenticated rpc connection.
var conn *grpc.ClientConn
if err = wait.Predicate(func() bool {
// If the node has been initialized stateless, we need to pass
// the macaroon to the client.
if initReq.StatelessInit {
adminMac := &macaroon.Macaroon{}
err := adminMac.UnmarshalBinary(response.AdminMacaroon)
if err != nil {
return false
}
conn, err = hn.ConnectRPCWithMacaroon(adminMac)
return err == nil
}
// Normal initialization, we expect a macaroon to be in the
// file system.
conn, err = hn.ConnectRPC(true)
return err == nil
}, lntest.DefaultTimeout); err != nil {
return nil, err
}