forked from btcsuite/btcd
-
Notifications
You must be signed in to change notification settings - Fork 26
/
cmd_pay.go
887 lines (757 loc) · 21.9 KB
/
cmd_pay.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
package main
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"io/ioutil"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
"github.com/lightninglabs/protobuf-hex-display/jsonpb"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/btcutil/util"
"github.com/pkt-cash/pktd/lnd/lnrpc"
"github.com/pkt-cash/pktd/lnd/lnrpc/routerrpc"
"github.com/pkt-cash/pktd/lnd/lntypes"
"github.com/pkt-cash/pktd/lnd/record"
"github.com/pkt-cash/pktd/lnd/routing/route"
"github.com/urfave/cli"
)
const (
// paymentTimeout is the default timeout for the payment loop in lnd.
// No new attempts will be started after the timeout.
paymentTimeout = time.Second * 60
)
var (
cltvLimitFlag = cli.UintFlag{
Name: "cltv_limit",
Usage: "the maximum time lock that may be used for " +
"this payment",
}
lastHopFlag = cli.StringFlag{
Name: "last_hop",
Usage: "pubkey of the last hop (penultimate node in the path) " +
"to route through for this payment",
}
dataFlag = cli.StringFlag{
Name: "data",
Usage: "attach custom data to the payment. The required " +
"format is: <record_id>=<hex_value>,<record_id>=" +
"<hex_value>,.. For example: --data 3438382=0a21ff. " +
"Custom record ids start from 65536.",
}
inflightUpdatesFlag = cli.BoolFlag{
Name: "inflight_updates",
Usage: "if set, intermediate payment state updates will be " +
"displayed. Only valid in combination with --json.",
}
maxPartsFlag = cli.UintFlag{
Name: "max_parts",
Usage: "the maximum number of partial payments that may be " +
"used",
Value: 1,
}
jsonFlag = cli.BoolFlag{
Name: "json",
Usage: "if set, payment updates are printed as json " +
"messages. Set by default on Windows because table " +
"formatting is unsupported.",
}
)
// paymentFlags returns common flags for sendpayment and payinvoice.
func paymentFlags() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "pay_req",
Usage: "a zpay32 encoded payment request to fulfill",
},
cli.Int64Flag{
Name: "fee_limit",
Usage: "maximum fee allowed in satoshis when " +
"sending the payment",
},
cli.Int64Flag{
Name: "fee_limit_percent",
Usage: "percentage of the payment's amount used as " +
"the maximum fee allowed when sending the " +
"payment",
},
cli.DurationFlag{
Name: "timeout",
Usage: "the maximum amount of time we should spend " +
"trying to fulfill the payment, failing " +
"after the timeout has elapsed",
Value: paymentTimeout,
},
cltvLimitFlag,
lastHopFlag,
cli.Uint64Flag{
Name: "outgoing_chan_id",
Usage: "short channel id of the outgoing channel to " +
"use for the first hop of the payment",
Value: 0,
},
cli.BoolFlag{
Name: "force, f",
Usage: "will skip payment request confirmation",
},
cli.BoolFlag{
Name: "allow_self_payment",
Usage: "allow sending a circular payment to self",
},
dataFlag, inflightUpdatesFlag, maxPartsFlag, jsonFlag,
}
}
var sendPaymentCommand = cli.Command{
Name: "sendpayment",
Category: "Payments",
Usage: "Send a payment over lightning.",
Description: `
Send a payment over Lightning. One can either specify the full
parameters of the payment, or just use a payment request which encodes
all the payment details.
If payment isn't manually specified, then only a payment request needs
to be passed using the --pay_req argument.
If the payment *is* manually specified, then all four alternative
arguments need to be specified in order to complete the payment:
* --dest=N
* --amt=A
* --final_cltv_delta=T
* --payment_hash=H
`,
ArgsUsage: "dest amt payment_hash final_cltv_delta | --pay_req=[payment request]",
Flags: append(paymentFlags(),
cli.StringFlag{
Name: "dest, d",
Usage: "the compressed identity pubkey of the " +
"payment recipient",
},
cli.Int64Flag{
Name: "amt, a",
Usage: "number of satoshis to send",
},
cli.StringFlag{
Name: "payment_hash, r",
Usage: "the hash to use within the payment's HTLC",
},
cli.Int64Flag{
Name: "final_cltv_delta",
Usage: "the number of blocks the last hop has to reveal the preimage",
},
cli.BoolFlag{
Name: "keysend",
Usage: "will generate a pre-image and encode it in the sphinx packet, a dest must be set [experimental]",
},
),
Action: sendPayment,
}
// retrieveFeeLimit retrieves the fee limit based on the different fee limit
// flags passed. It always returns a value and doesn't rely on lnd applying a
// default.
func retrieveFeeLimit(ctx *cli.Context, amt int64) (int64, er.R) {
switch {
case ctx.IsSet("fee_limit") && ctx.IsSet("fee_limit_percent"):
return 0, er.Errorf("either fee_limit or fee_limit_percent " +
"can be set, but not both")
case ctx.IsSet("fee_limit"):
return ctx.Int64("fee_limit"), nil
case ctx.IsSet("fee_limit_percent"):
// Round up the fee limit to prevent hitting zero on small
// amounts.
feeLimitRoundedUp :=
(amt*ctx.Int64("fee_limit_percent") + 99) / 100
return feeLimitRoundedUp, nil
}
// If no fee limit is set, use the payment amount as a limit (100%).
return amt, nil
}
func confirmPayReq(resp *lnrpc.PayReq, amt, feeLimit int64) er.R {
fmt.Printf("Payment hash: %v\n", resp.GetPaymentHash())
fmt.Printf("Description: %v\n", resp.GetDescription())
fmt.Printf("Amount (in satoshis): %v\n", amt)
fmt.Printf("Fee limit (in satoshis): %v\n", feeLimit)
fmt.Printf("Destination: %v\n", resp.GetDestination())
confirm := promptForConfirmation("Confirm payment (yes/no): ")
if !confirm {
return er.Errorf("payment not confirmed")
}
return nil
}
func sendPayment(ctx *cli.Context) er.R {
// Show command help if no arguments provided
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
_ = cli.ShowCommandHelp(ctx, "sendpayment")
return nil
}
// If a payment request was provided, we can exit early since all of the
// details of the payment are encoded within the request.
if ctx.IsSet("pay_req") {
req := &routerrpc.SendPaymentRequest{
PaymentRequest: ctx.String("pay_req"),
Amt: ctx.Int64("amt"),
}
return sendPaymentRequest(ctx, req)
}
var (
destNode []byte
amount int64
err er.R
)
args := ctx.Args()
switch {
case ctx.IsSet("dest"):
destNode, err = util.DecodeHex(ctx.String("dest"))
case args.Present():
destNode, err = util.DecodeHex(args.First())
args = args.Tail()
default:
return er.Errorf("destination txid argument missing")
}
if err != nil {
return err
}
if len(destNode) != 33 {
return er.Errorf("dest node pubkey must be exactly 33 bytes, is "+
"instead: %v", len(destNode))
}
if ctx.IsSet("amt") {
amount = ctx.Int64("amt")
} else if args.Present() {
var err error
amount, err = strconv.ParseInt(args.First(), 10, 64)
args = args.Tail()
if err != nil {
return er.Errorf("unable to decode payment amount: %v", err)
}
}
req := &routerrpc.SendPaymentRequest{
Dest: destNode,
Amt: amount,
DestCustomRecords: make(map[uint64][]byte),
}
var rHash []byte
if ctx.Bool("keysend") {
if ctx.IsSet("payment_hash") {
return er.New("cannot set payment hash when using " +
"keysend")
}
var preimage lntypes.Preimage
if _, err := rand.Read(preimage[:]); err != nil {
return er.E(err)
}
// Set the preimage. If the user supplied a preimage with the
// data flag, the preimage that is set here will be overwritten
// later.
req.DestCustomRecords[record.KeySendType] = preimage[:]
hash := preimage.Hash()
rHash = hash[:]
} else {
switch {
case ctx.IsSet("payment_hash"):
rHash, err = util.DecodeHex(ctx.String("payment_hash"))
case args.Present():
rHash, err = util.DecodeHex(args.First())
args = args.Tail()
default:
return er.Errorf("payment hash argument missing")
}
}
if err != nil {
return err
}
if len(rHash) != 32 {
return er.Errorf("payment hash must be exactly 32 "+
"bytes, is instead %v", len(rHash))
}
req.PaymentHash = rHash
switch {
case ctx.IsSet("final_cltv_delta"):
req.FinalCltvDelta = int32(ctx.Int64("final_cltv_delta"))
case args.Present():
delta, err := strconv.ParseInt(args.First(), 10, 64)
if err != nil {
return er.E(err)
}
req.FinalCltvDelta = int32(delta)
}
return sendPaymentRequest(ctx, req)
}
func sendPaymentRequest(ctx *cli.Context,
req *routerrpc.SendPaymentRequest) er.R {
conn := getClientConn(ctx, false)
defer conn.Close()
client := lnrpc.NewLightningClient(conn)
routerClient := routerrpc.NewRouterClient(conn)
outChan := ctx.Uint64("outgoing_chan_id")
if outChan != 0 {
req.OutgoingChanIds = []uint64{outChan}
}
if ctx.IsSet(lastHopFlag.Name) {
lastHop, err := route.NewVertexFromStr(
ctx.String(lastHopFlag.Name),
)
if err != nil {
return err
}
req.LastHopPubkey = lastHop[:]
}
req.CltvLimit = int32(ctx.Int(cltvLimitFlag.Name))
pmtTimeout := ctx.Duration("timeout")
if pmtTimeout <= 0 {
return er.New("payment timeout must be greater than zero")
}
req.TimeoutSeconds = int32(pmtTimeout.Seconds())
req.AllowSelfPayment = ctx.Bool("allow_self_payment")
req.MaxParts = uint32(ctx.Uint(maxPartsFlag.Name))
var err er.R
// Parse custom data records.
data := ctx.String(dataFlag.Name)
if data != "" {
records := strings.Split(data, ",")
for _, r := range records {
kv := strings.Split(r, "=")
if len(kv) != 2 {
return er.New("invalid data format: " +
"multiple equal signs in record")
}
recordID, errr := strconv.ParseUint(kv[0], 10, 64)
if errr != nil {
return er.Errorf("invalid data format: %v",
errr)
}
hexValue, err := util.DecodeHex(kv[1])
if err != nil {
return er.Errorf("invalid data format: %v",
err)
}
req.DestCustomRecords[recordID] = hexValue
}
}
var feeLimit int64
if req.PaymentRequest != "" {
// Decode payment request to find out the amount.
decodeReq := &lnrpc.PayReqString{PayReq: req.PaymentRequest}
decodeResp, errr := client.DecodePayReq(
context.Background(), decodeReq,
)
if errr != nil {
return er.E(errr)
}
// If amount is present in the request, override the request
// amount.
amt := req.Amt
invoiceAmt := decodeResp.GetNumSatoshis()
if invoiceAmt != 0 {
amt = invoiceAmt
}
// Calculate fee limit based on the determined amount.
feeLimit, err = retrieveFeeLimit(ctx, amt)
if err != nil {
return err
}
// Ask for confirmation of amount and fee limit if payment is
// forced.
if !ctx.Bool("force") {
err := confirmPayReq(decodeResp, amt, feeLimit)
if err != nil {
return err
}
}
} else {
var err er.R
feeLimit, err = retrieveFeeLimit(ctx, req.Amt)
if err != nil {
return err
}
}
req.FeeLimitSat = feeLimit
// Always print in-flight updates for the table output.
printJSON := ctx.Bool(jsonFlag.Name)
req.NoInflightUpdates = !ctx.Bool(inflightUpdatesFlag.Name) && printJSON
stream, errr := routerClient.SendPaymentV2(context.Background(), req)
if errr != nil {
return er.E(errr)
}
finalState, err := printLivePayment(
stream, client, printJSON,
)
if err != nil {
return err
}
// If we get a payment error back, we pass an error up
// to main which eventually calls fatal() and returns
// with a non-zero exit code.
if finalState.Status != lnrpc.Payment_SUCCEEDED {
return er.New(finalState.Status.String())
}
return nil
}
var trackPaymentCommand = cli.Command{
Name: "trackpayment",
Category: "Payments",
Usage: "Track progress of an existing payment.",
Description: `
Pick up monitoring the progression of a previously initiated payment
specified by the hash argument.
`,
ArgsUsage: "hash",
Action: actionDecorator(trackPayment),
}
func trackPayment(ctx *cli.Context) er.R {
args := ctx.Args()
conn := getClientConn(ctx, false)
defer conn.Close()
routerClient := routerrpc.NewRouterClient(conn)
if !args.Present() {
return er.Errorf("hash argument missing")
}
hash, err := util.DecodeHex(args.First())
if err != nil {
return err
}
req := &routerrpc.TrackPaymentRequest{
PaymentHash: hash,
}
stream, errr := routerClient.TrackPaymentV2(context.Background(), req)
if errr != nil {
return er.E(errr)
}
client := lnrpc.NewLightningClient(conn)
_, err = printLivePayment(stream, client, ctx.Bool(jsonFlag.Name))
return err
}
// printLivePayment receives payment updates from the given stream and either
// outputs them as json or as a more user-friendly formatted table. The table
// option uses terminal control codes to rewrite the output. This call
// terminates when the payment reaches a final state.
func printLivePayment(stream routerrpc.Router_TrackPaymentV2Client,
client lnrpc.LightningClient, json bool) (*lnrpc.Payment, er.R) {
// Terminal escape codes aren't supported on Windows, fall back to json.
if !json && runtime.GOOS == "windows" {
json = true
}
aliases := newAliasCache(client)
first := true
var lastLineCount int
for {
payment, errr := stream.Recv()
if errr != nil {
return nil, er.E(errr)
}
if json {
// Delimit json messages by newlines (inspired by
// grpc over rest chunking).
if first {
first = false
} else {
fmt.Println()
}
// Write raw json to stdout.
printRespJSON(payment)
} else {
table := formatPayment(payment, aliases)
// Clear all previously written lines and print the
// updated table.
clearLines(lastLineCount)
fmt.Print(table)
// Store the number of lines written for the next update
// pass.
lastLineCount = 0
for _, b := range table {
if b == '\n' {
lastLineCount++
}
}
}
// Terminate loop if payments state is final.
if payment.Status != lnrpc.Payment_IN_FLIGHT {
return payment, nil
}
}
}
// aliasCache allows cached retrieval of node aliases.
type aliasCache struct {
cache map[string]string
client lnrpc.LightningClient
}
func newAliasCache(client lnrpc.LightningClient) *aliasCache {
return &aliasCache{
client: client,
cache: make(map[string]string),
}
}
// get returns a node alias either from cache or freshly requested from lnd.
func (a *aliasCache) get(pubkey string) string {
alias, ok := a.cache[pubkey]
if ok {
return alias
}
// Request node info.
resp, err := a.client.GetNodeInfo(
context.Background(),
&lnrpc.NodeInfoRequest{
PubKey: []byte(pubkey),
},
)
if err != nil {
// If no info is available, use the
// pubkey as identifier.
alias = pubkey[:6]
} else {
alias = resp.Node.Alias
}
a.cache[pubkey] = alias
return alias
}
// formatMsat formats msat amounts as fractional sats.
func formatMsat(amt int64) string {
return strconv.FormatFloat(float64(amt)/1000.0, 'f', -1, 64)
}
// formatPayment formats the payment state as an ascii table.
func formatPayment(payment *lnrpc.Payment, aliases *aliasCache) string {
t := table.NewWriter()
// Build table header.
t.AppendHeader(table.Row{
"HTLC_STATE", "ATTEMPT_TIME", "RESOLVE_TIME", "RECEIVER_AMT",
"FEE", "TIMELOCK", "CHAN_OUT", "ROUTE",
})
t.SetColumnConfigs([]table.ColumnConfig{
{Name: "ATTEMPT_TIME", Align: text.AlignRight},
{Name: "RESOLVE_TIME", Align: text.AlignRight},
{Name: "CHAN_OUT", Align: text.AlignLeft,
AlignHeader: text.AlignLeft},
})
// Add all htlcs as rows.
createTime := time.Unix(0, payment.CreationTimeNs)
var totalPaid, totalFees int64
for _, htlc := range payment.Htlcs {
formatTime := func(timeNs int64) string {
if timeNs == 0 {
return "-"
}
resolveTime := time.Unix(0, timeNs)
resolveTimeDiff := resolveTime.Sub(createTime)
resolveTimeMs := resolveTimeDiff / time.Millisecond
return fmt.Sprintf(
"%.3f", float64(resolveTimeMs)/1000.0,
)
}
attemptTime := formatTime(htlc.AttemptTimeNs)
resolveTime := formatTime(htlc.ResolveTimeNs)
route := htlc.Route
lastHop := route.Hops[len(route.Hops)-1]
hops := []string{}
for _, h := range route.Hops {
alias := aliases.get(h.PubKey)
hops = append(hops, alias)
}
state := htlc.Status.String()
if htlc.Failure != nil {
state = fmt.Sprintf(
"%v @ %v",
htlc.Failure.Code,
htlc.Failure.FailureSourceIndex,
)
}
t.AppendRow([]interface{}{
state, attemptTime, resolveTime,
formatMsat(lastHop.AmtToForwardMsat),
formatMsat(route.TotalFeesMsat),
route.TotalTimeLock, route.Hops[0].ChanId,
strings.Join(hops, "->")},
)
if htlc.Status == lnrpc.HTLCAttempt_SUCCEEDED {
totalPaid += lastHop.AmtToForwardMsat
totalFees += route.TotalFeesMsat
}
}
// Render table.
b := &bytes.Buffer{}
t.SetOutputMirror(b)
t.Render()
// Add additional payment-level data.
fmt.Fprintf(b, "Amount + fee: %v + %v sat\n",
formatMsat(totalPaid), formatMsat(totalFees))
fmt.Fprintf(b, "Payment hash: %v\n", payment.PaymentHash)
fmt.Fprintf(b, "Payment status: %v", payment.Status)
switch payment.Status {
case lnrpc.Payment_SUCCEEDED:
fmt.Fprintf(b, ", preimage: %v", payment.PaymentPreimage)
case lnrpc.Payment_FAILED:
fmt.Fprintf(b, ", reason: %v", payment.FailureReason)
}
fmt.Fprintf(b, "\n")
return b.String()
}
var payInvoiceCommand = cli.Command{
Name: "payinvoice",
Category: "Payments",
Usage: "Pay an invoice over lightning.",
ArgsUsage: "pay_req",
Flags: append(paymentFlags(),
cli.Int64Flag{
Name: "amt",
Usage: "(optional) number of satoshis to fulfill the " +
"invoice",
},
),
Action: actionDecorator(payInvoice),
}
func payInvoice(ctx *cli.Context) er.R {
args := ctx.Args()
var payReq string
switch {
case ctx.IsSet("pay_req"):
payReq = ctx.String("pay_req")
case args.Present():
payReq = args.First()
default:
return er.Errorf("pay_req argument missing")
}
req := &routerrpc.SendPaymentRequest{
PaymentRequest: payReq,
Amt: ctx.Int64("amt"),
DestCustomRecords: make(map[uint64][]byte),
}
return sendPaymentRequest(ctx, req)
}
var sendToRouteCommand = cli.Command{
Name: "sendtoroute",
Category: "Payments",
Usage: "Send a payment over a predefined route.",
Description: `
Send a payment over Lightning using a specific route. One must specify
the route to attempt and the payment hash. This command can even
be chained with the response to queryroutes or buildroute. This command
can be used to implement channel rebalancing by crafting a self-route,
or even atomic swaps using a self-route that crosses multiple chains.
There are three ways to specify a route:
* using the --routes parameter to manually specify a JSON encoded
route in the format of the return value of queryroutes or
buildroute:
(lncli sendtoroute --payment_hash=<pay_hash> --routes=<route>)
* passing the route as a positional argument:
(lncli sendtoroute --payment_hash=pay_hash <route>)
* or reading in the route from stdin, which can allow chaining the
response from queryroutes or buildroute, or even read in a file
with a pre-computed route:
(lncli queryroutes --args.. | lncli sendtoroute --payment_hash= -
notice the '-' at the end, which signals that lncli should read
the route in from stdin
`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "payment_hash, pay_hash",
Usage: "the hash to use within the payment's HTLC",
},
cli.StringFlag{
Name: "routes, r",
Usage: "a json array string in the format of the response " +
"of queryroutes that denotes which routes to use",
},
},
Action: sendToRoute,
}
func sendToRoute(ctx *cli.Context) er.R {
// Show command help if no arguments provided.
if ctx.NArg() == 0 && ctx.NumFlags() == 0 {
_ = cli.ShowCommandHelp(ctx, "sendtoroute")
return nil
}
args := ctx.Args()
var (
rHash []byte
err er.R
)
switch {
case ctx.IsSet("payment_hash"):
rHash, err = util.DecodeHex(ctx.String("payment_hash"))
case args.Present():
rHash, err = util.DecodeHex(args.First())
args = args.Tail()
default:
return er.Errorf("payment hash argument missing")
}
if err != nil {
return err
}
if len(rHash) != 32 {
return er.Errorf("payment hash must be exactly 32 "+
"bytes, is instead %d", len(rHash))
}
var jsonRoutes string
switch {
// The user is specifying the routes explicitly via the key word
// argument.
case ctx.IsSet("routes"):
jsonRoutes = ctx.String("routes")
// The user is specifying the routes as a positional argument.
case args.Present() && args.First() != "-":
jsonRoutes = args.First()
// The user is signalling that we should read stdin in order to parse
// the set of target routes.
case args.Present() && args.First() == "-":
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return er.E(err)
}
if len(b) == 0 {
return er.Errorf("queryroutes output is empty")
}
jsonRoutes = string(b)
}
// Try to parse the provided json both in the legacy QueryRoutes format
// that contains a list of routes and the single route BuildRoute
// format.
var route *lnrpc.Route
routes := &lnrpc.QueryRoutesResponse{}
errr := jsonpb.UnmarshalString(jsonRoutes, routes)
if errr == nil {
if len(routes.Routes) == 0 {
return er.Errorf("no routes provided")
}
if len(routes.Routes) != 1 {
return er.Errorf("expected a single route, but got %v",
len(routes.Routes))
}
route = routes.Routes[0]
} else {
routes := &routerrpc.BuildRouteResponse{}
errr = jsonpb.UnmarshalString(jsonRoutes, routes)
if errr != nil {
return er.Errorf("unable to unmarshal json string "+
"from incoming array of routes: %v", errr)
}
route = routes.Route
}
req := &routerrpc.SendToRouteRequest{
PaymentHash: rHash,
Route: route,
}
return sendToRouteRequest(ctx, req)
}
func sendToRouteRequest(ctx *cli.Context, req *routerrpc.SendToRouteRequest) er.R {
conn := getClientConn(ctx, false)
defer conn.Close()
client := routerrpc.NewRouterClient(conn)
resp, errr := client.SendToRouteV2(context.Background(), req)
if errr != nil {
return er.E(errr)
}
printRespJSON(resp)
return nil
}
// ESC is the ASCII code for escape character
const ESC = 27
// clearCode defines a terminal escape code to clear the currently line and move
// the cursor up.
var clearCode = fmt.Sprintf("%c[%dA%c[2K", ESC, 1, ESC)
// clearLines erases the last count lines in the terminal window.
func clearLines(count int) {
_, _ = fmt.Print(strings.Repeat(clearCode, count))
}