forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 24
/
commands.go
2450 lines (2120 loc) · 62.8 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"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"strconv"
"strings"
"sync"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrlnd/lnrpc"
"github.com/decred/dcrlnd/routing/route"
"github.com/decred/dcrlnd/signal"
"github.com/matheusd/protobuf-hex-display/json"
"github.com/matheusd/protobuf-hex-display/jsonpb"
"github.com/matheusd/protobuf-hex-display/proto"
"github.com/urfave/cli"
"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 = 20
const (
defaultUtxoMinConf = 1
)
func getContext() context.Context {
shutdownInterceptor, err := signal.Intercept()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
ctxc, cancel := context.WithCancel(context.Background())
go func() {
<-shutdownInterceptor.ShutdownChannel()
cancel()
}()
return ctxc
}
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,
OrigName: 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")
}
// dcrlnd might be active, but not possible to contact
// using RPC if the wallet is encrypted. If we get
// error code Unimplemented, it means that dcrlnd 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 'dcrlncli unlock', " +
"or set password using 'dcrlncli create'" +
" if this is the first time starting dcrlnd")
}
return err
}
return nil
}
}
var newAddressCommand = cli.Command{
Name: "newaddress",
Category: "Wallet",
Usage: "Generates a new address.",
ArgsUsage: "address-type",
Flags: []cli.Flag{
cli.StringFlag{
Name: "account",
Usage: "(optional) the name of the account to " +
"generate a new address for",
},
},
Description: `
Generate a wallet new address. Address-types has to be:
- p2pkh: Pay to public key hash(default)`,
Action: actionDecorator(newAddress),
}
func newAddress(ctx *cli.Context) error {
ctxc := getContext()
client, cleanUp := getClient(ctx)
defer cleanUp()
// Display the command's help message if we do not have the expected
// number of arguments/flags.
if ctx.NArg() != 1 || ctx.NumFlags() > 1 {
return cli.ShowCommandHelp(ctx, "newaddress")
}
// Map the string encoded address type, to the concrete typed address
// type enum. An unrecognized address type will result in an error.
stringAddrType := ctx.Args().First()
var addrType lnrpc.AddressType
switch stringAddrType { // TODO(roasbeef): make them ints on the cli?
case "p2pkh":
addrType = lnrpc.AddressType_PUBKEY_HASH
case "":
addrType = lnrpc.AddressType_PUBKEY_HASH
default:
return fmt.Errorf("invalid address type %v, support address type "+
"are: p2pkh", stringAddrType)
}
addr, err := client.NewAddress(ctxc, &lnrpc.NewAddressRequest{
Type: addrType,
Account: ctx.String("account"),
})
if err != nil {
return err
}
printRespJSON(addr)
return nil
}
var estimateFeeCommand = cli.Command{
Name: "estimatefee",
Category: "On-chain",
Usage: "Get fee estimates for sending decred on-chain to multiple addresses.",
ArgsUsage: "send-json-string [--conf_target=N]",
Description: `
Get fee estimates for sending a transaction paying the specified amount(s) to the passed address(es).
The 'send-json-string' param encodes addresses and the amount to send respectively in the following format:
{"ExampleAddr": NumCoinsInAtoms, "SecondAddr": NumCoins}
`,
Flags: []cli.Flag{
cli.Int64Flag{
Name: "conf_target",
Usage: "(optional) the number of blocks that the transaction *should* " +
"confirm in",
},
},
Action: actionDecorator(estimateFees),
}
func estimateFees(ctx *cli.Context) error {
ctxc := getContext()
var amountToAddr map[string]int64
jsonMap := ctx.Args().First()
if err := json.Unmarshal([]byte(jsonMap), &amountToAddr); err != nil {
return err
}
client, cleanUp := getClient(ctx)
defer cleanUp()
resp, err := client.EstimateFee(ctxc, &lnrpc.EstimateFeeRequest{
AddrToAmount: amountToAddr,
TargetConf: int32(ctx.Int64("conf_target")),
})
if err != nil {
return err
}
printRespJSON(resp)
return nil
}
var txLabelFlag = cli.StringFlag{
Name: "label",
Usage: "(optional) a label for the transaction",
}
var sendCoinsCommand = cli.Command{
Name: "sendcoins",
Category: "On-chain",
Usage: "Send decred on-chain to an address.",
ArgsUsage: "addr amt",
Description: `
Send amt coins in atoms to the BASE58 encoded decred address addr.
Fees used when sending the transaction can be specified via the '--conf_target', or
'--atoms_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 decred address to send coins to on-chain",
},
cli.BoolFlag{
Name: "sweepall",
Usage: "If set, then the amount field will be ignored, " +
"and the wallet will attempt to sweep all " +
"outputs within the wallet to the target " +
"address",
},
cli.Int64Flag{
Name: "amt",
Usage: "The number of decred denominated in atoms to send",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "The number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation (optional)",
},
cli.Int64Flag{
Name: "atoms_per_byte",
Usage: "A manual fee expressed in " +
"atoms/byte that should be used when crafting " +
"the transaction (optional)",
},
cli.Uint64Flag{
Name: "min_confs",
Usage: "(optional) the minimum number of confirmations " +
"each one of your outputs used for the transaction " +
"must satisfy",
Value: defaultUtxoMinConf,
},
txLabelFlag,
},
Action: actionDecorator(sendCoins),
}
func sendCoins(ctx *cli.Context) error {
var (
addr string
amt int64
err error
)
ctxc := getContext()
args := ctx.Args()
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
cli.ShowCommandHelp(ctx, "sendcoins")
return nil
}
if ctx.IsSet("conf_target") && ctx.IsSet("atoms_per_byte") {
return fmt.Errorf("either --conf_target or --atoms_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)
case !ctx.Bool("sweepall"):
return fmt.Errorf("amount argument missing")
}
if err != nil {
return fmt.Errorf("unable to decode amount: %v", err)
}
if amt != 0 && ctx.Bool("sweepall") {
return fmt.Errorf("amount cannot be set if attempting to " +
"sweep all coins out of the wallet")
}
client, cleanUp := getClient(ctx)
defer cleanUp()
minConfs := int32(ctx.Uint64("min_confs"))
req := &lnrpc.SendCoinsRequest{
Addr: addr,
Amount: amt,
TargetConf: int32(ctx.Int64("conf_target")),
AtomsPerByte: ctx.Int64("atoms_per_byte"),
SendAll: ctx.Bool("sweepall"),
Label: ctx.String(txLabelFlag.Name),
MinConfs: minConfs,
SpendUnconfirmed: minConfs == 0,
}
txid, err := client.SendCoins(ctxc, req)
if err != nil {
return err
}
printRespJSON(txid)
return nil
}
var listUnspentCommand = cli.Command{
Name: "listunspent",
Category: "On-chain",
Usage: "List UTXOs available for spending.",
ArgsUsage: "[min-confs [max-confs]] [--unconfirmed_only]",
Description: `
For each spendable UTXO currently in the wallet, with at least 'min_confs'
confirmations, and at most 'max_confs' confirmations, lists the txid,
index, amount, address, address type, scriptPubkey and number of
confirmations. Use '--min_confs=0' to include unconfirmed coins. To list
all coins with at least min_confs confirmations, omit the second
argument or flag '--max_confs'. To list all confirmed and unconfirmed
coins, no arguments are required. To see only unconfirmed coins, use
'--unconfirmed_only' with '--min_confs' and '--max_confs' set to zero or
not present.
`,
Flags: []cli.Flag{
cli.Int64Flag{
Name: "min_confs",
Usage: "The minimum number of confirmations for a UTXO",
},
cli.Int64Flag{
Name: "max_confs",
Usage: "The maximum number of confirmations for a UTXO",
},
cli.BoolFlag{
Name: "unconfirmed_only",
Usage: "When min_confs and max_confs are zero, " +
"setting false implicitly overrides 'max_confs' " +
"to be MaxInt32, otherwise 'max_confs' remains " +
"zero. An error is returned if the value is " +
"true and both 'min_confs' and 'max_confs' are " +
"non-zero. (default: false)",
},
},
Action: actionDecorator(listUnspent),
}
func listUnspent(ctx *cli.Context) error {
var (
minConfirms int64
maxConfirms int64
err error
)
ctxc := getContext()
args := ctx.Args()
if ctx.IsSet("max_confs") && !ctx.IsSet("min_confs") {
return fmt.Errorf("max_confs cannot be set without " +
"min_confs being set")
}
switch {
case ctx.IsSet("min_confs"):
minConfirms = ctx.Int64("min_confs")
case args.Present():
minConfirms, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil {
cli.ShowCommandHelp(ctx, "listunspent")
return nil
}
args = args.Tail()
}
switch {
case ctx.IsSet("max_confs"):
maxConfirms = ctx.Int64("max_confs")
case args.Present():
maxConfirms, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil {
cli.ShowCommandHelp(ctx, "listunspent")
return nil
}
args = args.Tail()
}
unconfirmedOnly := ctx.Bool("unconfirmed_only")
// Force minConfirms and maxConfirms to be zero if unconfirmedOnly is
// true.
if unconfirmedOnly && (minConfirms != 0 || maxConfirms != 0) {
cli.ShowCommandHelp(ctx, "listunspent")
return nil
}
// When unconfirmedOnly is inactive, we will override maxConfirms to be
// a MaxInt32 to return all confirmed and unconfirmed utxos.
if maxConfirms == 0 && !unconfirmedOnly {
maxConfirms = math.MaxInt32
}
client, cleanUp := getClient(ctx)
defer cleanUp()
req := &lnrpc.ListUnspentRequest{
MinConfs: int32(minConfirms),
MaxConfs: int32(maxConfirms),
}
resp, err := client.ListUnspent(ctxc, req)
if err != nil {
return err
}
// Parse the response into the final json object that will be printed
// to stdout. At the moment, this filters out the raw txid bytes from
// each utxo's outpoint and only prints the txid string.
var listUnspentResp = struct {
Utxos []*Utxo `json:"utxos"`
}{
Utxos: make([]*Utxo, 0, len(resp.Utxos)),
}
for _, protoUtxo := range resp.Utxos {
utxo := NewUtxoFromProto(protoUtxo)
listUnspentResp.Utxos = append(listUnspentResp.Utxos, utxo)
}
printJSON(listUnspentResp)
return nil
}
var sendManyCommand = cli.Command{
Name: "sendmany",
Category: "On-chain",
Usage: "Send decred on-chain to multiple addresses.",
ArgsUsage: "send-json-string [--conf_target=N] [--atoms_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": NumCoinsInAtoms, "SecondAddr": NumCoins}
`,
Flags: []cli.Flag{
cli.Int64Flag{
Name: "conf_target",
Usage: "The number of blocks that the transaction *should* " +
"confirm in, will be used for fee estimation (optional)",
},
cli.Int64Flag{
Name: "atoms_per_byte",
Usage: "Manual fee expressed in atom/byte that should be " +
"used when crafting the transaction (optional)",
},
cli.Uint64Flag{
Name: "min_confs",
Usage: "(optional) the minimum number of confirmations " +
"each one of your outputs used for the transaction " +
"must satisfy",
Value: defaultUtxoMinConf,
},
txLabelFlag,
},
Action: actionDecorator(sendMany),
}
func sendMany(ctx *cli.Context) error {
ctxc := getContext()
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("atoms_per_byte") {
return fmt.Errorf("either conf_target or atoms_per_byte should be " +
"set, but not both")
}
client, cleanUp := getClient(ctx)
defer cleanUp()
minConfs := int32(ctx.Uint64("min_confs"))
txid, err := client.SendMany(ctxc, &lnrpc.SendManyRequest{
AddrToAmount: amountToAddr,
TargetConf: int32(ctx.Int64("conf_target")),
AtomsPerByte: ctx.Int64("atoms_per_byte"),
Label: ctx.String(txLabelFlag.Name),
MinConfs: minConfs,
SpendUnconfirmed: minConfs == 0,
})
if err != nil {
return err
}
printRespJSON(txid)
return nil
}
var connectCommand = cli.Command{
Name: "connect",
Category: "Peers",
Usage: "Connect to a remote dcrlnd peer.",
ArgsUsage: "<pubkey>@host",
Description: `
Connect to a peer using its <pubkey> and host.
A custom timeout on the connection is supported. For instance, to timeout
the connection request in 30 seconds, use the following:
lncli connect <pubkey>@host --timeout 30s
`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "perm",
Usage: "If set, the daemon will attempt to persistently " +
"connect to the target peer. " +
"If not, the call will be synchronous.",
},
cli.DurationFlag{
Name: "timeout",
Usage: "The connection timeout value for current request. " +
"Valid uints are {ms, s, m, h}.\n" +
"If not set, the global connection " +
"timeout value (default to 120s) is used.",
},
},
Action: actionDecorator(connectPeer),
}
func connectPeer(ctx *cli.Context) error {
ctxc := getContext()
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"),
Timeout: uint64(ctx.Duration("timeout").Seconds()),
}
lnid, err := client.ConnectPeer(ctxc, req)
if err != nil {
return err
}
printRespJSON(lnid)
return nil
}
var disconnectCommand = cli.Command{
Name: "disconnect",
Category: "Peers",
Usage: "Disconnect a remote dcrlnd 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 {
ctxc := getContext()
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(ctxc, req)
if err != nil {
return err
}
printRespJSON(lnid)
return nil
}
// 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 with '--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
'--atoms_per_byte' arguments. This will be the starting value used during
fee negotiation. This is optional.
In the case of a cooperative closure, one can manually set the address
to deliver funds to upon closure. This is optional, and may only be used
if an upfront shutdown address has not already been set. If neither are
set the funds will be delivered to a new wallet address.
To view which 'funding_txids' or '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]",
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.BoolFlag{
Name: "force",
Usage: "Attempt an uncooperative closure",
},
cli.BoolFlag{
Name: "block",
Usage: "Block until the channel is closed",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "The number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation. If not set, " +
"then the conf-target value set in the main " +
"lnd config will be used.",
},
cli.Int64Flag{
Name: "atoms_per_byte",
Usage: "A manual fee expressed in " +
"atom/byte that should be used when crafting " +
"the transaction (optional)",
},
cli.StringFlag{
Name: "delivery_addr",
Usage: "An address to deliver funds " +
"upon cooperative channel closing, may only " +
"be used if an upfront shutdown address is not " +
"already set (optional)",
},
},
Action: actionDecorator(closeChannel),
}
func closeChannel(ctx *cli.Context) error {
ctxc := getContext()
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")),
AtomsPerByte: ctx.Int64("atoms_per_byte"),
DeliveryAddress: ctx.String("delivery_addr"),
}
// 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 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(ctxc, 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(ctxc context.Context, client lnrpc.LightningClient,
req *lnrpc.CloseChannelRequest, txidChan chan<- string, block bool) error {
stream, err := client.CloseChannel(ctxc, 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.
You can request to close inactive channels only by using the
'--inactive_only' flag.
By default, confirmation is prompted each 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.
In the case of cooperative closures, one can manually set the fee to
be used for the closing transactions via either the '--conf_target' or
'--atoms_per_byte' arguments. This will be the starting value used during
fee negotiation. This is optional.`,
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",
},
cli.Int64Flag{
Name: "conf_target",
Usage: "The number of blocks that the " +
"closing transactions *should* confirm in, will be " +
"used for fee estimation (optional)",
},
cli.Int64Flag{
Name: "atoms_per_byte",
Usage: "A manual fee expressed in " +
"atom/byte that should be used when crafting " +
"the closing transactions (optional)",
},
},
Action: actionDecorator(closeAllChannels),
}
func closeAllChannels(ctx *cli.Context) error {
ctxc := getContext()
client, cleanUp := getClient(ctx)
defer cleanUp()
listReq := &lnrpc.ListChannelsRequest{}
openChannels, err := client.ListChannels(ctxc, 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.LocalConstraints.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(),
TargetConf: int32(ctx.Int64("conf_target")),
AtomsPerByte: ctx.Int64("atoms_per_byte"),
}
txidChan := make(chan string, 1)