forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
commands.go
3292 lines (2845 loc) · 82.3 KB
/
commands.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 main
import (
"bufio"
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"strconv"
"strings"
"sync"
"syscall"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// TODO(roasbeef): cli logic for supporting both positional and unix style
// arguments.
// TODO(roasbeef): expose all fee conf targets
const defaultRecoveryWindow int32 = 250
func printJSON(resp interface{}) {
b, err := json.Marshal(resp)
if err != nil {
fatal(err)
}
var out bytes.Buffer
json.Indent(&out, b, "", "\t")
out.WriteString("\n")
out.WriteTo(os.Stdout)
}
func printRespJSON(resp proto.Message) {
jsonMarshaler := &jsonpb.Marshaler{
EmitDefaults: true,
Indent: " ",
}
jsonStr, err := jsonMarshaler.MarshalToString(resp)
if err != nil {
fmt.Println("unable to decode response: ", err)
return
}
fmt.Println(jsonStr)
}
// actionDecorator is used to add additional information and error handling
// to command actions.
func actionDecorator(f func(*cli.Context) error) func(*cli.Context) error {
return func(c *cli.Context) error {
if err := f(c); err != nil {
s, ok := status.FromError(err)
// If it's a command for the UnlockerService (like
// 'create' or 'unlock') but the wallet is already
// unlocked, then these methods aren't recognized any
// more because this service is shut down after
// successful unlock. That's why the code
// 'Unimplemented' means something different for these
// two commands.
if s.Code() == codes.Unimplemented &&
(c.Command.Name == "create" ||
c.Command.Name == "unlock") {
return fmt.Errorf("Wallet is already unlocked")
}
// lnd might be active, but not possible to contact
// using RPC if the wallet is encrypted. If we get
// error code Unimplemented, it means that lnd is
// running, but the RPC server is not active yet (only
// WalletUnlocker server active) and most likely this
// is because of an encrypted wallet.
if ok && s.Code() == codes.Unimplemented {
return fmt.Errorf("Wallet is encrypted. " +
"Please unlock using 'lncli unlock', " +
"or set password using 'lncli create'" +
" if this is the first time starting " +
"lnd.")
}
return err
}
return nil
}
}
var newAddressCommand = cli.Command{
Name: "newaddress",
Category: "Wallet",
Usage: "Generates a new address.",
ArgsUsage: "address-type",
Description: `
Generate a wallet new address. Address-types has to be one of:
- p2wkh: Pay to witness key hash
- np2wkh: Pay to nested witness key hash`,
Action: actionDecorator(newAddress),
}
func newAddress(ctx *cli.Context) error {
client, cleanUp := getClient(ctx)
defer cleanUp()
stringAddrType := ctx.Args().First()
// Map the string encoded address type, to the concrete typed address
// type enum. An unrecognized address type will result in an error.
var addrType lnrpc.NewAddressRequest_AddressType
switch stringAddrType { // TODO(roasbeef): make them ints on the cli?
case "p2wkh":
addrType = lnrpc.NewAddressRequest_WITNESS_PUBKEY_HASH
case "np2wkh":
addrType = lnrpc.NewAddressRequest_NESTED_PUBKEY_HASH
default:
return fmt.Errorf("invalid address type %v, support address type "+
"are: p2wkh and np2wkh", stringAddrType)
}
ctxb := context.Background()
addr, err := client.NewAddress(ctxb, &lnrpc.NewAddressRequest{
Type: addrType,
})
if err != nil {
return err
}
printRespJSON(addr)
return nil
}
var sendCoinsCommand = cli.Command{
Name: "sendcoins",
Category: "On-chain",
Usage: "Send bitcoin on-chain to an address.",
ArgsUsage: "addr amt",
Description: `
Send amt coins in satoshis to the BASE58 encoded bitcoin address addr.
Fees used when sending the transaction can be specified via the --conf_target, or
--sat_per_byte optional flags.
Positional arguments and flags can be used interchangeably but not at the same time!
`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "addr",
Usage: "the BASE58 encoded bitcoin address to send coins to on-chain",
},
// TODO(roasbeef): switch to BTC on command line? int may not be sufficient
cli.Int64Flag{
Name: "amt",
Usage: "the number of bitcoin denominated in satoshis to send",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation",
},
cli.Int64Flag{
Name: "sat_per_byte",
Usage: "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction",
},
},
Action: actionDecorator(sendCoins),
}
func sendCoins(ctx *cli.Context) error {
var (
addr string
amt int64
err error
)
args := ctx.Args()
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
cli.ShowCommandHelp(ctx, "sendcoins")
return nil
}
if ctx.IsSet("conf_target") && ctx.IsSet("sat_per_byte") {
return fmt.Errorf("either conf_target or sat_per_byte should be " +
"set, but not both")
}
switch {
case ctx.IsSet("addr"):
addr = ctx.String("addr")
case args.Present():
addr = args.First()
args = args.Tail()
default:
return fmt.Errorf("Address argument missing")
}
switch {
case ctx.IsSet("amt"):
amt = ctx.Int64("amt")
case args.Present():
amt, err = strconv.ParseInt(args.First(), 10, 64)
default:
return fmt.Errorf("Amount argument missing")
}
if err != nil {
return fmt.Errorf("unable to decode amount: %v", err)
}
ctxb := context.Background()
client, cleanUp := getClient(ctx)
defer cleanUp()
req := &lnrpc.SendCoinsRequest{
Addr: addr,
Amount: amt,
TargetConf: int32(ctx.Int64("conf_target")),
SatPerByte: ctx.Int64("sat_per_byte"),
}
txid, err := client.SendCoins(ctxb, req)
if err != nil {
return err
}
printRespJSON(txid)
return nil
}
var sendManyCommand = cli.Command{
Name: "sendmany",
Category: "On-chain",
Usage: "Send bitcoin on-chain to multiple addresses.",
ArgsUsage: "send-json-string [--conf_target=N] [--sat_per_byte=P]",
Description: `
Create and broadcast a transaction paying the specified amount(s) to the passed address(es).
The send-json-string' param decodes addresses and the amount to send
respectively in the following format:
'{"ExampleAddr": NumCoinsInSatoshis, "SecondAddr": NumCoins}'
`,
Flags: []cli.Flag{
cli.Int64Flag{
Name: "conf_target",
Usage: "(optional) the number of blocks that the transaction *should* " +
"confirm in, will be used for fee estimation",
},
cli.Int64Flag{
Name: "sat_per_byte",
Usage: "(optional) a manual fee expressed in sat/byte that should be " +
"used when crafting the transaction",
},
},
Action: actionDecorator(sendMany),
}
func sendMany(ctx *cli.Context) error {
var amountToAddr map[string]int64
jsonMap := ctx.Args().First()
if err := json.Unmarshal([]byte(jsonMap), &amountToAddr); err != nil {
return err
}
if ctx.IsSet("conf_target") && ctx.IsSet("sat_per_byte") {
return fmt.Errorf("either conf_target or sat_per_byte should be " +
"set, but not both")
}
ctxb := context.Background()
client, cleanUp := getClient(ctx)
defer cleanUp()
txid, err := client.SendMany(ctxb, &lnrpc.SendManyRequest{
AddrToAmount: amountToAddr,
TargetConf: int32(ctx.Int64("conf_target")),
SatPerByte: ctx.Int64("sat_per_byte"),
})
if err != nil {
return err
}
printRespJSON(txid)
return nil
}
var connectCommand = cli.Command{
Name: "connect",
Category: "Peers",
Usage: "Connect to a remote lnd peer.",
ArgsUsage: "<pubkey>@host",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "perm",
Usage: "If set, the daemon will attempt to persistently " +
"connect to the target peer.\n" +
" If not, the call will be synchronous.",
},
},
Action: actionDecorator(connectPeer),
}
func connectPeer(ctx *cli.Context) error {
ctxb := context.Background()
client, cleanUp := getClient(ctx)
defer cleanUp()
targetAddress := ctx.Args().First()
splitAddr := strings.Split(targetAddress, "@")
if len(splitAddr) != 2 {
return fmt.Errorf("target address expected in format: " +
"pubkey@host:port")
}
addr := &lnrpc.LightningAddress{
Pubkey: splitAddr[0],
Host: splitAddr[1],
}
req := &lnrpc.ConnectPeerRequest{
Addr: addr,
Perm: ctx.Bool("perm"),
}
lnid, err := client.ConnectPeer(ctxb, req)
if err != nil {
return err
}
printRespJSON(lnid)
return nil
}
var disconnectCommand = cli.Command{
Name: "disconnect",
Category: "Peers",
Usage: "Disconnect a remote lnd peer identified by public key.",
ArgsUsage: "<pubkey>",
Flags: []cli.Flag{
cli.StringFlag{
Name: "node_key",
Usage: "The hex-encoded compressed public key of the peer " +
"to disconnect from",
},
},
Action: actionDecorator(disconnectPeer),
}
func disconnectPeer(ctx *cli.Context) error {
ctxb := context.Background()
client, cleanUp := getClient(ctx)
defer cleanUp()
var pubKey string
switch {
case ctx.IsSet("node_key"):
pubKey = ctx.String("node_key")
case ctx.Args().Present():
pubKey = ctx.Args().First()
default:
return fmt.Errorf("must specify target public key")
}
req := &lnrpc.DisconnectPeerRequest{
PubKey: pubKey,
}
lnid, err := client.DisconnectPeer(ctxb, req)
if err != nil {
return err
}
printRespJSON(lnid)
return nil
}
// TODO(roasbeef): change default number of confirmations
var openChannelCommand = cli.Command{
Name: "openchannel",
Category: "Channels",
Usage: "Open a channel to a node or an existing peer.",
Description: `
Attempt to open a new channel to an existing peer with the key node-key
optionally blocking until the channel is 'open'.
One can also connect to a node before opening a new channel to it by
setting its host:port via the --connect argument. For this to work,
the node_key must be provided, rather than the peer_id. This is optional.
The channel will be initialized with local-amt satoshis local and push-amt
satoshis for the remote node. Note that specifying push-amt means you give that
amount to the remote node as part of the channel opening. Once the channel is open,
a channelPoint (txid:vout) of the funding output is returned.
One can manually set the fee to be used for the funding transaction via either
the --conf_target or --sat_per_byte arguments. This is optional.`,
ArgsUsage: "node-key local-amt push-amt",
Flags: []cli.Flag{
cli.StringFlag{
Name: "node_key",
Usage: "the identity public key of the target node/peer " +
"serialized in compressed format",
},
cli.StringFlag{
Name: "connect",
Usage: "(optional) the host:port of the target node",
},
cli.IntFlag{
Name: "local_amt",
Usage: "the number of satoshis the wallet should commit to the channel",
},
cli.IntFlag{
Name: "push_amt",
Usage: "the number of satoshis to give the remote side " +
"as part of the initial commitment state, " +
"this is equivalent to first opening a " +
"channel and sending the remote party funds, " +
"but done all in one step",
},
cli.BoolFlag{
Name: "block",
Usage: "block and wait until the channel is fully open",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation",
},
cli.Int64Flag{
Name: "sat_per_byte",
Usage: "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction",
},
cli.BoolFlag{
Name: "private",
Usage: "make the channel private, such that it won't " +
"be announced to the greater network, and " +
"nodes other than the two channel endpoints " +
"must be explicitly told about it to be able " +
"to route through it",
},
cli.Int64Flag{
Name: "min_htlc_msat",
Usage: "(optional) the minimum value we will require " +
"for incoming HTLCs on the channel",
},
cli.Uint64Flag{
Name: "remote_csv_delay",
Usage: "(optional) the number of blocks we will require " +
"our channel counterparty to wait before accessing " +
"its funds in case of unilateral close. If this is " +
"not set, we will scale the value according to the " +
"channel size",
},
cli.Uint64Flag{
Name: "min_confs",
Usage: "(optional) the minimum number of confirmations " +
"each one of your outputs used for the funding " +
"transaction must satisfy",
Value: 1,
},
},
Action: actionDecorator(openChannel),
}
func openChannel(ctx *cli.Context) error {
// TODO(roasbeef): add deadline to context
ctxb := context.Background()
client, cleanUp := getClient(ctx)
defer cleanUp()
args := ctx.Args()
var err error
// Show command help if no arguments provided
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
cli.ShowCommandHelp(ctx, "openchannel")
return nil
}
req := &lnrpc.OpenChannelRequest{
TargetConf: int32(ctx.Int64("conf_target")),
SatPerByte: ctx.Int64("sat_per_byte"),
MinHtlcMsat: ctx.Int64("min_htlc_msat"),
RemoteCsvDelay: uint32(ctx.Uint64("remote_csv_delay")),
MinConfs: int32(ctx.Uint64("min_confs")),
}
switch {
case ctx.IsSet("node_key"):
nodePubHex, err := hex.DecodeString(ctx.String("node_key"))
if err != nil {
return fmt.Errorf("unable to decode node public key: %v", err)
}
req.NodePubkey = nodePubHex
case args.Present():
nodePubHex, err := hex.DecodeString(args.First())
if err != nil {
return fmt.Errorf("unable to decode node public key: %v", err)
}
args = args.Tail()
req.NodePubkey = nodePubHex
default:
return fmt.Errorf("node id argument missing")
}
// As soon as we can confirm that the node's node_key was set, rather
// than the peer_id, we can check if the host:port was also set to
// connect to it before opening the channel.
if req.NodePubkey != nil && ctx.IsSet("connect") {
addr := &lnrpc.LightningAddress{
Pubkey: hex.EncodeToString(req.NodePubkey),
Host: ctx.String("connect"),
}
req := &lnrpc.ConnectPeerRequest{
Addr: addr,
Perm: false,
}
// Check if connecting to the node was successful.
// We discard the peer id returned as it is not needed.
_, err := client.ConnectPeer(ctxb, req)
if err != nil &&
!strings.Contains(err.Error(), "already connected") {
return err
}
}
switch {
case ctx.IsSet("local_amt"):
req.LocalFundingAmount = int64(ctx.Int("local_amt"))
case args.Present():
req.LocalFundingAmount, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil {
return fmt.Errorf("unable to decode local amt: %v", err)
}
args = args.Tail()
default:
return fmt.Errorf("local amt argument missing")
}
if ctx.IsSet("push_amt") {
req.PushSat = int64(ctx.Int("push_amt"))
} else if args.Present() {
req.PushSat, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil {
return fmt.Errorf("unable to decode push amt: %v", err)
}
}
req.Private = ctx.Bool("private")
stream, err := client.OpenChannel(ctxb, req)
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
switch update := resp.Update.(type) {
case *lnrpc.OpenStatusUpdate_ChanPending:
txid, err := chainhash.NewHash(update.ChanPending.Txid)
if err != nil {
return err
}
printJSON(struct {
FundingTxid string `json:"funding_txid"`
}{
FundingTxid: txid.String(),
},
)
if !ctx.Bool("block") {
return nil
}
case *lnrpc.OpenStatusUpdate_ChanOpen:
channelPoint := update.ChanOpen.ChannelPoint
// A channel point's funding txid can be get/set as a
// byte slice or a string. In the case it is a string,
// decode it.
var txidHash []byte
switch channelPoint.GetFundingTxid().(type) {
case *lnrpc.ChannelPoint_FundingTxidBytes:
txidHash = channelPoint.GetFundingTxidBytes()
case *lnrpc.ChannelPoint_FundingTxidStr:
s := channelPoint.GetFundingTxidStr()
h, err := chainhash.NewHashFromStr(s)
if err != nil {
return err
}
txidHash = h[:]
}
txid, err := chainhash.NewHash(txidHash)
if err != nil {
return err
}
index := channelPoint.OutputIndex
printJSON(struct {
ChannelPoint string `json:"channel_point"`
}{
ChannelPoint: fmt.Sprintf("%v:%v", txid, index),
},
)
}
}
}
// TODO(roasbeef): also allow short relative channel ID.
var closeChannelCommand = cli.Command{
Name: "closechannel",
Category: "Channels",
Usage: "Close an existing channel.",
Description: `
Close an existing channel. The channel can be closed either cooperatively,
or unilaterally (--force).
A unilateral channel closure means that the latest commitment
transaction will be broadcast to the network. As a result, any settled
funds will be time locked for a few blocks before they can be spent.
In the case of a cooperative closure, One can manually set the fee to
be used for the closing transaction via either the --conf_target or
--sat_per_byte arguments. This will be the starting value used during
fee negotiation. This is optional.
To view which funding_txids/output_indexes can be used for a channel close,
see the channel_point values within the listchannels command output.
The format for a channel_point is 'funding_txid:output_index'.`,
ArgsUsage: "funding_txid [output_index [time_limit]]",
Flags: []cli.Flag{
cli.StringFlag{
Name: "funding_txid",
Usage: "the txid of the channel's funding transaction",
},
cli.IntFlag{
Name: "output_index",
Usage: "the output index for the funding output of the funding " +
"transaction",
},
cli.StringFlag{
Name: "time_limit",
Usage: "a relative deadline afterwhich the attempt should be " +
"abandoned",
},
cli.BoolFlag{
Name: "force",
Usage: "after the time limit has passed, attempt an " +
"uncooperative closure",
},
cli.BoolFlag{
Name: "block",
Usage: "block until the channel is closed",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation",
},
cli.Int64Flag{
Name: "sat_per_byte",
Usage: "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction",
},
},
Action: actionDecorator(closeChannel),
}
func closeChannel(ctx *cli.Context) error {
client, cleanUp := getClient(ctx)
defer cleanUp()
// Show command help if no arguments and flags were provided.
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
cli.ShowCommandHelp(ctx, "closechannel")
return nil
}
channelPoint, err := parseChannelPoint(ctx)
if err != nil {
return err
}
// TODO(roasbeef): implement time deadline within server
req := &lnrpc.CloseChannelRequest{
ChannelPoint: channelPoint,
Force: ctx.Bool("force"),
TargetConf: int32(ctx.Int64("conf_target")),
SatPerByte: ctx.Int64("sat_per_byte"),
}
// After parsing the request, we'll spin up a goroutine that will
// retrieve the closing transaction ID when attempting to close the
// channel. We do this to because `executeChannelClose` can block, so we
// would like to present the closing transaction ID to the user as soon
// as it is broadcasted.
var wg sync.WaitGroup
txidChan := make(chan string, 1)
wg.Add(1)
go func() {
defer wg.Done()
printJSON(struct {
ClosingTxid string `json:"closing_txid"`
}{
ClosingTxid: <-txidChan,
})
}()
err = executeChannelClose(client, req, txidChan, ctx.Bool("block"))
if err != nil {
return err
}
// In the case that the user did not provide the `block` flag, then we
// need to wait for the goroutine to be done to prevent it from being
// destroyed when exiting before printing the closing transaction ID.
wg.Wait()
return nil
}
// executeChannelClose attempts to close the channel from a request. The closing
// transaction ID is sent through `txidChan` as soon as it is broadcasted to the
// network. The block boolean is used to determine if we should block until the
// closing transaction receives all of its required confirmations.
func executeChannelClose(client lnrpc.LightningClient, req *lnrpc.CloseChannelRequest,
txidChan chan<- string, block bool) error {
stream, err := client.CloseChannel(context.Background(), req)
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
switch update := resp.Update.(type) {
case *lnrpc.CloseStatusUpdate_ClosePending:
closingHash := update.ClosePending.Txid
txid, err := chainhash.NewHash(closingHash)
if err != nil {
return err
}
txidChan <- txid.String()
if !block {
return nil
}
case *lnrpc.CloseStatusUpdate_ChanClose:
return nil
}
}
}
var closeAllChannelsCommand = cli.Command{
Name: "closeallchannels",
Category: "Channels",
Usage: "Close all existing channels.",
Description: `
Close all existing channels.
Channels will be closed either cooperatively or unilaterally, depending
on whether the channel is active or not. If the channel is inactive, any
settled funds within it will be time locked for a few blocks before they
can be spent.
One can request to close inactive channels only by using the
--inactive_only flag.
By default, one is prompted for confirmation every time an inactive
channel is requested to be closed. To avoid this, one can set the
--force flag, which will only prompt for confirmation once for all
inactive channels and proceed to close them.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "inactive_only",
Usage: "close inactive channels only",
},
cli.BoolFlag{
Name: "force",
Usage: "ask for confirmation once before attempting " +
"to close existing channels",
},
},
Action: actionDecorator(closeAllChannels),
}
func closeAllChannels(ctx *cli.Context) error {
client, cleanUp := getClient(ctx)
defer cleanUp()
listReq := &lnrpc.ListChannelsRequest{}
openChannels, err := client.ListChannels(context.Background(), listReq)
if err != nil {
return fmt.Errorf("unable to fetch open channels: %v", err)
}
if len(openChannels.Channels) == 0 {
return errors.New("no open channels to close")
}
var channelsToClose []*lnrpc.Channel
switch {
case ctx.Bool("force") && ctx.Bool("inactive_only"):
msg := "Unilaterally close all inactive channels? The funds " +
"within these channels will be locked for some blocks " +
"(CSV delay) before they can be spent. (yes/no): "
confirmed := promptForConfirmation(msg)
// We can safely exit if the user did not confirm.
if !confirmed {
return nil
}
// Go through the list of open channels and only add inactive
// channels to the closing list.
for _, channel := range openChannels.Channels {
if !channel.GetActive() {
channelsToClose = append(
channelsToClose, channel,
)
}
}
case ctx.Bool("force"):
msg := "Close all active and inactive channels? Inactive " +
"channels will be closed unilaterally, so funds " +
"within them will be locked for a few blocks (CSV " +
"delay) before they can be spent. (yes/no): "
confirmed := promptForConfirmation(msg)
// We can safely exit if the user did not confirm.
if !confirmed {
return nil
}
channelsToClose = openChannels.Channels
default:
// Go through the list of open channels and determine which
// should be added to the closing list.
for _, channel := range openChannels.Channels {
// If the channel is inactive, we'll attempt to
// unilaterally close the channel, so we should prompt
// the user for confirmation beforehand.
if !channel.GetActive() {
msg := fmt.Sprintf("Unilaterally close channel "+
"with node %s and channel point %s? "+
"The closing transaction will need %d "+
"confirmations before the funds can be "+
"spent. (yes/no): ", channel.RemotePubkey,
channel.ChannelPoint, channel.CsvDelay)
confirmed := promptForConfirmation(msg)
if confirmed {
channelsToClose = append(
channelsToClose, channel,
)
}
} else if !ctx.Bool("inactive_only") {
// Otherwise, we'll only add active channels if
// we were not requested to close inactive
// channels only.
channelsToClose = append(
channelsToClose, channel,
)
}
}
}
// result defines the result of closing a channel. The closing
// transaction ID is populated if a channel is successfully closed.
// Otherwise, the error that prevented closing the channel is populated.
type result struct {
RemotePubKey string `json:"remote_pub_key"`
ChannelPoint string `json:"channel_point"`
ClosingTxid string `json:"closing_txid"`
FailErr string `json:"error"`
}
// Launch each channel closure in a goroutine in order to execute them
// in parallel. Once they're all executed, we will print the results as
// they come.
resultChan := make(chan result, len(channelsToClose))
for _, channel := range channelsToClose {
go func(channel *lnrpc.Channel) {
res := result{}
res.RemotePubKey = channel.RemotePubkey
res.ChannelPoint = channel.ChannelPoint
defer func() {
resultChan <- res
}()
// Parse the channel point in order to create the close
// channel request.
s := strings.Split(res.ChannelPoint, ":")
if len(s) != 2 {
res.FailErr = "expected channel point with " +
"format txid:index"
return
}
index, err := strconv.ParseUint(s[1], 10, 32)
if err != nil {
res.FailErr = fmt.Sprintf("unable to parse "+
"channel point output index: %v", err)
return
}
req := &lnrpc.CloseChannelRequest{
ChannelPoint: &lnrpc.ChannelPoint{
FundingTxid: &lnrpc.ChannelPoint_FundingTxidStr{
FundingTxidStr: s[0],
},
OutputIndex: uint32(index),
},
Force: !channel.GetActive(),
}
txidChan := make(chan string, 1)
err = executeChannelClose(client, req, txidChan, false)
if err != nil {
res.FailErr = fmt.Sprintf("unable to close "+
"channel: %v", err)
return
}
res.ClosingTxid = <-txidChan
}(channel)
}
for range channelsToClose {
res := <-resultChan
printJSON(res)
}
return nil
}
// promptForConfirmation continuously prompts the user for the message until
// receiving a response of "yes" or "no" and returns their answer as a bool.
func promptForConfirmation(msg string) bool {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(msg)
answer, err := reader.ReadString('\n')
if err != nil {
return false
}
answer = strings.ToLower(strings.TrimSpace(answer))
switch {
case answer == "yes":
return true
case answer == "no":