-
Notifications
You must be signed in to change notification settings - Fork 901
/
channeld.c
2991 lines (2631 loc) · 90.6 KB
/
channeld.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
/* Main channel operation daemon: runs from funding_locked to shutdown_complete.
*
* We're fairly synchronous: our main loop looks for gossip, master or
* peer requests and services them synchronously.
*
* The exceptions are:
* 1. When we've asked the master something: in that case, we queue
* non-response packets for later processing while we await the reply.
* 2. We queue and send non-blocking responses to peers: if both peers were
* reading and writing synchronously we could deadlock if we hit buffer
* limits, unlikely as that is.
*/
#include <bitcoin/chainparams.h>
#include <bitcoin/privkey.h>
#include <bitcoin/script.h>
#include <ccan/cast/cast.h>
#include <ccan/container_of/container_of.h>
#include <ccan/crypto/hkdf_sha256/hkdf_sha256.h>
#include <ccan/crypto/shachain/shachain.h>
#include <ccan/err/err.h>
#include <ccan/fdpass/fdpass.h>
#include <ccan/mem/mem.h>
#include <ccan/take/take.h>
#include <ccan/tal/str/str.h>
#include <ccan/time/time.h>
#include <channeld/commit_tx.h>
#include <channeld/full_channel.h>
#include <channeld/gen_channel_wire.h>
#include <common/crypto_sync.h>
#include <common/dev_disconnect.h>
#include <common/features.h>
#include <common/htlc_tx.h>
#include <common/key_derive.h>
#include <common/memleak.h>
#include <common/msg_queue.h>
#include <common/peer_billboard.h>
#include <common/peer_failed.h>
#include <common/ping.h>
#include <common/read_peer_msg.h>
#include <common/sphinx.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/timeout.h>
#include <common/type_to_string.h>
#include <common/version.h>
#include <common/wire_error.h>
#include <errno.h>
#include <fcntl.h>
#include <gossipd/gen_gossip_peerd_wire.h>
#include <gossipd/gossip_constants.h>
#include <hsmd/gen_hsm_wire.h>
#include <inttypes.h>
#include <secp256k1.h>
#include <stdio.h>
#include <wire/gen_onion_wire.h>
#include <wire/peer_wire.h>
#include <wire/wire.h>
#include <wire/wire_io.h>
#include <wire/wire_sync.h>
/* stdin == requests, 3 == peer, 4 = gossip, 5 = HSM */
#define MASTER_FD STDIN_FILENO
#define PEER_FD 3
#define GOSSIP_FD 4
#define HSM_FD 5
struct peer {
struct crypto_state cs;
bool funding_locked[NUM_SIDES];
u64 next_index[NUM_SIDES];
/* Features peer supports. */
u8 *localfeatures;
/* Tolerable amounts for feerate (only relevant for fundee). */
u32 feerate_min, feerate_max;
/* Local next per-commit point. */
struct pubkey next_local_per_commit;
/* Remote's current per-commit point. */
struct pubkey remote_per_commit;
/* Remotes's last per-commitment point: we keep this to check
* revoke_and_ack's `per_commitment_secret` is correct. */
struct pubkey old_remote_per_commit;
/* Their sig for current commit. */
struct bitcoin_signature their_commit_sig;
/* BOLT #2:
*
* A sending node:
*...
* - for the first HTLC it offers:
* - MUST set `id` to 0.
*/
u64 htlc_id;
struct bitcoin_blkid chain_hash;
struct channel_id channel_id;
struct channel *channel;
/* Messages from master / gossipd: we queue them since we
* might be waiting for a specific reply. */
struct msg_queue *from_master, *from_gossipd;
struct timers timers;
struct oneshot *commit_timer;
u64 commit_timer_attempts;
u32 commit_msec;
/* Are we expecting a pong? */
bool expecting_pong;
/* The feerate we want. */
u32 desired_feerate;
/* Announcement related information */
struct pubkey node_ids[NUM_SIDES];
struct short_channel_id short_channel_ids[NUM_SIDES];
secp256k1_ecdsa_signature announcement_node_sigs[NUM_SIDES];
secp256k1_ecdsa_signature announcement_bitcoin_sigs[NUM_SIDES];
bool have_sigs[NUM_SIDES];
/* Which direction of the channel do we control? */
u16 channel_direction;
/* CLTV delta to announce to peers */
u16 cltv_delta;
u32 fee_base;
u32 fee_per_satoshi;
/* The scriptpubkey to use for shutting down. */
u8 *final_scriptpubkey;
/* If master told us to shut down */
bool send_shutdown;
/* Has shutdown been sent by each side? */
bool shutdown_sent[NUM_SIDES];
/* Information used for reestablishment. */
bool last_was_revoke;
struct changed_htlc *last_sent_commit;
u64 revocations_received;
u8 channel_flags;
bool announce_depth_reached;
bool channel_local_active;
/* Make sure timestamps move forward. */
u32 last_update_timestamp;
/* Make sure peer is live. */
struct timeabs last_recv;
};
static u8 *create_channel_announcement(const tal_t *ctx, struct peer *peer);
static void start_commit_timer(struct peer *peer);
static void billboard_update(const struct peer *peer)
{
const char *funding_status, *announce_status, *shutdown_status;
if (peer->funding_locked[LOCAL] && peer->funding_locked[REMOTE])
funding_status = "Funding transaction locked.";
else if (!peer->funding_locked[LOCAL] && !peer->funding_locked[REMOTE])
/* FIXME: Say how many blocks to go! */
funding_status = "Funding needs more confirmations.";
else if (peer->funding_locked[LOCAL] && !peer->funding_locked[REMOTE])
funding_status = "We've confirmed funding, they haven't yet.";
else if (!peer->funding_locked[LOCAL] && peer->funding_locked[REMOTE])
funding_status = "They've confirmed funding, we haven't yet.";
if (peer->have_sigs[LOCAL] && peer->have_sigs[REMOTE])
announce_status = " Channel announced.";
else if (peer->have_sigs[LOCAL] && !peer->have_sigs[REMOTE])
announce_status = " Waiting for their announcement signatures.";
else if (!peer->have_sigs[LOCAL] && peer->have_sigs[REMOTE])
announce_status = " They need our announcement signatures.";
else if (!peer->have_sigs[LOCAL] && !peer->have_sigs[REMOTE])
announce_status = "";
if (!peer->shutdown_sent[LOCAL] && !peer->shutdown_sent[REMOTE])
shutdown_status = "";
else if (!peer->shutdown_sent[LOCAL] && peer->shutdown_sent[REMOTE])
shutdown_status = " We've send shutdown, waiting for theirs";
else if (peer->shutdown_sent[LOCAL] && !peer->shutdown_sent[REMOTE])
shutdown_status = " They've sent shutdown, waiting for ours";
else if (peer->shutdown_sent[LOCAL] && peer->shutdown_sent[REMOTE]) {
size_t num_htlcs = num_channel_htlcs(peer->channel);
if (num_htlcs)
shutdown_status = tal_fmt(tmpctx,
" Shutdown messages exchanged,"
" waiting for %zu HTLCs to complete.",
num_htlcs);
else
shutdown_status = tal_fmt(tmpctx,
" Shutdown messages exchanged.");
}
peer_billboard(false, "%s%s%s", funding_status,
announce_status, shutdown_status);
}
static const u8 *hsm_req(const tal_t *ctx, const u8 *req TAKES)
{
u8 *msg;
int type = fromwire_peektype(req);
if (!wire_sync_write(HSM_FD, req))
status_failed(STATUS_FAIL_HSM_IO,
"Writing %s to HSM: %s",
hsm_wire_type_name(type),
strerror(errno));
msg = wire_sync_read(ctx, HSM_FD);
if (!msg)
status_failed(STATUS_FAIL_HSM_IO,
"Reading resp to %s: %s",
hsm_wire_type_name(type),
strerror(errno));
return msg;
}
/*
* The maximum msat that this node will accept for an htlc.
* It's flagged as an optional field in `channel_update`.
*
* We advertise the maximum value possible, defined as the smaller
* of the remote's maximum in-flight HTLC or the total channel
* capacity minus the cumulative reserve.
* FIXME: does this need fuzz?
*/
static struct amount_msat advertised_htlc_max(const struct channel *channel)
{
struct amount_sat cumulative_reserve, lower_bound;
struct amount_msat lower_bound_msat;
/* This shouldn't fail */
if (!amount_sat_add(&cumulative_reserve,
channel->config[LOCAL].channel_reserve,
channel->config[REMOTE].channel_reserve)) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"reserve overflow: local %s + remote %s",
type_to_string(tmpctx, struct amount_sat,
&channel->config[LOCAL].channel_reserve),
type_to_string(tmpctx, struct amount_sat,
&channel->config[REMOTE].channel_reserve));
}
/* This shouldn't fail either */
if (!amount_sat_sub(&lower_bound, channel->funding, cumulative_reserve)) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"funding %s - cumulative_reserve %s?",
type_to_string(tmpctx, struct amount_sat,
&channel->funding),
type_to_string(tmpctx, struct amount_sat,
&cumulative_reserve));
}
if (!amount_sat_to_msat(&lower_bound_msat, lower_bound)) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"lower_bound %s invalid?",
type_to_string(tmpctx, struct amount_sat,
&lower_bound));
}
/* FIXME BOLT QUOTE: https://github.com/lightningnetwork/lightning-rfc/pull/512 once merged */
if (amount_msat_greater(lower_bound_msat,
channel->chainparams->max_payment))
lower_bound_msat = channel->chainparams->max_payment;
return lower_bound_msat;
}
/* Create and send channel_update to gossipd (and maybe peer) */
static void send_channel_update(struct peer *peer, int disable_flag)
{
u8 *msg;
assert(disable_flag == 0 || disable_flag == ROUTING_FLAGS_DISABLED);
/* Only send an update if we told gossipd */
if (!peer->channel_local_active)
return;
assert(peer->short_channel_ids[LOCAL].u64);
msg = towire_gossipd_local_channel_update(NULL,
&peer->short_channel_ids[LOCAL],
disable_flag
== ROUTING_FLAGS_DISABLED,
peer->cltv_delta,
peer->channel->config[REMOTE].htlc_minimum,
peer->fee_base,
peer->fee_per_satoshi,
advertised_htlc_max(peer->channel));
wire_sync_write(GOSSIP_FD, take(msg));
}
/**
* Add a channel locally and send a channel update to the peer
*
* Send a local_add_channel message to gossipd in order to make the channel
* usable locally, and also tell our peer about our parameters via a
* channel_update message. The peer may accept the update and use the contained
* information to route incoming payments through the channel. The
* channel_update is not preceeded by a channel_announcement and won't make much
* sense to other nodes, so we don't tell gossipd about it.
*/
static void make_channel_local_active(struct peer *peer)
{
u8 *msg;
/* Tell gossipd about local channel. */
msg = towire_gossipd_local_add_channel(NULL,
&peer->short_channel_ids[LOCAL],
&peer->node_ids[REMOTE],
peer->channel->funding);
wire_sync_write(GOSSIP_FD, take(msg));
/* Tell gossipd and the other side what parameters we expect should
* they route through us */
send_channel_update(peer, 0);
}
static void send_announcement_signatures(struct peer *peer)
{
/* First 2 + 256 byte are the signatures and msg type, skip them */
size_t offset = 258;
struct sha256_double hash;
const u8 *msg, *ca, *req;
status_trace("Exchanging announcement signatures.");
ca = create_channel_announcement(tmpctx, peer);
req = towire_hsm_cannouncement_sig_req(tmpctx, ca);
msg = hsm_req(tmpctx, req);
if (!fromwire_hsm_cannouncement_sig_reply(msg,
&peer->announcement_node_sigs[LOCAL],
&peer->announcement_bitcoin_sigs[LOCAL]))
status_failed(STATUS_FAIL_HSM_IO,
"Reading cannouncement_sig_resp: %s",
strerror(errno));
/* Double-check that HSM gave valid signatures. */
sha256_double(&hash, ca + offset, tal_count(ca) - offset);
if (!check_signed_hash(&hash, &peer->announcement_node_sigs[LOCAL],
&peer->node_ids[LOCAL])) {
/* It's ok to fail here, the channel announcement is
* unique, unlike the channel update which may have
* been replaced in the meantime. */
status_failed(STATUS_FAIL_HSM_IO,
"HSM returned an invalid node signature");
}
if (!check_signed_hash(&hash, &peer->announcement_bitcoin_sigs[LOCAL],
&peer->channel->funding_pubkey[LOCAL])) {
/* It's ok to fail here, the channel announcement is
* unique, unlike the channel update which may have
* been replaced in the meantime. */
status_failed(STATUS_FAIL_HSM_IO,
"HSM returned an invalid bitcoin signature");
}
msg = towire_announcement_signatures(
NULL, &peer->channel_id, &peer->short_channel_ids[LOCAL],
&peer->announcement_node_sigs[LOCAL],
&peer->announcement_bitcoin_sigs[LOCAL]);
sync_crypto_write(&peer->cs, PEER_FD, take(msg));
}
/* Tentatively create a channel_announcement, possibly with invalid
* signatures. The signatures need to be collected first, by asking
* the HSM and by exchanging announcement_signature messages. */
static u8 *create_channel_announcement(const tal_t *ctx, struct peer *peer)
{
int first, second;
u8 *cannounce, *features = tal_arr(ctx, u8, 0);
if (peer->channel_direction == 0) {
first = LOCAL;
second = REMOTE;
} else {
first = REMOTE;
second = LOCAL;
}
cannounce = towire_channel_announcement(
ctx, &peer->announcement_node_sigs[first],
&peer->announcement_node_sigs[second],
&peer->announcement_bitcoin_sigs[first],
&peer->announcement_bitcoin_sigs[second],
features,
&peer->chain_hash,
&peer->short_channel_ids[LOCAL], &peer->node_ids[first],
&peer->node_ids[second], &peer->channel->funding_pubkey[first],
&peer->channel->funding_pubkey[second]);
tal_free(features);
return cannounce;
}
/* Once we have both, we'd better make sure we agree what they are! */
static void check_short_ids_match(struct peer *peer)
{
assert(peer->have_sigs[LOCAL]);
assert(peer->have_sigs[REMOTE]);
if (!short_channel_id_eq(&peer->short_channel_ids[LOCAL],
&peer->short_channel_ids[REMOTE]))
peer_failed(&peer->cs,
&peer->channel_id,
"We disagree on short_channel_ids:"
" I have %s, you say %s",
type_to_string(peer, struct short_channel_id,
&peer->short_channel_ids[LOCAL]),
type_to_string(peer, struct short_channel_id,
&peer->short_channel_ids[REMOTE]));
}
static void announce_channel(struct peer *peer)
{
u8 *cannounce;
check_short_ids_match(peer);
cannounce = create_channel_announcement(tmpctx, peer);
wire_sync_write(GOSSIP_FD, cannounce);
send_channel_update(peer, 0);
}
static void channel_announcement_negotiate(struct peer *peer)
{
/* Don't do any announcement work if we're shutting down */
if (peer->shutdown_sent[LOCAL])
return;
/* Can't do anything until funding is locked. */
if (!peer->funding_locked[LOCAL] || !peer->funding_locked[REMOTE])
return;
if (!peer->channel_local_active) {
peer->channel_local_active = true;
make_channel_local_active(peer);
}
/* BOLT #7:
*
* A node:
* - if the `open_channel` message has the `announce_channel` bit set AND a `shutdown` message has not been sent:
* - MUST send the `announcement_signatures` message.
* - MUST NOT send `announcement_signatures` messages until `funding_locked`
* has been sent and received AND the funding transaction has at least six confirmations.
* - otherwise:
* - MUST NOT send the `announcement_signatures` message.
*/
if (!(peer->channel_flags & CHANNEL_FLAGS_ANNOUNCE_CHANNEL))
return;
/* BOLT #7:
*
* - MUST NOT send `announcement_signatures` messages until `funding_locked`
* has been sent and received AND the funding transaction has at least six confirmations.
*/
if (peer->announce_depth_reached && !peer->have_sigs[LOCAL]) {
send_announcement_signatures(peer);
peer->have_sigs[LOCAL] = true;
billboard_update(peer);
}
/* If we've completed the signature exchange, we can send a real
* announcement, otherwise we send a temporary one */
if (peer->have_sigs[LOCAL] && peer->have_sigs[REMOTE])
announce_channel(peer);
}
static void handle_peer_funding_locked(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
/* BOLT #2:
*
* A node:
*...
* - upon reconnection:
* - MUST ignore any redundant `funding_locked` it receives.
*/
if (peer->funding_locked[REMOTE])
return;
/* Too late, we're shutting down! */
if (peer->shutdown_sent[LOCAL])
return;
peer->old_remote_per_commit = peer->remote_per_commit;
if (!fromwire_funding_locked(msg, &chanid,
&peer->remote_per_commit))
peer_failed(&peer->cs,
&peer->channel_id,
"Bad funding_locked %s", tal_hex(msg, msg));
if (!channel_id_eq(&chanid, &peer->channel_id))
peer_failed(&peer->cs,
&peer->channel_id,
"Wrong channel id in %s (expected %s)",
tal_hex(tmpctx, msg),
type_to_string(msg, struct channel_id,
&peer->channel_id));
peer->funding_locked[REMOTE] = true;
wire_sync_write(MASTER_FD,
take(towire_channel_got_funding_locked(NULL,
&peer->remote_per_commit)));
channel_announcement_negotiate(peer);
billboard_update(peer);
}
static void handle_peer_announcement_signatures(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
if (!fromwire_announcement_signatures(msg,
&chanid,
&peer->short_channel_ids[REMOTE],
&peer->announcement_node_sigs[REMOTE],
&peer->announcement_bitcoin_sigs[REMOTE]))
peer_failed(&peer->cs,
&peer->channel_id,
"Bad announcement_signatures %s",
tal_hex(msg, msg));
/* Make sure we agree on the channel ids */
if (!channel_id_eq(&chanid, &peer->channel_id)) {
peer_failed(&peer->cs,
&peer->channel_id,
"Wrong channel_id: expected %s, got %s",
type_to_string(tmpctx, struct channel_id,
&peer->channel_id),
type_to_string(tmpctx, struct channel_id, &chanid));
}
peer->have_sigs[REMOTE] = true;
billboard_update(peer);
channel_announcement_negotiate(peer);
}
static struct secret *get_shared_secret(const tal_t *ctx,
const struct htlc *htlc,
enum onion_type *why_bad,
struct sha256 *next_onion_sha)
{
struct onionpacket *op;
struct secret *secret = tal(ctx, struct secret);
const u8 *msg;
struct route_step *rs;
/* We unwrap the onion now. */
op = parse_onionpacket(tmpctx, htlc->routing, TOTAL_PACKET_SIZE,
why_bad);
if (!op)
return tal_free(secret);
/* Because wire takes struct pubkey. */
msg = hsm_req(tmpctx, towire_hsm_ecdh_req(tmpctx, &op->ephemeralkey));
if (!fromwire_hsm_ecdh_resp(msg, secret))
status_failed(STATUS_FAIL_HSM_IO, "Reading ecdh response");
/* We make sure we can parse onion packet, so we know if shared secret
* is actually valid (this checks hmac). */
rs = process_onionpacket(tmpctx, op, secret->data,
htlc->rhash.u.u8,
sizeof(htlc->rhash));
if (!rs) {
*why_bad = WIRE_INVALID_ONION_HMAC;
return tal_free(secret);
}
/* Calculate sha256 we'll hand to next peer, in case they complain. */
msg = serialize_onionpacket(tmpctx, rs->next);
sha256(next_onion_sha, msg, tal_bytelen(msg));
return secret;
}
static void handle_peer_add_htlc(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u64 id;
struct amount_msat amount;
u32 cltv_expiry;
struct sha256 payment_hash;
u8 onion_routing_packet[TOTAL_PACKET_SIZE];
enum channel_add_err add_err;
struct htlc *htlc;
if (!fromwire_update_add_htlc(msg, &channel_id, &id, &amount,
&payment_hash, &cltv_expiry,
onion_routing_packet))
peer_failed(&peer->cs,
&peer->channel_id,
"Bad peer_add_htlc %s", tal_hex(msg, msg));
add_err = channel_add_htlc(peer->channel, REMOTE, id, amount,
cltv_expiry, &payment_hash,
onion_routing_packet, &htlc);
if (add_err != CHANNEL_ERR_ADD_OK)
peer_failed(&peer->cs,
&peer->channel_id,
"Bad peer_add_htlc: %s",
channel_add_err_name(add_err));
/* If this is wrong, we don't complain yet; when it's confirmed we'll
* send it to the master which handles all HTLC failures. */
htlc->shared_secret = get_shared_secret(htlc, htlc,
&htlc->why_bad_onion,
&htlc->next_onion_sha);
}
static void handle_peer_feechange(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u32 feerate;
if (!fromwire_update_fee(msg, &channel_id, &feerate)) {
peer_failed(&peer->cs,
&peer->channel_id,
"Bad update_fee %s", tal_hex(msg, msg));
}
/* BOLT #2:
*
* A receiving node:
*...
* - if the sender is not responsible for paying the Bitcoin fee:
* - MUST fail the channel.
*/
if (peer->channel->funder != REMOTE)
peer_failed(&peer->cs,
&peer->channel_id,
"update_fee from non-funder?");
status_trace("update_fee %u, range %u-%u",
feerate, peer->feerate_min, peer->feerate_max);
/* BOLT #2:
*
* A receiving node:
* - if the `update_fee` is too low for timely processing, OR is
* unreasonably large:
* - SHOULD fail the channel.
*/
if (feerate < peer->feerate_min || feerate > peer->feerate_max)
peer_failed(&peer->cs,
&peer->channel_id,
"update_fee %u outside range %u-%u",
feerate, peer->feerate_min, peer->feerate_max);
/* BOLT #2:
*
* - if the sender cannot afford the new fee rate on the receiving
* node's current commitment transaction:
* - SHOULD fail the channel,
* - but MAY delay this check until the `update_fee` is committed.
*/
if (!channel_update_feerate(peer->channel, feerate))
peer_failed(&peer->cs,
&peer->channel_id,
"update_fee %u unaffordable",
feerate);
status_trace("peer updated fee to %u", feerate);
}
static struct changed_htlc *changed_htlc_arr(const tal_t *ctx,
const struct htlc **changed_htlcs)
{
struct changed_htlc *changed;
size_t i;
changed = tal_arr(ctx, struct changed_htlc, tal_count(changed_htlcs));
for (i = 0; i < tal_count(changed_htlcs); i++) {
changed[i].id = changed_htlcs[i]->id;
changed[i].newstate = changed_htlcs[i]->state;
}
return changed;
}
static u8 *sending_commitsig_msg(const tal_t *ctx,
u64 remote_commit_index,
u32 remote_feerate,
const struct htlc **changed_htlcs,
const struct bitcoin_signature *commit_sig,
const secp256k1_ecdsa_signature *htlc_sigs)
{
struct changed_htlc *changed;
u8 *msg;
/* We tell master what (of our) HTLCs peer will now be
* committed to. */
changed = changed_htlc_arr(tmpctx, changed_htlcs);
msg = towire_channel_sending_commitsig(ctx, remote_commit_index,
remote_feerate,
changed, commit_sig, htlc_sigs);
return msg;
}
static bool shutdown_complete(const struct peer *peer)
{
return peer->shutdown_sent[LOCAL]
&& peer->shutdown_sent[REMOTE]
&& num_channel_htlcs(peer->channel) == 0
/* We could be awaiting revoke-and-ack for a feechange */
&& peer->revocations_received == peer->next_index[REMOTE] - 1;
}
/* BOLT #2:
*
* A sending node:
*...
* - if there are updates pending on the receiving node's commitment
* transaction:
* - MUST NOT send a `shutdown`.
*/
/* So we only call this after reestablish or immediately after sending commit */
static void maybe_send_shutdown(struct peer *peer)
{
u8 *msg;
if (!peer->send_shutdown)
return;
/* Send a disable channel_update so others don't try to route
* over us */
send_channel_update(peer, ROUTING_FLAGS_DISABLED);
msg = towire_shutdown(NULL, &peer->channel_id, peer->final_scriptpubkey);
sync_crypto_write(&peer->cs, PEER_FD, take(msg));
peer->send_shutdown = false;
peer->shutdown_sent[LOCAL] = true;
billboard_update(peer);
}
/* This queues other traffic from the fd until we get reply. */
static u8 *wait_sync_reply(const tal_t *ctx,
const u8 *msg,
int replytype,
int fd,
struct msg_queue *queue,
const char *who)
{
u8 *reply;
status_trace("Sending %s %u", who, fromwire_peektype(msg));
if (!wire_sync_write(fd, msg))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not set sync write to %s: %s",
who, strerror(errno));
status_trace("... , awaiting %u", replytype);
for (;;) {
reply = wire_sync_read(ctx, fd);
if (!reply)
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not set sync read from %s: %s",
who, strerror(errno));
if (fromwire_peektype(reply) == replytype) {
status_trace("Got it!");
break;
}
status_trace("Nope, got %u instead", fromwire_peektype(reply));
msg_enqueue(queue, take(reply));
}
return reply;
}
static u8 *master_wait_sync_reply(const tal_t *ctx,
struct peer *peer, const u8 *msg,
enum channel_wire_type replytype)
{
return wait_sync_reply(ctx, msg, replytype,
MASTER_FD, peer->from_master, "master");
}
static u8 *gossipd_wait_sync_reply(const tal_t *ctx,
struct peer *peer, const u8 *msg,
enum gossip_peerd_wire_type replytype)
{
return wait_sync_reply(ctx, msg, replytype,
GOSSIP_FD, peer->from_gossipd, "gossipd");
}
static u8 *foreign_channel_update(const tal_t *ctx,
struct peer *peer,
const struct short_channel_id *scid)
{
u8 *msg, *update, *channel_update;
msg = towire_gossipd_get_update(NULL, scid);
msg = gossipd_wait_sync_reply(tmpctx, peer, take(msg),
WIRE_GOSSIPD_GET_UPDATE_REPLY);
if (!fromwire_gossipd_get_update_reply(ctx, msg, &update))
status_failed(STATUS_FAIL_GOSSIP_IO,
"Invalid update reply");
/* Strip the type from the channel_update. Due to the specification
* being underspecified, some implementations skipped the type
* prefix. Since we are in the minority we adapt (See #1730 and
* lightningnetwork/lnd#1599 for details). */
if (update && fromwire_peektype(update) == WIRE_CHANNEL_UPDATE) {
assert(tal_bytelen(update) > 2);
channel_update = tal_arr(ctx, u8, 0);
towire(&channel_update, update + 2, tal_bytelen(update) - 2);
tal_free(update);
return channel_update;
} else {
return update;
}
}
static u8 *make_failmsg(const tal_t *ctx,
struct peer *peer,
const struct htlc *htlc,
enum onion_type failcode,
const struct short_channel_id *scid,
const struct sha256 *sha256)
{
u8 *msg, *channel_update = NULL;
u32 cltv_expiry = abs_locktime_to_blocks(&htlc->expiry);
switch (failcode) {
case WIRE_INVALID_REALM:
msg = towire_invalid_realm(ctx);
goto done;
case WIRE_TEMPORARY_NODE_FAILURE:
msg = towire_temporary_node_failure(ctx);
goto done;
case WIRE_PERMANENT_NODE_FAILURE:
msg = towire_permanent_node_failure(ctx);
goto done;
case WIRE_REQUIRED_NODE_FEATURE_MISSING:
msg = towire_required_node_feature_missing(ctx);
goto done;
case WIRE_TEMPORARY_CHANNEL_FAILURE:
channel_update = foreign_channel_update(ctx, peer, scid);
msg = towire_temporary_channel_failure(ctx, channel_update);
goto done;
case WIRE_CHANNEL_DISABLED:
msg = towire_channel_disabled(ctx);
goto done;
case WIRE_PERMANENT_CHANNEL_FAILURE:
msg = towire_permanent_channel_failure(ctx);
goto done;
case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING:
msg = towire_required_channel_feature_missing(ctx);
goto done;
case WIRE_UNKNOWN_NEXT_PEER:
msg = towire_unknown_next_peer(ctx);
goto done;
case WIRE_AMOUNT_BELOW_MINIMUM:
channel_update = foreign_channel_update(ctx, peer, scid);
msg = towire_amount_below_minimum(ctx, htlc->amount,
channel_update);
goto done;
case WIRE_FEE_INSUFFICIENT:
channel_update = foreign_channel_update(ctx, peer, scid);
msg = towire_fee_insufficient(ctx, htlc->amount,
channel_update);
goto done;
case WIRE_INCORRECT_CLTV_EXPIRY:
channel_update = foreign_channel_update(ctx, peer, scid);
msg = towire_incorrect_cltv_expiry(ctx, cltv_expiry,
channel_update);
goto done;
case WIRE_EXPIRY_TOO_SOON:
channel_update = foreign_channel_update(ctx, peer, scid);
msg = towire_expiry_too_soon(ctx, channel_update);
goto done;
case WIRE_EXPIRY_TOO_FAR:
msg = towire_expiry_too_far(ctx);
goto done;
case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS:
msg = towire_incorrect_or_unknown_payment_details(
ctx, htlc->amount);
goto done;
case WIRE_FINAL_EXPIRY_TOO_SOON:
msg = towire_final_expiry_too_soon(ctx);
goto done;
case WIRE_FINAL_INCORRECT_CLTV_EXPIRY:
msg = towire_final_incorrect_cltv_expiry(ctx, cltv_expiry);
goto done;
case WIRE_FINAL_INCORRECT_HTLC_AMOUNT:
msg = towire_final_incorrect_htlc_amount(ctx, htlc->amount);
goto done;
case WIRE_INVALID_ONION_VERSION:
msg = towire_invalid_onion_version(ctx, sha256);
goto done;
case WIRE_INVALID_ONION_HMAC:
msg = towire_invalid_onion_hmac(ctx, sha256);
goto done;
case WIRE_INVALID_ONION_KEY:
msg = towire_invalid_onion_key(ctx, sha256);
goto done;
case WIRE_INCORRECT_PAYMENT_AMOUNT:
/* Deprecated: we should never make this any more! */
break;
}
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Asked to create failmsg %u (%s)",
failcode, onion_type_name(failcode));
done:
tal_free(channel_update);
return msg;
}
/* Returns HTLC sigs, sets commit_sig */
static secp256k1_ecdsa_signature *calc_commitsigs(const tal_t *ctx,
const struct peer *peer,
u64 commit_index,
struct bitcoin_signature *commit_sig)
{
size_t i;
struct bitcoin_tx **txs;
const u8 **wscripts;
const struct htlc **htlc_map;
struct pubkey local_htlckey;
const u8 *msg;
secp256k1_ecdsa_signature *htlc_sigs;
txs = channel_txs(tmpctx, &htlc_map, &wscripts, peer->channel,
&peer->remote_per_commit,
commit_index,
REMOTE);
msg = towire_hsm_sign_remote_commitment_tx(NULL, txs[0],
&peer->channel->funding_pubkey[REMOTE],
*txs[0]->input[0].amount);
msg = hsm_req(tmpctx, take(msg));
if (!fromwire_hsm_sign_tx_reply(msg, commit_sig))
status_failed(STATUS_FAIL_HSM_IO,
"Reading sign_remote_commitment_tx reply: %s",
tal_hex(tmpctx, msg));
status_trace("Creating commit_sig signature %"PRIu64" %s for tx %s wscript %s key %s",
commit_index,
type_to_string(tmpctx, struct bitcoin_signature,
commit_sig),
type_to_string(tmpctx, struct bitcoin_tx, txs[0]),
tal_hex(tmpctx, wscripts[0]),
type_to_string(tmpctx, struct pubkey,
&peer->channel->funding_pubkey[LOCAL]));
dump_htlcs(peer->channel, "Sending commit_sig");
if (!derive_simple_key(&peer->channel->basepoints[LOCAL].htlc,
&peer->remote_per_commit,
&local_htlckey))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Deriving local_htlckey");
/* BOLT #2:
*
* A sending node:
*...
* - MUST include one `htlc_signature` for every HTLC transaction
* corresponding to BIP69 lexicographic ordering of the commitment
* transaction.
*/
htlc_sigs = tal_arr(ctx, secp256k1_ecdsa_signature, tal_count(txs) - 1);
for (i = 0; i < tal_count(htlc_sigs); i++) {
struct bitcoin_signature sig;
msg = towire_hsm_sign_remote_htlc_tx(NULL, txs[i + 1],
wscripts[i + 1],
*txs[i+1]->input[0].amount,
&peer->remote_per_commit);
msg = hsm_req(tmpctx, take(msg));
if (!fromwire_hsm_sign_tx_reply(msg, &sig))
status_failed(STATUS_FAIL_HSM_IO,
"Bad sign_remote_htlc_tx reply: %s",
tal_hex(tmpctx, msg));
htlc_sigs[i] = sig.s;
status_trace("Creating HTLC signature %s for tx %s wscript %s key %s",
type_to_string(tmpctx, struct bitcoin_signature,
&sig),
type_to_string(tmpctx, struct bitcoin_tx, txs[1+i]),
tal_hex(tmpctx, wscripts[1+i]),
type_to_string(tmpctx, struct pubkey,
&local_htlckey));
assert(check_tx_sig(txs[1+i], 0, NULL, wscripts[1+i],