forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channeld.c
4104 lines (3620 loc) · 126 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 channel_ready to shutdown_complete.
*
* We're fairly synchronous: our main loop looks for 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 "config.h"
#include <ccan/asort/asort.h>
#include <ccan/cast/cast.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <channeld/channeld.h>
#include <channeld/channeld_wiregen.h>
#include <channeld/full_channel.h>
#include <channeld/watchtower.h>
#include <common/billboard.h>
#include <common/ecdh_hsmd.h>
#include <common/gossip_store.h>
#include <common/key_derive.h>
#include <common/memleak.h>
#include <common/msg_queue.h>
#include <common/onionreply.h>
#include <common/peer_billboard.h>
#include <common/peer_failed.h>
#include <common/peer_io.h>
#include <common/per_peer_state.h>
#include <common/private_channel_announcement.h>
#include <common/read_peer_msg.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/timeout.h>
#include <common/type_to_string.h>
#include <common/wire_error.h>
#include <errno.h>
#include <fcntl.h>
#include <gossipd/gossip_store_wiregen.h>
#include <gossipd/gossipd_peerd_wiregen.h>
#include <hsmd/hsmd_wiregen.h>
#include <wally_bip32.h>
#include <wire/peer_wire.h>
#include <wire/wire_sync.h>
/* stdin == requests, 3 == peer, 4 = HSM */
#define MASTER_FD STDIN_FILENO
#define HSM_FD 4
struct peer {
struct per_peer_state *pps;
bool channel_ready[NUM_SIDES];
u64 next_index[NUM_SIDES];
/* Features peer supports. */
u8 *their_features;
/* Features we support. */
struct feature_set *our_features;
/* Tolerable amounts for feerate (only relevant for fundee). */
u32 feerate_min, feerate_max;
/* Feerate to be used when creating penalty transactions. */
u32 feerate_penalty;
/* 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 channel_id channel_id;
struct channel *channel;
/* Messages from master: we queue them since we might be
* waiting for a specific reply. */
struct msg_queue *from_master;
struct timers timers;
struct oneshot *commit_timer;
u64 commit_timer_attempts;
u32 commit_msec;
/* The feerate we want. */
u32 desired_feerate;
/* Current blockheight */
u32 our_blockheight;
/* Announcement related information */
struct node_id 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;
/* We only really know these because we're the ones who create
* the channel_updates. */
u32 fee_base;
u32 fee_per_satoshi;
/* Note: the real min constraint is channel->config[REMOTE].htlc_minimum:
* they could kill the channel if we violate that! */
struct amount_msat htlc_minimum_msat, htlc_maximum_msat;
/* The scriptpubkey to use for shutting down. */
u32 *final_index;
struct ext_key *final_ext_key;
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];
/* If master told us to send wrong_funding */
struct bitcoin_outpoint *shutdown_wrong_funding;
#if EXPERIMENTAL_FEATURES
/* Do we want quiescence? */
bool stfu;
/* Which side is considered the initiator? */
enum side stfu_initiator;
/* Has stfu been sent by each side? */
bool stfu_sent[NUM_SIDES];
/* Updates master asked, which we've deferred while quiescing */
struct msg_queue *update_queue;
#endif
#if DEVELOPER
/* If set, don't fire commit counter when this hits 0 */
u32 *dev_disable_commit;
/* If set, send channel_announcement after 1 second, not 30 */
bool dev_fast_gossip;
#endif
/* 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;
/* Additional confirmations need for local lockin. */
u32 depth_togo;
/* Non-empty if they specified a fixed shutdown script */
u8 *remote_upfront_shutdown_script;
/* Empty commitments. Spec violation, but a minor one. */
u64 last_empty_commitment;
/* Penalty bases for this channel / peer. */
struct penalty_base **pbases;
/* We allow a 'tx-sigs' message between reconnect + channel_ready */
bool tx_sigs_allowed;
/* Have we announced the real scid with a
* local_channel_announcement? This can be different from the
* `channel_local_active` flag in case we are using zeroconf,
* in which case we'll have announced the channels with the
* two aliases (LOCAL and REMOTE) but not with the real scid
* just yet. If we get a funding depth change, with a scid,
* and the two flags not equal we know we have to announce the
* channel with the real scid. */
bool gossip_scid_announced;
/* Most recent channel_update message. */
u8 *channel_update;
};
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 *update = billboard_message(tmpctx, peer->channel_ready,
peer->have_sigs,
peer->shutdown_sent,
peer->depth_togo,
num_channel_htlcs(peer->channel));
peer_billboard(false, update);
}
const u8 *hsm_req(const tal_t *ctx, const u8 *req TAKES)
{
u8 *msg;
/* hsmd goes away at shutdown. That's OK. */
if (!wire_sync_write(HSM_FD, req))
exit(0);
msg = wire_sync_read(ctx, HSM_FD);
if (!msg)
exit(0);
return msg;
}
#if EXPERIMENTAL_FEATURES
static void maybe_send_stfu(struct peer *peer)
{
if (!peer->stfu)
return;
if (!peer->stfu_sent[LOCAL] && !pending_updates(peer->channel, LOCAL, false)) {
u8 *msg = towire_stfu(NULL, &peer->channel_id,
peer->stfu_initiator == LOCAL);
peer_write(peer->pps, take(msg));
peer->stfu_sent[LOCAL] = true;
}
if (peer->stfu_sent[LOCAL] && peer->stfu_sent[REMOTE]) {
status_unusual("STFU complete: we are quiescent");
wire_sync_write(MASTER_FD,
towire_channeld_dev_quiesce_reply(tmpctx));
}
}
static void handle_stfu(struct peer *peer, const u8 *stfu)
{
struct channel_id channel_id;
u8 remote_initiated;
if (!fromwire_stfu(stfu, &channel_id, &remote_initiated))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad stfu %s", tal_hex(peer, stfu));
if (!channel_id_eq(&channel_id, &peer->channel_id)) {
peer_failed_err(peer->pps, &channel_id,
"Wrong stfu channel_id: expected %s, got %s",
type_to_string(tmpctx, struct channel_id,
&peer->channel_id),
type_to_string(tmpctx, struct channel_id,
&channel_id));
}
/* Sanity check */
if (pending_updates(peer->channel, REMOTE, false))
peer_failed_warn(peer->pps, &peer->channel_id,
"STFU but you still have updates pending?");
if (!peer->stfu) {
peer->stfu = true;
if (!remote_initiated)
peer_failed_warn(peer->pps, &peer->channel_id,
"Unsolicited STFU but you said"
" you didn't initiate?");
peer->stfu_initiator = REMOTE;
} else {
/* BOLT-quiescent #2:
*
* If both sides send `stfu` simultaneously, they will both
* set `initiator` to `1`, in which case the "initiator" is
* arbitrarily considered to be the channel funder (the sender
* of `open_channel`).
*/
if (remote_initiated)
peer->stfu_initiator = peer->channel->opener;
}
/* BOLT-quiescent #2:
* The receiver of `stfu`:
* - if it has sent `stfu` then:
* - MUST now consider the channel to be quiescent
* - otherwise:
* - SHOULD NOT send any more update messages.
* - MUST reply with `stfu` once it can do so.
*/
peer->stfu_sent[REMOTE] = true;
maybe_send_stfu(peer);
}
/* Returns true if we queued this for later handling (steals if true) */
static bool handle_master_request_later(struct peer *peer, const u8 *msg)
{
if (peer->stfu) {
msg_enqueue(peer->update_queue, take(msg));
return true;
}
return false;
}
/* Compare, with false if either is NULL */
static bool match_type(const u8 *t1, const u8 *t2)
{
/* Missing fields are possible. */
if (!t1 || !t2)
return false;
return featurebits_eq(t1, t2);
}
static void set_channel_type(struct channel *channel, const u8 *type)
{
const struct channel_type *cur = channel->type;
if (featurebits_eq(cur->features, type))
return;
/* We only allow one upgrade at the moment, so that's it. */
assert(!channel_has(channel, OPT_STATIC_REMOTEKEY));
assert(feature_offered(type, OPT_STATIC_REMOTEKEY));
/* Do upgrade, tell master. */
tal_free(channel->type);
channel->type = channel_type_from(channel, type);
status_unusual("Upgraded channel to [%s]",
fmt_featurebits(tmpctx, type));
wire_sync_write(MASTER_FD,
take(towire_channeld_upgraded(NULL, channel->type)));
}
#else /* !EXPERIMENTAL_FEATURES */
static bool handle_master_request_later(struct peer *peer, const u8 *msg)
{
return false;
}
static void maybe_send_stfu(struct peer *peer)
{
}
#endif
/* Tell gossipd to create channel_update (then it goes into
* gossip_store, then streams out to peers, or sends it directly if
* it's a private channel) */
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_channeld_local_channel_update(NULL,
&peer->short_channel_ids[LOCAL],
disable_flag
== ROUTING_FLAGS_DISABLED,
peer->cltv_delta,
peer->htlc_minimum_msat,
peer->fee_base,
peer->fee_per_satoshi,
peer->htlc_maximum_msat);
wire_sync_write(MASTER_FD, take(msg));
}
/* Tell gossipd and the other side what parameters we expect should
* they route through us */
static void send_channel_initial_update(struct peer *peer)
{
send_channel_update(peer, 0);
}
/**
* 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;
const u8 *annfeatures = get_agreed_channelfeatures(tmpctx,
peer->our_features,
peer->their_features);
/* Tell lightningd to tell gossipd about local channel. */
msg = towire_channeld_local_private_channel(NULL,
peer->channel->funding_sats,
annfeatures);
wire_sync_write(MASTER_FD, take(msg));
/* Under CI, because blocks come so fast, we often find that the
* peer sends its first channel_update before the above message has
* reached it. */
notleak(new_reltimer(&peer->timers, peer,
time_from_sec(5),
send_channel_initial_update, peer));
}
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;
struct pubkey mykey;
status_debug("Exchanging announcement signatures.");
ca = create_channel_announcement(tmpctx, peer);
req = towire_hsmd_cannouncement_sig_req(tmpctx, ca);
msg = hsm_req(tmpctx, req);
if (!fromwire_hsmd_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 (!pubkey_from_node_id(&mykey, &peer->node_ids[LOCAL]))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not convert my id '%s' to pubkey",
type_to_string(tmpctx, struct node_id,
&peer->node_ids[LOCAL]));
if (!check_signed_hash(&hash, &peer->announcement_node_sigs[LOCAL],
&mykey)) {
/* 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]);
peer_write(peer->pps, 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
= get_agreed_channelfeatures(tmpctx, peer->our_features,
peer->their_features);
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,
&chainparams->genesis_blockhash,
&peer->short_channel_ids[LOCAL],
&peer->node_ids[first],
&peer->node_ids[second],
&peer->channel->funding_pubkey[first],
&peer->channel->funding_pubkey[second]);
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_warn(peer->pps, &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;
cannounce = create_channel_announcement(tmpctx, peer);
wire_sync_write(MASTER_FD,
take(towire_channeld_local_channel_announcement(NULL,
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->channel_ready[LOCAL] || !peer->channel_ready[REMOTE])
return;
if (!peer->channel_local_active) {
peer->channel_local_active = true;
make_channel_local_active(peer);
} else if(!peer->gossip_scid_announced) {
/* So we know a short_channel_id, i.e., a point on
* chain, but haven't added it to our local view of
* the gossip yet. We need to add it now (and once
* only), so our `channel_update` we'll send a couple
* of lines down has something to attach to. */
peer->gossip_scid_announced = 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 `channel_ready`
* 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 `channel_ready`
* has been sent and received AND the funding transaction has at least six confirmations.
*/
if (peer->announce_depth_reached && !peer->have_sigs[LOCAL]) {
/* When we reenable the channel, we will also send the announcement to remote peer, and
* receive the remote announcement reply. But we will rebuild the channel with announcement
* from the DB directly, other than waiting for the remote announcement reply.
*/
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]) {
check_short_ids_match(peer);
/* After making sure short_channel_ids match, we can send remote
* announcement to MASTER. */
wire_sync_write(MASTER_FD,
take(towire_channeld_got_announcement(NULL,
&peer->announcement_node_sigs[REMOTE],
&peer->announcement_bitcoin_sigs[REMOTE])));
/* Give other nodes time to notice new block. */
notleak(new_reltimer(&peer->timers, peer,
time_from_sec(GOSSIP_ANNOUNCE_DELAY(peer->dev_fast_gossip)),
announce_channel, peer));
}
}
static void handle_peer_channel_ready(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
struct tlv_channel_ready_tlvs *tlvs;
/* BOLT #2:
*
* A node:
*...
* - upon reconnection:
* - MUST ignore any redundant `channel_ready` it receives.
*/
if (peer->channel_ready[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_channel_ready(msg, msg, &chanid,
&peer->remote_per_commit, &tlvs))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad channel_ready %s", tal_hex(msg, msg));
if (!channel_id_eq(&chanid, &peer->channel_id))
peer_failed_err(peer->pps, &chanid,
"Wrong channel id in %s (expected %s)",
tal_hex(tmpctx, msg),
type_to_string(msg, struct channel_id,
&peer->channel_id));
peer->tx_sigs_allowed = false;
peer->channel_ready[REMOTE] = true;
if (tlvs->short_channel_id != NULL) {
status_debug(
"Peer told us that they'll use alias=%s for this channel",
type_to_string(tmpctx, struct short_channel_id,
tlvs->short_channel_id));
peer->short_channel_ids[REMOTE] = *tlvs->short_channel_id;
}
wire_sync_write(MASTER_FD,
take(towire_channeld_got_channel_ready(
NULL, &peer->remote_per_commit, tlvs->short_channel_id)));
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_warn(peer->pps, &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_err(peer->pps, &chanid,
"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 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(ROUTING_INFO_SIZE)];
enum channel_add_err add_err;
struct htlc *htlc;
#if EXPERIMENTAL_FEATURES
struct tlv_update_add_tlvs *tlvs;
#endif
struct pubkey *blinding = NULL;
if (!fromwire_update_add_htlc
#if EXPERIMENTAL_FEATURES
(msg, msg, &channel_id, &id, &amount,
&payment_hash, &cltv_expiry,
onion_routing_packet, &tlvs)
#else
(msg, &channel_id, &id, &amount,
&payment_hash, &cltv_expiry,
onion_routing_packet)
#endif
)
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad peer_add_htlc %s", tal_hex(msg, msg));
#if EXPERIMENTAL_FEATURES
blinding = tlvs->blinding;
#endif
add_err = channel_add_htlc(peer->channel, REMOTE, id, amount,
cltv_expiry, &payment_hash,
onion_routing_packet, blinding, &htlc, NULL,
/* We don't immediately fail incoming htlcs,
* instead we wait and fail them after
* they've been committed */
false);
if (add_err != CHANNEL_ERR_ADD_OK)
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad peer_add_htlc: %s",
channel_add_err_name(add_err));
}
/* We don't get upset if they're outside the range, as long as they're
* improving (or at least, not getting worse!). */
static bool feerate_same_or_better(const struct channel *channel,
u32 feerate, u32 feerate_min, u32 feerate_max)
{
u32 current = channel_feerate(channel, LOCAL);
/* Too low? But is it going upwards? */
if (feerate < feerate_min)
return feerate >= current;
if (feerate > feerate_max)
return feerate <= current;
return true;
}
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_warn(peer->pps, &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 send a `warning` and close the connection, or send an
* `error` and fail the channel.
*/
if (peer->channel->opener != REMOTE)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee from non-opener?");
status_debug("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:
* - MUST send a `warning` and close the connection, or send an
* `error` and fail the channel.
*/
if (!feerate_same_or_better(peer->channel, feerate,
peer->feerate_min, peer->feerate_max))
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee %u outside range %u-%u"
" (currently %u)",
feerate,
peer->feerate_min, peer->feerate_max,
channel_feerate(peer->channel, LOCAL));
/* BOLT #2:
*
* - if the sender cannot afford the new fee rate on the receiving
* node's current commitment transaction:
* - SHOULD send a `warning` and close the connection, or send an
* `error` and fail the channel.
* - but MAY delay this check until the `update_fee` is committed.
*/
if (!channel_update_feerate(peer->channel, feerate))
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee %u unaffordable",
feerate);
status_debug("peer updated fee to %u", feerate);
}
static void handle_peer_blockheight_change(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u32 blockheight, current;
if (!fromwire_update_blockheight(msg, &channel_id, &blockheight))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad update_blockheight %s",
tal_hex(msg, msg));
/* BOLT- #2:
* A receiving node:
* ...
* - if the sender is not the initiator:
* - MUST fail the channel.
*/
if (peer->channel->opener != REMOTE)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_blockheight from non-opener?");
current = get_blockheight(peer->channel->blockheight_states,
peer->channel->opener, LOCAL);
status_debug("update_blockheight %u. last update height %u,"
" our current height %u",
blockheight, current, peer->our_blockheight);
/* BOLT- #2:
* A receiving node:
* - if the `update_blockheight` is less than the last
* received `blockheight`:
* - SHOULD fail the channel.
* ...
* - if `blockheight` is more than 1008 blocks behind
* the current blockheight:
* - SHOULD fail the channel
*/
/* Overflow check */
if (blockheight + 1008 < blockheight)
peer_failed_warn(peer->pps, &peer->channel_id,
"blockheight + 1008 overflow (%u)",
blockheight);
/* If they're behind the last one they sent, we just warn and
* reconnect, as they might be catching up */
/* FIXME: track for how long they send backwards blockheight? */
if (blockheight < current)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_blockheight %u older than previous %u",
blockheight, current);
/* BOLT- #2:
* A receiving node:
* ...
* - if `blockheight` is more than 1008 blocks behind
* the current blockheight:
* - SHOULD fail the channel
*/
assert(blockheight < blockheight + 1008);
if (blockheight + 1008 < peer->our_blockheight)
peer_failed_err(peer->pps, &peer->channel_id,
"update_blockheight %u outside"
" permissible range", blockheight);
channel_update_blockheight(peer->channel, blockheight);
status_debug("peer updated blockheight to %u", blockheight);
}
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,
struct penalty_base *pbase,
const struct fee_states *fee_states,
const struct height_states *blockheight_states,
const struct htlc **changed_htlcs,
const struct bitcoin_signature *commit_sig,
const struct bitcoin_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_channeld_sending_commitsig(ctx, remote_commit_index,
pbase, fee_states,
blockheight_states, 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;
struct tlv_shutdown_tlvs *tlvs;
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);
if (peer->shutdown_wrong_funding) {
tlvs = tlv_shutdown_tlvs_new(tmpctx);
tlvs->wrong_funding
= tal(tlvs, struct tlv_shutdown_tlvs_wrong_funding);
tlvs->wrong_funding->txid = peer->shutdown_wrong_funding->txid;
tlvs->wrong_funding->outnum = peer->shutdown_wrong_funding->n;
} else
tlvs = NULL;
msg = towire_shutdown(NULL, &peer->channel_id, peer->final_scriptpubkey,
tlvs);
peer_write(peer->pps, take(msg));
peer->send_shutdown = false;
peer->shutdown_sent[LOCAL] = true;
billboard_update(peer);
}
static void send_shutdown_complete(struct peer *peer)
{
/* Now we can tell master shutdown is complete. */
wire_sync_write(MASTER_FD,
take(towire_channeld_shutdown_complete(NULL)));
per_peer_state_fdpass_send(MASTER_FD, peer->pps);
close(MASTER_FD);
}
/* This queues other traffic from the fd until we get reply. */
static u8 *master_wait_sync_reply(const tal_t *ctx,
struct peer *peer,
const u8 *msg,
int replytype)
{
u8 *reply;
status_debug("Sending master %u", fromwire_peektype(msg));
if (!wire_sync_write(MASTER_FD, msg))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not set sync write to master: %s",
strerror(errno));
status_debug("... , awaiting %u", replytype);
for (;;) {
int type;
reply = wire_sync_read(ctx, MASTER_FD);
if (!reply)
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not set sync read from master: %s",
strerror(errno));
type = fromwire_peektype(reply);
if (type == replytype) {
status_debug("Got it!");
break;
}
status_debug("Nope, got %u instead", type);
msg_enqueue(peer->from_master, take(reply));
}
return reply;
}
/* Collect the htlcs for call to hsmd. */
static struct simple_htlc **collect_htlcs(const tal_t *ctx, const struct htlc **htlc_map)