-
Notifications
You must be signed in to change notification settings - Fork 997
Expand file tree
/
Copy pathxpay.c
More file actions
2554 lines (2259 loc) · 79.3 KB
/
xpay.c
File metadata and controls
2554 lines (2259 loc) · 79.3 KB
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 "config.h"
#include <ccan/array_size/array_size.h>
#include <ccan/crypto/siphash24/siphash24.h>
#include <ccan/htable/htable_type.h>
#include <ccan/json_escape/json_escape.h>
#include <ccan/json_out/json_out.h>
#include <ccan/tal/str/str.h>
#include <common/bolt11.h>
#include <common/bolt12.h>
#include <common/clock_time.h>
#include <common/daemon.h>
#include <common/dijkstra.h>
#include <common/features.h>
#include <common/gossmap.h>
#include <common/gossmods_listpeerchannels.h>
#include <common/json_param.h>
#include <common/json_stream.h>
#include <common/memleak.h>
#include <common/onion_encode.h>
#include <common/onionreply.h>
#include <common/pseudorand.h>
#include <common/route.h>
#include <common/wireaddr.h>
#include <errno.h>
#include <inttypes.h>
#include <plugins/libplugin.h>
#include <stdarg.h>
/* For the whole plugin */
struct xpay {
struct pubkey local_id;
/* Access via get_gossmap() */
struct gossmap *global_gossmap;
/* Creates unique layer names */
size_t counter;
/* Can-never-exist fake key for blinded paths */
struct pubkey fakenode;
/* We need to know current block height */
u32 blockheight;
/* Do we take over "pay" commands? */
bool take_over_pay;
/* Are we to wait for all parts to complete before returning? */
bool slow_mode;
/* Suppress calls to askrene-age */
bool dev_no_age;
};
static struct xpay *xpay_of(struct plugin *plugin)
{
return plugin_get_data(plugin, struct xpay);
}
/* This refreshes the gossmap. */
static struct gossmap *get_gossmap(struct xpay *xpay)
{
gossmap_refresh(xpay->global_gossmap);
return xpay->global_gossmap;
}
/* The unifies bolt11 and bolt12 handling */
struct payment {
struct plugin *plugin;
/* Stop sending new payments after this */
struct timemono deadline;
/* Blockheight when we started (if in future, wait for this!) */
u32 start_blockheight;
/* This is the command which is expecting the success/fail. When
* it's NULL, that means we're just cleaning up */
struct command *cmd;
/* Unique id */
u64 unique_id;
/* For logging, and for sendpays */
const char *invstring;
/* Explicit layers they told us to include */
const char **layers;
/* Where we're trying to pay */
struct pubkey destination;
/* Hash we want the preimage for */
struct sha256 payment_hash;
/* Amount we're trying to pay */
struct amount_msat amount;
/* Fullamount of invoice (usually the same as above) */
struct amount_msat full_amount;
/* Maximum fee we're prepare to pay */
struct amount_msat maxfee;
/* Maximum delay on the route we're ok with */
u32 maxdelay;
/* If non-zero: maximum number of payment routes that can be pending. */
u32 maxparts;
/* Do we have to do it all in a single part? */
bool disable_mpp;
/* BOLT11 payment secret (NULL for BOLT12, it uses blinded paths) */
const struct secret *payment_secret;
/* BOLT11 payment metadata (NULL for BOLT12, it uses blinded paths) */
const u8 *payment_metadata;
/* Final CLTV value */
u32 final_cltv;
/* Group id for this payment */
uint64_t group_id;
/* Counter for partids (also, total attempts) */
uint64_t total_num_attempts;
/* How many parts failed? */
uint64_t num_failures;
/* Name of our temporary additional layer */
const char *private_layer;
/* For bolt11 we have route hints */
struct route_info **route_hints;
/* For bolt12 we have blinded paths */
struct blinded_path **paths;
struct blinded_payinfo **payinfos;
/* Current attempts, waiting for injectpaymentonion. */
struct list_head current_attempts;
/* We keep these around, since they may still be cleaning up. */
struct list_head past_attempts;
/* Amount we just asked getroutes for (0 means no getroutes
* call outstanding). */
struct amount_msat amount_being_routed;
/* Useful information from prior attempts if any. */
char *prior_results;
/* Requests currently outstanding */
struct out_req **requests;
/* Are we pretending to be "pay"? */
bool pay_compat;
/* When did we start? */
struct timeabs start_time;
};
/* One step in a path. */
struct hop {
/* Node this hop leads to. */
struct pubkey next_node;
/* Via this channel */
struct short_channel_id_dir scidd;
/* This is amount the node needs (including fees) */
struct amount_msat amount_in;
/* ... to send this amount */
struct amount_msat amount_out;
/* This is the delay, including delay across node */
u32 cltv_value_in;
/* This is the delay, out from node. */
u32 cltv_value_out;
/* This is a fake channel. */
bool fake_channel;
};
/* Each actual payment attempt */
struct attempt {
/* Inside payment->attempts */
struct list_node list;
u64 partid;
struct payment *payment;
struct amount_msat delivers;
struct timemono start_time;
/* Path we tried, so we can unreserve, and tell askrene the results */
const struct hop *hops;
/* Secrets, so we can decrypt error onions */
struct secret *shared_secrets;
/* Preimage, iff we succeeded. */
const struct preimage *preimage;
};
/* Recursion */
static struct command_result *xpay_core(struct command *cmd,
const char *invstring TAKES,
const struct amount_msat *msat,
const struct amount_msat *maxfee,
const char **layers,
u32 retryfor,
const struct amount_msat *partial,
u32 maxdelay,
bool as_pay);
/* Wrapper for pending commands (ignores return) */
static void was_pending(const struct command_result *res)
{
assert(res);
}
/* Recursion, so declare now */
static struct command_result *getroutes_for(struct command *cmd,
struct payment *payment,
struct amount_msat deliver);
/* Pretty printing paths */
static const char *fmt_path(const tal_t *ctx,
const struct attempt *attempt)
{
char *s = tal_strdup(ctx, "");
for (size_t i = 0; i < tal_count(attempt->hops); i++) {
tal_append_fmt(&s, "->%s",
fmt_pubkey(tmpctx, &attempt->hops[i].next_node));
}
return s;
}
static void payment_log(struct payment *payment,
enum log_level level,
const char *fmt,
...)
PRINTF_FMT(3,4);
/* Logging: both to the command itself and the log file */
static void payment_log(struct payment *payment,
enum log_level level,
const char *fmt,
...)
{
va_list args;
const char *msg;
va_start(args, fmt);
msg = tal_vfmt(tmpctx, fmt, args);
va_end(args);
if (payment->cmd)
plugin_notify_message(payment->cmd, level, "%s", msg);
plugin_log(payment->plugin, level, "%"PRIu64": %s",
payment->unique_id, msg);
}
static void attempt_log(struct attempt *attempt,
enum log_level level,
const char *fmt,
...)
PRINTF_FMT(3,4);
static void attempt_log(struct attempt *attempt,
enum log_level level,
const char *fmt,
...)
{
va_list args;
const char *msg, *path;
va_start(args, fmt);
msg = tal_vfmt(tmpctx, fmt, args);
va_end(args);
path = fmt_path(tmpctx, attempt);
payment_log(attempt->payment, level, "%s: %s", path, msg);
}
#define attempt_unusual(attempt, fmt, ...) \
attempt_log((attempt), LOG_UNUSUAL, (fmt), __VA_ARGS__)
#define attempt_info(attempt, fmt, ...) \
attempt_log((attempt), LOG_INFORM, (fmt), __VA_ARGS__)
#define attempt_debug(attempt, fmt, ...) \
attempt_log((attempt), LOG_DBG, (fmt), __VA_ARGS__)
static struct command_result *ignore_result(struct command *aux_cmd,
const char *method,
const char *buf,
const jsmntok_t *result,
void *arg)
{
return command_still_pending(aux_cmd);
}
static struct command_result *ignore_result_error(struct command *aux_cmd,
const char *method,
const char *buf,
const jsmntok_t *result,
struct attempt *attempt)
{
attempt_unusual(attempt, "%s failed: '%.*s'",
method,
json_tok_full_len(result),
json_tok_full(buf, result));
return ignore_result(aux_cmd, method, buf, result, attempt);
}
/* A request, but we don't care about result. Submit with send_payment_req */
static struct out_req *payment_ignored_req(struct command *aux_cmd,
struct attempt *attempt,
const char *method)
{
return jsonrpc_request_start(aux_cmd, method,
ignore_result, ignore_result_error, attempt);
}
static struct command_result *cleanup_finished(struct command *aux_cmd,
const char *method,
const char *buf,
const jsmntok_t *result,
struct payment *payment)
{
/* payment is a child of aux_cmd, so freed now */
return aux_command_done(aux_cmd);
}
/* Last of all we destroy the private layer */
static struct command_result *cleanup(struct command *aux_cmd,
struct payment *payment)
{
struct out_req *req;
req = jsonrpc_request_start(aux_cmd,
"askrene-remove-layer",
cleanup_finished,
cleanup_finished,
payment);
json_add_string(req->js, "layer", payment->private_layer);
return send_outreq(req);
}
/* Last request finished after xpay command is done gets to clean up */
static void destroy_payment_request(struct out_req *req,
struct payment *payment)
{
for (size_t i = 0; i < tal_count(payment->requests); i++) {
if (payment->requests[i] == req) {
tal_arr_remove(&payment->requests, i);
if (tal_count(payment->requests) == 0 && payment->cmd == NULL) {
cleanup(req->cmd, payment);
}
return;
}
}
abort();
}
static struct command_result *
send_payment_req(struct command *aux_cmd,
struct payment *payment, struct out_req *req)
{
tal_arr_expand(&payment->requests, req);
tal_add_destructor2(req, destroy_payment_request, payment);
return send_outreq(req);
}
/* For self-pay, we don't have hops. */
static struct amount_msat initial_sent(const struct attempt *attempt)
{
if (tal_count(attempt->hops) == 0)
return attempt->delivers;
return attempt->hops[0].amount_in;
}
static u32 initial_cltv_delta(const struct attempt *attempt)
{
if (tal_count(attempt->hops) == 0)
return attempt->payment->final_cltv;
return attempt->hops[0].cltv_value_in;
}
/* Find the total number of pending attempts */
static size_t count_current_attempts(const struct payment *payment)
{
const struct attempt *i;
size_t result = 0;
list_for_each(&payment->current_attempts, i, list) { result++; }
return result;
}
/* We total up all attempts which succeeded in the past (if we're not
* in slow mode, that's only the one which just succeeded), and then we
* assume any others currently-in-flight will also succeed. */
static struct amount_msat total_sent(const struct payment *payment)
{
struct amount_msat total = AMOUNT_MSAT(0);
const struct attempt *i;
list_for_each(&payment->past_attempts, i, list) {
if (!i->preimage)
continue;
if (!amount_msat_accumulate(&total, initial_sent(i)))
abort();
}
list_for_each(&payment->current_attempts, i, list) {
if (!amount_msat_accumulate(&total, initial_sent(i)))
abort();
}
return total;
}
/* Should we finish command now? */
static bool should_finish_command(const struct payment *payment)
{
const struct xpay *xpay = xpay_of(payment->plugin);
if (!xpay->slow_mode)
return true;
/* In slow mode, only finish when no remaining attempts
* (caller has already moved it to past_attempts). */
return list_empty(&payment->current_attempts);
}
static void payment_succeeded(struct payment *payment,
const struct preimage *preimage)
{
struct json_stream *js;
/* Only succeed once */
if (payment->cmd && should_finish_command(payment)) {
js = jsonrpc_stream_success(payment->cmd);
json_add_preimage(js, "payment_preimage", preimage);
json_add_amount_msat(js, "amount_msat", payment->amount);
json_add_amount_msat(js, "amount_sent_msat", total_sent(payment));
/* Pay's schema expects these fields */
if (payment->pay_compat) {
json_add_u64(js, "parts", payment->total_num_attempts);
json_add_pubkey(js, "destination", &payment->destination);
json_add_sha256(js, "payment_hash", &payment->payment_hash);
json_add_string(js, "status", "complete");
json_add_timeabs(js, "created_at", payment->start_time);
} else {
json_add_u64(js, "failed_parts", payment->num_failures);
json_add_u64(js, "successful_parts",
payment->total_num_attempts - payment->num_failures);
}
was_pending(command_finished(payment->cmd, js));
payment->cmd = NULL;
}
}
static void payment_give_up(struct command *aux_cmd,
struct payment *payment,
enum jsonrpc_errcode code,
const char *fmt,
...)
PRINTF_FMT(4,5);
/* Returns NULL if no past attempts succeeded, otherwise the preimage */
static const struct preimage *
any_attempts_succeeded(const struct payment *payment)
{
struct attempt *attempt;
list_for_each(&payment->past_attempts, attempt, list) {
if (attempt->preimage)
return attempt->preimage;
}
return NULL;
}
/* We won't try sending any more. Usually this means we return this
* failure to the user, but see below. */
static void payment_give_up(struct command *aux_cmd,
struct payment *payment,
enum jsonrpc_errcode code,
const char *fmt,
...)
{
va_list args;
const char *msg;
va_start(args, fmt);
msg = tal_vfmt(tmpctx, fmt, args);
va_end(args);
/* Only fail once */
if (payment->cmd && should_finish_command(payment)) {
const struct preimage *preimage;
/* Corner case: in slow_mode, an earlier one could have
* theoretically succeeded. */
preimage = any_attempts_succeeded(payment);
if (preimage)
payment_succeeded(payment, preimage);
else {
was_pending(command_fail(payment->cmd, code, "%s", msg));
payment->cmd = NULL;
}
}
/* If no commands outstanding, we can now clean up */
if (tal_count(payment->requests) == 0)
cleanup(aux_cmd, payment);
}
static void add_result_summary(struct attempt *attempt,
enum log_level level,
const char *fmt, ...)
PRINTF_FMT(3,4);
static void add_result_summary(struct attempt *attempt,
enum log_level level,
const char *fmt, ...)
{
va_list args;
const char *msg;
va_start(args, fmt);
msg = tal_vfmt(tmpctx, fmt, args);
va_end(args);
tal_append_fmt(&attempt->payment->prior_results, "%s. ", msg);
attempt_log(attempt, level, "%s", msg);
}
static const char *describe_scidd(struct attempt *attempt, size_t index)
{
struct short_channel_id_dir scidd = attempt->hops[index].scidd;
struct payment *payment = attempt->payment;
assert(index < tal_count(attempt->hops));
/* Blinded paths? */
if (scidd.scid.u64 < tal_count(payment->paths)) {
if (tal_count(payment->paths) == 1)
return tal_fmt(tmpctx, "the invoice's blinded path (%s)",
fmt_short_channel_id_dir(tmpctx, &scidd));
return tal_fmt(tmpctx, "the invoice's blinded path %s (%"PRIu64" of %zu)",
fmt_short_channel_id_dir(tmpctx, &scidd),
scidd.scid.u64 + 1,
tal_count(payment->paths));
}
/* Routehint? Often they are a single hop. */
if (tal_count(payment->route_hints) == 1
&& tal_count(payment->route_hints[0]) == 1
&& short_channel_id_eq(scidd.scid,
payment->route_hints[0][0].short_channel_id))
return tal_fmt(tmpctx, "the invoice's route hint (%s)",
fmt_short_channel_id_dir(tmpctx, &scidd));
for (size_t i = 0; i < tal_count(payment->route_hints); i++) {
for (size_t j = 0; j < tal_count(payment->route_hints[i]); j++) {
if (short_channel_id_eq(scidd.scid,
payment->route_hints[i][j].short_channel_id)) {
return tal_fmt(tmpctx, "%s inside invoice's route hint%s",
fmt_short_channel_id_dir(tmpctx, &scidd),
tal_count(payment->route_hints) == 1 ? "" : "s");
}
}
}
/* Just use normal names otherwise (may be public, may be local) */
return fmt_short_channel_id_dir(tmpctx, &scidd);
}
/* How much did previous successes deliver? */
static struct amount_msat total_delivered(const struct payment *payment)
{
struct amount_msat sum = AMOUNT_MSAT(0);
struct attempt *attempt;
list_for_each(&payment->past_attempts, attempt, list) {
if (!attempt->preimage)
continue;
if (!amount_msat_accumulate(&sum, attempt->delivers))
abort();
}
return sum;
}
/* We can notify others of what the details are, so they can do their own
* layer heuristics. */
static void json_add_attempt_fields(struct json_stream *js,
const struct attempt *attempt)
{
/* These three uniquely identify this attempt */
json_add_sha256(js, "payment_hash", &attempt->payment->payment_hash);
json_add_u64(js, "groupid", attempt->payment->group_id);
json_add_u64(js, "partid", attempt->partid);
}
static void outgoing_notify_start(const struct attempt *attempt)
{
struct json_stream *js = plugin_notification_start(NULL, "pay_part_start");
json_add_attempt_fields(js, attempt);
json_add_amount_msat(js, "total_payment_msat", attempt->payment->amount);
json_add_amount_msat(js, "attempt_msat", attempt->delivers);
json_array_start(js, "hops");
for (size_t i = 0; i < tal_count(attempt->hops); i++) {
const struct hop *hop = &attempt->hops[i];
json_object_start(js, NULL);
json_add_pubkey(js, "next_node", &hop->next_node);
json_add_short_channel_id(js, "short_channel_id", hop->scidd.scid);
json_add_u32(js, "direction", hop->scidd.dir);
json_add_amount_msat(js, "channel_in_msat", hop->amount_in);
json_add_amount_msat(js, "channel_out_msat", hop->amount_out);
json_object_end(js);
}
json_array_end(js);
plugin_notification_end(attempt->payment->plugin, js);
}
static void outgoing_notify_success(const struct attempt *attempt)
{
struct json_stream *js = plugin_notification_start(NULL, "pay_part_end");
json_add_string(js, "status", "success");
json_add_timerel(js, "duration", timemono_between(time_mono(), attempt->start_time));
json_add_attempt_fields(js, attempt);
plugin_notification_end(attempt->payment->plugin, js);
}
static void outgoing_notify_failure(const struct attempt *attempt,
int failindex, int errcode,
const u8 *replymsg,
const char *errstr)
{
struct json_stream *js = plugin_notification_start(NULL, "pay_part_end");
json_add_string(js, "status", "failure");
json_add_attempt_fields(js, attempt);
if (replymsg)
json_add_hex_talarr(js, "failed_msg", replymsg);
json_add_timerel(js, "duration", timemono_between(time_mono(), attempt->start_time));
if (failindex != -1) {
if (failindex != 0)
json_add_pubkey(js, "failed_node_id", &attempt->hops[failindex-1].next_node);
if (failindex != tal_count(attempt->hops)) {
const struct hop *hop = &attempt->hops[failindex];
json_add_short_channel_id(js, "failed_short_channel_id", hop->scidd.scid);
json_add_u32(js, "failed_direction", hop->scidd.dir);
}
}
if (errcode != -1)
json_add_u32(js, "error_code", errcode);
json_add_string(js, "error_message", errstr);
plugin_notification_end(attempt->payment->plugin, js);
}
/* Extract blockheight from the error */
static u32 error_blockheight(const u8 *errmsg)
{
struct amount_msat htlc_msat;
u32 height;
if (!fromwire_incorrect_or_unknown_payment_details(errmsg,
&htlc_msat,
&height))
return 0;
return height;
}
static void update_knowledge_from_error(struct command *aux_cmd,
const char *buf,
const jsmntok_t *error,
struct attempt *attempt)
{
const jsmntok_t *tok;
struct onionreply *reply;
struct out_req *req;
const u8 *replymsg;
int index;
enum onion_wire failcode;
bool from_final;
const char *failcode_name, *errmsg, *description;
enum jsonrpc_errcode ecode;
tok = json_get_member(buf, error, "code");
if (!tok || !json_to_jsonrpc_errcode(buf, tok, &ecode))
plugin_err(aux_cmd->plugin, "Invalid injectpaymentonion result '%.*s'",
json_tok_full_len(error), json_tok_full(buf, error));
if (ecode == PAY_INJECTPAYMENTONION_ALREADY_PAID) {
payment_give_up(aux_cmd, attempt->payment,
PAY_INJECTPAYMENTONION_FAILED,
"Already paid this invoice successfully");
return;
}
if (ecode != PAY_INJECTPAYMENTONION_FAILED) {
payment_give_up(aux_cmd, attempt->payment,
PLUGIN_ERROR,
"Unexpected injectpaymentonion error %i: %.*s",
ecode,
json_tok_full_len(error),
json_tok_full(buf, error));
return;
}
tok = json_get_member(buf, error, "data");
if (!tok)
plugin_err(aux_cmd->plugin, "Invalid injectpaymentonion result '%.*s'",
json_tok_full_len(error), json_tok_full(buf, error));
tok = json_get_member(buf, tok, "onionreply");
if (!tok)
plugin_err(aux_cmd->plugin, "Invalid injectpaymentonion result '%.*s'",
json_tok_full_len(error), json_tok_full(buf, error));
reply = new_onionreply(tmpctx, take(json_tok_bin_from_hex(NULL, buf, tok)));
replymsg = unwrap_onionreply(tmpctx,
attempt->shared_secrets,
tal_count(attempt->shared_secrets),
reply,
&index);
/* Garbled? Blame random hop. */
if (!replymsg) {
outgoing_notify_failure(attempt, -1, -1, replymsg, "Garbled error message");
index = pseudorand(tal_count(attempt->hops));
description = "Garbled error message";
add_result_summary(attempt, LOG_UNUSUAL,
"We got a garbled error message, and chose to (randomly) to disable %s for this payment",
describe_scidd(attempt, index));
goto disable_channel;
}
/* We learned something about prior nodes */
for (size_t i = 0; i < index; i++) {
req = payment_ignored_req(aux_cmd, attempt, "askrene-inform-channel");
/* Put what we learned in xpay, unless it's a fake channel */
json_add_string(req->js, "layer",
attempt->hops[i].fake_channel
? attempt->payment->private_layer
: "xpay");
json_add_short_channel_id_dir(req->js,
"short_channel_id_dir",
attempt->hops[i].scidd);
json_add_amount_msat(req->js, "amount_msat",
attempt->hops[i].amount_out);
json_add_string(req->js, "inform", "unconstrained");
send_payment_req(aux_cmd, attempt->payment, req);
}
from_final = (index == tal_count(attempt->hops));
failcode = fromwire_peektype(replymsg);
failcode_name = onion_wire_name(failcode);
if (strstarts(failcode_name, "WIRE_"))
failcode_name = str_lowering(tmpctx,
failcode_name
+ strlen("WIRE_"));
/* For local errors, error message is informative. */
if (index == 0) {
tok = json_get_member(buf, error, "message");
errmsg = json_strdup(tmpctx, buf, tok);
} else
errmsg = failcode_name;
outgoing_notify_failure(attempt, index, failcode, replymsg, errmsg);
description = tal_fmt(tmpctx,
"Error %s for path %s, from %s",
errmsg,
fmt_path(tmpctx, attempt),
from_final ? "destination"
: index == 0 ? "local node"
: fmt_pubkey(tmpctx, &attempt->hops[index-1].next_node));
attempt_debug(attempt, "%s", description);
/* Final node sent an error */
if (from_final) {
switch (failcode) {
/* These two are deprecated */
case WIRE_FINAL_INCORRECT_CLTV_EXPIRY:
case WIRE_FINAL_INCORRECT_HTLC_AMOUNT:
/* These ones are weird any time (did we encode wrongly?) */
case WIRE_INVALID_ONION_VERSION:
case WIRE_INVALID_ONION_HMAC:
case WIRE_INVALID_ONION_KEY:
case WIRE_INVALID_ONION_PAYLOAD:
/* These should not be sent by final node */
case WIRE_TEMPORARY_CHANNEL_FAILURE:
case WIRE_PERMANENT_CHANNEL_FAILURE:
case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING:
case WIRE_UNKNOWN_NEXT_PEER:
case WIRE_AMOUNT_BELOW_MINIMUM:
case WIRE_FEE_INSUFFICIENT:
case WIRE_INCORRECT_CLTV_EXPIRY:
case WIRE_EXPIRY_TOO_FAR:
case WIRE_EXPIRY_TOO_SOON:
case WIRE_CHANNEL_DISABLED:
case WIRE_PERMANENT_NODE_FAILURE:
case WIRE_TEMPORARY_NODE_FAILURE:
case WIRE_REQUIRED_NODE_FEATURE_MISSING:
case WIRE_INVALID_ONION_BLINDING:
/* Blame hop *leading to* final node */
index--;
goto strange_error;
case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS: {
struct xpay *xpay = xpay_of(attempt->payment->plugin);
u32 blockheight = error_blockheight(replymsg);
if (blockheight > attempt->payment->start_blockheight) {
attempt_log(attempt, LOG_INFORM,
"Destination failed and said their blockheight was %u (we're at %u): waiting",
blockheight, xpay->blockheight);
/* This will make the next attempt wait. */
attempt->payment->start_blockheight = blockheight;
return;
}
payment_give_up(aux_cmd, attempt->payment,
PAY_DESTINATION_PERM_FAIL,
"Destination said it doesn't know invoice: %s",
errmsg);
return;
}
case WIRE_MPP_TIMEOUT:
/* Not actually an error at all, nothing to do. */
add_result_summary(attempt, LOG_DBG,
"Payment of %s reached destination,"
" but timed out before the rest arrived.",
fmt_amount_msat(tmpctx, attempt->delivers));
return;
}
} else {
/* Non-final node */
switch (failcode) {
/* These ones are weird any time (did we encode wrongly?) */
case WIRE_INVALID_ONION_VERSION:
case WIRE_INVALID_ONION_HMAC:
case WIRE_INVALID_ONION_KEY:
case WIRE_INVALID_ONION_PAYLOAD:
/* These should not be sent by non-final node */
case WIRE_FINAL_INCORRECT_CLTV_EXPIRY:
case WIRE_FINAL_INCORRECT_HTLC_AMOUNT:
case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS:
case WIRE_MPP_TIMEOUT:
goto strange_error;
case WIRE_TEMPORARY_CHANNEL_FAILURE:
add_result_summary(attempt, LOG_DBG,
"We got %s for %s, assuming it can't carry %s",
errmsg,
describe_scidd(attempt, index),
fmt_amount_msat(tmpctx, attempt->hops[index].amount_out));
goto channel_capacity;
case WIRE_PERMANENT_CHANNEL_FAILURE:
case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING:
case WIRE_UNKNOWN_NEXT_PEER:
case WIRE_AMOUNT_BELOW_MINIMUM:
case WIRE_FEE_INSUFFICIENT:
case WIRE_INCORRECT_CLTV_EXPIRY:
case WIRE_EXPIRY_TOO_FAR:
case WIRE_EXPIRY_TOO_SOON:
case WIRE_CHANNEL_DISABLED:
case WIRE_PERMANENT_NODE_FAILURE:
case WIRE_TEMPORARY_NODE_FAILURE:
case WIRE_REQUIRED_NODE_FEATURE_MISSING:
add_result_summary(attempt, LOG_DBG,
"We got a weird error (%s) for %s: disabling it for this payment",
errmsg,
describe_scidd(attempt, index));
goto disable_channel;
case WIRE_INVALID_ONION_BLINDING:
/* FIXME: This could be an MPP_TIMEOUT! */
add_result_summary(attempt, LOG_DBG,
"We got an error from inside the blinded path %s:"
" we assume it means insufficient capacity",
fmt_short_channel_id_dir(tmpctx,
&attempt->hops[index].scidd));
goto channel_capacity;
}
}
strange_error:
/* We disable the erroneous channel for this */
add_result_summary(attempt, LOG_UNUSUAL,
"Unexpected error (%s) from %s node: disabling %s for this payment",
errmsg,
from_final ? "final" : "intermediate",
describe_scidd(attempt, index));
disable_channel:
/* We only do this for the current payment */
req = payment_ignored_req(aux_cmd, attempt, "askrene-update-channel");
json_add_string(req->js, "layer", attempt->payment->private_layer);
json_add_short_channel_id_dir(req->js,
"short_channel_id_dir",
attempt->hops[index].scidd);
json_add_bool(req->js, "enabled", false);
send_payment_req(aux_cmd, attempt->payment, req);
goto check_previous_success;
channel_capacity:
req = payment_ignored_req(aux_cmd, attempt, "askrene-inform-channel");
/* Put what we learned in xpay, unless it's a fake channel */
json_add_string(req->js, "layer",
attempt->hops[index].fake_channel
? attempt->payment->private_layer
: "xpay");
json_add_short_channel_id_dir(req->js,
"short_channel_id_dir",
attempt->hops[index].scidd);
json_add_amount_msat(req->js, "amount_msat", attempt->hops[index].amount_out);
json_add_string(req->js, "inform", "constrained");
send_payment_req(aux_cmd, attempt->payment, req);
check_previous_success:
/* If they give us the preimage but we didn't succeed in giving them
* all the money, that's a win for us. But either the destination is
* buggy, or someone along the way lost money! */
if (any_attempts_succeeded(attempt->payment)) {
payment_log(attempt->payment, LOG_UNUSUAL,
"Destination accepted partial payment,"
" failed a part (%s), but accepted only %s of %s."
" Winning?!",
description,
fmt_amount_msat(tmpctx,
total_delivered(attempt->payment)),
fmt_amount_msat(tmpctx, attempt->payment->amount));
}
}
static struct command_result *unreserve_path(struct command *aux_cmd,
struct attempt *attempt)
{
struct out_req *req;
req = payment_ignored_req(aux_cmd, attempt, "askrene-unreserve");
json_array_start(req->js, "path");
for (size_t i = 0; i < tal_count(attempt->hops); i++) {
const struct hop *hop = &attempt->hops[i];
json_object_start(req->js, NULL);
json_add_short_channel_id_dir(req->js, "short_channel_id_dir", hop->scidd);
json_add_amount_msat(req->js, "amount_msat", hop->amount_out);
if (hop->fake_channel)
json_add_string(req->js, "layer", attempt->payment->private_layer);
json_object_end(req->js);
}
json_array_end(req->js);
return send_payment_req(aux_cmd, attempt->payment, req);
}
static struct command_result *injectpaymentonion_failed(struct command *aux_cmd,
const char *method,
const char *buf,
const jsmntok_t *error,
struct attempt *attempt)
{
struct payment *payment = attempt->payment;
struct amount_msat delivers = attempt->delivers;
payment->num_failures++;
/* Move from current_attempts to past_attempts */
list_del_from(&payment->current_attempts, &attempt->list);
list_add(&payment->past_attempts, &attempt->list);
/* We're no longer using this path: submit request to release it */
unreserve_path(aux_cmd, attempt);
/* Once reserve is removed, we can tell lightningd what we
* learned. Might fail payment! */
update_knowledge_from_error(aux_cmd, buf, error, attempt);
/* If xpay is done, return now */
if (!payment->cmd)
return command_still_pending(aux_cmd);
/* If we're not waiting for getroutes, kick one off */
if (amount_msat_is_zero(payment->amount_being_routed))
return getroutes_for(aux_cmd, payment, delivers);
/* Wait for getroutes to finish */
return command_still_pending(aux_cmd);
}
static struct amount_msat total_being_sent(const struct payment *payment)
{
struct attempt *attempt;
struct amount_msat sum = AMOUNT_MSAT(0);
list_for_each(&payment->current_attempts, attempt, list) {
if (!amount_msat_accumulate(&sum, attempt->delivers))
abort();
}
return sum;
}
static struct amount_msat total_fees_being_sent(const struct payment *payment)
{
struct attempt *attempt;
struct amount_msat sum = AMOUNT_MSAT(0);
list_for_each(&payment->current_attempts, attempt, list) {
struct amount_msat fee;
if (tal_count(attempt->hops) == 0)
continue;
if (!amount_msat_sub(&fee,
attempt->hops[0].amount_in,
attempt->delivers))
abort();
if (!amount_msat_accumulate(&sum, fee))
abort();
}
return sum;
}
static struct command_result *injectpaymentonion_succeeded(struct command *aux_cmd,
const char *method,
const char *buf,
const jsmntok_t *result,
struct attempt *attempt)
{
struct preimage preimage;
struct payment *payment = attempt->payment;
if (!json_to_preimage(buf,