-
Notifications
You must be signed in to change notification settings - Fork 990
Expand file tree
/
Copy pathmultiplex.c
More file actions
1767 lines (1523 loc) · 49.9 KB
/
multiplex.c
File metadata and controls
1767 lines (1523 loc) · 49.9 KB
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
/*~ This contains all the code to shuffle data between socket to the peer
* itself, and the subdaemons. */
#include "config.h"
#include <ccan/tal/str/str.h>
#include <common/cryptomsg.h>
#include <common/daemon_conn.h>
#include <common/dev_disconnect.h>
#include <common/gossmap.h>
#include <common/memleak.h>
#include <common/ping.h>
#include <common/status.h>
#include <common/timeout.h>
#include <common/utils.h>
#include <common/wire_error.h>
#include <connectd/connectd.h>
#include <connectd/connectd_gossipd_wiregen.h>
#include <connectd/connectd_wiregen.h>
#include <connectd/gossip_rcvd_filter.h>
#include <connectd/multiplex.h>
#include <connectd/onion_message.h>
#include <connectd/queries.h>
#include <errno.h>
#include <inttypes.h>
#include <netinet/in.h>
#include <wire/peer_wire.h>
#include <wire/wire_io.h>
/* Size of write(), to create uniform size packets. */
#define UNIFORM_MESSAGE_SIZE 1460
struct subd {
/* Owner: we are in peer->subds[] */
struct peer *peer;
/* The temporary or permanant channel_id */
struct channel_id channel_id;
/* In passing, we can have a temporary one, too. */
struct channel_id *temporary_channel_id;
/* The opening revocation basepoint, for v2 channel_id. */
struct pubkey *opener_revocation_basepoint;
/* The actual connection to talk to it (NULL if it's not connected yet) */
struct io_conn *conn;
/* Input buffer */
u8 *in;
/* Output buffer */
struct msg_queue *outq;
/* After we've told it to tx_abort, we don't send anything else. */
bool rcvd_tx_abort;
};
/* FIXME: reorder! */
static bool is_urgent(enum peer_wire type);
static void destroy_connected_subd(struct subd *subd);
static struct io_plan *write_to_peer(struct io_conn *peer_conn,
struct peer *peer);
static struct subd *find_subd(struct peer *peer,
const struct channel_id *channel_id)
{
for (size_t i = 0; i < tal_count(peer->subds); i++) {
struct subd *subd = peer->subds[i];
/* Once we sent it tx_abort, we pretend it doesn't exist */
if (subd->rcvd_tx_abort)
continue;
/* Once we see a message using the real channel_id, we
* clear the temporary_channel_id */
if (channel_id_eq(&subd->channel_id, channel_id)) {
subd->temporary_channel_id
= tal_free(subd->temporary_channel_id);
return subd;
}
if (subd->temporary_channel_id
&& channel_id_eq(subd->temporary_channel_id, channel_id)) {
return subd;
}
}
return NULL;
}
/* We try to send the final messages, but if buffer is full and they're
* not reading, we have to give up. */
static void close_peer_io_timeout(struct peer *peer)
{
status_peer_unusual(&peer->id, CI_UNEXPECTED "Peer did not close, forcing close");
io_close(peer->to_peer);
}
static void close_subd_timeout(struct subd *subd)
{
status_peer_broken(&subd->peer->id, "Subd did not close, forcing close");
io_close(subd->conn);
}
static void msg_to_peer_outq(struct peer *peer, const u8 *msg TAKES)
{
if (is_urgent(fromwire_peektype(msg)))
peer->peer_out_urgent++;
msg_enqueue(peer->peer_outq, msg);
}
void inject_peer_msg(struct peer *peer, const u8 *msg TAKES)
{
status_peer_io(LOG_IO_OUT, &peer->id, msg);
msg_to_peer_outq(peer, msg);
}
static void drain_peer(struct peer *peer)
{
assert(tal_count(peer->subds) == 0);
/* You have five seconds to drain. */
peer->draining_state = WRITING_TO_PEER;
status_peer_debug(&peer->id, "disconnect_peer: draining with 5 second timer.");
notleak(new_reltimer(&peer->daemon->timers,
peer->to_peer, time_from_sec(5),
close_peer_io_timeout, peer));
io_wake(peer->peer_outq);
/* We will discard what they send us, but listen so we catch closes */
io_wake(&peer->peer_in);
}
void disconnect_peer(struct peer *peer)
{
peer->draining_state = READING_FROM_SUBDS;
for (size_t i = 0; i < tal_count(peer->subds); i++) {
/* Start timer in case it doesn't close by itself */
if (peer->subds[i]->conn) {
status_peer_debug(&peer->id, "disconnect_peer: setting 5 second timer for subd %zu/%zu.",
i, tal_count(peer->subds));
notleak(new_reltimer(&peer->daemon->timers, peer->subds[i],
time_from_sec(5),
close_subd_timeout, peer->subds[i]));
} else {
/* We told lightningd that peer spoke, but it hasn't returned yet. */
tal_arr_remove(&peer->subds, i);
i--;
}
}
if (tal_count(peer->subds) != 0) {
status_peer_debug(&peer->id, "disconnect_peer: waking %zu subds.",
tal_count(peer->subds));
/* Wake them up so we read again */
io_wake(&peer->subds);
} else {
status_peer_debug(&peer->id, "disconnect_peer: no subds, draining now.");
/* No subds left, start draining peer */
drain_peer(peer);
}
}
static void free_all_subds(struct peer *peer)
{
for (size_t i = 0; i < tal_count(peer->subds); i++) {
/* Once conn exists, subd is a child of the conn. Free conn, free subd. */
if (peer->subds[i]->conn) {
tal_del_destructor(peer->subds[i], destroy_connected_subd);
tal_free(peer->subds[i]->conn);
} else {
/* We told lightningd that peer spoke, but it hasn't returned yet. */
tal_free(peer->subds[i]);
}
}
tal_resize(&peer->subds, 0);
}
/* Send warning, close connection to peer */
static void send_warning(struct peer *peer, const char *fmt, ...)
{
va_list ap;
u8 *msg;
va_start(ap, fmt);
status_vfmt(LOG_UNUSUAL, &peer->id, fmt, ap);
va_end(ap);
va_start(ap, fmt);
msg = towire_warningfmtv(NULL, NULL, fmt, ap);
va_end(ap);
inject_peer_msg(peer, take(msg));
/* Free all the subds immediately */
free_all_subds(peer);
disconnect_peer(peer);
}
/* Kicks off write_to_peer() to look for more gossip to send from store */
static void wake_gossip(struct peer *peer);
static struct oneshot *gossip_stream_timer(struct peer *peer)
{
u32 next;
/* BOLT #7:
*
* A node:
*...
* - SHOULD flush outgoing gossip messages once every 60 seconds,
* independently of the arrival times of the messages.
* - Note: this results in staggered announcements that are unique
* (not duplicated).
*/
/* We shorten this for dev_fast_gossip! */
next = GOSSIP_FLUSH_INTERVAL(peer->daemon->dev_fast_gossip);
return new_reltimer(&peer->daemon->timers,
peer, time_from_sec(next),
wake_gossip, peer);
}
/* Statistically, how many peers to we tell about each channel? */
#define GOSSIP_SPAM_REDUNDANCY 50
/* BOLT #7:
* A node:
* - MUST NOT relay any gossip messages it did not generate itself,
* unless explicitly requested.
*/
/* i.e. the strong implication is that we spam our own gossip aggressively!
* "Look at me!" "Look at me!!!!".
*/
static void spam_new_peer(struct peer *peer, struct gossmap *gossmap)
{
struct gossmap_node *me;
const u8 *msg;
u64 send_threshold;
/* Find ourselves; if no channels, nothing to send */
me = gossmap_find_node(gossmap, &peer->daemon->id);
if (!me)
return;
send_threshold = -1ULL;
/* Just in case we have many peers and not all are connecting or
* some other corner case, send everything to first few. */
if (peer_htable_count(peer->daemon->peers) > GOSSIP_SPAM_REDUNDANCY
&& me->num_chans > GOSSIP_SPAM_REDUNDANCY) {
send_threshold = -1ULL / me->num_chans * GOSSIP_SPAM_REDUNDANCY;
}
for (size_t i = 0; i < me->num_chans; i++) {
struct gossmap_chan *chan = gossmap_nth_chan(gossmap, me, i, NULL);
/* We set this so we'll send a fraction of all our channels */
if (pseudorand_u64() > send_threshold)
continue;
/* Send channel_announce */
msg = gossmap_chan_get_announce(NULL, gossmap, chan);
inject_peer_msg(peer, take(msg));
/* Send both channel_updates (if they exist): both help people
* use our channel, so we care! */
for (int dir = 0; dir < 2; dir++) {
if (!gossmap_chan_set(chan, dir))
continue;
msg = gossmap_chan_get_update(NULL, gossmap, chan, dir);
inject_peer_msg(peer, take(msg));
}
}
/* If we have one, we should send our own node_announcement */
msg = gossmap_node_get_announce(NULL, gossmap, me);
if (msg)
inject_peer_msg(peer, take(msg));
}
void setup_peer_gossip_store(struct peer *peer,
const struct feature_set *our_features,
const u8 *their_features)
{
struct gossmap *gossmap = get_gossmap(peer->daemon);
peer->gs.grf = new_gossip_rcvd_filter(peer);
peer->gs.iter = gossmap_iter_new(peer, gossmap);
peer->gs.bytes_this_second = 0;
peer->gs.bytes_start_time = time_mono();
/* BOLT #7:
*
* A node:
* - MUST NOT relay any gossip messages it did not generate itself,
* unless explicitly requested.
*/
peer->gs.gossip_timer = NULL;
peer->gs.active = false;
spam_new_peer(peer, gossmap);
return;
}
static bool is_urgent(enum peer_wire type)
{
switch (type) {
/* We are happy to batch UPDATE_ADD messages: it's the
* commitment signed which matters. */
case WIRE_UPDATE_ADD_HTLC:
case WIRE_UPDATE_FULFILL_HTLC:
case WIRE_UPDATE_FAIL_HTLC:
case WIRE_UPDATE_FAIL_MALFORMED_HTLC:
case WIRE_UPDATE_FEE:
/* Gossip messages are also non-urgent */
case WIRE_CHANNEL_ANNOUNCEMENT:
case WIRE_NODE_ANNOUNCEMENT:
case WIRE_CHANNEL_UPDATE:
return false;
/* We don't delay for anything else, but we use a switch
* statement to make you think about new cases! */
case WIRE_INIT:
case WIRE_ERROR:
case WIRE_WARNING:
case WIRE_TX_ADD_INPUT:
case WIRE_TX_ADD_OUTPUT:
case WIRE_TX_REMOVE_INPUT:
case WIRE_TX_REMOVE_OUTPUT:
case WIRE_TX_COMPLETE:
case WIRE_TX_ABORT:
case WIRE_TX_SIGNATURES:
case WIRE_OPEN_CHANNEL:
case WIRE_ACCEPT_CHANNEL:
case WIRE_FUNDING_CREATED:
case WIRE_FUNDING_SIGNED:
case WIRE_CHANNEL_READY:
case WIRE_OPEN_CHANNEL2:
case WIRE_ACCEPT_CHANNEL2:
case WIRE_TX_INIT_RBF:
case WIRE_TX_ACK_RBF:
case WIRE_SHUTDOWN:
case WIRE_CLOSING_SIGNED:
case WIRE_CLOSING_COMPLETE:
case WIRE_CLOSING_SIG:
case WIRE_UPDATE_BLOCKHEIGHT:
case WIRE_CHANNEL_REESTABLISH:
case WIRE_ANNOUNCEMENT_SIGNATURES:
case WIRE_QUERY_SHORT_CHANNEL_IDS:
case WIRE_REPLY_SHORT_CHANNEL_IDS_END:
case WIRE_QUERY_CHANNEL_RANGE:
case WIRE_REPLY_CHANNEL_RANGE:
case WIRE_GOSSIP_TIMESTAMP_FILTER:
case WIRE_ONION_MESSAGE:
case WIRE_PEER_STORAGE:
case WIRE_PEER_STORAGE_RETRIEVAL:
case WIRE_STFU:
case WIRE_SPLICE:
case WIRE_SPLICE_ACK:
case WIRE_SPLICE_LOCKED:
case WIRE_PING:
case WIRE_PONG:
case WIRE_PROTOCOL_BATCH_ELEMENT:
case WIRE_START_BATCH:
case WIRE_COMMITMENT_SIGNED:
case WIRE_REVOKE_AND_ACK:
return true;
};
/* plugins can inject other messages. */
return true;
}
/* Process and eat protocol_batch_element messages, encrypt each element message
* and return the encrypted messages as one long byte array. */
static u8 *process_batch_elements(const tal_t *ctx, struct peer *peer, const u8 *msg TAKES)
{
u8 *ret = tal_arr(ctx, u8, 0);
size_t ret_size = 0;
const u8 *cursor = msg;
size_t plen = tal_count(msg);
status_debug("Processing batch elements of %zu bytes. %s", plen,
tal_hex(tmpctx, msg));
do {
u8 *element_bytes;
u16 element_size;
struct channel_id channel_id;
u8 *enc_msg;
if (fromwire_u16(&cursor, &plen) != WIRE_PROTOCOL_BATCH_ELEMENT) {
status_broken("process_batch_elements on msg that is"
" not WIRE_PROTOCOL_BATCH_ELEMENT. %s",
tal_hexstr(tmpctx, cursor, plen));
return tal_free(ret);
}
fromwire_channel_id(&cursor, &plen, &channel_id);
element_size = fromwire_u16(&cursor, &plen);
if (!element_size) {
status_broken("process_batch_elements cannot have zero"
" length elements. %s",
tal_hexstr(tmpctx, cursor, plen));
return tal_free(ret);
}
element_bytes = fromwire_tal_arrn(NULL, &cursor, &plen,
element_size);
if (!element_bytes) {
status_broken("process_batch_elements fromwire_tal_arrn"
" %s",
tal_hexstr(tmpctx, cursor, plen));
return tal_free(ret);
}
status_debug("Processing batch extracted item %s. %s",
peer_wire_name(fromwire_peektype(element_bytes)),
tal_hex(tmpctx, element_bytes));
enc_msg = cryptomsg_encrypt_msg(tmpctx, &peer->cs,
take(element_bytes));
tal_resize(&ret, ret_size + tal_bytelen(enc_msg));
memcpy(&ret[ret_size], enc_msg, tal_bytelen(enc_msg));
ret_size += tal_bytelen(enc_msg);
} while(plen);
tal_free_if_taken(msg);
return ret;
}
/* --dev-disconnect can do magic things: if this returns non-NULL,
free msg and do that */
static struct io_plan *msg_out_dev_disconnect(struct peer *peer, const u8 *msg)
{
int type = fromwire_peektype(msg);
switch (dev_disconnect_out(&peer->id, type)) {
case DEV_DISCONNECT_OUT_BEFORE:
return io_close(peer->to_peer);
case DEV_DISCONNECT_OUT_AFTER:
/* Disallow reads from now on */
peer->dev_read_enabled = false;
free_all_subds(peer);
drain_peer(peer);
return NULL;
case DEV_DISCONNECT_OUT_BLACKHOLE:
/* Disable both reads and writes from now on */
peer->dev_read_enabled = false;
peer->dev_writes_enabled = talz(peer, u32);
return NULL;
case DEV_DISCONNECT_OUT_NORMAL:
return NULL;
case DEV_DISCONNECT_OUT_DROP:
/* Tell them to read again. */
io_wake(&peer->subds);
return msg_queue_wait(peer->to_peer, peer->peer_outq,
write_to_peer, peer);
case DEV_DISCONNECT_OUT_DISABLE_AFTER:
peer->dev_read_enabled = false;
peer->dev_writes_enabled = tal(peer, u32);
*peer->dev_writes_enabled = 1;
return NULL;
}
abort();
}
/* Do we have enough bytes without padding? */
static bool have_full_encrypted_queue(const struct peer *peer)
{
return membuf_num_elems(&peer->encrypted_peer_out) >= UNIFORM_MESSAGE_SIZE;
}
/* Do we have nothing in queue? */
static bool have_empty_encrypted_queue(const struct peer *peer)
{
return membuf_num_elems(&peer->encrypted_peer_out) == 0;
}
/* (Continue) writing the encrypted_peer_out array */
static struct io_plan *write_encrypted_to_peer(struct peer *peer)
{
assert(membuf_num_elems(&peer->encrypted_peer_out) >= UNIFORM_MESSAGE_SIZE);
return io_write_partial(peer->to_peer,
membuf_elems(&peer->encrypted_peer_out),
UNIFORM_MESSAGE_SIZE,
&peer->encrypted_peer_out_sent,
write_to_peer, peer);
}
/* Close the connection if this fails */
static bool encrypt_append(struct peer *peer, const u8 *msg TAKES)
{
int type = fromwire_peektype(msg);
const u8 *enc;
size_t enclen;
/* Special message type directing us to process batch items. */
if (type == WIRE_PROTOCOL_BATCH_ELEMENT) {
enc = process_batch_elements(tmpctx, peer, msg);
if (!enc)
return false;
} else {
enc = cryptomsg_encrypt_msg(tmpctx, &peer->cs, msg);
}
enclen = tal_bytelen(enc);
memcpy(membuf_add(&peer->encrypted_peer_out, enclen),
enc,
enclen);
return true;
}
static void pad_encrypted_queue(struct peer *peer)
{
size_t needed, pingpad;
u8 *ping;
/* BOLT #8:
*
* ```
* +-------------------------------
* |2-byte encrypted message length|
* +-------------------------------
* | 16-byte MAC of the encrypted |
* | message length |
* +-------------------------------
* | |
* | |
* | encrypted Lightning |
* | message |
* | |
* +-------------------------------
* | 16-byte MAC of the |
* | Lightning message |
* +-------------------------------
* ```
*
* The prefixed message length is encoded as a 2-byte big-endian integer,
* for a total maximum packet length of `2 + 16 + 65535 + 16` = `65569` bytes.
*/
assert(membuf_num_elems(&peer->encrypted_peer_out) < UNIFORM_MESSAGE_SIZE);
needed = UNIFORM_MESSAGE_SIZE - membuf_num_elems(&peer->encrypted_peer_out);
/* BOLT #1:
* 1. type: 18 (`ping`)
* 2. data:
* * [`u16`:`num_pong_bytes`]
* * [`u16`:`byteslen`]
* * [`byteslen*byte`:`ignored`]
*/
/* So smallest possible ping is 6 bytes (2 byte type field) */
if (needed < 2 + 16 + 16 + 6)
needed += UNIFORM_MESSAGE_SIZE;
pingpad = needed - (2 + 16 + 16 + 6);
/* Note: we don't bother --dev-disconnect here */
/* BOLT #1:
* A node receiving a `ping` message:
* - if `num_pong_bytes` is less than 65532:
* - MUST respond by sending a `pong` message, with `byteslen` equal to `num_pong_bytes`.
* - otherwise (`num_pong_bytes` is **not** less than 65532):
* - MUST ignore the `ping`.
*/
ping = make_ping(NULL, 65535, pingpad);
if (!encrypt_append(peer, take(ping)))
abort();
assert(have_full_encrypted_queue(peer));
assert(membuf_num_elems(&peer->encrypted_peer_out) % UNIFORM_MESSAGE_SIZE == 0);
}
/* Kicks off write_to_peer() to look for more gossip to send from store */
static void wake_gossip(struct peer *peer)
{
bool flush_gossip_filter = true;
/* With dev-fast-gossip, we clean every 2 seconds, which is too
* fast for our slow tests! So we only call this one time in 5
* actually twice that, as it's not per-peer! */
static int gossip_age_count;
if (peer->daemon->dev_fast_gossip && gossip_age_count++ % 5 != 0)
flush_gossip_filter = false;
/* Don't remember sent per-peer gossip forever. */
if (flush_gossip_filter)
gossip_rcvd_filter_age(peer->gs.grf);
peer->gs.active = !peer->daemon->dev_suppress_gossip;
io_wake(peer->peer_outq);
/* And go again in 60 seconds (from now, now when we finish!) */
peer->gs.gossip_timer = gossip_stream_timer(peer);
}
/* Gossip response or something from gossip store */
static const u8 *maybe_gossip_msg(const tal_t *ctx, struct peer *peer)
{
const u8 *msg;
struct timemono now;
struct gossmap *gossmap;
u32 timestamp;
const u8 **msgs;
/* If it's been over a second, make a fresh start. */
now = time_mono();
if (time_to_sec(timemono_between(now, peer->gs.bytes_start_time)) > 0) {
peer->gs.bytes_start_time = now;
peer->gs.bytes_this_second = 0;
}
/* Sent too much this second? */
if (peer->gs.bytes_this_second > peer->daemon->gossip_stream_limit) {
/* Replace normal timer with a timer after throttle. */
peer->gs.active = false;
tal_free(peer->gs.gossip_timer);
peer->gs.gossip_timer
= new_abstimer(&peer->daemon->timers,
peer,
timemono_add(peer->gs.bytes_start_time,
time_from_sec(1)),
wake_gossip, peer);
return NULL;
}
gossmap = get_gossmap(peer->daemon);
/* This can return more than one. */
msgs = maybe_create_query_responses(tmpctx, peer, gossmap);
if (tal_count(msgs) > 0) {
/* We return the first one for immediate sending, and queue
* others for future. We add all the lengths now though! */
for (size_t i = 0; i < tal_count(msgs); i++) {
peer->gs.bytes_this_second += tal_bytelen(msgs[i]);
status_peer_io(LOG_IO_OUT, &peer->id, msgs[i]);
if (i > 0)
msg_to_peer_outq(peer, take(msgs[i]));
}
return msgs[0];
}
/* dev-mode can suppress all gossip */
if (peer->daemon->dev_suppress_gossip)
return NULL;
/* Not streaming right now? */
if (!peer->gs.active)
return NULL;
/* This should be around to kick us every 60 seconds */
assert(peer->gs.gossip_timer);
again:
msg = gossmap_stream_next(ctx, gossmap, peer->gs.iter, ×tamp);
if (msg) {
/* Don't send back gossip they sent to us! */
if (gossip_rcvd_filter_del(peer->gs.grf, msg)) {
msg = tal_free(msg);
goto again;
}
/* Check timestamp (zero for channel_announcement with
* no update yet!): FIXME: we could ignore this! */
if (timestamp
&& (timestamp < peer->gs.timestamp_min || timestamp > peer->gs.timestamp_max)) {
msg = tal_free(msg);
goto again;
}
peer->gs.bytes_this_second += tal_bytelen(msg);
status_peer_io(LOG_IO_OUT, &peer->id, msg);
return msg;
}
/* No gossip left to send */
peer->gs.active = false;
return NULL;
}
/* Mutual recursion */
static void send_ping(struct peer *peer);
static void set_ping_timer(struct peer *peer)
{
if (peer->daemon->dev_no_ping_timer) {
peer->ping_timer = NULL;
return;
}
peer->ping_timer = new_reltimer(&peer->daemon->timers, peer,
time_from_sec(15 + pseudorand(30)),
send_ping, peer);
}
static void send_ping(struct peer *peer)
{
/* If it's still sending us traffic, maybe ping reply is backed up?
* That's OK, ping is just to make sure it's still alive, and clearly
* it is. */
if (timemono_before(peer->last_recv_time,
timemono_sub(time_mono(), time_from_sec(60)))) {
/* Already have a ping in flight? */
if (peer->expecting_pong != PONG_UNEXPECTED) {
status_peer_debug(&peer->id, "Last ping unreturned: hanging up");
if (peer->to_peer)
io_close(peer->to_peer);
return;
}
inject_peer_msg(peer, take(make_ping(NULL, 1, 0)));
peer->ping_start = time_mono();
peer->expecting_pong = PONG_EXPECTED_PROBING;
}
set_ping_timer(peer);
}
void set_custommsgs(struct daemon *daemon, const u8 *msg)
{
tal_free(daemon->custom_msgs);
if (!fromwire_connectd_set_custommsgs(daemon, msg, &daemon->custom_msgs))
master_badmsg(WIRE_CONNECTD_SET_CUSTOMMSGS, msg);
status_debug("Now allowing %zu custom message types",
tal_count(daemon->custom_msgs));
}
void send_custommsg(struct daemon *daemon, const u8 *msg)
{
struct node_id id;
u8 *custommsg;
struct peer *peer;
if (!fromwire_connectd_custommsg_out(tmpctx, msg, &id, &custommsg))
master_badmsg(WIRE_CONNECTD_CUSTOMMSG_OUT, msg);
/* Races can happen: this might be gone by now. */
peer = peer_htable_get(daemon->peers, &id);
if (peer)
inject_peer_msg(peer, take(custommsg));
}
static void handle_ping_in(struct peer *peer, const u8 *msg)
{
u8 *pong;
if (!check_ping_make_pong(NULL, msg, &pong)) {
send_warning(peer, "Invalid ping %s", tal_hex(msg, msg));
return;
}
if (pong)
inject_peer_msg(peer, take(pong));
}
static void handle_ping_reply(struct peer *peer, const u8 *msg)
{
u8 *ignored;
size_t i;
/* We print this out because we asked for pong, so can't spam us... */
if (!fromwire_pong(msg, msg, &ignored))
status_peer_unusual(&peer->id, "Got malformed ping reply %s",
tal_hex(tmpctx, msg));
/* We print this because dev versions of Core Lightning embed
* version here: see check_ping_make_pong! */
for (i = 0; i < tal_count(ignored); i++) {
if (ignored[i] < ' ' || ignored[i] == 127)
break;
}
status_debug("Got pong %zu bytes (%.*s...)",
tal_count(ignored), (int)i, (char *)ignored);
daemon_conn_send(peer->daemon->master,
take(towire_connectd_ping_done(NULL, peer->ping_reqid, true,
tal_bytelen(msg))));
}
static void handle_pong_in(struct peer *peer, const u8 *msg)
{
switch (peer->expecting_pong) {
case PONG_EXPECTED_COMMAND:
handle_ping_reply(peer, msg);
/* fall thru */
case PONG_EXPECTED_PROBING:
peer->expecting_pong = PONG_UNEXPECTED;
daemon_conn_send(peer->daemon->master,
take(towire_connectd_ping_latency(NULL,
&peer->id,
time_to_nsec(timemono_since(peer->ping_start)))));
return;
case PONG_UNEXPECTED:
status_debug("Unexpected pong?");
return;
}
abort();
}
/* Various cases where we don't send the msg to a gossipd, we want to
* do IO logging! */
static void log_peer_io(const struct peer *peer, const u8 *msg)
{
status_peer_io(LOG_IO_IN, &peer->id, msg);
io_wake(peer->peer_outq);
}
/* Forward to gossipd */
static void handle_gossip_in(struct peer *peer, const u8 *msg)
{
u8 *gmsg;
/* We warn at 250000, drop at 500000 */
if (daemon_conn_queue_length(peer->daemon->gossipd) > 500000)
return;
gmsg = towire_gossipd_recv_gossip(NULL, &peer->id, msg);
/* gossipd doesn't log IO, so we log it here. */
log_peer_io(peer, msg);
daemon_conn_send(peer->daemon->gossipd, take(gmsg));
}
static void handle_gossip_timestamp_filter_in(struct peer *peer, const u8 *msg)
{
struct bitcoin_blkid chain_hash;
u32 first_timestamp, timestamp_range;
struct gossmap *gossmap = get_gossmap(peer->daemon);
if (!fromwire_gossip_timestamp_filter(msg, &chain_hash,
&first_timestamp,
×tamp_range)) {
send_warning(peer, "gossip_timestamp_filter invalid: %s",
tal_hex(tmpctx, msg));
return;
}
if (!bitcoin_blkid_eq(&chainparams->genesis_blockhash, &chain_hash)) {
send_warning(peer, "gossip_timestamp_filter for bad chain: %s",
tal_hex(tmpctx, msg));
return;
}
peer->gs.timestamp_min = first_timestamp;
peer->gs.timestamp_max = first_timestamp + timestamp_range - 1;
/* Make sure we never leave it on an impossible value. */
if (peer->gs.timestamp_max < peer->gs.timestamp_min)
peer->gs.timestamp_max = UINT32_MAX;
/* BOLT-gossip-filter-simplify #7:
* The receiver:
*...
* - if `first_timestamp` is 0:
* - SHOULD send all known gossip messages.
* - otherwise, if `first_timestamp` is 0xFFFFFFFF:
* - SHOULD NOT send any gossip messages (except its own).
* - otherwise:
* - SHOULD send gossip messages it receives from now own.
*/
/* For us, this means we only sweep the gossip store for messages
* if the first_timestamp is 0 */
tal_free(peer->gs.iter);
if (first_timestamp == 0) {
peer->gs.iter = gossmap_iter_new(peer, gossmap);
} else if (first_timestamp == 0xFFFFFFFF) {
peer->gs.iter = gossmap_iter_new(peer, gossmap);
gossmap_iter_end(gossmap, peer->gs.iter);
} else {
/* We are actually a bit nicer than the spec, and we include
* "recent" gossip here. */
update_recent_timestamp(peer->daemon, gossmap);
peer->gs.iter = gossmap_iter_dup(peer,
peer->daemon->gossmap_iter_recent);
}
/* BOLT #7:
* - MAY wait for the next outgoing gossip flush to send these.
*/
/* We send immediately the first time, after that we wait. */
if (!peer->gs.gossip_timer)
wake_gossip(peer);
}
static bool find_custom_msg(const u16 *custom_msgs, u16 type)
{
for (size_t i = 0; i < tal_count(custom_msgs); i++) {
if (custom_msgs[i] == type)
return true;
}
return false;
}
static bool handle_custommsg(struct daemon *daemon,
struct peer *peer,
const u8 *msg)
{
enum peer_wire type = fromwire_peektype(msg);
/* Messages we expect to handle ourselves. */
if (peer_wire_is_internal(type))
return false;
/* We log it, since it's not going to a subdaemon */
status_peer_io(LOG_IO_IN, &peer->id, msg);
/* Even unknown messages must be explicitly allowed */
if (type % 2 == 0 && !find_custom_msg(daemon->custom_msgs, type)) {
send_warning(peer, "Invalid unknown even msg %s",
tal_hex(msg, msg));
/* We "handled" it... */
return true;
}
/* The message is not part of the messages we know how to
* handle. Assuming this is a custommsg, we just forward it to the
* master. */
daemon_conn_send(daemon->master,
take(towire_connectd_custommsg_in(NULL,
&peer->id,
msg)));
return true;
}
void custommsg_completed(struct daemon *daemon, const u8 *msg)
{
struct node_id id;
const struct peer *peer;
if (!fromwire_connectd_custommsg_in_complete(msg, &id))
master_badmsg(WIRE_CONNECTD_CUSTOMMSG_IN_COMPLETE, msg);
/* If it's still around, log it. */
peer = peer_htable_get(daemon->peers, &id);
if (peer) {
status_peer_debug(&peer->id, "custommsg processing finished");
log_peer_io(peer, msg);
}
}
/* We handle pings and gossip messages. */
static bool handle_message_locally(struct peer *peer, const u8 *msg)
{
enum peer_wire type = fromwire_peektype(msg);
/* We remember these so we don't rexmit them */
gossip_rcvd_filter_add(peer->gs.grf, msg);
if (type == WIRE_GOSSIP_TIMESTAMP_FILTER) {
log_peer_io(peer, msg);
handle_gossip_timestamp_filter_in(peer, msg);
return true;
} else if (type == WIRE_PING) {
log_peer_io(peer, msg);
handle_ping_in(peer, msg);
return true;
} else if (type == WIRE_PONG) {
log_peer_io(peer, msg);
handle_pong_in(peer, msg);
return true;
} else if (type == WIRE_ONION_MESSAGE) {
log_peer_io(peer, msg);
handle_onion_message(peer->daemon, peer, msg);
return true;
} else if (type == WIRE_QUERY_CHANNEL_RANGE) {
handle_query_channel_range(peer, msg);
return true;
} else if (type == WIRE_QUERY_SHORT_CHANNEL_IDS) {
handle_query_short_channel_ids(peer, msg);
return true;
} else if (handle_custommsg(peer->daemon, peer, msg)) {
return true;
}
/* Do we want to divert to gossipd? */
if (is_msg_for_gossipd(msg)) {
handle_gossip_in(peer, msg);
return true;
}
return false;
}
/* Move "channel_id" to temporary. */
static void move_channel_id_to_temp(struct subd *subd)
{
tal_free(subd->temporary_channel_id);
subd->temporary_channel_id
= tal_dup(subd, struct channel_id, &subd->channel_id);
}
/* Only works for open_channel2 and accept_channel2 */
static struct pubkey *extract_revocation_basepoint(const tal_t *ctx,
const u8 *msg)
{
const u8 *cursor = msg;
size_t max = tal_bytelen(msg);
enum peer_wire t;
struct pubkey pubkey;
t = fromwire_u16(&cursor, &max);
switch (t) {