forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
invoice.c
1860 lines (1640 loc) · 56.4 KB
/
invoice.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/asort/asort.h>
#include <ccan/cast/cast.h>
#include <ccan/json_escape/json_escape.h>
#include <ccan/str/hex/hex.h>
#include <ccan/tal/str/str.h>
#include <common/blindedpath.h>
#include <common/bolt11_json.h>
#include <common/bolt12_merkle.h>
#include <common/configdir.h>
#include <common/invoice_path_id.h>
#include <common/json_command.h>
#include <common/json_param.h>
#include <common/overflows.h>
#include <common/random_select.h>
#include <common/timeout.h>
#include <common/type_to_string.h>
#include <db/exec.h>
#include <errno.h>
#include <hsmd/hsmd_wiregen.h>
#include <lightningd/channel.h>
#include <lightningd/invoice.h>
#include <lightningd/notification.h>
#include <lightningd/plugin_hook.h>
#include <lightningd/routehint.h>
#include <sodium/randombytes.h>
#include <wire/wire_sync.h>
static const char *invoice_status_str(const struct invoice_details *inv)
{
if (inv->state == PAID)
return "paid";
if (inv->state == EXPIRED)
return "expired";
return "unpaid";
}
static void json_add_invoice_fields(struct json_stream *response,
const struct invoice_details *inv)
{
json_add_escaped_string(response, "label", inv->label);
if (inv->invstring)
json_add_invstring(response, inv->invstring);
json_add_sha256(response, "payment_hash", &inv->rhash);
if (inv->msat)
json_add_amount_msat_compat(response, *inv->msat,
"msatoshi", "amount_msat");
json_add_string(response, "status", invoice_status_str(inv));
if (inv->state == PAID) {
json_add_u64(response, "pay_index", inv->pay_index);
json_add_amount_msat_compat(response, inv->received,
"msatoshi_received",
"amount_received_msat");
json_add_u64(response, "paid_at", inv->paid_timestamp);
json_add_preimage(response, "payment_preimage", &inv->r);
}
if (inv->description)
json_add_string(response, "description", inv->description);
json_add_u64(response, "expires_at", inv->expiry_time);
if (inv->local_offer_id) {
char *fail;
struct tlv_invoice *tinv;
json_add_sha256(response, "local_offer_id", inv->local_offer_id);
/* Everyone loves seeing their own payer notes!
* Well: they will. Trust me. */
tinv = invoice_decode(tmpctx,
inv->invstring, strlen(inv->invstring),
NULL, NULL, &fail);
if (tinv && tinv->invreq_payer_note)
json_add_stringn(response, "invreq_payer_note",
tinv->invreq_payer_note,
tal_bytelen(tinv->invreq_payer_note));
}
}
static void json_add_invoice(struct json_stream *response,
const char *fieldname,
const struct invoice_details *inv)
{
json_object_start(response, fieldname);
json_add_invoice_fields(response, inv);
json_object_end(response);
}
static struct command_result *tell_waiter(struct command *cmd,
const struct invoice *inv)
{
struct json_stream *response;
const struct invoice_details *details;
details = wallet_invoice_details(cmd, cmd->ld->wallet, *inv);
if (details->state == PAID) {
response = json_stream_success(cmd);
json_add_invoice_fields(response, details);
return command_success(cmd, response);
} else {
response = json_stream_fail(cmd, INVOICE_EXPIRED_DURING_WAIT,
"invoice expired during wait");
json_add_invoice_fields(response, details);
json_object_end(response);
return command_failed(cmd, response);
}
}
static void tell_waiter_deleted(struct command *cmd)
{
was_pending(command_fail(cmd, LIGHTNINGD,
"Invoice deleted during wait"));
}
static void wait_on_invoice(const struct invoice *invoice, void *cmd)
{
if (invoice)
tell_waiter((struct command *) cmd, invoice);
else
tell_waiter_deleted((struct command *) cmd);
}
static void wait_timed_out(struct command *cmd)
{
was_pending(command_fail(cmd, INVOICE_WAIT_TIMED_OUT,
"Timed out while waiting "
"for invoice to be paid"));
}
/* We derive invoice secret using 1-way function from payment_preimage
* (just a different one from the payment_hash!) */
static void invoice_secret(const struct preimage *payment_preimage,
struct secret *payment_secret)
{
struct preimage modified;
struct sha256 secret;
modified = *payment_preimage;
modified.r[0] ^= 1;
sha256(&secret, modified.r,
ARRAY_SIZE(modified.r) * sizeof(*modified.r));
BUILD_ASSERT(sizeof(secret.u.u8) == sizeof(payment_secret->data));
memcpy(payment_secret->data, secret.u.u8, sizeof(secret.u.u8));
}
/* FIXME: The spec should require a *real* secret: a signature of the
* payment_hash using the payer_id key. This just means they've
* *seen* the invoice! */
static void invoice_secret_bolt12(struct lightningd *ld,
const struct sha256 *payment_hash,
struct secret *payment_secret)
{
const void *path_id = invoice_path_id(tmpctx,
&ld->invoicesecret_base,
payment_hash);
assert(tal_bytelen(path_id) == sizeof(*payment_secret));
memcpy(payment_secret, path_id, sizeof(*payment_secret));
}
struct invoice_payment_hook_payload {
struct lightningd *ld;
/* Set to NULL if it is deleted while waiting for plugin */
struct htlc_set *set;
/* What invoice it's trying to pay. */
const struct json_escape *label;
/* Amount it's offering. */
struct amount_msat msat;
/* Preimage we'll give it if succeeds. */
struct preimage preimage;
/* FIXME: Include raw payload! */
};
#ifdef DEVELOPER
static void invoice_payment_add_tlvs(struct json_stream *stream,
struct htlc_set *hset)
{
struct htlc_in *hin;
const struct tlv_tlv_payload *tlvs;
assert(tal_count(hset->htlcs) > 0);
/* Pick the first HTLC as representative for the entire set. */
hin = hset->htlcs[0];
tlvs = hin->payload->tlv;
json_array_start(stream, "extratlvs");
for (size_t i = 0; i < tal_count(tlvs->fields); i++) {
struct tlv_field *field = &tlvs->fields[i];
/* If we have metadata attached it is not an extra TLV field. */
if (field->meta == NULL) {
json_object_start(stream, NULL);
json_add_u64(stream, "type", field->numtype);
json_add_num(stream, "length", field->length);
json_add_hex_talarr(stream, "value", field->value);
json_object_end(stream);
}
}
json_array_end(stream);
}
#endif
static void
invoice_payment_serialize(struct invoice_payment_hook_payload *payload,
struct json_stream *stream,
struct plugin *plugin)
{
json_object_start(stream, "payment");
json_add_escaped_string(stream, "label", payload->label);
json_add_preimage(stream, "preimage", &payload->preimage);
json_add_string(stream, "msat",
type_to_string(tmpctx, struct amount_msat,
&payload->msat));
#ifdef DEVELOPER
invoice_payment_add_tlvs(stream, payload->set);
#endif
json_object_end(stream); /* .payment */
}
/* Set times out or HTLC deleted? Remove set ptr from payload so we
* know to ignore plugin return */
static void invoice_payload_remove_set(struct htlc_set *set,
struct invoice_payment_hook_payload *payload)
{
assert(payload->set == set);
payload->set = NULL;
}
static const u8 *hook_gives_failmsg(const tal_t *ctx,
struct lightningd *ld,
const struct htlc_in *hin,
const char *buffer,
const jsmntok_t *toks)
{
const jsmntok_t *resulttok;
const jsmntok_t *t;
unsigned int val;
/* No plugin registered on hook at all? */
if (!buffer)
return NULL;
resulttok = json_get_member(buffer, toks, "result");
if (resulttok) {
if (json_tok_streq(buffer, resulttok, "continue")) {
return NULL;
} else if (json_tok_streq(buffer, resulttok, "reject")) {
return failmsg_incorrect_or_unknown(ctx, ld, hin);
} else
fatal("Invalid invoice_payment hook result: %.*s",
toks[0].end - toks[0].start, buffer);
}
t = json_get_member(buffer, toks, "failure_message");
if (t) {
const u8 *failmsg = json_tok_bin_from_hex(ctx, buffer, t);
if (!failmsg)
fatal("Invalid invoice_payment_hook failure_message: %.*s",
toks[0].end - toks[1].start, buffer);
return failmsg;
}
if (!deprecated_apis)
return NULL;
t = json_get_member(buffer, toks, "failure_code");
if (!t) {
static bool warned = false;
if (!warned) {
warned = true;
log_unusual(ld->log,
"Plugin did not return object with "
"'result' or 'failure_message' fields. "
"This is now deprecated and you should "
"return {'result': 'continue' } or "
"{'result': 'reject'} or "
"{'failure_message'... instead.");
}
return failmsg_incorrect_or_unknown(ctx, ld, hin);
}
if (!json_to_number(buffer, t, &val))
fatal("Invalid invoice_payment_hook failure_code: %.*s",
toks[0].end - toks[1].start, buffer);
if (val == WIRE_TEMPORARY_NODE_FAILURE)
return towire_temporary_node_failure(ctx);
if (val != WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS)
log_broken(hin->key.channel->log,
"invoice_payment hook returned failcode %u,"
" changing to incorrect_or_unknown_payment_details",
val);
return failmsg_incorrect_or_unknown(ctx, ld, hin);
}
static void
invoice_payment_hooks_done(struct invoice_payment_hook_payload *payload STEALS)
{
struct invoice invoice;
struct lightningd *ld = payload->ld;
tal_del_destructor2(payload->set, invoice_payload_remove_set, payload);
/* We want to free this, whatever happens. */
tal_steal(tmpctx, payload);
/* If invoice gets paid meanwhile (plugin responds out-of-order?) then
* we can also fail */
if (!wallet_invoice_find_by_label(ld->wallet, &invoice, payload->label)) {
htlc_set_fail(payload->set, take(failmsg_incorrect_or_unknown(
NULL, ld, payload->set->htlcs[0])));
return;
}
/* Paid or expired in the meantime. */
if (!wallet_invoice_resolve(ld->wallet, invoice, payload->msat)) {
htlc_set_fail(payload->set, take(failmsg_incorrect_or_unknown(
NULL, ld, payload->set->htlcs[0])));
return;
}
log_info(ld->log, "Resolved invoice '%s' with amount %s in %zu htlcs",
payload->label->s,
type_to_string(tmpctx, struct amount_msat, &payload->msat),
tal_count(payload->set->htlcs));
htlc_set_fulfill(payload->set, &payload->preimage);
notify_invoice_payment(ld, payload->msat, payload->preimage,
payload->label);
}
static bool
invoice_payment_deserialize(struct invoice_payment_hook_payload *payload,
const char *buffer,
const jsmntok_t *toks)
{
struct lightningd *ld = payload->ld;
const u8 *failmsg;
/* If peer dies or something, this can happen. */
if (!payload->set) {
log_debug(ld->log, "invoice '%s' paying htlc_in has gone!",
payload->label->s);
return false;
}
/* Did we have a hook result? */
failmsg = hook_gives_failmsg(NULL, ld,
payload->set->htlcs[0], buffer, toks);
if (failmsg) {
htlc_set_fail(payload->set, take(failmsg));
return false;
}
return true;
}
REGISTER_PLUGIN_HOOK(invoice_payment,
invoice_payment_deserialize,
invoice_payment_hooks_done,
invoice_payment_serialize,
struct invoice_payment_hook_payload *);
const struct invoice_details *
invoice_check_payment(const tal_t *ctx,
struct lightningd *ld,
const struct sha256 *payment_hash,
const struct amount_msat msat,
const struct secret *payment_secret)
{
struct invoice invoice;
const struct invoice_details *details;
/* BOLT #4:
* - if the payment hash has already been paid:
* - MAY treat the payment hash as unknown.
* - MAY succeed in accepting the HTLC.
*...
* - if the payment hash is unknown:
* - MUST fail the HTLC.
* - MUST return an `incorrect_or_unknown_payment_details` error.
*/
if (!wallet_invoice_find_unpaid(ld->wallet, &invoice, payment_hash)) {
log_debug(ld->log, "Unknown paid invoice %s",
type_to_string(tmpctx, struct sha256, payment_hash));
if (wallet_invoice_find_by_rhash(ld->wallet, &invoice, payment_hash)) {
log_debug(ld->log, "ALREADY paid invoice %s",
type_to_string(tmpctx, struct sha256, payment_hash));
}
return NULL;
}
details = wallet_invoice_details(ctx, ld->wallet, invoice);
/* BOLT #4:
* - if the `payment_secret` doesn't match the expected value for that
* `payment_hash`, or the `payment_secret` is required and is not
* present:
* - MUST fail the HTLC.
*/
if (feature_is_set(details->features, COMPULSORY_FEATURE(OPT_VAR_ONION))
&& !payment_secret) {
log_debug(ld->log, "Attept to pay %s without secret",
type_to_string(tmpctx, struct sha256, &details->rhash));
return tal_free(details);
}
if (payment_secret) {
struct secret expected;
if (details->invstring && strstarts(details->invstring, "lni1"))
invoice_secret_bolt12(ld, payment_hash, &expected);
else
invoice_secret(&details->r, &expected);
if (!secret_eq_consttime(payment_secret, &expected)) {
log_debug(ld->log, "Attept to pay %s with wrong secret",
type_to_string(tmpctx, struct sha256,
&details->rhash));
return tal_free(details);
}
}
/* BOLT #4:
*
* An _intermediate hop_ MUST NOT, but the _final node_:
*...
* - if the amount paid is less than the amount expected:
* - MUST fail the HTLC.
*/
if (details->msat != NULL) {
struct amount_msat twice;
if (amount_msat_less(msat, *details->msat)) {
log_debug(ld->log, "Attept to pay %s with amount %s < %s",
type_to_string(tmpctx, struct sha256,
&details->rhash),
type_to_string(tmpctx, struct amount_msat, &msat),
type_to_string(tmpctx, struct amount_msat, details->msat));
return tal_free(details);
}
if (amount_msat_add(&twice, *details->msat, *details->msat)
&& amount_msat_greater(msat, twice)) {
log_debug(ld->log, "Attept to pay %s with amount %s > %s",
type_to_string(tmpctx, struct sha256,
&details->rhash),
type_to_string(tmpctx, struct amount_msat, &msat),
type_to_string(tmpctx, struct amount_msat, &twice));
/* BOLT #4:
*
* - if the amount paid is more than twice the amount
* expected:
* - SHOULD fail the HTLC.
*/
return tal_free(details);
}
}
return details;
}
void invoice_try_pay(struct lightningd *ld,
struct htlc_set *set,
const struct invoice_details *details)
{
struct invoice_payment_hook_payload *payload;
payload = tal(NULL, struct invoice_payment_hook_payload);
payload->ld = ld;
payload->label = tal_steal(payload, details->label);
payload->msat = set->so_far;
payload->preimage = details->r;
payload->set = set;
tal_add_destructor2(set, invoice_payload_remove_set, payload);
plugin_hook_call_invoice_payment(ld, NULL, payload);
}
static bool hsm_sign_b11(const u5 *u5bytes,
const u8 *hrpu8,
secp256k1_ecdsa_recoverable_signature *rsig,
struct lightningd *ld)
{
u8 *msg = towire_hsmd_sign_invoice(NULL, u5bytes, hrpu8);
if (!wire_sync_write(ld->hsm_fd, take(msg)))
fatal("Could not write to HSM: %s", strerror(errno));
msg = wire_sync_read(tmpctx, ld->hsm_fd);
if (!fromwire_hsmd_sign_invoice_reply(msg, rsig))
fatal("HSM gave bad sign_invoice_reply %s",
tal_hex(msg, msg));
return true;
}
static void hsm_sign_b12_invoice(struct lightningd *ld,
struct tlv_invoice *invoice)
{
struct sha256 merkle;
u8 *msg;
assert(!invoice->signature);
merkle_tlv(invoice->fields, &merkle);
msg = towire_hsmd_sign_bolt12(NULL, "invoice", "signature", &merkle, NULL);
if (!wire_sync_write(ld->hsm_fd, take(msg)))
fatal("Could not write to HSM: %s", strerror(errno));
msg = wire_sync_read(tmpctx, ld->hsm_fd);
invoice->signature = tal(invoice, struct bip340sig);
if (!fromwire_hsmd_sign_bolt12_reply(msg, invoice->signature))
fatal("HSM gave bad sign_invoice_reply %s",
tal_hex(msg, msg));
}
static struct command_result *parse_fallback(struct command *cmd,
const char *buffer,
const jsmntok_t *fallback,
const u8 **fallback_script)
{
enum address_parse_result fallback_parse;
fallback_parse
= json_to_address_scriptpubkey(cmd,
chainparams,
buffer, fallback,
fallback_script);
if (fallback_parse == ADDRESS_PARSE_UNRECOGNIZED) {
return command_fail(cmd, LIGHTNINGD,
"Fallback address not valid");
} else if (fallback_parse == ADDRESS_PARSE_WRONG_NETWORK) {
return command_fail(cmd, LIGHTNINGD,
"Fallback address does not match our network %s",
chainparams->network_name);
}
return NULL;
}
/*
* From array of incoming channels [inchan], find suitable ones for
* a payment-to-us of [amount_needed], using criteria:
* 1. Channel's peer is known, in state CHANNELD_NORMAL and is online.
* 2. Channel's peer capacity to pay us is sufficient.
*
* Then use weighted reservoir sampling, which makes probing channel balances
* harder, to choose one channel from the set of suitable channels. It favors
* channels that have less balance on our side as fraction of their capacity.
*/
static struct route_info **select_inchan(const tal_t *ctx,
struct lightningd *ld,
struct amount_msat amount_needed,
const struct routehint_candidate
*candidates)
{
/* BOLT11 struct wants an array of arrays (can provide multiple routes) */
struct route_info **r = NULL;
double total_weight = 0.0;
/* Collect suitable channels and assign each a weight. */
for (size_t i = 0; i < tal_count(candidates); i++) {
struct amount_msat excess, capacity;
struct amount_sat cumulative_reserve;
double excess_frac;
/* Does the peer have sufficient balance to pay us,
* even after having taken into account their reserve? */
if (!amount_msat_sub(&excess, candidates[i].capacity,
amount_needed))
continue;
/* Channel balance as seen by our node:
|<----------------- capacity ----------------->|
. .
. |<------------------ their_msat -------------------->|
. | . |
. |<----- capacity_to_pay_us ----->|<- their_reserve ->|
. | | |
. |<- amount_needed --><- excess ->| |
. | | |
|-------|-------------|--------------------------------|-------------------|
0 ^ ^ ^ funding
our_reserve our_msat */
/* Find capacity and calculate its excess fraction */
if (!amount_sat_add(&cumulative_reserve,
candidates[i].c->our_config.channel_reserve,
candidates[i].c->channel_info.their_config.channel_reserve)
|| !amount_sat_to_msat(&capacity, candidates[i].c->funding_sats)
|| !amount_msat_sub_sat(&capacity, capacity, cumulative_reserve)) {
log_broken(ld->log, "Channel %s capacity overflow!",
type_to_string(tmpctx, struct short_channel_id, candidates[i].c->scid));
continue;
}
/* We don't want a 0 probability if 0 excess; it might be the
* only one! So bump it by 1 msat */
if (!amount_msat_add(&excess, excess, AMOUNT_MSAT(1))) {
log_broken(ld->log, "Channel %s excess overflow!",
type_to_string(tmpctx,
struct short_channel_id,
candidates[i].c->scid));
continue;
}
excess_frac = amount_msat_ratio(excess, capacity);
if (random_select(excess_frac, &total_weight)) {
tal_free(r);
r = tal_arr(ctx, struct route_info *, 1);
r[0] = tal_dup(r, struct route_info, candidates[i].r);
}
}
return r;
}
static int cmp_rr_number(const struct routehint_candidate *a,
const struct routehint_candidate *b,
struct lightningd *ld)
{
if (a->c->rr_number > b->c->rr_number)
return 1;
if (a->c->rr_number < b->c->rr_number)
return -1;
/* They're unique, so can't be equal */
log_broken(ld->log, "Two equal candidates %p and %p, channels %p and %p, rr_number %"PRIu64" and %"PRIu64,
a, b, a->c, b->c, a->c->rr_number, b->c->rr_number);
return 0;
}
/** select_inchan_mpp
*
* @brief fallback in case select_inchan cannot find a *single*
* channel capable of accepting the payment as a whole.
* Also the main routehint-selector if we are completely unpublished
* (i.e. all our channels are unpublished), since if we are completely
* unpublished then the payer cannot fall back to just directly routing
* to us.
*/
static struct route_info **select_inchan_mpp(const tal_t *ctx,
struct lightningd *ld,
struct amount_msat amount_needed,
struct routehint_candidate
*candidates)
{
/* The total amount we have gathered for incoming channels. */
struct amount_msat gathered;
/* Routehint array. */
struct route_info **routehints;
gathered = AMOUNT_MSAT(0);
routehints = tal_arr(ctx, struct route_info *, 0);
/* Sort by rr_number, so we get fresh channels. */
asort(candidates, tal_count(candidates), cmp_rr_number, ld);
for (size_t i = 0; i < tal_count(candidates); i++) {
if (amount_msat_greater_eq(gathered, amount_needed))
break;
/* Add to current routehints set. */
if (!amount_msat_add(&gathered, gathered, candidates[i].capacity)) {
log_broken(ld->log,
"Gathered channel capacity overflow: "
"%s + %s",
type_to_string(tmpctx, struct amount_msat, &gathered),
type_to_string(tmpctx, struct amount_msat,
&candidates[i].capacity));
continue;
}
tal_arr_expand(&routehints,
tal_dup(routehints, struct route_info,
candidates[i].r));
/* Put to the back of the round-robin list */
candidates[i].c->rr_number = ld->rr_counter++;
}
return routehints;
}
/* Encapsulating struct while we wait for gossipd to give us incoming channels */
struct chanhints {
bool expose_all_private;
struct short_channel_id *hints;
};
struct invoice_info {
struct command *cmd;
struct preimage payment_preimage;
struct bolt11 *b11;
struct json_escape *label;
struct chanhints *chanhints;
};
/* Add routehints based on listincoming results: NULL means success. */
static struct command_result *
add_routehints(struct invoice_info *info,
const char *buffer,
const jsmntok_t *toks,
bool *warning_mpp,
bool *warning_capacity,
bool *warning_deadends,
bool *warning_offline,
bool *warning_private_unused)
{
const struct chanhints *chanhints = info->chanhints;
bool node_unpublished;
struct amount_msat avail_capacity, deadend_capacity, offline_capacity,
private_capacity;
struct routehint_candidate *candidates;
struct amount_msat total, needed;
/* Dev code can force routes. */
if (info->b11->routes) {
*warning_mpp = *warning_capacity = *warning_deadends
= *warning_offline = *warning_private_unused
= false;
return NULL;
}
candidates = routehint_candidates(tmpctx, info->cmd->ld,
buffer, toks,
chanhints ? &chanhints->expose_all_private : NULL,
chanhints ? chanhints->hints : NULL,
&node_unpublished,
&avail_capacity,
&private_capacity,
&deadend_capacity,
&offline_capacity);
/* If they told us to use scids and we couldn't, fail. */
if (tal_count(candidates) == 0
&& chanhints && tal_count(chanhints->hints) != 0) {
return command_fail(info->cmd,
INVOICE_HINTS_GAVE_NO_ROUTES,
"None of those hints were suitable local channels");
}
needed = info->b11->msat ? *info->b11->msat : AMOUNT_MSAT(1);
/* If we are not completely unpublished, try with reservoir
* sampling first.
*
* Why do we not do this if we are completely unpublished?
* Because it is possible that multiple invoices will, by
* chance, select the same channel as routehint.
* This single channel might not be able to accept all the
* incoming payments on all the invoices generated.
* If we were published, that is fine because the payer can
* fall back to just attempting to route directly.
* But if we were unpublished, the only way for the payer to
* reach us would be via the routehints we provide, so we
* should make an effort to avoid overlapping incoming
* channels, which is done by select_inchan_mpp.
*/
if (!node_unpublished)
info->b11->routes = select_inchan(info->b11,
info->cmd->ld,
needed,
candidates);
/* If we are completely unpublished, or if the above reservoir
* sampling fails, select channels by round-robin. */
if (tal_count(info->b11->routes) == 0) {
info->b11->routes = select_inchan_mpp(info->b11,
info->cmd->ld,
needed,
candidates);
*warning_mpp = (tal_count(info->b11->routes) > 1);
} else {
*warning_mpp = false;
}
log_debug(info->cmd->ld->log, "needed = %s, avail_capacity = %s, private_capacity = %s, offline_capacity = %s, deadend_capacity = %s",
type_to_string(tmpctx, struct amount_msat, &needed),
type_to_string(tmpctx, struct amount_msat, &avail_capacity),
type_to_string(tmpctx, struct amount_msat, &private_capacity),
type_to_string(tmpctx, struct amount_msat, &offline_capacity),
type_to_string(tmpctx, struct amount_msat, &deadend_capacity));
if (!amount_msat_add(&total, avail_capacity, offline_capacity)
|| !amount_msat_add(&total, total, deadend_capacity)
|| !amount_msat_add(&total, total, private_capacity))
fatal("Cannot add %s + %s + %s + %s",
type_to_string(tmpctx, struct amount_msat,
&avail_capacity),
type_to_string(tmpctx, struct amount_msat,
&offline_capacity),
type_to_string(tmpctx, struct amount_msat,
&deadend_capacity),
type_to_string(tmpctx, struct amount_msat,
&private_capacity));
/* If we literally didn't have capacity at all, warn. */
*warning_capacity = amount_msat_greater_eq(needed, total);
/* We only warn about these if we didn't have capacity and
* they would have helped. */
*warning_offline = false;
*warning_deadends = false;
*warning_private_unused = false;
if (amount_msat_greater(needed, avail_capacity)) {
struct amount_msat tot;
/* We didn't get enough: would offline have helped? */
if (!amount_msat_add(&tot, avail_capacity, offline_capacity))
abort();
if (amount_msat_greater_eq(tot, needed)) {
*warning_offline = true;
goto done;
}
/* Hmm, what about deadends? */
if (!amount_msat_add(&tot, tot, deadend_capacity))
abort();
if (amount_msat_greater_eq(tot, needed)) {
*warning_deadends = true;
goto done;
}
/* What about private channels? */
if (!amount_msat_add(&tot, tot, private_capacity))
abort();
if (amount_msat_greater_eq(tot, needed)) {
*warning_private_unused = true;
goto done;
}
}
done:
return NULL;
}
static struct command_result *
invoice_complete(struct invoice_info *info,
bool warning_no_listincoming,
bool warning_mpp,
bool warning_capacity,
bool warning_deadends,
bool warning_offline,
bool warning_private_unused)
{
struct json_stream *response;
struct invoice invoice;
char *b11enc;
const struct invoice_details *details;
struct secret payment_secret;
struct wallet *wallet = info->cmd->ld->wallet;
b11enc = bolt11_encode(info, info->b11, false,
hsm_sign_b11, info->cmd->ld);
/* Check duplicate preimage (unlikely unless they specified it!) */
if (wallet_invoice_find_by_rhash(wallet,
&invoice, &info->b11->payment_hash)) {
return command_fail(info->cmd,
INVOICE_PREIMAGE_ALREADY_EXISTS,
"preimage already used");
}
if (!wallet_invoice_create(wallet,
&invoice,
info->b11->msat,
info->label,
info->b11->expiry,
b11enc,
info->b11->description,
info->b11->features,
&info->payment_preimage,
&info->b11->payment_hash,
NULL)) {
return command_fail(info->cmd, INVOICE_LABEL_ALREADY_EXISTS,
"Duplicate label '%s'",
info->label->s);
}
/* Get details */
details = wallet_invoice_details(info, wallet, invoice);
response = json_stream_success(info->cmd);
json_add_sha256(response, "payment_hash", &details->rhash);
json_add_u64(response, "expires_at", details->expiry_time);
json_add_string(response, "bolt11", details->invstring);
invoice_secret(&details->r, &payment_secret);
json_add_secret(response, "payment_secret", &payment_secret);
notify_invoice_creation(info->cmd->ld, info->b11->msat,
info->payment_preimage, info->label);
if (warning_no_listincoming)
json_add_string(response, "warning_listincoming",
"No listincoming command available, cannot add routehints to invoice");
if (warning_mpp)
json_add_string(response, "warning_mpp",
"The invoice is only payable by MPP-capable payers.");
if (warning_capacity)
json_add_string(response, "warning_capacity",
"Insufficient incoming channel capacity to pay invoice");
if (warning_deadends)
json_add_string(response, "warning_deadends",
"Insufficient incoming capacity, once dead-end peers were excluded");
if (warning_offline)
json_add_string(response, "warning_offline",
"Insufficient incoming capacity, once offline peers were excluded");
if (warning_private_unused)
json_add_string(response, "warning_private_unused",
"Insufficient incoming capacity, once private channels were excluded (try exposeprivatechannels=true?)");
return command_success(info->cmd, response);
}
/* Return from "listincoming". */
static void listincoming_done(const char *buffer,
const jsmntok_t *toks,
const jsmntok_t *idtok UNUSED,
struct invoice_info *info)
{
struct lightningd *ld = info->cmd->ld;
struct command_result *ret;
bool warning_mpp, warning_capacity, warning_deadends, warning_offline, warning_private_unused;
ret = add_routehints(info, buffer, toks,
&warning_mpp,
&warning_capacity,
&warning_deadends,
&warning_offline,
&warning_private_unused);
if (ret)
return;
/* We're actually outside a db transaction here: spooky! */
db_begin_transaction(ld->wallet->db);
invoice_complete(info,
false,
warning_mpp,
warning_capacity,
warning_deadends,
warning_offline,
warning_private_unused);
db_commit_transaction(ld->wallet->db);
}
#if DEVELOPER
/* Since this is a dev-only option, we will crash if dev-routes is not
* an array-of-arrays-of-correct-items. */
static struct route_info *unpack_route(const tal_t *ctx,
const char *buffer,
const jsmntok_t *routetok)
{
const jsmntok_t *t;
size_t i;
struct route_info *route = tal_arr(ctx, struct route_info, routetok->size);
json_for_each_arr(i, t, routetok) {
const jsmntok_t *pubkey, *fee_base, *fee_prop, *scid, *cltv;
struct route_info *r = &route[i];
u32 cltv_u32;
pubkey = json_get_member(buffer, t, "id");
scid = json_get_member(buffer, t, "short_channel_id");
fee_base = json_get_member(buffer, t, "fee_base_msat");
fee_prop = json_get_member(buffer, t,
"fee_proportional_millionths");
cltv = json_get_member(buffer, t, "cltv_expiry_delta");
if (!json_to_node_id(buffer, pubkey, &r->pubkey)
|| !json_to_short_channel_id(buffer, scid,
&r->short_channel_id)
|| !json_to_number(buffer, fee_base, &r->fee_base_msat)
|| !json_to_number(buffer, fee_prop,
&r->fee_proportional_millionths)
|| !json_to_number(buffer, cltv, &cltv_u32))
abort();
/* We don't have a json_to_u16 */
r->cltv_expiry_delta = cltv_u32;
}
return route;
}
static struct route_info **unpack_routes(const tal_t *ctx,
const char *buffer,
const jsmntok_t *routestok)
{
struct route_info **routes;
const jsmntok_t *t;
size_t i;
if (!routestok)
return NULL;
routes = tal_arr(ctx, struct route_info *, routestok->size);
json_for_each_arr(i, t, routestok)
routes[i] = unpack_route(routes, buffer, t);
return routes;
}
#endif /* DEVELOPER */