forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.c
2759 lines (2417 loc) · 81.7 KB
/
channel.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/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/structeq/structeq.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/derive_basepoints.h>
#include <common/dev_disconnect.h>
#include <common/htlc_tx.h>
#include <common/io_debug.h>
#include <common/key_derive.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_wire.h>
#include <gossipd/routing.h>
#include <hsmd/gen_hsm_client_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 commit_sigs {
struct peer *peer;
secp256k1_ecdsa_signature commit_sig;
secp256k1_ecdsa_signature *htlc_sigs;
};
struct peer {
struct crypto_state cs;
struct channel_config conf[NUM_SIDES];
bool funding_locked[NUM_SIDES];
u64 next_index[NUM_SIDES];
/* Tolerable amounts for feerate (only relevant for fundee). */
u32 feerate_min, feerate_max;
/* 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. */
secp256k1_ecdsa_signature their_commit_sig;
/* Secret keys and basepoint secrets. */
struct secrets our_secrets;
/* Our shaseed for generating per-commitment-secrets. */
struct sha256 shaseed;
/* BOLT #2:
*
* A sending node MUST set `id` to 0 for the first HTLC it offers, and
* increase the value by 1 for each successive offer.
*/
u64 htlc_id;
struct bitcoin_blkid chain_hash;
struct channel_id channel_id;
struct channel *channel;
/* Pending msgs to send (not encrypted) */
struct msg_queue peer_out;
/* Current msg to send, and offset (encrypted) */
const u8 *peer_outmsg;
size_t peer_outoff;
/* 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;
/* Don't accept a pong we didn't ping for. */
size_t num_pings_outstanding;
/* 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;
/* We save calculated commit sigs while waiting for master approval */
struct commit_sigs *next_commit_sigs;
/* 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;
/* Where we got up to in gossip broadcasts. */
u64 gossip_index;
/* Make sure timestamps move forward. */
u32 last_update_timestamp;
};
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);
}
/* Returns a pointer to the new end */
static void *tal_arr_append_(void **p, size_t size)
{
size_t n = tal_len(*p) / size;
tal_resize_(p, size, n+1, false);
return (char *)(*p) + n * size;
}
#define tal_arr_append(p) tal_arr_append_((void **)(p), sizeof(**(p)))
static void do_peer_write(struct peer *peer)
{
int r;
size_t len = tal_len(peer->peer_outmsg);
r = write(PEER_FD, peer->peer_outmsg + peer->peer_outoff,
len - peer->peer_outoff);
if (r < 0)
peer_failed_connection_lost();
peer->peer_outoff += r;
if (peer->peer_outoff == len)
peer->peer_outmsg = tal_free(peer->peer_outmsg);
}
static bool peer_write_pending(struct peer *peer)
{
const u8 *msg;
if (peer->peer_outmsg)
return true;
msg = msg_dequeue(&peer->peer_out);
if (!msg)
return false;
status_io(LOG_IO_OUT, msg);
peer->peer_outmsg = cryptomsg_encrypt_msg(peer, &peer->cs, take(msg));
peer->peer_outoff = 0;
return true;
}
/* Synchronous flush of all pending packets. */
static void flush_peer_out(struct peer *peer)
{
while (peer_write_pending(peer))
do_peer_write(peer);
}
static void enqueue_peer_msg(struct peer *peer, const u8 *msg TAKES)
{
#if DEVELOPER
enum dev_disconnect d = dev_disconnect(fromwire_peektype(msg));
/* We want to effect this exact packet, so flush any pending. */
if (d != DEV_DISCONNECT_NORMAL)
flush_peer_out(peer);
switch (d) {
case DEV_DISCONNECT_BEFORE:
/* Fail immediately. */
dev_sabotage_fd(PEER_FD);
msg_enqueue(&peer->peer_out, msg);
flush_peer_out(peer);
/* Should not return */
abort();
case DEV_DISCONNECT_DROPPKT:
tal_free(msg);
/* Fail next time we try to do something. */
dev_sabotage_fd(PEER_FD);
return;
case DEV_DISCONNECT_AFTER:
msg_enqueue(&peer->peer_out, msg);
flush_peer_out(peer);
dev_sabotage_fd(PEER_FD);
return;
case DEV_DISCONNECT_BLACKHOLE:
msg_enqueue(&peer->peer_out, msg);
dev_blackhole_fd(PEER_FD);
return;
case DEV_DISCONNECT_NORMAL:
break;
}
#endif
msg_enqueue(&peer->peer_out, msg);
}
static void gossip_in(struct peer *peer, const u8 *msg)
{
u8 *gossip;
u64 gossip_index;
if (!fromwire_gossip_send_gossip(msg, msg, &gossip_index, &gossip))
status_failed(STATUS_FAIL_GOSSIP_IO,
"Got bad message from gossipd: %s",
tal_hex(msg, msg));
/* Zero is a special index meaning this is unindexed gossip. */
if (gossip_index != 0)
peer->gossip_index = gossip_index;
if (is_msg_for_gossipd(gossip))
enqueue_peer_msg(peer, gossip);
else if (fromwire_peektype(gossip) == WIRE_ERROR) {
struct channel_id channel_id;
char *what = sanitize_error(msg, msg, &channel_id);
peer_failed(&peer->cs, peer->gossip_index, &channel_id,
"gossipd said: %s", what);
} else
status_failed(STATUS_FAIL_GOSSIP_IO,
"Got bad message type %s from gossipd: %s",
wire_type_name(fromwire_peektype(gossip)),
tal_hex(msg, msg));
}
/* Send a temporary `channel_announcement` and `channel_update`. These
* are unsigned and mainly used to tell gossip about the channel
* before we have reached the `announcement_depth`, not being signed
* means they will not be relayed, but we can already rely on them for
* our own outgoing payments */
static void send_temporary_announcement(struct peer *peer)
{
u8 *msg;
/* If we are supposed to send a real announcement, don't do a
* dummy one here, hence the check for announce_depth. */
if (peer->announce_depth_reached || !peer->funding_locked[LOCAL] ||
!peer->funding_locked[REMOTE])
return;
msg = towire_gossip_local_add_channel(
NULL, &peer->short_channel_ids[LOCAL], &peer->chain_hash,
&peer->node_ids[REMOTE], peer->cltv_delta,
peer->conf[REMOTE].htlc_minimum_msat, peer->fee_base,
peer->fee_per_satoshi);
wire_sync_write(GOSSIP_FD, take(msg));
}
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;
u8 *msg, *ca, *req;
/* BOLT #7:
*
* If sent, `announcement_signatures` messages MUST NOT be sent until
* `funding_locked` has been sent and the funding transaction has
* at least 6 confirmations.
*/
/* Actually defer a bit further until both ends have signaled */
if (!peer->announce_depth_reached || !peer->funding_locked[LOCAL] ||
!peer->funding_locked[REMOTE])
return;
status_trace("Exchanging announcement signatures.");
ca = create_channel_announcement(tmpctx, peer);
req = towire_hsm_cannouncement_sig_req(
tmpctx, &peer->channel->funding_pubkey[LOCAL], ca);
if (!wire_sync_write(HSM_FD, req))
status_failed(STATUS_FAIL_HSM_IO,
"Writing cannouncement_sig_req: %s",
strerror(errno));
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg || !fromwire_hsm_cannouncement_sig_reply(msg,
&peer->announcement_node_sigs[LOCAL]))
status_failed(STATUS_FAIL_HSM_IO,
"Reading cannouncement_sig_resp: %s",
strerror(errno));
/* Double-check that HSM gave a valid signature. */
sha256_double(&hash, ca + offset, tal_len(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 signature");
}
/* TODO(cdecker) Move this to the HSM once we store the
* funding_privkey there */
sign_hash(&peer->our_secrets.funding_privkey, &hash,
&peer->announcement_bitcoin_sigs[LOCAL]);
peer->have_sigs[LOCAL] = true;
billboard_update(peer);
msg = towire_announcement_signatures(
NULL, &peer->channel_id, &peer->short_channel_ids[LOCAL],
&peer->announcement_node_sigs[LOCAL],
&peer->announcement_bitcoin_sigs[LOCAL]);
enqueue_peer_msg(peer, take(msg));
}
static u8 *create_channel_update(const tal_t *ctx,
struct peer *peer, bool disabled)
{
u32 timestamp = time_now().ts.tv_sec;
u16 flags;
u8 *cupdate, *msg;
/* Identical timestamps will be ignored. */
if (timestamp <= peer->last_update_timestamp)
timestamp = peer->last_update_timestamp + 1;
peer->last_update_timestamp = timestamp;
/* Set the signature to empty so that valgrind doesn't complain */
secp256k1_ecdsa_signature *sig =
talz(tmpctx, secp256k1_ecdsa_signature);
flags = peer->channel_direction | (disabled << 1);
cupdate = towire_channel_update(
tmpctx, sig, &peer->chain_hash,
&peer->short_channel_ids[LOCAL], timestamp, flags,
peer->cltv_delta, peer->conf[REMOTE].htlc_minimum_msat,
peer->fee_base, peer->fee_per_satoshi);
msg = towire_hsm_cupdate_sig_req(tmpctx, cupdate);
if (!wire_sync_write(HSM_FD, msg))
status_failed(STATUS_FAIL_HSM_IO,
"Writing cupdate_sig_req: %s",
strerror(errno));
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg || !fromwire_hsm_cupdate_sig_reply(ctx, msg, &cupdate))
status_failed(STATUS_FAIL_HSM_IO,
"Reading cupdate_sig_req: %s",
strerror(errno));
return cupdate;
}
/* 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;
}
static void handle_peer_funding_locked(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
/* BOLT #2:
*
* On reconnection, a node MUST ignore a redundant `funding_locked` if
* it receives one.
*/
if (peer->funding_locked[REMOTE])
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->gossip_index,
&peer->channel_id,
"Bad funding_locked %s", tal_hex(msg, msg));
if (!structeq(&chanid, &peer->channel_id))
peer_failed(&peer->cs, peer->gossip_index,
&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)));
if (peer->funding_locked[LOCAL]) {
wire_sync_write(MASTER_FD,
take(towire_channel_normal_operation(NULL)));
}
billboard_update(peer);
/* Send temporary or final announcements */
send_temporary_announcement(peer);
send_announcement_signatures(peer);
}
/* 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 (!structeq(&peer->short_channel_ids[LOCAL],
&peer->short_channel_ids[REMOTE]))
peer_failed(&peer->cs, peer->gossip_index,
&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, *cupdate;
check_short_ids_match(peer);
cannounce = create_channel_announcement(tmpctx, peer);
cupdate = create_channel_update(tmpctx, peer, false);
wire_sync_write(GOSSIP_FD, cannounce);
wire_sync_write(GOSSIP_FD, cupdate);
}
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->gossip_index,
&peer->channel_id,
"Bad announcement_signatures %s",
tal_hex(msg, msg));
/* Make sure we agree on the channel ids */
if (!structeq(&chanid, &peer->channel_id)) {
peer_failed(&peer->cs, peer->gossip_index,
&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);
/* We have the remote sigs, do we have the local ones as well? */
if (peer->funding_locked[LOCAL] && peer->have_sigs[LOCAL])
announce_channel(peer);
}
static bool get_shared_secret(const struct htlc *htlc,
struct secret *shared_secret)
{
struct pubkey ephemeral;
struct onionpacket *op;
u8 *msg;
/* We unwrap the onion now. */
op = parse_onionpacket(tmpctx, htlc->routing, TOTAL_PACKET_SIZE);
if (!op) {
/* Return an invalid shared secret. */
memset(shared_secret, 0, sizeof(*shared_secret));
return false;
}
/* Because wire takes struct pubkey. */
ephemeral.pubkey = op->ephemeralkey;
msg = towire_hsm_ecdh_req(tmpctx, &ephemeral);
if (!wire_sync_write(HSM_FD, msg))
status_failed(STATUS_FAIL_HSM_IO, "Writing ecdh req");
msg = wire_sync_read(tmpctx, HSM_FD);
/* Gives all-zero shares_secret if it was invalid. */
if (!msg || !fromwire_hsm_ecdh_resp(msg, shared_secret))
status_failed(STATUS_FAIL_HSM_IO, "Reading ecdh response");
return !memeqzero(shared_secret, sizeof(*shared_secret));
}
static void handle_peer_add_htlc(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u64 id;
u64 amount_msat;
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_msat,
&payment_hash, &cltv_expiry,
onion_routing_packet))
peer_failed(&peer->cs,
peer->gossip_index,
&peer->channel_id,
"Bad peer_add_htlc %s", tal_hex(msg, msg));
add_err = channel_add_htlc(peer->channel, REMOTE, id, amount_msat,
cltv_expiry, &payment_hash,
onion_routing_packet, &htlc);
if (add_err != CHANNEL_ERR_ADD_OK)
peer_failed(&peer->cs,
peer->gossip_index,
&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 = tal(htlc, struct secret);
get_shared_secret(htlc, htlc->shared_secret);
}
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->gossip_index,
&peer->channel_id,
"Bad update_fee %s", tal_hex(msg, msg));
}
/* BOLT #2:
*
* A receiving node MUST fail the channel if the sender is not
* responsible for paying the bitcoin fee.
*/
if (peer->channel->funder != REMOTE)
peer_failed(&peer->cs,
peer->gossip_index,
&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 SHOULD fail the channel if the `update_fee` is too
* low for timely processing, or unreasonably large.
*/
if (feerate < peer->feerate_min || feerate > peer->feerate_max)
peer_failed(&peer->cs,
peer->gossip_index,
&peer->channel_id,
"update_fee %u outside range %u-%u",
feerate, peer->feerate_min, peer->feerate_max);
/* BOLT #2:
*
* A receiving node SHOULD fail the channel if the sender cannot
* afford the new fee rate on the receiving node's current commitment
* transaction, but it MAY delay this check until the `update_fee` is
* committed.
*/
if (!channel_update_feerate(peer->channel, feerate))
peer_failed(&peer->cs,
peer->gossip_index,
&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 secp256k1_ecdsa_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 node MUST NOT send a `shutdown` if there are updates pending on
* the receiving node's commitment transaction.
*/
/* 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 */
msg = create_channel_update(NULL, peer, true);
wire_sync_write(GOSSIP_FD, msg);
enqueue_peer_msg(peer, take(msg));
msg = towire_shutdown(NULL, &peer->channel_id, peer->final_scriptpubkey);
enqueue_peer_msg(peer, 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_wire_type replytype)
{
return wait_sync_reply(ctx, msg, replytype,
GOSSIP_FD, &peer->from_gossipd, "gossipd");
}
static struct commit_sigs *calc_commitsigs(const tal_t *ctx,
const struct peer *peer,
u64 commit_index)
{
size_t i;
struct bitcoin_tx **txs;
const u8 **wscripts;
const struct htlc **htlc_map;
struct pubkey local_htlckey;
struct privkey local_htlcsecretkey;
struct commit_sigs *commit_sigs = tal(ctx, struct commit_sigs);
if (!derive_simple_privkey(&peer->our_secrets.htlc_basepoint_secret,
&peer->channel->basepoints[LOCAL].htlc,
&peer->remote_per_commit,
&local_htlcsecretkey))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Deriving local_htlcsecretkey");
if (!derive_simple_key(&peer->channel->basepoints[LOCAL].htlc,
&peer->remote_per_commit,
&local_htlckey))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Deriving local_htlckey");
status_trace("Derived key %s from basepoint %s, point %s",
type_to_string(tmpctx, struct pubkey, &local_htlckey),
type_to_string(tmpctx, struct pubkey,
&peer->channel->basepoints[LOCAL].htlc),
type_to_string(tmpctx, struct pubkey,
&peer->remote_per_commit));
txs = channel_txs(tmpctx, &htlc_map, &wscripts, peer->channel,
&peer->remote_per_commit,
commit_index,
REMOTE);
sign_tx_input(txs[0], 0, NULL,
wscripts[0],
&peer->our_secrets.funding_privkey,
&peer->channel->funding_pubkey[LOCAL],
&commit_sigs->commit_sig);
status_trace("Creating commit_sig signature %"PRIu64" %s for tx %s wscript %s key %s",
commit_index,
type_to_string(tmpctx, secp256k1_ecdsa_signature,
&commit_sigs->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");
/* BOLT #2:
*
* A node MUST include one `htlc_signature` for every HTLC transaction
* corresponding to BIP69 lexicographic ordering of the commitment
* transaction.
*/
commit_sigs->htlc_sigs = tal_arr(commit_sigs, secp256k1_ecdsa_signature,
tal_count(txs) - 1);
for (i = 0; i < tal_count(commit_sigs->htlc_sigs); i++) {
sign_tx_input(txs[1 + i], 0,
NULL,
wscripts[1 + i],
&local_htlcsecretkey, &local_htlckey,
&commit_sigs->htlc_sigs[i]);
status_trace("Creating HTLC signature %s for tx %s wscript %s key %s",
type_to_string(tmpctx, secp256k1_ecdsa_signature,
&commit_sigs->htlc_sigs[i]),
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],
&local_htlckey,
&commit_sigs->htlc_sigs[i]));
}
return commit_sigs;
}
static void send_commit(struct peer *peer)
{
u8 *msg;
const struct htlc **changed_htlcs;
#if DEVELOPER
/* Hack to suppress all commit sends if dev_disconnect says to */
if (dev_suppress_commit) {
peer->commit_timer = NULL;
return;
}
#endif
/* FIXME: Document this requirement in BOLT 2! */
/* We can't send two commits in a row. */
if (peer->revocations_received != peer->next_index[REMOTE] - 1) {
assert(peer->revocations_received
== peer->next_index[REMOTE] - 2);
peer->commit_timer_attempts++;
/* Only report this in extreme cases */
if (peer->commit_timer_attempts % 100 == 0)
status_trace("Can't send commit:"
" waiting for revoke_and_ack with %"
PRIu64" attempts",
peer->commit_timer_attempts);
/* Mark this as done and try again. */
peer->commit_timer = NULL;
start_commit_timer(peer);
return;
}
/* BOLT #2:
*
* - if no HTLCs remain in either commitment transaction:
* - MUST NOT send any `update` message after a `shutdown`.
*/
if (peer->shutdown_sent[LOCAL] && !num_channel_htlcs(peer->channel)) {
status_trace("Can't send commit: final shutdown phase");
peer->commit_timer = NULL;
return;
}
/* If we wanted to update fees, do it now. */
if (peer->channel->funder == LOCAL
&& peer->desired_feerate != channel_feerate(peer->channel, REMOTE)) {
u8 *msg;
u32 feerate, max = approx_max_feerate(peer->channel);
feerate = peer->desired_feerate;
/* FIXME: We should avoid adding HTLCs until we can meet this
* feerate! */
if (feerate > max)
feerate = max;
if (!channel_update_feerate(peer->channel, feerate))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not afford feerate %u"
" (vs max %u)",
feerate, max);
msg = towire_update_fee(NULL, &peer->channel_id, feerate);
enqueue_peer_msg(peer, take(msg));
}
/* BOLT #2:
*
* A node MUST NOT send a `commitment_signed` message which does not
* include any updates.
*/
changed_htlcs = tal_arr(tmpctx, const struct htlc *, 0);
if (!channel_sending_commit(peer->channel, &changed_htlcs)) {
status_trace("Can't send commit: nothing to send");
/* Covers the case where we've just been told to shutdown. */
maybe_send_shutdown(peer);
peer->commit_timer = NULL;
return;
}
peer->next_commit_sigs = calc_commitsigs(peer, peer,
peer->next_index[REMOTE]);
status_trace("Telling master we're about to commit...");