forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_htlcs.c
3060 lines (2671 loc) · 90.6 KB
/
peer_htlcs.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/cast/cast.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <channeld/channeld_wiregen.h>
#include <common/blinding.h>
#include <common/configdir.h>
#include <common/ecdh.h>
#include <common/json_command.h>
#include <common/json_param.h>
#include <common/onion_decode.h>
#include <common/onionreply.h>
#include <common/timeout.h>
#include <common/type_to_string.h>
#include <connectd/connectd_wiregen.h>
#include <db/exec.h>
#include <gossipd/gossipd_wiregen.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel.h>
#include <lightningd/coin_mvts.h>
#include <lightningd/pay.h>
#include <lightningd/peer_control.h>
#include <lightningd/peer_htlcs.h>
#include <lightningd/plugin_hook.h>
#include <lightningd/subd.h>
#include <onchaind/onchaind_wiregen.h>
#ifndef SUPERVERBOSE
#define SUPERVERBOSE(...)
#endif
static bool state_update_ok(struct channel *channel,
enum htlc_state oldstate, enum htlc_state newstate,
u64 htlc_id, const char *dir)
{
enum htlc_state expected = oldstate + 1;
/* We never get told about RCVD_REMOVE_HTLC, so skip over that
* (we initialize in SENT_ADD_HTLC / RCVD_ADD_COMMIT, so those
* work). */
if (expected == RCVD_REMOVE_HTLC)
expected = RCVD_REMOVE_COMMIT;
if (newstate != expected) {
channel_internal_error(channel,
"HTLC %s %"PRIu64" invalid update %s->%s",
dir, htlc_id,
htlc_state_name(oldstate),
htlc_state_name(newstate));
return false;
}
log_debug(channel->log, "HTLC %s %"PRIu64" %s->%s",
dir, htlc_id,
htlc_state_name(oldstate), htlc_state_name(newstate));
return true;
}
static bool htlc_in_update_state(struct channel *channel,
struct htlc_in *hin,
enum htlc_state newstate)
{
if (!state_update_ok(channel, hin->hstate, newstate, hin->key.id, "in"))
return false;
wallet_htlc_update(channel->peer->ld->wallet,
hin->dbid, newstate, hin->preimage,
max_unsigned(channel->next_index[LOCAL],
channel->next_index[REMOTE]),
hin->badonion, hin->failonion, NULL,
hin->we_filled);
hin->hstate = newstate;
return true;
}
static bool htlc_out_update_state(struct channel *channel,
struct htlc_out *hout,
enum htlc_state newstate)
{
if (!state_update_ok(channel, hout->hstate, newstate, hout->key.id,
"out"))
return false;
bool we_filled = false;
wallet_htlc_update(channel->peer->ld->wallet, hout->dbid, newstate,
hout->preimage,
max_unsigned(channel->next_index[LOCAL],
channel->next_index[REMOTE]),
0, hout->failonion,
hout->failmsg, &we_filled);
hout->hstate = newstate;
return true;
}
/* BOLT-route-blinding #4:
* - if `blinding_point` is set in the incoming `update_add_htlc`:
* - MUST return an `invalid_onion_blinding` error.
* - if `current_blinding_point` is set in the onion payload and it is not the
* final node:
* - MUST return an `invalid_onion_blinding` error.
*/
static bool blind_error_return(const struct htlc_in *hin)
{
if (hin->blinding)
return true;
if (hin->payload
&& hin->payload->blinding
&& !hin->payload->final)
return true;
return false;
}
static struct failed_htlc *mk_failed_htlc_badonion(const tal_t *ctx,
const struct htlc_in *hin,
enum onion_wire badonion)
{
struct failed_htlc *f = tal(ctx, struct failed_htlc);
if (blind_error_return(hin))
badonion = WIRE_INVALID_ONION_BLINDING;
f->id = hin->key.id;
f->onion = NULL;
f->badonion = badonion;
f->sha256_of_onion = tal(f, struct sha256);
sha256(f->sha256_of_onion, hin->onion_routing_packet,
sizeof(hin->onion_routing_packet));
return f;
}
static struct failed_htlc *mk_failed_htlc(const tal_t *ctx,
const struct htlc_in *hin,
const struct onionreply *failonion)
{
struct failed_htlc *f = tal(ctx, struct failed_htlc);
if (blind_error_return(hin)) {
return mk_failed_htlc_badonion(ctx, hin,
WIRE_INVALID_ONION_BLINDING);
}
/* Also, at head of the blinded path, return "normal" invalid
* onion blinding. */
if (hin->payload && hin->payload->blinding) {
struct sha256 sha;
sha256(&sha, hin->onion_routing_packet,
sizeof(hin->onion_routing_packet));
failonion = create_onionreply(tmpctx, hin->shared_secret,
towire_invalid_onion_blinding(tmpctx, &sha));
}
f->id = hin->key.id;
f->sha256_of_onion = NULL;
f->badonion = 0;
/* Wrap onion error */
f->onion = wrap_onionreply(f, hin->shared_secret, failonion);
return f;
}
static void tell_channeld_htlc_failed(const struct htlc_in *hin,
const struct failed_htlc *failed_htlc)
{
/* Tell peer, if we can. */
if (!hin->key.channel->owner)
return;
/* onchaind doesn't care, it can't do anything but wait */
if (!channel_state_can_remove_htlc(hin->key.channel->state))
return;
subd_send_msg(hin->key.channel->owner,
take(towire_channeld_fail_htlc(NULL, failed_htlc)));
}
static void fail_in_htlc(struct htlc_in *hin,
const struct onionreply *failonion TAKES)
{
struct failed_htlc *failed_htlc;
assert(!hin->preimage);
hin->failonion = dup_onionreply(hin, failonion);
/* We update state now to signal it's in progress, for persistence. */
htlc_in_update_state(hin->key.channel, hin, SENT_REMOVE_HTLC);
htlc_in_check(hin, __func__);
failed_htlc = mk_failed_htlc(tmpctx, hin, hin->failonion);
bool we_filled = false;
wallet_htlc_update(hin->key.channel->peer->ld->wallet,
hin->dbid, hin->hstate,
hin->preimage,
max_unsigned(hin->key.channel->next_index[LOCAL],
hin->key.channel->next_index[REMOTE]),
hin->badonion,
hin->failonion, NULL, &we_filled);
tell_channeld_htlc_failed(hin, failed_htlc);
}
/* Immediately fail HTLC with a BADONION code */
static void local_fail_in_htlc_badonion(struct htlc_in *hin,
enum onion_wire badonion)
{
struct failed_htlc *failed_htlc;
assert(!hin->preimage);
assert(badonion & BADONION);
hin->badonion = badonion;
/* We update state now to signal it's in progress, for persistence. */
htlc_in_update_state(hin->key.channel, hin, SENT_REMOVE_HTLC);
htlc_in_check(hin, __func__);
failed_htlc = mk_failed_htlc_badonion(tmpctx, hin, badonion);
tell_channeld_htlc_failed(hin, failed_htlc);
}
/* This is used for cases where we can immediately fail the HTLC. */
void local_fail_in_htlc(struct htlc_in *hin, const u8 *failmsg TAKES)
{
struct onionreply *failonion = create_onionreply(NULL,
hin->shared_secret,
failmsg);
if (taken(failmsg))
tal_free(failmsg);
fail_in_htlc(hin, take(failonion));
}
/* Helper to create (common) WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS */
const u8 *failmsg_incorrect_or_unknown_(const tal_t *ctx,
struct lightningd *ld,
const struct htlc_in *hin,
const char *file, int line)
{
log_debug(ld->log, "WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS: %s:%u",
file, line);
return towire_incorrect_or_unknown_payment_details(
ctx, hin->msat,
get_block_height(ld->topology));
}
/* localfail are for handing to the local payer if it's local. */
static void fail_out_htlc(struct htlc_out *hout, const char *localfail)
{
htlc_out_check(hout, __func__);
assert(hout->failmsg || hout->failonion);
if (hout->am_origin) {
payment_failed(hout->key.channel->peer->ld, hout, localfail);
} else if (hout->in) {
const struct onionreply *failonion;
/* If we have an onion, simply copy it. */
if (hout->failonion)
failonion = hout->failonion;
/* Otherwise, we need to onionize this local error. */
else
failonion = create_onionreply(hout,
hout->in->shared_secret,
hout->failmsg);
fail_in_htlc(hout->in, failonion);
} else {
log_broken(hout->key.channel->log, "Neither origin nor in?");
}
}
/* BOLT #4:
*
* - if it is not the final node:
* - MUST return an error if:
* ...
* - incoming `amount_msat` - `fee` < `amt_to_forward` (where `fee` is the advertised fee as described in [BOLT #7](07-routing-gossip.md#htlc-fees))
*/
static bool check_fwd_amount(struct htlc_in *hin,
struct amount_msat amt_to_forward,
struct amount_msat amt_in_htlc,
u32 feerate_base, u32 feerate_ppm)
{
struct amount_msat fee;
struct amount_msat fwd;
if (!amount_msat_fee(&fee, amt_to_forward,
feerate_base, feerate_ppm)) {
log_broken(hin->key.channel->log, "Fee overflow forwarding %s!",
type_to_string(tmpctx, struct amount_msat,
&amt_to_forward));
return false;
}
if (amount_msat_sub(&fwd, amt_in_htlc, fee)
&& amount_msat_greater_eq(fwd, amt_to_forward))
return true;
log_debug(hin->key.channel->log, "HTLC %"PRIu64" incorrect amount:"
" %s in, %s out, fee reqd %s",
hin->key.id,
type_to_string(tmpctx, struct amount_msat, &amt_in_htlc),
type_to_string(tmpctx, struct amount_msat, &amt_to_forward),
type_to_string(tmpctx, struct amount_msat, &fee));
return false;
}
/* BOLT #4:
*
* - if it is not the final node:
* - MUST return an error if:
* ...
* - `cltv_expiry` - `cltv_expiry_delta` < `outgoing_cltv_value`
* - If it is the final node:
*...
* - MUST return an error if:
*...
* - incoming `cltv_expiry` < `outgoing_cltv_value`.
*/
static bool check_cltv(struct htlc_in *hin,
u32 cltv_expiry, u32 outgoing_cltv_value, u32 delta)
{
if (delta < cltv_expiry && cltv_expiry - delta >= outgoing_cltv_value)
return true;
log_debug(hin->key.channel->log, "HTLC %"PRIu64" incorrect CLTV:"
" %u in, %u out, delta reqd %u",
hin->key.id, cltv_expiry, outgoing_cltv_value, delta);
return false;
}
void fulfill_htlc(struct htlc_in *hin, const struct preimage *preimage)
{
u8 *msg;
struct channel *channel = hin->key.channel;
struct wallet *wallet = channel->peer->ld->wallet;
if (hin->hstate != RCVD_ADD_ACK_REVOCATION) {
log_debug(channel->log,
"HTLC fulfilled, but not ready any more (%s).",
htlc_state_name(hin->hstate));
return;
}
hin->preimage = tal_dup(hin, struct preimage, preimage);
/* We update state now to signal it's in progress, for persistence. */
htlc_in_update_state(channel, hin, SENT_REMOVE_HTLC);
htlc_in_check(hin, __func__);
/* Update channel stats */
wallet_channel_stats_incr_in_fulfilled(wallet,
channel->dbid,
hin->msat);
/* No owner? We'll either send to channeld in peer_htlcs, or
* onchaind in onchaind_tell_fulfill. */
if (!channel->owner) {
log_debug(channel->log, "HTLC fulfilled, but no owner.");
return;
}
if (streq(channel->owner->name, "onchaind")) {
msg = towire_onchaind_known_preimage(hin, preimage);
} else {
struct fulfilled_htlc fulfilled_htlc;
fulfilled_htlc.id = hin->key.id;
fulfilled_htlc.payment_preimage = *preimage;
msg = towire_channeld_fulfill_htlc(hin, &fulfilled_htlc);
}
subd_send_msg(channel->owner, take(msg));
}
static void handle_localpay(struct htlc_in *hin,
struct amount_msat amt_to_forward,
u32 outgoing_cltv_value,
struct amount_msat total_msat,
const struct secret *payment_secret,
const u8 *payment_metadata)
{
const u8 *failmsg;
struct lightningd *ld = hin->key.channel->peer->ld;
/* BOLT #4:
* - If it is the final node:
* - MUST treat `total_msat` as if it were equal to `amt_to_forward` if it
* is not present.
* - MUST return an error if:
* - incoming `amount_msat` < `amt_to_forward`.
*/
if (amount_msat_less(hin->msat, amt_to_forward)) {
log_debug(hin->key.channel->log,
"HTLC %"PRIu64" final incorrect amount:"
" %s in, %s expected",
hin->key.id,
type_to_string(tmpctx, struct amount_msat, &hin->msat),
type_to_string(tmpctx, struct amount_msat,
&amt_to_forward));
/* BOLT #4:
* 1. type: 19 (`final_incorrect_htlc_amount`)
* 2. data:
* * [`u64`:`incoming_htlc_amt`]
*
* The amount in the HTLC is less than the value in the onion.
*/
failmsg = towire_final_incorrect_htlc_amount(NULL, hin->msat);
goto fail;
}
/* BOLT #4:
* - If it is the final node:
* - MUST treat `total_msat` as if it were equal to `amt_to_forward` if it
* is not present.
* - MUST return an error if:
*...
* - incoming `cltv_expiry` < `outgoing_cltv_value`.
*/
if (!check_cltv(hin, hin->cltv_expiry, outgoing_cltv_value, 0)) {
/* BOLT #4:
*
* 1. type: 18 (`final_incorrect_cltv_expiry`)
* 2. data:
* * [`u32`:`cltv_expiry`]
*
* The CLTV expiry in the HTLC is less than the value in the onion.
*/
failmsg = towire_final_incorrect_cltv_expiry(NULL,
hin->cltv_expiry);
goto fail;
}
/* BOLT #4:
*
* incoming `cltv_expiry` < `current_block_height` + `min_final_cltv_expiry_delta`. */
if (get_block_height(ld->topology) + ld->config.cltv_final
> hin->cltv_expiry) {
log_debug(hin->key.channel->log,
"Expiry cltv too soon %u < %u + %u",
hin->cltv_expiry,
get_block_height(ld->topology),
ld->config.cltv_final);
failmsg = failmsg_incorrect_or_unknown(NULL, ld, hin);
goto fail;
}
/* We don't expect payment_metadata; reject here */
if (payment_metadata) {
log_debug(hin->key.channel->log,
"Unexpected payment_metadata %s",
tal_hex(tmpctx, payment_metadata));
/* BOLT #4:
* 1. type: PERM|22 (`invalid_onion_payload`)
* 2. data:
* * [`bigsize`:`type`]
* * [`u16`:`offset`]
*
* The decrypted onion per-hop payload was not understood by the processing node
* or is incomplete. If the failure can be narrowed down to a specific tlv type in
* the payload, the erring node may include that `type` and its byte `offset` in
* the decrypted byte stream.
*/
failmsg = towire_invalid_onion_payload(NULL, TLV_PAYLOAD_PAYMENT_METADATA,
/* FIXME: offset? */ 0);
goto fail;
}
htlc_set_add(ld, hin, total_msat, payment_secret);
return;
fail:
local_fail_in_htlc(hin, take(failmsg));
}
/*
* A catchall in case outgoing peer disconnects before getting fwd.
*
* We could queue this and wait for it to come back, but this is simple.
*/
static void destroy_hout_subd_died(struct htlc_out *hout)
{
struct db *db = hout->key.channel->peer->ld->wallet->db;
/* Under some circumstances we may need to start a DB
* transaction and commit it here again. This is the case when
* we're getting called from the destructor chain. */
bool have_tx =
db_in_transaction(db);
log_debug(hout->key.channel->log,
"Failing HTLC %"PRIu64" due to peer death",
hout->key.id);
hout->failmsg = towire_temporary_channel_failure(hout,
channel_update_for_error(tmpctx,
hout->key.channel));
/* Assign a temporary state (we're about to free it!) so checks
* are happy that it has a failure message */
assert(hout->hstate == SENT_ADD_HTLC);
hout->hstate = RCVD_REMOVE_HTLC;
if (!have_tx)
db_begin_transaction(db);
fail_out_htlc(hout, "Outgoing subdaemon died");
if (!have_tx)
db_commit_transaction(db);
}
/* This is where channeld gives us the HTLC id, and also reports if it
* failed immediately. */
static void rcvd_htlc_reply(struct subd *subd, const u8 *msg, const int *fds UNUSED,
struct htlc_out *hout)
{
u8 *failmsg;
char *failurestr;
struct lightningd *ld = subd->ld;
if (!fromwire_channeld_offer_htlc_reply(msg, msg,
&hout->key.id,
&failmsg,
&failurestr)) {
channel_internal_error(subd->channel,
"Bad channel_offer_htlc_reply");
tal_free(hout);
return;
}
if (tal_count(failmsg)) {
/* It's our job to append the channel_update */
if (fromwire_peektype(failmsg) & UPDATE) {
const u8 *update = channel_update_for_error(tmpctx, hout->key.channel);
towire(&failmsg, update, tal_bytelen(update));
}
hout->failmsg = tal_steal(hout, failmsg);
if (hout->am_origin) {
char *localfail = tal_fmt(msg, "%s: %s",
onion_wire_name(fromwire_peektype(failmsg)),
failurestr);
payment_failed(ld, hout, localfail);
} else if (hout->in) {
struct onionreply *failonion;
failonion = create_onionreply(hout,
hout->in->shared_secret,
hout->failmsg);
fail_in_htlc(hout->in, failonion);
/* here we haven't called connect_htlc_out(),
* so set htlc field with NULL (db wants it to exist!) */
wallet_forwarded_payment_add(ld->wallet,
hout->in,
FORWARD_STYLE_TLV,
channel_scid_or_local_alias(hout->key.channel), NULL,
FORWARD_LOCAL_FAILED,
fromwire_peektype(hout->failmsg));
}
/* Prevent hout from being failed twice. */
tal_del_destructor(hout, destroy_hout_subd_died);
tal_free(hout);
return;
}
if (find_htlc_out(subd->ld->htlcs_out, hout->key.channel, hout->key.id)
|| hout->key.id == HTLC_INVALID_ID) {
channel_internal_error(subd->channel,
"Bad offer_htlc_reply HTLC id %"PRIu64
" is a duplicate",
hout->key.id);
tal_free(hout);
return;
}
/* Add it to lookup table now we know id. */
connect_htlc_out(subd->ld->htlcs_out, hout);
/* When channeld includes it in commitment, we'll make it persistent. */
}
static void htlc_offer_timeout(struct htlc_out *out)
{
struct channel *channel = out->key.channel;
out->timeout = NULL;
/* Otherwise, timer would be removed. */
assert(out->hstate == SENT_ADD_HTLC);
/* If owner died, we should already be taken care of. */
if (!channel->owner || !channel_state_can_add_htlc(channel->state))
return;
log_unusual(channel->owner->log,
"Adding HTLC %"PRIu64" too slow: killing connection",
out->key.id);
channel_fail_transient(channel, true,
"Adding HTLC timed out: killed connection");
}
/* Returns failmsg, or NULL on success. */
const u8 *send_htlc_out(const tal_t *ctx,
struct channel *out,
struct amount_msat amount, u32 cltv,
struct amount_msat final_msat,
const struct sha256 *payment_hash,
const struct pubkey *blinding,
u64 partid,
u64 groupid,
const u8 *onion_routing_packet,
struct htlc_in *in,
struct htlc_out **houtp)
{
u8 *msg;
*houtp = NULL;
if (!channel_state_can_add_htlc(out->state)) {
log_info(out->log, "Attempt to send HTLC but not ready (%s)",
channel_state_name(out));
return towire_unknown_next_peer(ctx);
}
if (!out->owner) {
log_info(out->log, "Attempt to send HTLC but unowned (%s)",
channel_state_name(out));
return towire_temporary_channel_failure(ctx,
channel_update_for_error(tmpctx, out));
}
if (!topology_synced(out->peer->ld->topology)) {
log_info(out->log, "Attempt to send HTLC but still syncing"
" with bitcoin network");
return towire_temporary_node_failure(ctx);
}
/* Make peer's daemon own it, catch if it dies. */
*houtp = new_htlc_out(out->owner, out, amount, cltv,
payment_hash, onion_routing_packet,
blinding, in == NULL,
final_msat,
partid, groupid, in);
tal_add_destructor(*houtp, destroy_hout_subd_died);
/* Give channel 30 seconds to commit this htlc. */
if (!out->peer->ld->dev_no_htlc_timeout) {
(*houtp)->timeout = new_reltimer(out->peer->ld->timers,
*houtp, time_from_sec(30),
htlc_offer_timeout,
*houtp);
}
msg = towire_channeld_offer_htlc(out, amount, cltv, payment_hash,
onion_routing_packet, blinding);
subd_req(out->peer->ld, out->owner, take(msg), -1, 0, rcvd_htlc_reply,
*houtp);
return NULL;
}
/* What's the best channel to this peer?
* If @hint is set, channel must match that one. */
static struct channel *best_channel(struct lightningd *ld,
const struct peer *next_peer,
struct amount_msat amt_to_forward,
struct channel *hint)
{
struct amount_msat best_spendable = AMOUNT_MSAT(0);
struct channel *channel, *best = hint;
/* Seek channel with largest spendable! */
list_for_each(&next_peer->channels, channel, list) {
struct amount_msat spendable;
if (!channel_state_can_add_htlc(channel->state))
continue;
spendable = channel_amount_spendable(channel);
if (!amount_msat_greater(spendable, best_spendable))
continue;
/* Don't override if fees differ... */
if (hint) {
if (hint->feerate_base != channel->feerate_base
|| hint->feerate_ppm != channel->feerate_ppm)
continue;
}
/* Or if this would be below min for channel! */
if (amount_msat_less(amt_to_forward,
channel->channel_info.their_config.htlc_minimum))
continue;
best = channel;
best_spendable = spendable;
}
return best;
}
/* forward_to is where we're actually sending it (or NULL), and
* forward_scid is where they asked to send it (or NULL). */
static void forward_htlc(struct htlc_in *hin,
u32 cltv_expiry,
struct amount_msat amt_to_forward,
u32 outgoing_cltv_value,
const struct short_channel_id *forward_scid,
const struct channel_id *forward_to,
const u8 next_onion[TOTAL_PACKET_SIZE(ROUTING_INFO_SIZE)],
const struct pubkey *next_blinding)
{
const u8 *failmsg;
struct lightningd *ld = hin->key.channel->peer->ld;
struct channel *next;
struct htlc_out *hout = NULL;
if (forward_to) {
next = channel_by_cid(ld, forward_to);
/* Update this to where we're actually trying to send. */
if (next)
forward_scid = channel_scid_or_local_alias(next);
} else
next = NULL;
/* Unknown peer, or peer not ready. */
if (!next || !channel_state_can_add_htlc(next->state)) {
local_fail_in_htlc(hin, take(towire_unknown_next_peer(NULL)));
wallet_forwarded_payment_add(hin->key.channel->peer->ld->wallet,
hin, FORWARD_STYLE_TLV,
forward_scid, NULL,
FORWARD_LOCAL_FAILED,
WIRE_UNKNOWN_NEXT_PEER);
return;
}
/* BOLT #7:
*
* The origin node:
* - SHOULD accept HTLCs that pay a fee equal to or greater than:
* - fee_base_msat + ( amount_to_forward * fee_proportional_millionths / 1000000 )
*/
if (!check_fwd_amount(hin, amt_to_forward, hin->msat,
next->feerate_base,
next->feerate_ppm)) {
/* BOLT #7:
* - If it creates a new `channel_update` with updated channel parameters:
* - SHOULD keep accepting the previous channel parameters for 10 minutes
*/
if (!time_before(time_now(), next->old_feerate_timeout)
|| !check_fwd_amount(hin, amt_to_forward, hin->msat,
next->old_feerate_base,
next->old_feerate_ppm)) {
failmsg = towire_fee_insufficient(tmpctx, hin->msat,
channel_update_for_error(tmpctx,
next));
goto fail;
}
log_info(hin->key.channel->log,
"Allowing payment using older feerate");
}
if (amount_msat_greater(amt_to_forward, next->htlc_maximum_msat)
|| amount_msat_less(amt_to_forward, next->htlc_minimum_msat)) {
/* Are we in old-range grace-period? */
if (!time_before(time_now(), next->old_feerate_timeout)
|| amount_msat_less(amt_to_forward, next->old_htlc_minimum_msat)
|| amount_msat_greater(amt_to_forward, next->old_htlc_maximum_msat)) {
failmsg = towire_temporary_channel_failure(tmpctx,
channel_update_for_error(tmpctx, next));
goto fail;
}
log_info(hin->key.channel->log,
"Allowing htlc using older htlc_minimum/maximum_msat");
}
if (!check_cltv(hin, cltv_expiry, outgoing_cltv_value,
ld->config.cltv_expiry_delta)) {
failmsg = towire_incorrect_cltv_expiry(tmpctx, cltv_expiry,
channel_update_for_error(tmpctx, next));
goto fail;
}
/* BOLT #2:
*
* An offering node:
* - MUST estimate a timeout deadline for each HTLC it offers.
* - MUST NOT offer an HTLC with a timeout deadline before its
* `cltv_expiry`.
*/
/* In our case, G = 1, so we need to expire it one after it's expiration.
* But never offer an expired HTLC; that's dumb. */
if (get_block_height(ld->topology) >= outgoing_cltv_value) {
log_debug(hin->key.channel->log,
"Expiry cltv %u too close to current %u",
outgoing_cltv_value,
get_block_height(ld->topology));
failmsg = towire_expiry_too_soon(tmpctx,
channel_update_for_error(tmpctx, next));
goto fail;
}
/* BOLT #4:
*
* - if the `cltv_expiry` is unreasonably far in the future:
* - return an `expiry_too_far` error.
*/
if (get_block_height(ld->topology)
+ ld->config.locktime_max < outgoing_cltv_value) {
log_debug(hin->key.channel->log,
"Expiry cltv %u too far from current %u + max %u",
outgoing_cltv_value,
get_block_height(ld->topology),
ld->config.locktime_max);
failmsg = towire_expiry_too_far(tmpctx);
goto fail;
}
failmsg = send_htlc_out(tmpctx, next, amt_to_forward,
outgoing_cltv_value, AMOUNT_MSAT(0),
&hin->payment_hash,
next_blinding, 0 /* partid */, 0 /* groupid */,
next_onion, hin, &hout);
if (!failmsg)
return;
fail:
local_fail_in_htlc(hin, failmsg);
wallet_forwarded_payment_add(ld->wallet,
hin, FORWARD_STYLE_TLV, forward_scid, hout,
FORWARD_LOCAL_FAILED,
fromwire_peektype(failmsg));
}
/**
* Data passed to the plugin, and as the context for the hook callback
*/
struct htlc_accepted_hook_payload {
struct route_step *route_step;
/* NULL if it couldn't be parsed! */
struct onion_payload *payload;
struct htlc_in *hin;
struct channel *channel;
struct lightningd *ld;
struct pubkey *next_blinding;
/* NULL if we couldn't find it */
struct channel_id *fwd_channel_id;
u8 *next_onion;
u64 failtlvtype;
size_t failtlvpos;
};
/* We only handle the simplest cases here */
static u8 *convert_failcode(const tal_t *ctx,
struct lightningd *ld,
unsigned int failure_code)
{
switch (failure_code) {
case WIRE_INVALID_REALM:
return towire_invalid_realm(ctx);
case WIRE_TEMPORARY_NODE_FAILURE:
return towire_temporary_node_failure(ctx);
case WIRE_PERMANENT_NODE_FAILURE:
return towire_permanent_node_failure(ctx);
case WIRE_REQUIRED_NODE_FEATURE_MISSING:
return towire_required_node_feature_missing(ctx);
case WIRE_PERMANENT_CHANNEL_FAILURE:
return towire_permanent_channel_failure(ctx);
case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING:
return towire_required_channel_feature_missing(ctx);
case WIRE_UNKNOWN_NEXT_PEER:
return towire_unknown_next_peer(ctx);
default:
log_broken(ld->log,
"htlc_accepted_hook plugin returned failure_code %u,"
" turning to WIRE_TEMPORARY_NODE_FAILURE",
failure_code);
return towire_temporary_node_failure(ctx);
}
}
static void
htlc_accepted_hook_try_resolve(struct htlc_accepted_hook_payload *request,
struct preimage *payment_preimage)
{
struct sha256 payment_hash;
struct htlc_in *hin = request->hin;
u8 *unknown_details;
/* Verify that the provided secret hashes to what we need. */
sha256(&payment_hash, payment_preimage, sizeof(struct preimage));
if (!sha256_eq(&payment_hash, &hin->payment_hash)) {
log_broken(
request->channel->log,
"Plugin returned a preimage (sha256(%s) = %s) that doesn't "
"match the HTLC hash (%s) it tries to resolve.",
type_to_string(tmpctx, struct preimage, payment_preimage),
type_to_string(tmpctx, struct sha256, &payment_hash),
type_to_string(tmpctx, struct sha256, &hin->payment_hash));
unknown_details = tal_arr(NULL, u8, 0);
towire_u16(&unknown_details, 0x400f);
local_fail_in_htlc(hin, take(unknown_details));
} else {
hin->we_filled = tal(hin, bool);
*hin->we_filled = true;
fulfill_htlc(hin, payment_preimage);
}
}
static u8 *prepend_length(const tal_t *ctx, const u8 *payload TAKES)
{
u8 buf[BIGSIZE_MAX_LEN], *ret;
size_t len;
len = bigsize_put(buf, tal_bytelen(payload));
ret = tal_arr(ctx, u8, len + tal_bytelen(payload));
memcpy(ret, buf, len);
memcpy(ret + len, payload, tal_bytelen(payload));
if (taken(payload))
tal_free(payload);
return ret;
}
/**
* Callback when a plugin answers to the htlc_accepted hook
*/
static bool htlc_accepted_hook_deserialize(struct htlc_accepted_hook_payload *request,
const char *buffer,
const jsmntok_t *toks)
{
struct route_step *rs = request->route_step;
struct htlc_in *hin = request->hin;
struct lightningd *ld = request->ld;
struct preimage payment_preimage;
const jsmntok_t *resulttok, *paykeytok, *payloadtok, *fwdtok;
u8 *failonion;
if (!toks || !buffer)
return true;
resulttok = json_get_member(buffer, toks, "result");
/* If the result is "continue" we can just return NULL since
* this is the default behavior for this hook anyway */
if (!resulttok) {
fatal("Plugin return value does not contain 'result' key %s",
json_strdup(tmpctx, buffer, toks));
}
payloadtok = json_get_member(buffer, toks, "payload");
if (payloadtok) {
u8 *payload = json_tok_bin_from_hex(rs, buffer, payloadtok);
if (!payload)
fatal("Bad payload for htlc_accepted"
" hook: %.*s",
payloadtok->end - payloadtok->start,
buffer + payloadtok->start);
tal_free(request->payload);
tal_free(rs->raw_payload);
rs->raw_payload = prepend_length(rs, take(payload));
request->payload = onion_decode(request,
feature_offered(ld->our_features->bits[INIT_FEATURE],
OPT_ROUTE_BLINDING),
rs,
hin->blinding,
ld->accept_extra_tlv_types,
hin->msat,
hin->cltv_expiry,
&request->failtlvtype,
&request->failtlvpos);
}
fwdtok = json_get_member(buffer, toks, "forward_to");
if (fwdtok) {
tal_free(request->fwd_channel_id);
request->fwd_channel_id = tal(request, struct channel_id);
if (!json_to_channel_id(buffer, fwdtok,
request->fwd_channel_id)) {
fatal("Bad forward_to for htlc_accepted"
" hook: %.*s",
fwdtok->end - fwdtok->start,
buffer + fwdtok->start);
}
}
if (json_tok_streq(buffer, resulttok, "continue")) {
return true;
}
if (json_tok_streq(buffer, resulttok, "fail")) {
u8 *failmsg;
const jsmntok_t *failoniontok, *failmsgtok, *failcodetok;
failoniontok = json_get_member(buffer, toks, "failure_onion");
failmsgtok = json_get_member(buffer, toks, "failure_message");
if (failoniontok) {
failonion = json_tok_bin_from_hex(tmpctx, buffer,
failoniontok);
if (!failonion)