forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libplugin-pay.c
3942 lines (3428 loc) · 120 KB
/
libplugin-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 "config.h"
#include <ccan/array_size/array_size.h>
#include <ccan/tal/str/str.h>
#include <common/blindedpay.h>
#include <common/daemon.h>
#include <common/dijkstra.h>
#include <common/gossmap.h>
#include <common/gossmods_listpeerchannels.h>
#include <common/json_stream.h>
#include <common/memleak.h>
#include <common/pseudorand.h>
#include <common/random_select.h>
#include <common/type_to_string.h>
#include <errno.h>
#include <math.h>
#include <plugins/libplugin-pay.h>
#include <sys/types.h>
#include <wire/peer_wire.h>
static struct gossmap *global_gossmap;
static bool got_gossmap;
static void init_gossmap(struct plugin *plugin)
{
size_t num_channel_updates_rejected;
global_gossmap
= notleak_with_children(gossmap_load(NULL,
GOSSIP_STORE_FILENAME,
&num_channel_updates_rejected));
if (!global_gossmap)
plugin_err(plugin, "Could not load gossmap %s: %s",
GOSSIP_STORE_FILENAME, strerror(errno));
if (num_channel_updates_rejected)
plugin_log(plugin, LOG_DBG,
"gossmap ignored %zu channel updates",
num_channel_updates_rejected);
}
static struct gossmap *get_gossmap(struct payment *payment)
{
assert(!got_gossmap);
if (!global_gossmap)
init_gossmap(payment->plugin);
else
gossmap_refresh(global_gossmap, NULL);
got_gossmap = true;
assert(payment->mods);
gossmap_apply_localmods(global_gossmap, payment->mods);
return global_gossmap;
}
static void put_gossmap(struct payment *payment)
{
assert(got_gossmap);
got_gossmap = false;
gossmap_remove_localmods(global_gossmap, payment->mods);
}
int libplugin_pay_poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
assert(!got_gossmap);
return daemon_poll(fds, nfds, timeout);
}
struct payment *payment_new(tal_t *ctx, struct command *cmd,
struct payment *parent,
struct payment_modifier **mods)
{
struct payment *p = tal(ctx, struct payment);
static u64 next_id = 0;
p->children = tal_arr(p, struct payment *, 0);
p->parent = parent;
p->modifiers = mods;
p->cmd = cmd;
p->start_time = time_now();
p->result = NULL;
p->why = NULL;
p->getroute = tal(p, struct getroute_request);
p->label = NULL;
p->failreason = NULL;
p->getroute->riskfactorppm = 10000000;
p->abort = false;
p->invstring_used = false;
p->route = NULL;
p->temp_exclusion = NULL;
p->failroute_retry = false;
p->routetxt = NULL;
p->max_htlcs = UINT32_MAX;
p->aborterror = NULL;
p->on_payment_success = NULL;
p->on_payment_failure = NULL;
/* Copy over the relevant pieces of information. */
if (parent != NULL) {
assert(cmd == NULL);
tal_arr_expand(&parent->children, p);
p->destination = parent->destination;
p->amount = parent->amount;
p->label = parent->label;
p->payment_hash = parent->payment_hash;
p->partid = payment_root(p->parent)->next_partid++;
p->plugin = parent->plugin;
/* Re-establish the unmodified constraints for our sub-payment. */
p->constraints = *parent->start_constraints;
p->deadline = parent->deadline;
p->min_final_cltv_expiry = parent->min_final_cltv_expiry;
p->routes = parent->routes;
p->features = parent->features;
p->id = parent->id;
p->local_id = parent->local_id;
p->local_invreq_id = parent->local_invreq_id;
p->groupid = parent->groupid;
p->invstring = parent->invstring;
p->description = parent->description;
p->mods = parent->mods;
} else {
assert(cmd != NULL);
p->partid = 0;
p->next_partid = 1;
p->plugin = cmd->plugin;
p->channel_hints = tal_arr(p, struct channel_hint, 0);
p->excluded_nodes = tal_arr(p, struct node_id, 0);
p->id = next_id++;
p->description = NULL;
/* Caller must set this. */
p->local_id = NULL;
p->local_invreq_id = NULL;
p->groupid = 0;
p->mods = NULL;
}
/* Initialize all modifier data so we can point to the fields when
* wiring into the param() call in a JSON-RPC handler. The callback
* can also just `memcpy` the parent if this outside access is not
* required. */
p->modifier_data = tal_arr(p, void *, 0);
for (size_t i=0; mods[i] != NULL; i++) {
if (mods[i]->data_init != NULL)
tal_arr_expand(&p->modifier_data,
mods[i]->data_init(p));
else
tal_arr_expand(&p->modifier_data, NULL);
}
return p;
}
struct payment *payment_root(struct payment *p)
{
if (p->parent == NULL)
return p;
else
return payment_root(p->parent);
}
static void
paymod_log_header(struct payment *p, const char **type, u64 *id)
{
struct payment *root = payment_root(p);
/* We prefer to show the command ID here since it is also known
* by `lightningd`, so in theory it can be used to correlate
* debugging logs between the main `lightningd` and whatever
* plugin is using the paymod system.
* We only fall back to a unique id per root payment if there
* is no command with an id associated with this payment.
*/
if (root->cmd && root->cmd->id) {
*type = "cmd";
*id = *root->cmd->id;
} else {
*type = "id";
*id = root->id;
}
}
static void
paymod_log(struct payment *p, enum log_level l, const char *fmt, ...)
{
const char *type;
u64 id;
char *txt;
va_list ap;
va_start(ap, fmt);
txt = tal_vfmt(tmpctx, fmt, ap);
va_end(ap);
paymod_log_header(p, &type, &id);
plugin_log(p->plugin, l, "%s %"PRIu64" partid %"PRIu32": %s",
type, id, p->partid, txt);
}
static void
paymod_err(struct payment *p, const char *fmt, ...)
{
const char *type;
u64 id;
char *txt;
va_list ap;
va_start(ap, fmt);
txt = tal_vfmt(tmpctx, fmt, ap);
va_end(ap);
paymod_log_header(p, &type, &id);
plugin_err(p->plugin, "%s %"PRIu64" partid %"PRIu32": %s",
type, id, p->partid, txt);
}
/* Generic handler for RPC failures that should end up failing the payment. */
static struct command_result *payment_rpc_failure(struct command *cmd,
const char *buffer,
const jsmntok_t *toks,
struct payment *p)
{
payment_fail(p,
"Failing a partial payment due to a failed RPC call: %.*s",
toks->end - toks->start, buffer + toks->start);
return command_still_pending(cmd);
}
struct payment_tree_result payment_collect_result(struct payment *p)
{
struct payment_tree_result res;
size_t numchildren = tal_count(p->children);
res.sent = AMOUNT_MSAT(0);
res.attempts = 1;
res.treestates = p->step;
res.leafstates = 0;
res.preimage = NULL;
res.failure = NULL;
if (p->step == PAYMENT_STEP_FAILED && p->result != NULL)
res.failure = p->result;
if (numchildren == 0) {
res.leafstates |= p->step;
if (p->result && p->result->state == PAYMENT_COMPLETE) {
res.sent = p->result->amount_sent;
res.preimage = p->result->payment_preimage;
}
}
for (size_t i = 0; i < numchildren; i++) {
struct payment_tree_result cres =
payment_collect_result(p->children[i]);
/* Some of our subpayments have succeeded, aggregate how much
* we sent in total. */
if (!amount_msat_add(&res.sent, res.sent, cres.sent))
paymod_err(
p,
"Number overflow summing partial payments: %s + %s",
type_to_string(tmpctx, struct amount_msat,
&res.sent),
type_to_string(tmpctx, struct amount_msat,
&cres.sent));
/* Bubble up the first preimage we see. */
if (res.preimage == NULL && cres.preimage != NULL)
res.preimage = cres.preimage;
res.leafstates |= cres.leafstates;
res.treestates |= cres.treestates;
res.attempts += cres.attempts;
/* We bubble the failure result with the highest failcode up
* to the root. */
if (res.failure == NULL ||
(cres.failure != NULL &&
cres.failure->failcode > res.failure->failcode)) {
res.failure = cres.failure;
}
}
return res;
}
static struct command_result *
payment_getblockheight_success(struct command *cmd,
const char *buffer,
const jsmntok_t *toks,
struct payment *p)
{
const jsmntok_t *blockheighttok =
json_get_member(buffer, toks, "blockheight");
json_to_number(buffer, blockheighttok, &p->start_block);
payment_continue(p);
return command_still_pending(cmd);
}
#define INVALID_BLOCKHEIGHT UINT32_MAX
static
void payment_start_at_blockheight(struct payment *p, u32 blockheight)
{
struct payment *root = payment_root(p);
/* Should have been set in root payment, or propagated from root
* payment to all child payments. */
assert(p->local_id);
p->step = PAYMENT_STEP_INITIALIZED;
p->current_modifier = -1;
/* Pre-generate the getroute request, so modifiers can have their say,
* before we actually call `getroute` */
p->getroute->destination = p->destination;
p->getroute->max_hops = ROUTING_MAX_HOPS;
p->getroute->cltv = root->min_final_cltv_expiry;
p->getroute->amount = p->amount;
p->start_constraints = tal_dup(p, struct payment_constraints, &p->constraints);
if (blockheight != INVALID_BLOCKHEIGHT) {
/* The caller knows the actual blockheight. */
p->start_block = blockheight;
return payment_continue(p);
}
if (p->parent) {
/* The parent should have a start block. */
p->start_block = p->parent->start_block;
return payment_continue(p);
}
/* `waitblockheight 0` can be used as a query for the current
* block height.
* This is slightly better than `getinfo` since `getinfo`
* counts the channels and addresses and pushes more data
* onto the RPC but all we care about is the blockheight.
*/
struct out_req *req;
req = jsonrpc_request_start(p->plugin, NULL, "waitblockheight",
&payment_getblockheight_success,
&payment_rpc_failure, p);
json_add_u32(req->js, "blockheight", 0);
send_outreq(p->plugin, req);
}
void payment_start(struct payment *p)
{
payment_start_at_blockheight(p, INVALID_BLOCKHEIGHT);
}
static void channel_hints_update(struct payment *p,
const struct short_channel_id scid,
int direction, bool enabled, bool local,
const struct amount_msat *estimated_capacity,
u16 *htlc_budget)
{
struct payment *root = payment_root(p);
struct channel_hint newhint;
/* If the channel is marked as enabled it must have an estimate. */
assert(!enabled || estimated_capacity != NULL);
/* Try and look for an existing hint: */
for (size_t i=0; i<tal_count(root->channel_hints); i++) {
struct channel_hint *hint = &root->channel_hints[i];
if (short_channel_id_eq(&hint->scid.scid, &scid) &&
hint->scid.dir == direction) {
bool modified = false;
/* Prefer to disable a channel. */
if (!enabled && hint->enabled) {
hint->enabled = false;
modified = true;
}
/* Prefer the more conservative estimate. */
if (estimated_capacity != NULL &&
amount_msat_greater(hint->estimated_capacity,
*estimated_capacity)) {
hint->estimated_capacity = *estimated_capacity;
modified = true;
}
if (htlc_budget != NULL) {
assert(hint->local);
hint->local->htlc_budget = *htlc_budget;
modified = true;
}
if (modified)
paymod_log(p, LOG_DBG,
"Updated a channel hint for %s: "
"enabled %s, "
"estimated capacity %s",
type_to_string(tmpctx,
struct short_channel_id_dir,
&hint->scid),
hint->enabled ? "true" : "false",
type_to_string(tmpctx,
struct amount_msat,
&hint->estimated_capacity));
return;
}
}
/* No hint found, create one. */
newhint.enabled = enabled;
newhint.scid.scid = scid;
newhint.scid.dir = direction;
if (local) {
newhint.local = tal(root->channel_hints, struct local_hint);
assert(htlc_budget);
newhint.local->htlc_budget = *htlc_budget;
} else
newhint.local = NULL;
if (estimated_capacity != NULL)
newhint.estimated_capacity = *estimated_capacity;
tal_arr_expand(&root->channel_hints, newhint);
paymod_log(
p, LOG_DBG,
"Added a channel hint for %s: enabled %s, estimated capacity %s",
type_to_string(tmpctx, struct short_channel_id_dir, &newhint.scid),
newhint.enabled ? "true" : "false",
type_to_string(tmpctx, struct amount_msat,
&newhint.estimated_capacity));
}
static void payment_exclude_most_expensive(struct payment *p)
{
struct route_hop *e = &p->route[0];
struct amount_msat fee, worst = AMOUNT_MSAT(0);
for (size_t i = 0; i < tal_count(p->route)-1; i++) {
if (!amount_msat_sub(&fee, p->route[i].amount, p->route[i+1].amount))
paymod_err(p, "Negative fee in a route.");
if (amount_msat_greater_eq(fee, worst)) {
e = &p->route[i];
worst = fee;
}
}
channel_hints_update(p, e->scid, e->direction, false, false,
NULL, NULL);
}
static void payment_exclude_longest_delay(struct payment *p)
{
struct route_hop *e = &p->route[0];
u32 delay, worst = 0;
for (size_t i = 0; i < tal_count(p->route)-1; i++) {
delay = p->route[i].delay - p->route[i+1].delay;
if (delay >= worst) {
e = &p->route[i];
worst = delay;
}
}
channel_hints_update(p, e->scid, e->direction, false, false,
NULL, NULL);
}
static struct amount_msat payment_route_fee(struct payment *p)
{
struct amount_msat fee;
if (!amount_msat_sub(&fee, p->route[0].amount, p->amount)) {
paymod_log(
p,
LOG_BROKEN,
"gossipd returned a route with a negative fee: sending %s "
"to deliver %s",
type_to_string(tmpctx, struct amount_msat,
&p->route[0].amount),
type_to_string(tmpctx, struct amount_msat, &p->amount));
abort();
}
return fee;
}
/* Update the constraints by subtracting the delta_fee and delta_cltv if the
* result is positive. Returns whether or not the update has been applied. */
static WARN_UNUSED_RESULT bool
payment_constraints_update(struct payment_constraints *cons,
const struct amount_msat delta_fee,
const u32 delta_cltv)
{
if (delta_cltv > cons->cltv_budget)
return false;
/* amount_msat_sub performs a check before actually subtracting. */
if (!amount_msat_sub(&cons->fee_budget, cons->fee_budget, delta_fee))
return false;
cons->cltv_budget -= delta_cltv;
return true;
}
static struct channel_hint *payment_chanhints_get(struct payment *p,
struct route_hop *h)
{
struct payment *root = payment_root(p);
struct channel_hint *curhint;
for (size_t j = 0; j < tal_count(root->channel_hints); j++) {
curhint = &root->channel_hints[j];
if (short_channel_id_eq(&curhint->scid.scid, &h->scid) &&
curhint->scid.dir == h->direction) {
return curhint;
}
}
return NULL;
}
/* Given a route and a couple of channel hints, apply the route to the channel
* hints, so we have a better estimation of channel's capacity. We apply a
* route to a channel hint before calling `sendonion` so subsequent `route`
* calls don't accidentally try to use those out-of-date estimates. We unapply
* if the payment failed, i.e., all HTLCs we might have added have been torn
* down again. Finally we leave the update in place if the payment went
* through, since the balances really changed in that case. The `remove`
* argument indicates whether we want to apply (`remove=false`), or clear a
* prior application (`remove=true`). */
static bool payment_chanhints_apply_route(struct payment *p, bool remove)
{
bool apply;
struct route_hop *curhop;
struct channel_hint *curhint;
struct payment *root = payment_root(p);
assert(p->route != NULL);
/* No need to check for applicability if we increase
* capacity and budgets. */
if (remove)
goto apply_changes;
/* First round: make sure we can cleanly apply the update. */
for (size_t i = 0; i < tal_count(p->route); i++) {
curhop = &p->route[i];
curhint = payment_chanhints_get(root, curhop);
/* If we don't have a hint we can't fail updating it. */
if (!curhint)
continue;
/* For local channels we check that we don't overwhelm
* them with too many HTLCs. */
apply = (!curhint->local) ||
(curhint->local->htlc_budget > 0);
/* For all channels we check that they have a
* sufficiently large estimated capacity to have some
* chance of succeeding. */
apply &= amount_msat_greater_eq(curhint->estimated_capacity,
curhop->amount);
if (!apply) {
/* This can happen in case of multiple
* concurrent getroute calls using the
* same channel_hints, no biggy, it's
* an estimation anyway. */
paymod_log(p, LOG_DBG,
"Could not update the channel hint "
"for %s. Could be a concurrent "
"`getroute` call.",
type_to_string(tmpctx,
struct short_channel_id_dir,
&curhint->scid));
paymod_log(
p, LOG_DBG,
"Capacity: estimated_capacity=%s, hop_amount=%s. "
"local=%s%s",
type_to_string(tmpctx, struct amount_msat,
&curhint->estimated_capacity),
type_to_string(tmpctx, struct amount_msat,
&curhop->amount),
curhint->local ? "Y" : "N",
curhint->local ?
tal_fmt(tmpctx, " HTLC Budget: htlc_budget=%d",
curhint->local->htlc_budget) : "");
return false;
}
}
apply_changes:
/* Second round: apply the changes, now that we know they'll succeed. */
for (size_t i = 0; i < tal_count(p->route); i++) {
curhop = &p->route[i];
curhint = payment_chanhints_get(root, curhop);
if (!curhint)
continue;
/* Update the number of htlcs for any local
* channel in the route */
if (curhint->local) {
if (remove)
curhint->local->htlc_budget++;
else
curhint->local->htlc_budget--;
}
if (remove && !amount_msat_add(
&curhint->estimated_capacity,
curhint->estimated_capacity,
curhop->amount)) {
/* This should never happen, it'd mean
* that we unapply a route that would
* result in a msatoshi
* wrap-around. */
abort();
} else if (!amount_msat_sub(
&curhint->estimated_capacity,
curhint->estimated_capacity,
curhop->amount)) {
/* Given our preemptive test
* above, this should never
* happen either. */
abort();
}
}
return true;
}
static const struct short_channel_id_dir *
payment_get_excluded_channels(const tal_t *ctx, struct payment *p)
{
struct payment *root = payment_root(p);
struct channel_hint *hint;
struct short_channel_id_dir *res =
tal_arr(ctx, struct short_channel_id_dir, 0);
for (size_t i = 0; i < tal_count(root->channel_hints); i++) {
hint = &root->channel_hints[i];
if (!hint->enabled)
tal_arr_expand(&res, hint->scid);
else if (amount_msat_greater(p->amount,
hint->estimated_capacity))
tal_arr_expand(&res, hint->scid);
else if (hint->local && hint->local->htlc_budget == 0)
/* If we cannot add any HTLCs to the channel we
* shouldn't look for a route through that channel */
tal_arr_expand(&res, hint->scid);
}
return res;
}
static const struct node_id *payment_get_excluded_nodes(const tal_t *ctx,
struct payment *p)
{
struct payment *root = payment_root(p);
return root->excluded_nodes;
}
/* FIXME: This is slow! */
static const struct channel_hint *find_hint(const struct channel_hint *hints,
const struct short_channel_id *scid,
int dir)
{
for (size_t i = 0; i < tal_count(hints); i++) {
if (short_channel_id_eq(scid, &hints[i].scid.scid)
&& dir == hints[i].scid.dir)
return &hints[i];
}
return NULL;
}
/* FIXME: This is slow! */
static bool dst_is_excluded(const struct gossmap *gossmap,
const struct gossmap_chan *c,
int dir,
const struct node_id *nodes)
{
struct node_id dstid;
/* Premature optimization */
if (!tal_count(nodes))
return false;
gossmap_node_get_id(gossmap, gossmap_nth_node(gossmap, c, !dir),
&dstid);
for (size_t i = 0; i < tal_count(nodes); i++) {
if (node_id_eq(&dstid, &nodes[i]))
return true;
}
return false;
}
static bool payment_route_check(const struct gossmap *gossmap,
const struct gossmap_chan *c,
int dir,
struct amount_msat amount,
struct payment *p)
{
struct short_channel_id scid;
const struct channel_hint *hint;
if (dst_is_excluded(gossmap, c, dir, payment_root(p)->excluded_nodes))
return false;
if (dst_is_excluded(gossmap, c, dir, p->temp_exclusion))
return false;
scid = gossmap_chan_scid(gossmap, c);
hint = find_hint(payment_root(p)->channel_hints, &scid, dir);
if (!hint)
return true;
if (!hint->enabled)
return false;
if (amount_msat_greater_eq(amount, hint->estimated_capacity))
/* We exclude on equality because we've set the
* estimate to the smallest failed attempt. */
return false;
if (hint->local && hint->local->htlc_budget == 0)
/* If we cannot add any HTLCs to the channel we
* shouldn't look for a route through that channel */
return false;
return true;
}
static bool payment_route_can_carry(const struct gossmap *map,
const struct gossmap_chan *c,
int dir,
struct amount_msat amount,
struct payment *p)
{
if (!route_can_carry(map, c, dir, amount, p))
return false;
return payment_route_check(map, c, dir, amount, p);
}
static bool payment_route_can_carry_even_disabled(const struct gossmap *map,
const struct gossmap_chan *c,
int dir,
struct amount_msat amount,
struct payment *p)
{
if (!route_can_carry_even_disabled(map, c, dir, amount, p))
return false;
return payment_route_check(map, c, dir, amount, p);
}
/* Rene Pickhardt:
*
* Btw the linear term of the Taylor series of -log((c+1-x)/(c+1)) is 1/(c+1)
* meaning that another suitable Weight for Dijkstra would be amt/(c+1) +
* \mu*fee(amt) which is the linearized version which for small amounts and
* suitable value of \mu should be good enough)
*/
static double capacity_bias(const struct gossmap *map,
const struct gossmap_chan *c,
int dir,
struct amount_msat amount)
{
struct amount_sat capacity;
u64 amtmsat = amount.millisatoshis; /* Raw: lengthy math */
double capmsat;
/* Can fail in theory if gossmap changed underneath. */
if (!gossmap_chan_get_capacity(map, c, &capacity))
return 0;
capmsat = (double)capacity.satoshis * 1000; /* Raw: lengthy math */
return -log((capmsat + 1 - amtmsat) / (capmsat + 1));
}
/* Prioritize costs over distance, but bias to larger channels. */
static u64 route_score(struct amount_msat fee,
struct amount_msat risk,
struct amount_msat total,
int dir,
const struct gossmap_chan *c)
{
double score;
struct amount_msat msat;
/* These two are comparable, so simply sum them. */
if (!amount_msat_add(&msat, fee, risk))
msat = AMOUNT_MSAT(-1ULL);
/* Slight tiebreaker bias: 1 msat per distance */
if (!amount_msat_add(&msat, msat, AMOUNT_MSAT(1)))
msat = AMOUNT_MSAT(-1ULL);
/* Percent penalty at different channel capacities:
* 1%: 1%
* 10%: 11%
* 25%: 29%
* 50%: 69%
* 75%: 138%
* 90%: 230%
* 95%: 300%
* 99%: 461%
*/
score = (capacity_bias(global_gossmap, c, dir, total) + 1)
* msat.millisatoshis; /* Raw: Weird math */
if (score > 0xFFFFFFFF)
return 0xFFFFFFFF;
/* Cast unnecessary, but be explicit! */
return (u64)score;
}
static struct route_hop *route(const tal_t *ctx,
struct gossmap *gossmap,
const struct gossmap_node *src,
const struct gossmap_node *dst,
struct amount_msat amount,
u32 final_delay,
double riskfactor,
size_t max_hops,
struct payment *p,
const char **errmsg)
{
const struct dijkstra *dij;
struct route_hop *r;
bool (*can_carry)(const struct gossmap *,
const struct gossmap_chan *,
int,
struct amount_msat,
struct payment *);
can_carry = payment_route_can_carry;
dij = dijkstra(tmpctx, gossmap, dst, amount, riskfactor,
can_carry, route_score, p);
r = route_from_dijkstra(ctx, gossmap, dij, src, amount, final_delay);
if (!r) {
/* Try using disabled channels too */
/* FIXME: is there somewhere we can annotate this for paystatus? */
can_carry = payment_route_can_carry_even_disabled;
dij = dijkstra(tmpctx, gossmap, dst, amount, riskfactor,
can_carry, route_score, p);
r = route_from_dijkstra(ctx, gossmap, dij, src,
amount, final_delay);
if (!r) {
*errmsg = "No path found";
return NULL;
}
}
/* If it's too far, fall back to using shortest path. */
if (tal_count(r) > max_hops) {
tal_free(r);
/* FIXME: is there somewhere we can annotate this for paystatus? */
dij = dijkstra(tmpctx, gossmap, dst, amount, riskfactor,
can_carry, route_score_shorter, p);
r = route_from_dijkstra(ctx, gossmap, dij, src,
amount, final_delay);
if (!r) {
*errmsg = "No path found";
return NULL;
}
/* If it's still too far, fail. */
if (tal_count(r) > max_hops) {
*errmsg = tal_fmt(ctx, "Shortest path found was length %zu",
tal_count(r));
return tal_free(r);
}
}
*errmsg = NULL;
return r;
}
static struct command_result *payment_getroute(struct payment *p)
{
const struct gossmap_node *dst, *src;
struct amount_msat fee;
const char *errstr;
struct gossmap *gossmap;
/* If we retry the getroute call we might already have a route, so
* free an eventual stale route. */
p->route = tal_free(p->route);
gossmap = get_gossmap(p);
dst = gossmap_find_node(gossmap, p->getroute->destination);
if (!dst) {
put_gossmap(p);
payment_fail(
p, "Unknown destination %s",
type_to_string(tmpctx, struct node_id,
p->getroute->destination));
/* Let payment_finished_ handle this, so we mark it as pending */
return command_still_pending(p->cmd);
}
/* If we don't exist in gossip, routing can't happen. */
src = gossmap_find_node(gossmap, p->local_id);
if (!src) {
put_gossmap(p);
payment_fail(p, "We don't have any channels");
/* Let payment_finished_ handle this, so we mark it as pending */
return command_still_pending(p->cmd);
}
p->route = route(p, gossmap, src, dst, p->getroute->amount, p->getroute->cltv,
p->getroute->riskfactorppm / 1000000.0, p->getroute->max_hops,
p, &errstr);
put_gossmap(p);
if (!p->route) {
payment_fail(p, "%s", errstr);
/* Let payment_finished_ handle this, so we mark it as pending */
return command_still_pending(p->cmd);
}
/* OK, now we *have* a route */
p->step = PAYMENT_STEP_GOT_ROUTE;
if (tal_count(p->route) == 0) {
payment_root(p)->abort = true;
payment_fail(p, "Empty route returned by getroute, are you "
"trying to pay yourself?");
}
fee = payment_route_fee(p);
/* Ensure that our fee and CLTV budgets are respected. */
if (amount_msat_greater(fee, p->constraints.fee_budget)) {
payment_exclude_most_expensive(p);
p->route = tal_free(p->route);
payment_fail(
p, "Fee exceeds our fee budget: %s > %s, discarding route",
type_to_string(tmpctx, struct amount_msat, &fee),
type_to_string(tmpctx, struct amount_msat,
&p->constraints.fee_budget));
return command_still_pending(p->cmd);
}
if (p->route[0].delay > p->constraints.cltv_budget) {
u32 delay = p->route[0].delay;
payment_exclude_longest_delay(p);
p->route = tal_free(p->route);
payment_fail(p, "CLTV delay exceeds our CLTV budget: %d > %d",
delay, p->constraints.cltv_budget);
return command_still_pending(p->cmd);
}
/* Now update the constraints in fee_budget and cltv_budget so
* modifiers know what constraints they need to adhere to. */
if (!payment_constraints_update(&p->constraints, fee, p->route[0].delay)) {
paymod_log(p, LOG_BROKEN,
"Could not update constraints.");
abort();
}
/* Allow modifiers to modify the route, before
* payment_compute_onion_payloads uses the route to generate the
* onion_payloads */
payment_continue(p);
return command_still_pending(p->cmd);
}
static struct command_result *
payment_listpeerchannels_success(struct command *cmd,
const char *buffer,
const jsmntok_t *toks,
struct payment *p)
{
p->mods = gossmods_from_listpeerchannels(p, p->local_id,
buffer, toks, true,
gossmod_add_localchan,
NULL);
return payment_getroute(p);
}
static struct command_result *payment_getlocalmods(struct payment *p)
{
struct out_req *req;
/* Don't call listpeerchannels if we already have mods */
if (p->mods)
return payment_getroute(p);
req = jsonrpc_request_start(p->plugin, NULL, "listpeerchannels",
&payment_listpeerchannels_success,
&payment_rpc_failure, p);
return send_outreq(p->plugin, req);
}
static struct payment_result *tal_sendpay_result_from_json(const tal_t *ctx,
const char *buffer,
const jsmntok_t *toks)
{
const jsmntok_t *idtok = json_get_member(buffer, toks, "id");
const jsmntok_t *hashtok = json_get_member(buffer, toks, "payment_hash");
const jsmntok_t *partidtok = json_get_member(buffer, toks, "partid");
const jsmntok_t *senttok = json_get_member(buffer, toks, "amount_sent_msat");
const jsmntok_t *statustok = json_get_member(buffer, toks, "status");
const jsmntok_t *preimagetok = json_get_member(buffer, toks, "payment_preimage");
const jsmntok_t *codetok = json_get_member(buffer, toks, "code");
const jsmntok_t *datatok = json_get_member(buffer, toks, "data");
const jsmntok_t *erridxtok, *msgtok, *failcodetok, *rawmsgtok,
*failcodenametok, *errchantok, *errnodetok, *errdirtok;
struct payment_result *result;