-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathxpay.c
More file actions
3438 lines (3062 loc) · 108 KB
/
Copy pathxpay.c
File metadata and controls
3438 lines (3062 loc) · 108 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/randbytes.h>
#include <common/route.h>
#include <common/wireaddr.h>
#include <errno.h>
#include <inttypes.h>
#include <plugins/libplugin.h>
#include <plugins/xpay/listpays.h>
#include <plugins/xpay/xpay.h>
#include <stdarg.h>
#define PREIMAGE_TLV_TYPE 5482373484
/* For the whole plugin */
struct xpay {
/* This is me. */
struct pubkey local_id;
/* These are my struct payments */
struct list_head payments;
/* 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;
const char **user_layers;
};
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 {
/* Inside xpay->payments */
struct list_node list;
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: NULL for xkeysend! */
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, either the desired deliver or desired spend amount depending
* on the context. */
struct amount_msat amount;
/* Relevant for partial payments. This is the value that must be written
* in the final hop's payload for MPP coordination. */
struct amount_msat mpp_amount;
/* Maximum fee we're prepare to pay */
struct amount_msat maxfee;
/* local invreqid to asociate with this payment, for atomicity. */
const struct sha256 *localinvreqid;
/* Optional label the user wants attached to these payments. */
const struct json_escape *label;
/* 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;
/* BOLT-11 payment secret (NULL for BOLT-12, it uses blinded paths) */
const struct secret *payment_secret;
/* BOLT-11 payment metadata (NULL for BOLT-12, 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;
/* Any extra tlvs to include in final payload (keysend) */
const u8 *extra_tlvs;
/* 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;
/* sender pays for fees */
bool includefees;
/* Are we to add a shadow route? */
bool use_shadow;
};
/* 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;
/* "amount" is either the intended deliver amount or the send amount,
* depending on the payment context. */
struct amount_msat amount;
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,
const struct json_escape *label,
const struct sha256 *local_invreq_id,
bool use_shadow,
bool as_pay,
const struct amount_msat *includefees_msat);
/* 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->amount;
return attempt->hops[0].amount_out;
}
static struct amount_msat inject_amount(const struct attempt *attempt)
{
if (tal_count(attempt->hops) == 0)
return attempt->amount;
return attempt->hops[0].amount_in;
}
static struct amount_msat attempt_deliver(const struct attempt *attempt)
{
const size_t len = tal_count(attempt->hops);
if (len == 0)
return attempt->amount;
return attempt->hops[len - 1].amount_out;
}
static struct amount_msat attempt_mpp_amount(const struct attempt *attempt)
{
if (!attempt->payment->includefees)
return attempt->payment->mpp_amount;
assert(attempt->payment->maxparts == 1);
return attempt_deliver(attempt);
}
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_deliver(attempt)))
abort();
}
return sum;
}
/* This payment should deliver this amount. */
static struct amount_msat payment_deliver(const struct payment *payment)
{
return payment->amount;
}
/* 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->amount);
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;
}
/* Return true if this contained a channel_update which (potentially) changed something. */
static bool process_channel_update_from_onion_error(struct command *aux_cmd,
struct attempt *attempt,
const u8 *onion_message,
const char *errname)
{
u8 *channel_update;
struct amount_msat unused_msat;
u32 unused32;
secp256k1_ecdsa_signature signature;
struct bitcoin_blkid chain_hash;
struct short_channel_id_dir scidd;
u32 timestamp;
u8 message_flags, channel_flags;
u16 cltv_expiry_delta;
struct amount_msat htlc_minimum_msat, htlc_maximum_msat;
u32 fee_base_msat, fee_proportional_millionths;
struct out_req *req;
const struct gossmap *gossmap;
const struct gossmap_chan *c;
/* Identify failcodes that have some channel_update.
*
* TODO > BOLT 1.0: Add new failcodes when updating to a
* new BOLT version. */
if (!fromwire_temporary_channel_failure(tmpctx,
onion_message,
&channel_update) &&
!fromwire_amount_below_minimum(tmpctx,
onion_message, &unused_msat,
&channel_update) &&
!fromwire_fee_insufficient(tmpctx,
onion_message, &unused_msat,
&channel_update) &&
!fromwire_incorrect_cltv_expiry(tmpctx,
onion_message, &unused32,
&channel_update) &&
!fromwire_expiry_too_soon(tmpctx,
onion_message,
&channel_update))
/* No channel update. */
return false;
/* LND before v0.18 (May 2024) would not include the
* WIRE_CHANNEL_UPDATE type field, but now they do. */
if (!fromwire_channel_update(channel_update,
&signature,
&chain_hash,
&scidd.scid,
×tamp,
&message_flags,
&channel_flags,
&cltv_expiry_delta,
&htlc_minimum_msat,
&fee_base_msat,
&fee_proportional_millionths,
&htlc_maximum_msat))
return false;
scidd.dir = (channel_flags & ROUTING_FLAGS_DIRECTION);
/* If this is substantially the same as the one we already have, ignore it. */
gossmap = get_gossmap(xpay_of(aux_cmd->plugin));
c = gossmap_find_chan(gossmap, &scidd.scid);
if (c) {
const struct half_chan *hc = &c->half[scidd.dir];
if (gossmap_chan_set(c, scidd.dir)
&& hc->enabled == !(channel_flags & ROUTING_FLAGS_DISABLED)
/* We convert the same way gossmap.c does */
&& u64_to_fp16(htlc_minimum_msat.millisatoshis, false) == hc->htlc_min /* Raw: convert */
&& u64_to_fp16(htlc_maximum_msat.millisatoshis, true) == hc->htlc_max /* Raw: convert */
&& fee_base_msat == hc->base_fee
&& fee_proportional_millionths == hc->proportional_fee
&& cltv_expiry_delta == hc->delay) {
return false;
}
}
attempt_log(attempt, LOG_DBG, "Got channel_update from error for %s: %s",
fmt_short_channel_id_dir(tmpctx, &scidd),
tal_hex(tmpctx, channel_update));
/* Update our local layer so it applies to this payment *only*. We
* don't bother checking the signature; we don't even check what
* channel it is! */
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",
scidd);
json_add_bool(req->js, "enabled", !(channel_flags & ROUTING_FLAGS_DISABLED));
json_add_amount_msat(req->js, "htlc_minimum_msat", htlc_minimum_msat);
json_add_amount_msat(req->js, "htlc_maximum_msat", htlc_maximum_msat);
json_add_u32(req->js, "fee_base_msat", fee_base_msat);
json_add_u32(req->js, "fee_proportional_millionths", fee_proportional_millionths);
json_add_u32(req->js, "cltv_expiry_delta", cltv_expiry_delta);
send_payment_req(aux_cmd, attempt->payment, req);
/* We also bias *against* the channel. This should help if the node is
* stuck somehow, or trying to track us. */
req = payment_ignored_req(aux_cmd, attempt, "askrene-bias-channel");
json_add_string(req->js, "layer", attempt->payment->private_layer);
json_add_short_channel_id_dir(req->js,
"short_channel_id_dir",
scidd);
json_add_s32(req->js, "bias", -1);
json_add_string(req->js, "description",
tal_fmt(tmpctx, "negative bias due to channel_update in error %s",
errname));
json_add_bool(req->js, "relative", true);
send_payment_req(aux_cmd, attempt->payment, req);
return true;
}
/* pay used to "work" if you asked it to pay again. */
static struct command_result *
payment_listsendpays_previous(struct command *cmd,
const char *method,
const char *buf,
const jsmntok_t *result,
struct payment *payment)
{
size_t i;
const jsmntok_t *t, *arr;
size_t parts = 0;
struct preimage preimage;
struct amount_msat sent, msat;
u32 created_at;
arr = json_get_member(buf, result, "payments");
json_for_each_arr(i, t, arr) {
const jsmntok_t *status = json_get_member(buf, t, "status");
if (!json_tok_streq(buf, status, "complete"))
continue;
if (parts == 0) {
json_scan(tmpctx, buf, t,
"{created_at:%"
",amount_msat:%"
",amount_sent_msat:%"
",payment_preimage:%}",
JSON_SCAN(json_to_u32, &created_at),
JSON_SCAN(json_to_msat, &msat),
JSON_SCAN(json_to_msat, &sent),
JSON_SCAN(json_to_preimage, &preimage));
} else {
struct amount_msat diff_msat, diff_sent;
json_scan(tmpctx, buf, t,
"{amount_msat:%"
",amount_sent_msat:%}",
JSON_SCAN(json_to_msat, &diff_msat),
JSON_SCAN(json_to_msat, &diff_sent));
if (!amount_msat_accumulate(&msat, diff_msat) ||
!amount_msat_accumulate(&sent, diff_sent))
plugin_err(cmd->plugin,
"msat overflow adding up parts");
}
parts++;
}
/* Avoid terminating twice */
payment->cmd = NULL;
/* Shouldn't happen! */
if (parts == 0) {
return command_fail(cmd,
PAY_INJECTPAYMENTONION_ALREADY_PAID,
"Already paid this invoice successfully");
} else {
struct json_stream *js = jsonrpc_stream_success(cmd);
json_add_preimage(js, "payment_preimage", &preimage);
json_add_string(js, "status", "complete");
json_add_amount_msat(js, "amount_msat", msat);
json_add_amount_msat(js, "amount_sent_msat", sent);
json_add_pubkey(js, "destination", &payment->destination);
json_add_sha256(js, "payment_hash", &payment->payment_hash);
json_add_u32(js, "created_at", created_at);
json_add_num(js, "parts", parts);
return command_finished(cmd, js);
}
}
static void payment_already_paid(struct payment *payment)
{
struct out_req *req;
req = jsonrpc_request_start(payment->cmd, "listsendpays",
payment_listsendpays_previous,
payment_listsendpays_previous,
payment);
json_add_sha256(req->js, "payment_hash", &payment->payment_hash);
send_outreq(req);
}
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) {
/* pay was OK when this happened, so we fake it up. */
if (attempt->payment->pay_compat && attempt->payment->cmd) {
payment_already_paid(attempt->payment);
return;
}
payment_give_up(aux_cmd, attempt->payment,
PAY_INJECTPAYMENTONION_ALREADY_PAID,
"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);
}
/* Because we might include blinded paths, final node is end of route, OR destination node id */
if (index == tal_count(attempt->hops)) {
from_final = true;
} else if (index > 0 && pubkey_eq(&attempt->hops[index-1].next_node,
&attempt->payment->destination)) {
from_final = true;
} else
from_final = false;
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;