forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_htlcs.c
2249 lines (1943 loc) · 65.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 <bitcoin/preimage.h>
#include <bitcoin/tx.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/cast/cast.h>
#include <ccan/crypto/ripemd160/ripemd160.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <channeld/gen_channel_wire.h>
#include <common/json_command.h>
#include <common/jsonrpc_errors.h>
#include <common/overflows.h>
#include <common/param.h>
#include <common/sphinx.h>
#include <common/timeout.h>
#include <gossipd/gen_gossip_wire.h>
#include <lightningd/chaintopology.h>
#include <lightningd/htlc_end.h>
#include <lightningd/json.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/lightningd.h>
#include <lightningd/log.h>
#include <lightningd/options.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/gen_onchain_wire.h>
#include <onchaind/onchain_wire.h>
#include <wallet/wallet.h>
#include <wire/gen_onion_wire.h>
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,
hin->failcode, hin->failuremsg);
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;
wallet_htlc_update(channel->peer->ld->wallet, hout->dbid, newstate,
hout->preimage, hout->failcode, hout->failuremsg);
hout->hstate = newstate;
return true;
}
static void fail_in_htlc(struct htlc_in *hin,
enum onion_type failcode,
const u8 *failuremsg,
const struct short_channel_id *out_channelid)
{
struct failed_htlc failed_htlc;
assert(!hin->preimage);
assert(failcode || failuremsg);
hin->failcode = failcode;
if (failuremsg)
hin->failuremsg = tal_dup_arr(hin, u8, failuremsg, tal_count(failuremsg), 0);
/* We need this set, since we send it to channeld. */
if (hin->failcode & UPDATE)
hin->failoutchannel = *out_channelid;
/* 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__);
/* Tell peer, if we can. */
if (!hin->key.channel->owner)
return;
/* onchaind doesn't care, it can't do anything but wait */
if (channel_on_chain(hin->key.channel))
return;
failed_htlc.id = hin->key.id;
failed_htlc.failcode = hin->failcode;
failed_htlc.failreason = cast_const(u8 *, hin->failuremsg);
if (failed_htlc.failcode & UPDATE)
failed_htlc.scid = &hin->failoutchannel;
else
failed_htlc.scid = NULL;
subd_send_msg(hin->key.channel->owner,
take(towire_channel_fail_htlc(NULL, &failed_htlc,
get_block_height(hin->key.channel->owner->ld->topology))));
}
/* This is used for cases where we can immediately fail the HTLC. */
static void local_fail_htlc(struct htlc_in *hin, enum onion_type failcode,
const struct short_channel_id *out_channel)
{
log_info(hin->key.channel->log, "failed htlc %"PRIu64" code 0x%04x (%s)",
hin->key.id, failcode, onion_type_name(failcode));
fail_in_htlc(hin, failcode, NULL, out_channel);
}
void fail_htlc(struct htlc_in *hin, enum onion_type failcode)
{
assert(failcode);
/* Final hop never sends an UPDATE. */
assert(!(failcode & UPDATE));
local_fail_htlc(hin, failcode, NULL);
}
/* 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->failcode || hout->failuremsg);
if (hout->am_origin) {
payment_failed(hout->key.channel->peer->ld, hout, localfail);
} else if (hout->in) {
fail_in_htlc(hout->in, hout->failcode, hout->failuremsg,
hout->key.channel->scid);
}
}
/* BOLT #4:
*
* * `amt_to_forward`: The amount, in millisatoshis, to forward to the next
* receiving peer specified within the routing information.
*
* This value amount MUST include the origin node's computed _fee_ for the
* receiving peer. When processing an incoming Sphinx packet and the HTLC
* message that it is encapsulated within, if the following inequality
* doesn't hold, then the HTLC should be rejected as it would indicate that
* a prior hop has deviated from the specified parameters:
*
* incoming_htlc_amt - fee >= amt_to_forward
*
* Where `fee` is either calculated according to the receiving peer's
* advertised fee schema (as described in [BOLT
* #7](07-routing-gossip.md#htlc-fees)) or is 0, if the processing node is
* the final node.
*/
static bool check_amount(struct htlc_in *hin,
struct amount_msat amt_to_forward,
struct amount_msat amt_in_htlc,
struct amount_msat fee)
{
struct amount_msat fwd;
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:
*
* * `outgoing_cltv_value`: The CLTV value that the _outgoing_ HTLC carrying
* the packet should have.
*
* cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
*
* Inclusion of this field allows a hop to both authenticate the
* information specified by the origin node, and the parameters of the
* HTLC forwarded, and ensure the origin node is using the current
* `cltv_expiry_delta` value. If there is no next hop,
* `cltv_expiry_delta` is 0. If the values don't correspond, then the
* HTLC should be failed and rejected, as this indicates that either a
* forwarding node has tampered with the intended HTLC values or that the
* origin node has an obsolete `cltv_expiry_delta` value. The hop MUST be
* consistent in responding to an unexpected `outgoing_cltv_value`,
* whether it is the final node or not, to avoid leaking its position in
* the route.
*/
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 (channel_on_chain(channel)) {
msg = towire_onchain_known_preimage(hin, preimage);
} else {
struct fulfilled_htlc fulfilled_htlc;
fulfilled_htlc.id = hin->key.id;
fulfilled_htlc.payment_preimage = *preimage;
msg = towire_channel_fulfill_htlc(hin, &fulfilled_htlc);
}
subd_send_msg(channel->owner, take(msg));
}
static void handle_localpay(struct htlc_in *hin,
u32 cltv_expiry,
const struct sha256 *payment_hash,
struct amount_msat amt_to_forward,
u32 outgoing_cltv_value)
{
enum onion_type failcode;
struct lightningd *ld = hin->key.channel->peer->ld;
/* BOLT #4:
*
* 1. type: 19 (`final_incorrect_htlc_amount`)
* 2. data:
* * [`u64`:`incoming_htlc_amt`]
*
* The amount in the HTLC doesn't match the value in the onion.
*/
if (!check_amount(hin, amt_to_forward, hin->msat, AMOUNT_MSAT(0))) {
failcode = WIRE_FINAL_INCORRECT_HTLC_AMOUNT;
goto fail;
}
/* BOLT #4:
*
* 1. type: 18 (`final_incorrect_cltv_expiry`)
* 2. data:
* * [`u32`:`cltv_expiry`]
*
* The CLTV expiry in the HTLC doesn't match the value in the onion.
*/
if (!check_cltv(hin, cltv_expiry, outgoing_cltv_value, 0)) {
failcode = WIRE_FINAL_INCORRECT_CLTV_EXPIRY;
goto fail;
}
/* BOLT #4:
*
* - if the `cltv_expiry` value is unreasonably near the present:
* - MUST fail the HTLC.
* - MUST return an `incorrect_or_unknown_payment_details` error.
*/
if (get_block_height(ld->topology) + ld->config.cltv_final
> cltv_expiry) {
log_debug(hin->key.channel->log,
"Expiry cltv too soon %u < %u + %u",
cltv_expiry,
get_block_height(ld->topology),
ld->config.cltv_final);
failcode = WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS;
goto fail;
}
invoice_try_pay(ld, hin, payment_hash, amt_to_forward);
return;
fail:
fail_htlc(hin, failcode);
}
/*
* 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)
{
log_debug(hout->key.channel->log,
"Failing HTLC %"PRIu64" due to peer death",
hout->key.id);
hout->failcode = WIRE_TEMPORARY_CHANNEL_FAILURE;
/* Assign a temporary state (we're about to free it!) so checks
* are happy that it has a failure code */
assert(hout->hstate == SENT_ADD_HTLC);
hout->hstate = RCVD_REMOVE_HTLC;
fail_out_htlc(hout, "Outgoing subdaemon died");
}
/* 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)
{
u16 failure_code;
u8 *failurestr;
struct lightningd *ld = subd->ld;
if (!fromwire_channel_offer_htlc_reply(msg, msg,
&hout->key.id,
&failure_code,
&failurestr)) {
channel_internal_error(subd->channel,
"Bad channel_offer_htlc_reply");
tal_free(hout);
return;
}
if (failure_code) {
hout->failcode = (enum onion_type) failure_code;
if (hout->am_origin) {
char *localfail = tal_fmt(msg, "%s: %.*s",
onion_type_name(failure_code),
(int)tal_count(failurestr),
(const char *)failurestr);
payment_failed(ld, hout, localfail);
} else if (hout->in) {
local_fail_htlc(hout->in, failure_code,
hout->key.channel->scid);
/* here we haven't called connect_htlc_out(),
* so set htlc field with NULL */
wallet_forwarded_payment_add(ld->wallet,
hout->in, NULL,
FORWARD_LOCAL_FAILED,
failure_code);
}
/* 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 channel *channel)
{
/* Unset this in case we reconnect and start again. */
channel->htlc_timeout = NULL;
/* If owner died, we should already be taken care of. */
if (!channel->owner || channel->state != CHANNELD_NORMAL)
return;
log_unusual(channel->owner->log,
"Adding HTLC too slow: killing connection");
tal_free(channel->owner);
channel_set_billboard(channel, false,
"Adding HTLC timed out: killed connection");
}
enum onion_type send_htlc_out(struct channel *out,
struct amount_msat amount, u32 cltv,
const struct sha256 *payment_hash,
const u8 *onion_routing_packet,
struct htlc_in *in,
struct htlc_out **houtp)
{
struct htlc_out *hout;
u8 *msg;
if (!channel_can_add_htlc(out)) {
log_info(out->log, "Attempt to send HTLC but not ready (%s)",
channel_state_name(out));
return WIRE_UNKNOWN_NEXT_PEER;
}
if (!out->owner) {
log_info(out->log, "Attempt to send HTLC but unowned (%s)",
channel_state_name(out));
return WIRE_TEMPORARY_CHANNEL_FAILURE;
}
if (!topology_synced(out->peer->ld->topology)) {
log_info(out->log, "Attempt to send HTLC but still syncing"
" with bitcoin network");
return WIRE_TEMPORARY_CHANNEL_FAILURE;
}
/* Make peer's daemon own it, catch if it dies. */
hout = new_htlc_out(out->owner, out, amount, cltv,
payment_hash, onion_routing_packet, in == NULL, in);
tal_add_destructor(hout, destroy_hout_subd_died);
/* Give channel 30 seconds to commit (first) htlc. */
if (!out->htlc_timeout)
out->htlc_timeout = new_reltimer(out->peer->ld->timers,
out, time_from_sec(30),
htlc_offer_timeout,
out);
msg = towire_channel_offer_htlc(out, amount, cltv, payment_hash,
onion_routing_packet);
subd_req(out->peer->ld, out->owner, take(msg), -1, 0, rcvd_htlc_reply, hout);
if (houtp)
*houtp = hout;
return 0;
}
static void forward_htlc(struct htlc_in *hin,
u32 cltv_expiry,
struct amount_msat amt_to_forward,
u32 outgoing_cltv_value,
const struct node_id *next_hop,
const u8 next_onion[TOTAL_PACKET_SIZE])
{
enum onion_type failcode;
struct amount_msat fee;
struct lightningd *ld = hin->key.channel->peer->ld;
struct channel *next = active_channel_by_id(ld, next_hop, NULL);
struct htlc_out *hout = NULL;
/* Unknown peer, or peer not ready. */
if (!next || !next->scid) {
local_fail_htlc(hin, WIRE_UNKNOWN_NEXT_PEER, NULL);
wallet_forwarded_payment_add(hin->key.channel->peer->ld->wallet,
hin, NULL,
FORWARD_LOCAL_FAILED,
hin->failcode);
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 (!amount_msat_fee(&fee, amt_to_forward,
next->feerate_base,
next->feerate_ppm)) {
log_broken(ld->log, "Fee overflow forwarding %s!",
type_to_string(tmpctx, struct amount_msat,
&amt_to_forward));
failcode = WIRE_FEE_INSUFFICIENT;
goto fail;
}
if (!check_amount(hin, amt_to_forward, hin->msat, fee)) {
failcode = WIRE_FEE_INSUFFICIENT;
goto fail;
}
if (!check_cltv(hin, cltv_expiry, outgoing_cltv_value,
ld->config.cltv_expiry_delta)) {
failcode = WIRE_INCORRECT_CLTV_EXPIRY;
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));
failcode = WIRE_EXPIRY_TOO_SOON;
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);
failcode = WIRE_EXPIRY_TOO_FAR;
goto fail;
}
hout = tal(tmpctx, struct htlc_out);
failcode = send_htlc_out(next, amt_to_forward,
outgoing_cltv_value, &hin->payment_hash,
next_onion, hin, &hout);
if (!failcode)
return;
/* In fact, we didn't get the new htlc_out in these 2 cases */
if (failcode == WIRE_UNKNOWN_NEXT_PEER ||
failcode == WIRE_TEMPORARY_CHANNEL_FAILURE) {
tal_free(hout);
hout = NULL;
}
fail:
local_fail_htlc(hin, failcode, next->scid);
wallet_forwarded_payment_add(ld->wallet,
hin, hout,
FORWARD_LOCAL_FAILED,
hin->failcode);
}
/* Temporary information, while we resolve the next hop */
struct gossip_resolve {
struct short_channel_id next_channel;
struct amount_msat amt_to_forward;
u32 outgoing_cltv_value;
u8 *next_onion;
struct htlc_in *hin;
};
/* We received a resolver reply, which gives us the node_ids of the
* channel we want to forward over */
static void channel_resolve_reply(struct subd *gossip, const u8 *msg,
const int *fds UNUSED, struct gossip_resolve *gr)
{
struct node_id *peer_id;
if (!fromwire_gossip_get_channel_peer_reply(msg, msg, &peer_id)) {
log_broken(gossip->log,
"bad fromwire_gossip_get_channel_peer_reply %s",
tal_hex(msg, msg));
return;
}
if (!peer_id) {
local_fail_htlc(gr->hin, WIRE_UNKNOWN_NEXT_PEER, NULL);
wallet_forwarded_payment_add(gr->hin->key.channel->peer->ld->wallet,
gr->hin, NULL,
FORWARD_LOCAL_FAILED,
gr->hin->failcode);
tal_free(gr);
return;
}
forward_htlc(gr->hin, gr->hin->cltv_expiry,
gr->amt_to_forward, gr->outgoing_cltv_value, peer_id,
gr->next_onion);
tal_free(gr);
}
/**
* Data passed to the plugin, and as the context for the hook callback
*/
struct htlc_accepted_hook_payload {
struct route_step *route_step;
struct htlc_in *hin;
struct channel *channel;
struct lightningd *ld;
u8 *next_onion;
};
/* The possible return value types that a plugin may return for the
* `htlc_accepted` hook. */
enum htlc_accepted_result {
htlc_accepted_continue,
htlc_accepted_fail,
htlc_accepted_resolve,
};
/**
* Parses the JSON-RPC response into a struct understood by the callback.
*/
static enum htlc_accepted_result htlc_accepted_hook_deserialize(const char *buffer, const jsmntok_t *toks,
/* If accepted */
struct preimage *payment_preimage,
/* If rejected */
enum onion_type *failure_code,
u8 **channel_update)
{
const jsmntok_t *resulttok, *failcodetok, *paykeytok, *chanupdtok;
enum htlc_accepted_result result;
if (!toks || !buffer)
return htlc_accepted_continue;
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));
}
if (json_tok_streq(buffer, resulttok, "continue")) {
return htlc_accepted_continue;
}
if (json_tok_streq(buffer, resulttok, "fail")) {
result = htlc_accepted_fail;
failcodetok = json_get_member(buffer, toks, "failure_code");
chanupdtok = json_get_member(buffer, toks, "channel_update");
if (failcodetok &&
!json_to_number(buffer, failcodetok, failure_code))
fatal("Plugin provided a non-numeric failcode "
"in response to an htlc_accepted hook");
if (!failcodetok)
*failure_code = WIRE_TEMPORARY_NODE_FAILURE;
if (chanupdtok)
*channel_update =
json_tok_bin_from_hex(buffer, buffer, chanupdtok);
else
*channel_update = NULL;
} else if (json_tok_streq(buffer, resulttok, "resolve")) {
result = htlc_accepted_resolve;
paykeytok = json_get_member(buffer, toks, "payment_key");
if (!paykeytok)
fatal(
"Plugin did not specify a 'payment_key' in return "
"value to the htlc_accepted hook: %s",
json_strdup(tmpctx, buffer, resulttok));
if (!json_to_preimage(buffer, paykeytok,
payment_preimage))
fatal("Plugin specified an invalid 'payment_key': %s",
json_tok_full(buffer, resulttok));
} else {
fatal("Plugin responded with an unknown result to the "
"htlc_accepted hook: %s",
json_strdup(tmpctx, buffer, resulttok));
}
return result;
}
static void htlc_accepted_hook_serialize(struct htlc_accepted_hook_payload *p,
struct json_stream *s)
{
const struct route_step *rs = p->route_step;
const struct htlc_in *hin = p->hin;
s32 expiry = hin->cltv_expiry, blockheight = p->ld->topology->tip->height;
json_object_start(s, "onion");
json_add_hex_talarr (s, "payload", rs->raw_payload);
if (rs->type == SPHINX_V0_PAYLOAD) {
json_object_start(s, "per_hop_v0");
json_add_string(s, "realm", "00");
json_add_short_channel_id(s, "short_channel_id", &rs->payload.v0.channel_id);
json_add_amount_msat_only(s, "forward_amount", rs->payload.v0.amt_forward);
json_add_u64(s, "outgoing_cltv_value", rs->payload.v0.outgoing_cltv);
json_object_end(s);
}
json_add_hex_talarr(s, "next_onion", p->next_onion);
json_add_secret(s, "shared_secret", hin->shared_secret);
json_object_end(s);
json_object_start(s, "htlc");
json_add_amount_msat_only(s, "amount", hin->msat);
json_add_u32(s, "cltv_expiry", expiry);
json_add_s32(s, "cltv_expiry_relative", expiry - blockheight);
json_add_sha256(s, "payment_hash", &hin->payment_hash);
json_object_end(s);
}
/**
* Callback when a plugin answers to the htlc_accepted hook
*/
static void
htlc_accepted_hook_callback(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 channel *channel = request->channel;
struct lightningd *ld = request->ld;
struct preimage payment_preimage;
u8 *req;
enum htlc_accepted_result result;
enum onion_type failure_code;
u8 *channel_update;
struct hop_data *hop_data;
result = htlc_accepted_hook_deserialize(buffer, toks, &payment_preimage, &failure_code, &channel_update);
hop_data = &rs->payload.v0;
switch (result) {
case htlc_accepted_continue:
if (rs->nextcase == ONION_FORWARD) {
struct gossip_resolve *gr = tal(ld, struct gossip_resolve);
gr->next_onion = serialize_onionpacket(gr, rs->next);
gr->next_channel = hop_data->channel_id;
gr->amt_to_forward = hop_data->amt_forward;
gr->outgoing_cltv_value = hop_data->outgoing_cltv;
gr->hin = hin;
req = towire_gossip_get_channel_peer(tmpctx, &gr->next_channel);
log_debug(channel->log, "Asking gossip to resolve channel %s",
type_to_string(tmpctx, struct short_channel_id,
&gr->next_channel));
subd_req(hin, ld->gossip, req, -1, 0,
channel_resolve_reply, gr);
} else
handle_localpay(hin, hin->cltv_expiry, &hin->payment_hash,
hop_data->amt_forward,
hop_data->outgoing_cltv);
break;
case htlc_accepted_fail:
log_debug(channel->log,
"Failing incoming HTLC as instructed by plugin hook");
fail_in_htlc(hin, failure_code, NULL, &hop_data->channel_id);
break;
case htlc_accepted_resolve:
fulfill_htlc(hin, &payment_preimage);
break;
}
tal_free(request);
}
REGISTER_PLUGIN_HOOK(htlc_accepted, htlc_accepted_hook_callback,
struct htlc_accepted_hook_payload *,
htlc_accepted_hook_serialize,
struct htlc_accepted_hook_payload *);
/**
* Everyone is committed to this htlc of theirs
*
* @param channel: The channel this HTLC was accepted from.
* @param id: the ID of the HTLC we accepted
* @param replay: Are we loading from the database and therefore should not
* perform the transition to RCVD_ADD_ACK_REVOCATION?
* @param[out] failcode: If we decide to fail right away this will be set to a
* non-zero failcode.
*/
static bool peer_accepted_htlc(struct channel *channel, u64 id,
bool replay, enum onion_type *failcode)
{
struct htlc_in *hin;
struct route_step *rs;
struct onionpacket *op;
struct lightningd *ld = channel->peer->ld;
struct htlc_accepted_hook_payload *hook_payload;
hin = find_htlc_in(&ld->htlcs_in, channel, id);
if (!hin) {
channel_internal_error(channel,
"peer_got_revoke unknown htlc %"PRIu64, id);
return false;
}
if (!replay && !htlc_in_update_state(channel, hin, RCVD_ADD_ACK_REVOCATION))
return false;
htlc_in_check(hin, __func__);
#if DEVELOPER
if (channel->peer->ignore_htlcs) {
log_debug(channel->log, "their htlc %"PRIu64" dev_ignore_htlcs",
id);
return true;
}
#endif
/* BOLT #2:
*
* - SHOULD fail to route any HTLC added after it has sent `shutdown`.
*/
if (channel->state == CHANNELD_SHUTTING_DOWN) {
*failcode = WIRE_PERMANENT_CHANNEL_FAILURE;
goto out;
}
/* BOLT #2:
*
* A fulfilling node:
* - for each HTLC it is attempting to fulfill:
* - MUST estimate a fulfillment deadline.
* - MUST fail (and not forward) an HTLC whose fulfillment deadline is
* already past.
*/
/* Our deadline is half the cltv_delta we insist on, so this check is
* a subset of the cltv check done in handle_localpay and
* forward_htlc. */
/* Channeld sets this to NULL if couldn't parse onion */
if (!hin->shared_secret) {
*failcode = WIRE_INVALID_ONION_KEY;
goto out;
}
/* FIXME: Have channeld hand through just the route_step! */
/* channeld tests this, so it should pass. */
op = parse_onionpacket(tmpctx, hin->onion_routing_packet,
sizeof(hin->onion_routing_packet),
failcode);
if (!op) {
channel_internal_error(channel,
"bad onion in got_revoke: %s",
tal_hexstr(channel, hin->onion_routing_packet,
sizeof(hin->onion_routing_packet)));
return false;
}
/* If it's crap, not channeld's fault, just fail it */
rs = process_onionpacket(tmpctx, op, hin->shared_secret->data,
hin->payment_hash.u.u8,
sizeof(hin->payment_hash));
if (!rs) {
channel_internal_error(channel,
"bad process_onionpacket in got_revoke: %s",
tal_hexstr(channel, hin->onion_routing_packet,
sizeof(hin->onion_routing_packet)));
return false;
}
/* Unknown realm isn't a bad onion, it's a normal failure. */
/* FIXME: if we want hooks to handle foreign realms we should
* move this check to the hook callback. */
if (rs->type != SPHINX_V0_PAYLOAD) {
*failcode = WIRE_INVALID_REALM;
goto out;
}
/* It's time to package up all the information and call the
* hook so plugins can interject if they want */
hook_payload = tal(hin, struct htlc_accepted_hook_payload);
hook_payload->route_step = tal_steal(hook_payload, rs);
hook_payload->ld = ld;
hook_payload->hin = hin;
hook_payload->channel = channel;
hook_payload->next_onion = serialize_onionpacket(hook_payload, rs->next);
plugin_hook_call_htlc_accepted(ld, hook_payload, hook_payload);
/* Falling through here is ok, after all the HTLC locked */
*failcode = 0;
out:
log_debug(channel->log, "their htlc %"PRIu64" %s",
id, *failcode ? onion_type_name(*failcode) : "locked");
return true;
}
static void fulfill_our_htlc_out(struct channel *channel, struct htlc_out *hout,
const struct preimage *preimage)
{
struct lightningd *ld = channel->peer->ld;
assert(!hout->preimage);
hout->preimage = tal_dup(hout, struct preimage, preimage);
htlc_out_check(hout, __func__);
wallet_htlc_update(ld->wallet, hout->dbid, hout->hstate,
hout->preimage, hout->failcode, hout->failuremsg);
/* Update channel stats */
wallet_channel_stats_incr_out_fulfilled(ld->wallet,
channel->dbid,
hout->msat);
if (hout->am_origin)
payment_succeeded(ld, hout, preimage);
else if (hout->in) {
fulfill_htlc(hout->in, preimage);
wallet_forwarded_payment_add(ld->wallet, hout->in, hout,
FORWARD_SETTLED, 0);
}
}
static bool peer_fulfilled_our_htlc(struct channel *channel,
const struct fulfilled_htlc *fulfilled)
{
struct lightningd *ld = channel->peer->ld;
struct htlc_out *hout;
hout = find_htlc_out(&ld->htlcs_out, channel, fulfilled->id);
if (!hout) {
channel_internal_error(channel,
"fulfilled_our_htlc unknown htlc %"PRIu64,
fulfilled->id);
return false;
}
if (!htlc_out_update_state(channel, hout, RCVD_REMOVE_COMMIT))
return false;
fulfill_our_htlc_out(channel, hout, &fulfilled->payment_preimage);
return true;
}
void onchain_fulfilled_htlc(struct channel *channel,
const struct preimage *preimage)
{
struct htlc_out_map_iter outi;
struct htlc_out *hout;
struct sha256 payment_hash;
struct lightningd *ld = channel->peer->ld;
sha256(&payment_hash, preimage, sizeof(*preimage));
/* FIXME: use db to look this up! */
for (hout = htlc_out_map_first(&ld->htlcs_out, &outi);
hout;
hout = htlc_out_map_next(&ld->htlcs_out, &outi)) {
if (hout->key.channel != channel)
continue;
/* It's possible that we failed some and succeeded one,
* if we got multiple errors. */
if (hout->failcode != 0 || hout->failuremsg)
continue;
if (!sha256_eq(&hout->payment_hash, &payment_hash))
continue;
/* We may have already fulfilled before going onchain, or
* we can fulfill onchain multiple times. */
if (!hout->preimage) {
/* Force state to something which allows a preimage */
hout->hstate = RCVD_REMOVE_HTLC;
fulfill_our_htlc_out(channel, hout, preimage);
}
/* We keep going: this is something of a leak, but onchain
* we have no real way of distinguishing HTLCs anyway */