-
Notifications
You must be signed in to change notification settings - Fork 912
/
Copy pathpay.c
1717 lines (1482 loc) · 50.1 KB
/
pay.c
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
#include <ccan/array_size/array_size.h>
#include <ccan/cast/cast.h>
#include <ccan/crypto/siphash24/siphash24.h>
#include <ccan/htable/htable_type.h>
#include <ccan/intmap/intmap.h>
#include <ccan/json_out/json_out.h>
#include <ccan/tal/str/str.h>
#include <common/amount.h>
#include <common/bolt11.h>
#include <common/errcode.h>
#include <common/features.h>
#include <common/gossip_constants.h>
#include <common/json_stream.h>
#include <common/pseudorand.h>
#include <common/type_to_string.h>
#include <inttypes.h>
#include <plugins/libplugin.h>
#include <stdint.h>
#include <stdio.h>
#include <wire/onion_defs.h>
#include <wire/wire.h>
/* Public key of this node. */
static struct node_id my_id;
static unsigned int maxdelay_default;
static LIST_HEAD(pay_status);
struct pay_attempt {
/* What we changed when starting this attempt. */
const char *why;
/* Time we started & finished attempt */
struct timeabs start, end;
/* Route hint we were using (if any) */
struct route_info *routehint;
/* Channels we excluded when doing route lookup. */
const char **excludes;
/* Route we got (NULL == route lookup fail). */
const char *route;
/* Did we actually try to send a payment? */
bool sendpay;
/* The failure result (NULL on success) */
struct json_out *failure;
/* The non-failure result (NULL on failure) */
const char *result;
/* The blockheight at which the payment attempt was
* started. */
u32 start_block;
};
struct pay_status {
/* Destination, as text */
const char *dest;
/* We're in 'pay_status' global list. */
struct list_node list;
/* Description user provided (if any) */
const char *label;
/* Amount they wanted to pay. */
struct amount_msat msat;
/* CLTV delay required by destination. */
u32 final_cltv;
/* Bolt11 invoice. */
const char *bolt11;
/* What we did about routehints (if anything) */
const char *routehint_modifications;
/* Details of shadow route we chose (if any) */
char *shadow;
/* Details of initial exclusions (if any) */
const char *exclusions;
/* Array of payment attempts. */
struct pay_attempt *attempts;
};
struct pay_command {
/* Global state */
struct plugin *plugin;
/* Destination, as text */
const char *dest;
/* How much we're paying, and what riskfactor for routing. */
struct amount_msat msat;
/* riskfactor 12.345% -> riskfactor_millionths = 12345000 */
u64 riskfactor_millionths;
unsigned int final_cltv;
/* Limits on what routes we'll accept. */
/* 12.345% -> maxfee_pct_millionths = 12345000 */
u64 maxfee_pct_millionths;
unsigned int maxdelay;
struct amount_msat exemptfee;
/* Payment hash, as text. */
const char *payment_hash;
/* Payment secret, if specified by invoice. */
const char *payment_secret;
/* Description, if any. */
const char *label;
/* Chatty description of attempts. */
struct pay_status *ps;
/* Error to use if getroute says it can't find route. */
const char *expensive_route;
/* Time to stop retrying. */
struct timeabs stoptime;
/* Channels which have failed us. */
const char **excludes;
/* Current routehint, if any. */
struct route_info *current_routehint;
/* Any remaining routehints to try. */
struct route_info **routehints;
#if DEVELOPER
/* Disable the use of shadow route ? */
double use_shadow;
#endif
/* Current node during shadow route calculation. */
const char *shadow_dest;
};
static struct pay_attempt *current_attempt(struct pay_command *pc)
{
return &pc->ps->attempts[tal_count(pc->ps->attempts)-1];
}
/* Helper to copy JSON object directly into a json_out */
static void json_out_add_raw_len(struct json_out *jout,
const char *fieldname,
const char *jsonstr, size_t len)
{
char *p;
p = json_out_member_direct(jout, fieldname, len);
memcpy(p, jsonstr, len);
}
static struct json_out *failed_start(struct pay_command *pc)
{
struct pay_attempt *attempt = current_attempt(pc);
attempt->end = time_now();
attempt->failure = json_out_new(pc->ps->attempts);
json_out_start(attempt->failure, NULL, '{');
return attempt->failure;
}
static void failed_end(struct json_out *jout)
{
json_out_end(jout, '}');
json_out_finished(jout);
}
/* Copy field and member to output, if it exists: return member */
static const jsmntok_t *copy_member(struct json_out *ret,
const char *buf, const jsmntok_t *obj,
const char *membername)
{
const jsmntok_t *m = json_get_member(buf, obj, membername);
if (!m)
return NULL;
/* FIXME: The fact it is a string is probably the wrong thing
* to handle: if it *is* a string we should probably copy
* the quote marks, but json_tok_full/json_tok_full_len
* specifically remove those.
* It works *now* because it is only used in "code" and
* "data": "code" is always numeric, and "data" is usually
* a JSON object/key-value table, but pure stromgs will
* probably result in invalid JSON.
*/
/* Literal copy: it's already JSON escaped, and may be a string. */
json_out_add_raw_len(ret, membername,
json_tok_full(buf, m), json_tok_full_len(m));
return m;
}
/* Copy (and modify) error object. */
static void attempt_failed_tok(struct pay_command *pc, const char *method,
const char *buf, const jsmntok_t *errtok)
{
const jsmntok_t *msg = json_get_member(buf, errtok, "message");
struct json_out *failed = failed_start(pc);
/* Every JSON error response has code and error. */
copy_member(failed, buf, errtok, "code");
json_out_add(failed, "message", true,
"Call to %s: %.*s",
method, msg->end - msg->start,
buf + msg->start);
copy_member(failed, buf, errtok, "data");
failed_end(failed);
}
static struct command_result *start_pay_attempt(struct command *cmd,
struct pay_command *pc,
const char *fmt, ...);
/* Is this (erring) channel within the routehint itself? */
static bool node_or_channel_in_routehint(struct plugin *plugin,
const struct route_info *routehint,
const char *idstr, size_t idlen)
{
struct node_id nodeid;
struct short_channel_id scid;
bool node_err = true;
if (!node_id_from_hexstr(idstr, idlen, &nodeid)) {
if (!short_channel_id_from_str(idstr, idlen, &scid))
plugin_err(plugin, "bad erring_node or erring_channel '%.*s'",
(int)idlen, idstr);
else
node_err = false;
}
for (size_t i = 0; i < tal_count(routehint); i++) {
if (node_err) {
if (node_id_eq(&nodeid, &routehint[i].pubkey))
return true;
} else {
if (short_channel_id_eq(&scid, &routehint[i].short_channel_id))
return true;
}
}
return false;
}
/* Count times we actually tried to pay, not where route lookup failed or
* we disliked route for being too expensive, etc. */
static size_t count_sendpays(const struct pay_attempt *attempts)
{
size_t n = 0;
for (size_t i = 0; i < tal_count(attempts); i++)
n += attempts[i].sendpay;
return n;
}
static struct command_result *waitsendpay_expired(struct command *cmd,
struct pay_command *pc)
{
char *errmsg;
struct json_stream *data;
size_t num_attempts = count_sendpays(pc->ps->attempts);
errmsg = tal_fmt(pc, "Gave up after %zu attempt%s: see paystatus",
num_attempts, num_attempts == 1 ? "" : "s");
data = jsonrpc_stream_fail(cmd, PAY_STOPPED_RETRYING, errmsg);
json_object_start(data, "data");
json_array_start(data, "attempts");
for (size_t i = 0; i < tal_count(pc->ps->attempts); i++) {
json_object_start(data, NULL);
if (pc->ps->attempts[i].route)
json_add_jsonstr(data, "route",
pc->ps->attempts[i].route);
json_out_add_splice(data->jout, "failure",
pc->ps->attempts[i].failure);
json_object_end(data);
}
json_array_end(data);
json_object_end(data);
return command_finished(cmd, data);
}
static bool routehint_excluded(struct plugin *plugin,
const struct route_info *routehint,
const char **excludes)
{
/* Note that we ignore direction here: in theory, we could have
* found that one direction of a channel is unavailable, but they
* are suggesting we use it the other way. Very unlikely though! */
for (size_t i = 0; i < tal_count(excludes); i++)
if (node_or_channel_in_routehint(plugin,
routehint,
excludes[i],
strlen(excludes[i])))
return true;
return false;
}
static struct command_result *next_routehint(struct command *cmd,
struct pay_command *pc)
{
size_t num_attempts = count_sendpays(pc->ps->attempts);
while (tal_count(pc->routehints) > 0) {
if (!routehint_excluded(pc->plugin, pc->routehints[0],
pc->excludes)) {
pc->current_routehint = pc->routehints[0];
tal_arr_remove(&pc->routehints, 0);
return start_pay_attempt(cmd, pc, "Trying route hint");
}
tal_free(pc->routehints[0]);
tal_arr_remove(&pc->routehints, 0);
}
/* No (more) routehints; we're out of routes. */
/* If we eliminated one because it was too pricy, return that. */
if (pc->expensive_route)
return command_fail(cmd, PAY_ROUTE_TOO_EXPENSIVE,
"%s", pc->expensive_route);
if (num_attempts > 0)
return command_fail(cmd, PAY_STOPPED_RETRYING,
"Ran out of routes to try after"
" %zu attempt%s: see paystatus",
num_attempts, num_attempts == 1 ? "" : "s");
return command_fail(cmd, PAY_ROUTE_NOT_FOUND,
"Could not find a route");
}
static struct command_result *
waitblockheight_done(struct command *cmd,
const char *buf UNUSED,
const jsmntok_t *result UNUSED,
struct pay_command *pc)
{
return start_pay_attempt(cmd, pc,
"Retried due to blockheight "
"disagreement with payee");
}
static struct command_result *
waitblockheight_error(struct command *cmd,
const char *buf UNUSED,
const jsmntok_t *error UNUSED,
struct pay_command *pc)
{
if (time_after(time_now(), pc->stoptime))
return waitsendpay_expired(cmd, pc);
else
/* Ehhh just retry it. */
return waitblockheight_done(cmd, buf, error, pc);
}
static struct command_result *
execute_waitblockheight(struct command *cmd,
u32 blockheight,
struct pay_command *pc)
{
struct out_req *req;
struct timeabs now = time_now();
struct timerel remaining;
if (time_after(now, pc->stoptime))
return waitsendpay_expired(cmd, pc);
remaining = time_between(pc->stoptime, now);
req = jsonrpc_request_start(cmd->plugin, cmd, "waitblockheight",
&waitblockheight_done,
&waitblockheight_error,
pc);
json_add_u32(req->js, "blockheight", blockheight);
json_add_u32(req->js, "timeout", time_to_sec(remaining));
return send_outreq(cmd->plugin, req);
}
/* Gets the remote height from a
* WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
* failure.
* Return 0 if unable to find such a height.
*/
static u32
get_remote_block_height(const char *buf, const jsmntok_t *error)
{
const jsmntok_t *raw_message_tok;
const u8 *raw_message;
size_t raw_message_len;
u16 type;
/* Is there even a raw_message? */
raw_message_tok = json_delve(buf, error, ".data.raw_message");
if (!raw_message_tok)
return 0;
if (raw_message_tok->type != JSMN_STRING)
return 0;
raw_message = json_tok_bin_from_hex(tmpctx, buf, raw_message_tok);
if (!raw_message)
return 0;
/* BOLT #4:
*
* 1. type: PERM|15 (`incorrect_or_unknown_payment_details`)
* 2. data:
* * [`u64`:`htlc_msat`]
* * [`u32`:`height`]
*
*/
raw_message_len = tal_count(raw_message);
type = fromwire_u16(&raw_message, &raw_message_len); /* type */
if (type != WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS)
return 0;
(void) fromwire_u64(&raw_message, &raw_message_len); /* htlc_msat */
return fromwire_u32(&raw_message, &raw_message_len); /* height */
}
static struct command_result *waitsendpay_error(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct pay_command *pc)
{
struct pay_attempt *attempt = current_attempt(pc);
const jsmntok_t *codetok, *failcodetok, *nodeidtok, *scidtok, *dirtok;
errcode_t code;
int failcode;
bool node_err = false;
attempt_failed_tok(pc, "waitsendpay", buf, error);
codetok = json_get_member(buf, error, "code");
if (!json_to_errcode(buf, codetok, &code))
plugin_err(cmd->plugin, "waitsendpay error gave no 'code'? '%.*s'",
error->end - error->start, buf + error->start);
if (code != PAY_UNPARSEABLE_ONION) {
failcodetok = json_delve(buf, error, ".data.failcode");
if (!json_to_int(buf, failcodetok, &failcode))
plugin_err(cmd->plugin, "waitsendpay error gave no 'failcode'? '%.*s'",
error->end - error->start, buf + error->start);
}
/* Special case for WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS.
*
* One possible trigger for this failure is that the receiver
* thinks the final timeout it gets is too near the future.
*
* For the most part, we respect the indicated `final_cltv`
* in the invoice, and our shadow routing feature also tends
* to give more timing budget to the receiver than the
* `final_cltv`.
*
* However, there is an edge case possible on real networks:
*
* * We send out a payment respecting the `final_cltv` of
* the receiver.
* * Miners mine a new block while the payment is in transit.
* * By the time the payment reaches the receiver, the
* payment violates the `final_cltv` because the receiver
* is now using a different basis blockheight.
*
* This is a transient error.
* Unfortunately, WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS
* is marked with the PERM bit.
* This means that we would give up on this since `waitsendpay`
* would return PAY_DESTINATION_PERM_FAIL instead of
* PAY_TRY_OTHER_ROUTE.
* Thus the `pay` plugin would not retry this case.
*
* Thus, we need to add this special-case checking here, where
* the blockheight when we started the pay attempt was not
* the same as what the payee reports.
*
* In the past this particular failure had its own failure code,
* equivalent to 17.
* In case the receiver is a really old software, we also
* special-case it here.
*/
if ((code != PAY_UNPARSEABLE_ONION) &&
((failcode == 17) ||
((failcode == WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS) &&
(attempt->start_block < get_remote_block_height(buf, error))))) {
u32 target_blockheight;
if (failcode == 17)
target_blockheight = attempt->start_block + 1;
else
target_blockheight = get_remote_block_height(buf, error);
return execute_waitblockheight(cmd, target_blockheight,
pc);
}
/* FIXME: Handle PAY_UNPARSEABLE_ONION! */
/* Many error codes are final. */
if (code != PAY_TRY_OTHER_ROUTE) {
return forward_error(cmd, buf, error, pc);
}
if (failcode & NODE) {
nodeidtok = json_delve(buf, error, ".data.erring_node");
if (!nodeidtok)
plugin_err(cmd->plugin, "waitsendpay error no erring_node '%.*s'",
error->end - error->start, buf + error->start);
node_err = true;
} else {
scidtok = json_delve(buf, error, ".data.erring_channel");
if (!scidtok)
plugin_err(cmd->plugin, "waitsendpay error no erring_channel '%.*s'",
error->end - error->start, buf + error->start);
dirtok = json_delve(buf, error, ".data.erring_direction");
if (!dirtok)
plugin_err(cmd->plugin, "waitsendpay error no erring_direction '%.*s'",
error->end - error->start, buf + error->start);
}
if (time_after(time_now(), pc->stoptime)) {
return waitsendpay_expired(cmd, pc);
}
if (node_err) {
/* If failure is in routehint part, try next one */
if (node_or_channel_in_routehint(pc->plugin, pc->current_routehint,
buf + nodeidtok->start,
nodeidtok->end - nodeidtok->start))
return next_routehint(cmd, pc);
/* Otherwise, add erring channel to exclusion list. */
tal_arr_expand(&pc->excludes,
tal_fmt(pc->excludes, "%.*s",
nodeidtok->end - nodeidtok->start,
buf + nodeidtok->start));
} else {
/* If failure is in routehint part, try next one */
if (node_or_channel_in_routehint(pc->plugin, pc->current_routehint,
buf + scidtok->start,
scidtok->end - scidtok->start))
return next_routehint(cmd, pc);
/* Otherwise, add erring channel to exclusion list. */
tal_arr_expand(&pc->excludes,
tal_fmt(pc->excludes, "%.*s/%c",
scidtok->end - scidtok->start,
buf + scidtok->start,
buf[dirtok->start]));
}
/* Try again. */
return start_pay_attempt(cmd, pc, "Excluded %s %s",
node_err ? "node" : "channel",
pc->excludes[tal_count(pc->excludes)-1]);
}
static struct command_result *waitsendpay_done(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct pay_command *pc)
{
struct pay_attempt *attempt = current_attempt(pc);
attempt->result = json_strdup(pc->ps->attempts, buf, result);
attempt->end = time_now();
return forward_result(cmd, buf, result, pc);
}
static struct command_result *sendpay_done(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct pay_command *pc)
{
struct out_req *req = jsonrpc_request_start(cmd->plugin, cmd,
"waitsendpay",
waitsendpay_done,
waitsendpay_error, pc);
json_add_string(req->js, "payment_hash", pc->payment_hash);
return send_outreq(cmd->plugin, req);
}
/* Calculate how many millisatoshi we need at the start of this route
* to get msatoshi to the end. */
static bool route_msatoshi(struct amount_msat *total,
const struct amount_msat msat,
const struct route_info *route, size_t num_route)
{
*total = msat;
for (ssize_t i = num_route - 1; i >= 0; i--) {
if (!amount_msat_add_fee(total,
route[i].fee_base_msat,
route[i].fee_proportional_millionths))
return false;
}
return true;
}
/* Calculate cltv we need at the start of this route to get cltv at the end. */
static u32 route_cltv(u32 cltv,
const struct route_info *route, size_t num_route)
{
for (size_t i = 0; i < num_route; i++)
cltv += route[i].cltv_expiry_delta;
return cltv;
}
/* The pubkey to use is the destination of this routehint. */
static const char *route_pubkey(const tal_t *ctx,
const struct pay_command *pc,
const struct route_info *routehint,
size_t n)
{
if (n == tal_count(routehint))
return pc->dest;
return type_to_string(ctx, struct node_id, &routehint[n].pubkey);
}
static const char *join_routehint(const tal_t *ctx,
const char *buf,
const jsmntok_t *route,
const struct pay_command *pc,
const struct route_info *routehint)
{
char *ret;
/* Truncate closing ] from route */
ret = tal_strndup(ctx, buf + route->start, route->end - route->start - 1);
for (size_t i = 0; i < tal_count(routehint); i++) {
/* amount to be received by *destination* */
struct amount_msat dest_amount;
if (!route_msatoshi(&dest_amount, pc->msat,
routehint + i + 1,
tal_count(routehint) - i - 1))
return tal_free(ret);
tal_append_fmt(&ret, ", {"
" \"id\": \"%s\","
" \"channel\": \"%s\","
" \"msatoshi\": \"%s\","
" \"delay\": %u }",
/* pubkey of *destination* */
route_pubkey(tmpctx, pc, routehint, i + 1),
type_to_string(tmpctx, struct short_channel_id,
&routehint[i].short_channel_id),
type_to_string(tmpctx, struct amount_msat,
&dest_amount),
/* cltv for *destination* */
route_cltv(pc->final_cltv, routehint + i + 1,
tal_count(routehint) - i - 1));
}
/* Put ] back */
tal_append_fmt(&ret, "]");
return ret;
}
static struct command_result *sendpay_error(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct pay_command *pc)
{
attempt_failed_tok(pc, "sendpay", buf, error);
return forward_error(cmd, buf, error, pc);
}
static const jsmntok_t *find_worst_channel(const char *buf,
const jsmntok_t *route,
const char *fieldname)
{
u64 prev, worstval = 0;
const jsmntok_t *worst = NULL, *t, *t_prev = NULL;
size_t i;
json_for_each_arr(i, t, route) {
u64 val;
json_to_u64(buf, json_get_member(buf, t, fieldname), &val);
/* For the first hop, now we can't know if it's the worst.
* Just store the info and continue. */
if (!i) {
prev = val;
t_prev = t;
continue;
}
if (worst == NULL || prev - val > worstval) {
worst = t_prev;
worstval = prev - val;
}
prev = val;
t_prev = t;
}
return worst;
}
/* Can't exclude if it's in routehint itself. */
static bool maybe_exclude(struct pay_command *pc,
const char *buf, const jsmntok_t *route)
{
const jsmntok_t *scid, *dir;
if (!route)
return false;
scid = json_get_member(buf, route, "channel");
if (node_or_channel_in_routehint(pc->plugin,
pc->current_routehint,
buf + scid->start,
scid->end - scid->start))
return false;
dir = json_get_member(buf, route, "direction");
tal_arr_expand(&pc->excludes,
tal_fmt(pc->excludes, "%.*s/%c",
scid->end - scid->start,
buf + scid->start,
buf[dir->start]));
return true;
}
static struct command_result *getroute_done(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct pay_command *pc)
{
struct pay_attempt *attempt = current_attempt(pc);
const jsmntok_t *t = json_get_member(buf, result, "route");
struct amount_msat fee;
struct amount_msat max_fee;
u32 delay;
struct out_req *req;
if (!t)
plugin_err(cmd->plugin, "getroute gave no 'route'? '%.*s'",
result->end - result->start, buf);
if (pc->current_routehint) {
attempt->route = join_routehint(pc->ps->attempts, buf, t,
pc, pc->current_routehint);
if (!attempt->route) {
struct json_out *failed = failed_start(pc);
json_out_add(failed, "message", true,
"Joining routehint gave absurd fee");
failed_end(failed);
return next_routehint(cmd, pc);
}
} else
attempt->route = json_strdup(pc->ps->attempts, buf, t);
if (!json_to_msat(buf, json_delve(buf, t, "[0].msatoshi"), &fee))
plugin_err(cmd->plugin, "getroute with invalid msatoshi? %.*s",
result->end - result->start, buf);
if (!amount_msat_sub(&fee, fee, pc->msat))
plugin_err(cmd->plugin, "final amount %s less than paid %s",
type_to_string(tmpctx, struct amount_msat, &fee),
type_to_string(tmpctx, struct amount_msat, &pc->msat));
if (!json_to_number(buf, json_delve(buf, t, "[0].delay"), &delay))
plugin_err(cmd->plugin, "getroute with invalid delay? %.*s",
result->end - result->start, buf);
if (pc->maxfee_pct_millionths / 100 > UINT32_MAX)
plugin_err(cmd->plugin, "max fee percent too large: %lf",
pc->maxfee_pct_millionths / 1000000.0);
if (!amount_msat_fee(&max_fee, pc->msat, 0,
(u32)(pc->maxfee_pct_millionths / 100)))
plugin_err(
cmd->plugin, "max fee too large: %s * %lf%%",
type_to_string(tmpctx, struct amount_msat, &pc->msat),
pc->maxfee_pct_millionths / 1000000.0);
if (amount_msat_greater(fee, pc->exemptfee) &&
amount_msat_greater(fee, max_fee)) {
const jsmntok_t *charger;
struct json_out *failed;
char *feemsg;
feemsg = tal_fmt(pc, "Route wanted fee of %s",
type_to_string(tmpctx, struct amount_msat,
&fee));
failed = failed_start(pc);
json_out_addstr(failed, "message", feemsg);
failed_end(failed);
/* Remember this if we eliminating this causes us to have no
* routes at all! */
if (!pc->expensive_route)
pc->expensive_route = feemsg;
else
tal_free(feemsg);
/* Try excluding most fee-charging channel (unless it's in
* routeboost). */
charger = find_worst_channel(buf, t, "msatoshi");
if (maybe_exclude(pc, buf, charger)) {
return start_pay_attempt(cmd, pc,
"Excluded expensive channel %s",
pc->excludes[tal_count(pc->excludes)-1]);
}
return next_routehint(cmd, pc);
}
if (delay > pc->maxdelay) {
const jsmntok_t *delayer;
struct json_out *failed;
char *feemsg;
feemsg = tal_fmt(pc, "Route wanted delay of %u blocks", delay);
failed = failed_start(pc);
json_out_addstr(failed, "message", feemsg);
failed_end(failed);
/* Remember this if we eliminating this causes us to have no
* routes at all! */
if (!pc->expensive_route)
pc->expensive_route = feemsg;
else
tal_free(failed);
delayer = find_worst_channel(buf, t, "delay");
/* Try excluding most delaying channel (unless it's in
* routeboost). */
if (maybe_exclude(pc, buf, delayer)) {
return start_pay_attempt(cmd, pc,
"Excluded delaying channel %s",
pc->excludes[tal_count(pc->excludes)-1]);
}
return next_routehint(cmd, pc);
}
attempt->sendpay = true;
req = jsonrpc_request_start(cmd->plugin, cmd, "sendpay",
sendpay_done, sendpay_error, pc);
json_add_jsonstr(req->js, "route", attempt->route);
json_add_string(req->js, "payment_hash", pc->payment_hash);
json_add_string(req->js, "bolt11", pc->ps->bolt11);
if (pc->label)
json_add_string(req->js, "label", pc->label);
if (pc->payment_secret)
json_add_string(req->js, "payment_secret", pc->payment_secret);
return send_outreq(cmd->plugin, req);
}
static struct command_result *getroute_error(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct pay_command *pc)
{
errcode_t code;
const jsmntok_t *codetok;
attempt_failed_tok(pc, "getroute", buf, error);
codetok = json_get_member(buf, error, "code");
if (!json_to_errcode(buf, codetok, &code))
plugin_err(cmd->plugin, "getroute error gave no 'code'? '%.*s'",
error->end - error->start, buf + error->start);
/* Strange errors from getroute should be forwarded. */
if (code != PAY_ROUTE_NOT_FOUND)
return forward_error(cmd, buf, error, pc);
return next_routehint(cmd, pc);
}
/* Deep copy of excludes array. */
static const char **dup_excludes(const tal_t *ctx, const char **excludes)
{
const char **ret = tal_dup_talarr(ctx, const char *, excludes);
for (size_t i = 0; i < tal_count(ret); i++)
ret[i] = tal_strdup(ret, excludes[i]);
return ret;
}
/* Get a route from the lightningd. */
static struct command_result *execute_getroute(struct command *cmd,
struct pay_command *pc)
{
struct pay_attempt *attempt = current_attempt(pc);
u32 max_hops = ROUTING_MAX_HOPS;
struct amount_msat msat;
const char *dest;
u32 cltv;
struct out_req *req;
/* routehint set below. */
/* If we have a routehint, try that first; we need to do extra
* checks that it meets our criteria though. */
if (pc->current_routehint) {
attempt->routehint = tal_steal(pc->ps, pc->current_routehint);
if (!route_msatoshi(&msat, pc->msat,
attempt->routehint,
tal_count(attempt->routehint))) {
struct json_out *failed;
failed = failed_start(pc);
json_out_addstr(failed, "message",
"Routehint absurd fee");
failed_end(failed);
return next_routehint(cmd, pc);
}
dest = type_to_string(tmpctx, struct node_id,
&attempt->routehint[0].pubkey);
max_hops -= tal_count(attempt->routehint);
cltv = route_cltv(pc->final_cltv,
attempt->routehint,
tal_count(attempt->routehint));
} else {
msat = pc->msat;
dest = pc->dest;
cltv = pc->final_cltv;
attempt->routehint = NULL;
}
/* OK, ask for route to destination */
req = jsonrpc_request_start(cmd->plugin, cmd, "getroute",
getroute_done, getroute_error, pc);
json_add_string(req->js, "id", dest);
json_add_string(req->js, "msatoshi",
type_to_string(tmpctx, struct amount_msat, &msat));
json_add_u32(req->js, "cltv", cltv);
json_add_u32(req->js, "maxhops", max_hops);
json_add_member(req->js, "riskfactor", false, "%lf",
pc->riskfactor_millionths / 1000000.0);
if (tal_count(pc->excludes) != 0) {
json_array_start(req->js, "exclude");
for (size_t i = 0; i < tal_count(pc->excludes); i++)
json_add_string(req->js, NULL, pc->excludes[i]);
json_array_end(req->js);
}
return send_outreq(cmd->plugin, req);
}
static struct command_result *
getstartblockheight_done(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct pay_command *pc)
{
const jsmntok_t *blockheight_tok;
u32 blockheight;
blockheight_tok = json_get_member(buf, result, "blockheight");
if (!blockheight_tok)
plugin_err(cmd->plugin, "getstartblockheight: "
"getinfo gave no 'blockheight'? '%.*s'",
result->end - result->start, buf);
if (!json_to_u32(buf, blockheight_tok, &blockheight))
plugin_err(cmd->plugin, "getstartblockheight: "
"getinfo gave non-unsigned-32-bit 'blockheight'? '%.*s'",
result->end - result->start, buf);
current_attempt(pc)->start_block = blockheight;
return execute_getroute(cmd, pc);
}
static struct command_result *
getstartblockheight_error(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct pay_command *pc)
{
/* Should never happen. */
plugin_err(cmd->plugin, "getstartblockheight: getinfo failed!? '%.*s'",
error->end - error->start, buf);
}
static struct command_result *
execute_getstartblockheight(struct command *cmd,
struct pay_command *pc)
{
struct out_req *req = jsonrpc_request_start(cmd->plugin, cmd, "getinfo",
&getstartblockheight_done,
&getstartblockheight_error,
pc);
return send_outreq(cmd->plugin, req);
}
static struct command_result *start_pay_attempt(struct command *cmd,
struct pay_command *pc,
const char *fmt, ...)
{
struct pay_attempt *attempt;
va_list ap;
size_t n;
n = tal_count(pc->ps->attempts);
tal_resize(&pc->ps->attempts, n+1);