forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgossipd.c
3411 lines (2988 loc) · 106 KB
/
gossipd.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
/*~ Welcome to the gossip daemon: keeper of maps!
*
* This is the last "global" daemon; it has three purposes.
*
* 1. To determine routes for payments when lightningd asks.
* 2. The second purpose is to receive gossip from peers (via their
* per-peer daemons) and send it out to them.
* 3. Talk to `connectd` to to answer address queries for nodes.
*
* The gossip protocol itself is fairly simple, but has some twists which
* add complexity to this daemon.
*/
#include <bitcoin/chainparams.h>
#include <ccan/array_size/array_size.h>
#include <ccan/asort/asort.h>
#include <ccan/bitmap/bitmap.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/cast/cast.h>
#include <ccan/container_of/container_of.h>
#include <ccan/crc32c/crc32c.h>
#include <ccan/crypto/hkdf_sha256/hkdf_sha256.h>
#include <ccan/crypto/siphash24/siphash24.h>
#include <ccan/endian/endian.h>
#include <ccan/fdpass/fdpass.h>
#include <ccan/io/fdpass/fdpass.h>
#include <ccan/io/io.h>
#include <ccan/list/list.h>
#include <ccan/mem/mem.h>
#include <ccan/noerr/noerr.h>
#include <ccan/take/take.h>
#include <ccan/tal/str/str.h>
#include <ccan/timer/timer.h>
#include <common/bech32.h>
#include <common/bech32_util.h>
#include <common/cryptomsg.h>
#include <common/daemon_conn.h>
#include <common/decode_short_channel_ids.h>
#include <common/features.h>
#include <common/memleak.h>
#include <common/ping.h>
#include <common/pseudorand.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/timeout.h>
#include <common/type_to_string.h>
#include <common/utils.h>
#include <common/version.h>
#include <common/wire_error.h>
#include <common/wireaddr.h>
#include <connectd/gen_connect_gossip_wire.h>
#include <errno.h>
#include <fcntl.h>
#include <gossipd/broadcast.h>
#include <gossipd/gen_gossip_peerd_wire.h>
#include <gossipd/gen_gossip_wire.h>
#include <gossipd/routing.h>
#include <hsmd/gen_hsm_wire.h>
#include <inttypes.h>
#include <lightningd/gossip_msg.h>
#include <netdb.h>
#include <netinet/in.h>
#include <secp256k1_ecdh.h>
#include <sodium/randombytes.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <wire/gen_peer_wire.h>
#include <wire/wire_io.h>
#include <wire/wire_sync.h>
#include <zlib.h>
/* We talk to `hsmd` to sign our gossip messages with the node key */
#define HSM_FD 3
/* connectd asks us for help finding nodes, and gossip fds for new peers */
#define CONNECTD_FD 4
/* In developer mode we provide hooks for whitebox testing */
#if DEVELOPER
static u32 max_encoding_bytes = -1U;
static bool suppress_gossip = false;
#endif
#if EXPERIMENTAL_FEATURES == 0
/* We want these definitions for convenience, even if we never encode/decode
* them when not EXPERIMENTAL_FEATURES */
struct tlv_reply_channel_range_tlvs_timestamps_tlv {
u8 encoding_type;
u8 *encoded_timestamps;
};
struct tlv_reply_channel_range_tlvs_checksums_tlv {
struct channel_update_checksums *checksums;
};
struct channel_update_timestamps {
u32 timestamp_node_id_1;
u32 timestamp_node_id_2;
};
struct channel_update_checksums {
u32 checksum_node_id_1;
u32 checksum_node_id_2;
};
static void towire_channel_update_timestamps(u8 **p,
const struct channel_update_timestamps *channel_update_timestamps)
{
abort();
}
#endif
/*~ The core daemon structure: */
struct daemon {
/* Who am I? Helps us find ourself in the routing map. */
struct node_id id;
/* Peers we are gossiping to: id is unique */
struct list_head peers;
/* Connection to lightningd. */
struct daemon_conn *master;
/* Connection to connect daemon. */
struct daemon_conn *connectd;
/* Routing information */
struct routing_state *rstate;
/* chainhash for checking/making gossip msgs */
struct bitcoin_blkid chain_hash;
/* Timers: we batch gossip, and also refresh announcements */
struct timers timers;
/* Global features to list in node_announcement. */
u8 *globalfeatures;
/* Alias (not NUL terminated) and favorite color for node_announcement */
u8 alias[32];
u8 rgb[3];
/* What addresses we can actually announce. */
struct wireaddr *announcable;
/* Do we think we're missing gossip? Contains timer to re-check */
struct oneshot *gossip_missing;
/* Channels we've heard about, but don't know. */
struct short_channel_id *unknown_scids;
};
/*~ How gossipy do we ask a peer to be? */
enum gossip_level {
/* Give us everything since epoch */
GOSSIP_HIGH,
/* Give us everything from 24 hours ago. */
GOSSIP_MEDIUM,
/* Give us everything from now. */
GOSSIP_LOW,
/* Give us nothing. */
GOSSIP_NONE,
};
/* What are our targets for each gossip level? (including levels above).
*
* If we're missing gossip: 3 high.
* Otherwise, 2 medium, and 8 low. Rest no limit..
*/
static const size_t gossip_level_targets[] = { 3, 2, 8, SIZE_MAX };
/* This represents each peer we're gossiping with */
struct peer {
/* daemon->peers */
struct list_node list;
/* parent pointer. */
struct daemon *daemon;
/* The ID of the peer (always unique) */
struct node_id id;
/* The two features gossip cares about (so far) */
bool gossip_queries_feature, initial_routing_sync_feature;
/* Are there outstanding responses for queries on short_channel_ids? */
const struct short_channel_id *scid_queries;
const bigsize_t *scid_query_flags;
size_t scid_query_idx;
/* Are there outstanding node_announcements from scid_queries? */
struct node_id *scid_query_nodes;
size_t scid_query_nodes_idx;
/* Do we have an scid_query outstanding? Was it internal? */
bool scid_query_outstanding;
bool scid_query_was_internal;
/* How many pongs are we expecting? */
size_t num_pings_outstanding;
/* Map of outstanding channel_range requests. */
bitmap *query_channel_blocks;
/* What we're querying: [range_first_blocknum, range_end_blocknum) */
u32 range_first_blocknum, range_end_blocknum;
u32 range_blocks_remaining;
struct short_channel_id *query_channel_scids;
/* Are we asking this peer to give us lot of gossip? */
enum gossip_level gossip_level;
/* The daemon_conn used to queue messages to/from the peer. */
struct daemon_conn *dc;
};
/*~ A channel consists of a `struct half_chan` for each direction, each of
* which has a `flags` word from the `channel_update`; bit 1 is
* ROUTING_FLAGS_DISABLED in the `channel_update`. But we also keep a local
* whole-channel flag which indicates it's not available; we use this when a
* peer disconnects, and generate a `channel_update` to tell the world lazily
* when someone asks. */
static void peer_disable_channels(struct daemon *daemon, struct node *node)
{
/* If this peer had a channel with us, mark it disabled. */
struct chan_map_iter i;
struct chan *c;
for (c = first_chan(node, &i); c; c = next_chan(node, &i)) {
if (node_id_eq(&other_node(node, c)->id, &daemon->id))
local_disable_chan(daemon->rstate, c);
}
}
/*~ Destroy a peer, usually because the per-peer daemon has exited.
*
* Were you wondering why we call this "destroy_peer" and not "peer_destroy"?
* I thought not! But while CCAN modules are required to keep to their own
* prefix namespace, leading to unnatural word order, we couldn't stomach that
* for our own internal use. We use 'find_foo', 'destroy_foo' and 'new_foo'.
*/
static void destroy_peer(struct peer *peer)
{
struct node *node;
/* Remove it from the peers list */
list_del_from(&peer->daemon->peers, &peer->list);
/* If we have a channel with this peer, disable it. */
node = get_node(peer->daemon->rstate, &peer->id);
if (node)
peer_disable_channels(peer->daemon, node);
/* This is tricky: our lifetime is tied to the daemon_conn; it's our
* parent, so we are freed if it is, but we need to free it if we're
* freed manually. tal_free() treats this as a noop if it's already
* being freed */
tal_free(peer->dc);
}
/* Search for a peer. */
static struct peer *find_peer(struct daemon *daemon, const struct node_id *id)
{
struct peer *peer;
list_for_each(&daemon->peers, peer, list)
if (node_id_eq(&peer->id, id))
return peer;
return NULL;
}
/* Queue a gossip message for the peer: the subdaemon on the other end simply
* forwards it to the peer. */
static void queue_peer_msg(struct peer *peer, const u8 *msg TAKES)
{
daemon_conn_send(peer->dc, msg);
}
/*~ We have a helper for messages from the store. */
static void queue_peer_from_store(struct peer *peer,
const struct broadcastable *bcast)
{
struct gossip_store *gs = peer->daemon->rstate->gs;
queue_peer_msg(peer, take(gossip_store_get(NULL, gs, bcast->index)));
}
/* BOLT #7:
*
* There are several messages which contain a long array of
* `short_channel_id`s (called `encoded_short_ids`) so we utilize a
* simple compression scheme: the first byte indicates the encoding, the
* rest contains the data.
*/
static u8 *encoding_start(const tal_t *ctx)
{
return tal_arr(ctx, u8, 0);
}
/* Marshal a single short_channel_id */
static void encoding_add_short_channel_id(u8 **encoded,
const struct short_channel_id *scid)
{
towire_short_channel_id(encoded, scid);
}
/* Marshal a single channel_update_timestamps */
static void encoding_add_timestamps(u8 **encoded,
const struct channel_update_timestamps *ts)
{
towire_channel_update_timestamps(encoded, ts);
}
/* Marshal a single query flag (we don't query, so not currently used) */
static UNNEEDED void encoding_add_query_flag(u8 **encoded, bigsize_t flag)
{
towire_bigsize(encoded, flag);
}
/* Greg Maxwell asked me privately about using zlib for communicating a set,
* and suggested that we'd be better off using Golomb-Rice coding a-la BIP
* 158. However, naively using Rice encoding isn't a win: we have to get
* more complex and use separate streams. The upside is that it's between
* 2 and 5 times smaller (assuming optimal Rice encoding + gzip). We can add
* that later. */
static u8 *zencode(const tal_t *ctx, const u8 *scids, size_t len)
{
u8 *z;
int err;
unsigned long compressed_len = len;
#ifdef ZLIB_EVEN_IF_EXPANDS
/* Needed for test vectors */
compressed_len = 128 * 1024;
#endif
/* Prefer to fail if zlib makes it larger */
z = tal_arr(ctx, u8, compressed_len);
err = compress2(z, &compressed_len, scids, len, Z_DEFAULT_COMPRESSION);
if (err == Z_OK) {
status_trace("compressed %zu into %lu",
len, compressed_len);
tal_resize(&z, compressed_len);
return z;
}
status_trace("compress %zu returned %i:"
" not compresssing", len, err);
return NULL;
}
/* Try compressing *encoded: fails if result would be longer.
* @off is offset to place result in *encoded.
*/
static bool encoding_end_zlib(u8 **encoded, size_t off)
{
u8 *z;
size_t len = tal_count(*encoded);
z = zencode(tmpctx, *encoded, len);
if (!z)
return false;
/* Successful: copy over and trim */
tal_resize(encoded, off + tal_count(z));
memcpy(*encoded + off, z, tal_count(z));
return true;
}
static void encoding_end_no_compress(u8 **encoded, size_t off)
{
size_t len = tal_count(*encoded);
tal_resize(encoded, off + len);
memmove(*encoded + off, *encoded, len);
}
/* Once we've assembled it, try compressing.
* Prepends encoding type to @encoding. */
static bool encoding_end_prepend_type(u8 **encoded, size_t max_bytes)
{
if (encoding_end_zlib(encoded, 1))
**encoded = SHORTIDS_ZLIB;
else {
encoding_end_no_compress(encoded, 1);
**encoded = SHORTIDS_UNCOMPRESSED;
}
#if DEVELOPER
if (tal_count(*encoded) > max_encoding_bytes)
return false;
#endif
return tal_count(*encoded) <= max_bytes;
}
/* Try compressing, leaving type external */
static UNNEEDED bool encoding_end_external_type(u8 **encoded, u8 *type, size_t max_bytes)
{
if (encoding_end_zlib(encoded, 0))
*type = SHORTIDS_ZLIB;
else {
encoding_end_no_compress(encoded, 0);
*type = SHORTIDS_UNCOMPRESSED;
}
return tal_count(*encoded) <= max_bytes;
}
/*~ We have different levels of gossipiness, depending on our needs. */
static u32 gossip_start(enum gossip_level gossip_level)
{
switch (gossip_level) {
case GOSSIP_HIGH:
return 0;
case GOSSIP_MEDIUM:
return time_now().ts.tv_sec - 24 * 3600;
case GOSSIP_LOW:
return time_now().ts.tv_sec;
case GOSSIP_NONE:
return UINT32_MAX;
}
abort();
}
/* BOLT #7:
*
* A node:
* - if the `gossip_queries` feature is negotiated:
* - MUST NOT relay any gossip messages unless explicitly requested.
*/
static void setup_gossip_range(struct peer *peer)
{
u8 *msg;
/*~ Without the `gossip_queries` feature, gossip flows automatically. */
if (!peer->gossip_queries_feature) {
/* This peer is gossipy whether we want it or not! */
return;
}
status_trace("Setting peer %s to gossip level %s",
type_to_string(tmpctx, struct node_id, &peer->id),
peer->gossip_level == GOSSIP_HIGH ? "HIGH"
: peer->gossip_level == GOSSIP_MEDIUM ? "MEDIUM"
: peer->gossip_level == GOSSIP_LOW ? "LOW"
: peer->gossip_level == GOSSIP_NONE ? "NONE"
: "INVALID");
/*~ We need to ask for something to start the gossip flowing. */
msg = towire_gossip_timestamp_filter(peer,
&peer->daemon->chain_hash,
gossip_start(peer->gossip_level),
UINT32_MAX);
queue_peer_msg(peer, take(msg));
}
/* Create a node_announcement with the given signature. It may be NULL in the
* case we need to create a provisional announcement for the HSM to sign.
* This is called twice: once with the dummy signature to get it signed and a
* second time to build the full packet with the signature. The timestamp is
* handed in rather than using time_now() internally, since that could change
* between the dummy creation and the call with a signature. */
static u8 *create_node_announcement(const tal_t *ctx, struct daemon *daemon,
secp256k1_ecdsa_signature *sig,
u32 timestamp)
{
u8 *addresses = tal_arr(tmpctx, u8, 0);
u8 *announcement;
size_t i;
if (!sig) {
sig = tal(tmpctx, secp256k1_ecdsa_signature);
memset(sig, 0, sizeof(*sig));
}
for (i = 0; i < tal_count(daemon->announcable); i++)
towire_wireaddr(&addresses, &daemon->announcable[i]);
announcement =
towire_node_announcement(ctx, sig, daemon->globalfeatures, timestamp,
&daemon->id, daemon->rgb, daemon->alias,
addresses);
return announcement;
}
/*~ This routine created a `node_announcement` for our node, and hands it to
* the routing.c code like any other `node_announcement`. Such announcements
* are only accepted if there is an announced channel associated with that node
* (to prevent spam), so we only call this once we've announced a channel. */
static void send_node_announcement(struct daemon *daemon)
{
u32 timestamp = time_now().ts.tv_sec;
secp256k1_ecdsa_signature sig;
u8 *msg, *nannounce, *err;
struct node *self = get_node(daemon->rstate, &daemon->id);
/* BOLT #7:
*
* The origin node:
* - MUST set `timestamp` to be greater than that of any previous
* `node_announcement` it has previously created.
*/
if (self && self->bcast.index && timestamp <= self->bcast.timestamp)
timestamp = self->bcast.timestamp + 1;
/* Get an unsigned one. */
nannounce = create_node_announcement(tmpctx, daemon, NULL, timestamp);
/* Ask hsmd to sign it (synchronous) */
if (!wire_sync_write(HSM_FD, take(towire_hsm_node_announcement_sig_req(NULL, nannounce))))
status_failed(STATUS_FAIL_MASTER_IO, "Could not write to HSM: %s", strerror(errno));
msg = wire_sync_read(tmpctx, HSM_FD);
if (!fromwire_hsm_node_announcement_sig_reply(msg, &sig))
status_failed(STATUS_FAIL_MASTER_IO, "HSM returned an invalid node_announcement sig");
/* We got the signature for out provisional node_announcement back
* from the HSM, create the real announcement and forward it to
* gossipd so it can take care of forwarding it. */
nannounce = create_node_announcement(NULL, daemon, &sig, timestamp);
/* This injects it into the routing code in routing.c; it should not
* reject it! */
err = handle_node_announcement(daemon->rstate, take(nannounce));
if (err)
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"rejected own node announcement: %s",
tal_hex(tmpctx, err));
}
/*~ We don't actually keep node_announcements in memory; we keep them in
* a file called `gossip_store`. If we need some node details, we reload
* and reparse. It's slow, but generally rare. */
static bool get_node_announcement(const tal_t *ctx,
struct daemon *daemon,
const struct node *n,
u8 rgb_color[3],
u8 alias[32],
u8 **features,
struct wireaddr **wireaddrs)
{
const u8 *msg;
struct node_id id;
secp256k1_ecdsa_signature signature;
u32 timestamp;
u8 *addresses;
if (!n->bcast.index)
return false;
msg = gossip_store_get(tmpctx, daemon->rstate->gs, n->bcast.index);
/* Note: validity of node_id is already checked. */
if (!fromwire_node_announcement(ctx, msg,
&signature, features,
×tamp,
&id, rgb_color, alias,
&addresses)) {
status_broken("Bad local node_announcement @%u: %s",
n->bcast.index, tal_hex(tmpctx, msg));
return false;
}
if (!node_id_eq(&id, &n->id) || timestamp != n->bcast.timestamp) {
status_broken("Wrong node_announcement @%u:"
" expected %s timestamp %u "
" got %s timestamp %u",
n->bcast.index,
type_to_string(tmpctx, struct node_id, &n->id),
timestamp,
type_to_string(tmpctx, struct node_id, &id),
n->bcast.timestamp);
return false;
}
*wireaddrs = read_addresses(ctx, addresses);
tal_free(addresses);
return true;
}
/* Version which also does nodeid lookup */
static bool get_node_announcement_by_id(const tal_t *ctx,
struct daemon *daemon,
const struct node_id *node_id,
u8 rgb_color[3],
u8 alias[32],
u8 **features,
struct wireaddr **wireaddrs)
{
struct node *n = get_node(daemon->rstate, node_id);
if (!n)
return false;
return get_node_announcement(ctx, daemon, n, rgb_color, alias,
features, wireaddrs);
}
/* Return true if the only change would be the timestamp. */
static bool node_announcement_redundant(struct daemon *daemon)
{
u8 rgb_color[3];
u8 alias[32];
u8 *features;
struct wireaddr *wireaddrs;
if (!get_node_announcement_by_id(tmpctx, daemon, &daemon->id,
rgb_color, alias, &features,
&wireaddrs))
return false;
if (tal_count(wireaddrs) != tal_count(daemon->announcable))
return false;
for (size_t i = 0; i < tal_count(wireaddrs); i++)
if (!wireaddr_eq(&wireaddrs[i], &daemon->announcable[i]))
return false;
BUILD_ASSERT(ARRAY_SIZE(daemon->alias) == ARRAY_SIZE(alias));
if (!memeq(daemon->alias, ARRAY_SIZE(daemon->alias),
alias, ARRAY_SIZE(alias)))
return false;
BUILD_ASSERT(ARRAY_SIZE(daemon->rgb) == ARRAY_SIZE(rgb_color));
if (!memeq(daemon->rgb, ARRAY_SIZE(daemon->rgb),
rgb_color, ARRAY_SIZE(rgb_color)))
return false;
if (!memeq(daemon->globalfeatures, tal_count(daemon->globalfeatures),
features, tal_count(features)))
return false;
return true;
}
/* Should we announce our own node? Called at strategic places. */
static void maybe_send_own_node_announce(struct daemon *daemon)
{
/* We keep an internal flag in the routing code to say we've announced
* a local channel. The alternative would be to have it make a
* callback, but when we start up we don't want to make multiple
* announcments, so we use this approach for now. */
if (!daemon->rstate->local_channel_announced)
return;
if (node_announcement_redundant(daemon))
return;
send_node_announcement(daemon);
daemon->rstate->local_channel_announced = false;
}
/* Query this peer for these short-channel-ids. */
static bool query_short_channel_ids(struct daemon *daemon,
struct peer *peer,
const struct short_channel_id *scids,
bool internal)
{
u8 *encoded, *msg;
/* BOLT #7:
*
* 1. type: 261 (`query_short_channel_ids`) (`gossip_queries`)
* 2. data:
* * [`chain_hash`:`chain_hash`]
* * [`u16`:`len`]
* * [`len*byte`:`encoded_short_ids`]
*/
const size_t reply_overhead = 32 + 2;
const size_t max_encoded_bytes = 65535 - 2 - reply_overhead;
/* Can't query if they don't have gossip_queries_feature */
if (!peer->gossip_queries_feature)
return false;
/* BOLT #7:
*
* The sender:
* - MUST NOT send `query_short_channel_ids` if it has sent a previous
* `query_short_channel_ids` to this peer and not received
* `reply_short_channel_ids_end`.
*/
if (peer->scid_query_outstanding)
return false;
encoded = encoding_start(tmpctx);
for (size_t i = 0; i < tal_count(scids); i++)
encoding_add_short_channel_id(&encoded, &scids[i]);
if (!encoding_end_prepend_type(&encoded, max_encoded_bytes)) {
status_broken("query_short_channel_ids: %zu is too many",
tal_count(scids));
return false;
}
#if EXPERIMENTAL_FEATURES
msg = towire_query_short_channel_ids(NULL, &daemon->chain_hash,
encoded, NULL);
#else
msg = towire_query_short_channel_ids(NULL, &daemon->chain_hash,
encoded);
#endif
queue_peer_msg(peer, take(msg));
peer->scid_query_outstanding = true;
peer->scid_query_was_internal = internal;
status_trace("%s: sending query for %zu scids",
type_to_string(tmpctx, struct node_id, &peer->id),
tal_count(scids));
return true;
}
/*~ This peer told us about an update to an unknown channel. Ask it for
* a channel_announcement. */
static void query_unknown_channel(struct daemon *daemon,
struct peer *peer,
const struct short_channel_id *id)
{
/* Don't go overboard if we're already asking for a lot. */
if (tal_count(daemon->unknown_scids) > 1000)
return;
/* Check we're not already getting this one. */
for (size_t i = 0; i < tal_count(daemon->unknown_scids); i++)
if (short_channel_id_eq(&daemon->unknown_scids[i], id))
return;
tal_arr_expand(&daemon->unknown_scids, *id);
/* This is best effort: if peer is busy, we'll try next time. */
query_short_channel_ids(daemon, peer, daemon->unknown_scids, true);
}
/*~Routines to handle gossip messages from peer, forwarded by subdaemons.
*-----------------------------------------------------------------------
*
* It's not the subdaemon's fault if they're malformed or invalid; so these
* all return an error packet which gets sent back to the subdaemon in that
* case.
*/
/* The routing code checks that it's basically valid, returning an
* error message for the peer or NULL. NULL means it's OK, but the
* message might be redundant, in which case scid is also NULL.
* Otherwise `scid` gives us the short_channel_id claimed by the
* message, and puts the announcemnt on an internal 'pending'
* queue. We'll send a request to lightningd to look it up, and continue
* processing in `handle_txout_reply`. */
static const u8 *handle_channel_announcement_msg(struct peer *peer,
const u8 *msg)
{
const struct short_channel_id *scid;
const u8 *err;
/* If it's OK, tells us the short_channel_id to lookup; it notes
* if this is the unknown channel the peer was looking for (in
* which case, it frees and NULLs that ptr) */
err = handle_channel_announcement(peer->daemon->rstate, msg, &scid);
if (err)
return err;
else if (scid)
daemon_conn_send(peer->daemon->master,
take(towire_gossip_get_txout(NULL, scid)));
return NULL;
}
static u8 *handle_channel_update_msg(struct peer *peer, const u8 *msg)
{
struct short_channel_id unknown_scid;
/* Hand the channel_update to the routing code */
u8 *err;
unknown_scid.u64 = 0;
err = handle_channel_update(peer->daemon->rstate, msg, "subdaemon",
&unknown_scid);
if (err) {
if (unknown_scid.u64 != 0)
query_unknown_channel(peer->daemon, peer, &unknown_scid);
return err;
}
/*~ As a nasty compromise in the spec, we only forward channel_announce
* once we have a channel_update; the channel isn't *usable* for
* routing until you have both anyway. For this reason, we might have
* just sent out our own channel_announce, so we check if it's time to
* send a node_announcement too. */
maybe_send_own_node_announce(peer->daemon);
return NULL;
}
/*~ The peer can ask about an array of short channel ids: we don't assemble the
* reply immediately but process them one at a time in dump_gossip which is
* called when there's nothing more important to send. */
static const u8 *handle_query_short_channel_ids(struct peer *peer, const u8 *msg)
{
struct bitcoin_blkid chain;
u8 *encoded;
struct short_channel_id *scids;
bigsize_t *flags;
#if EXPERIMENTAL_FEATURES
struct tlv_query_short_channel_ids_tlvs *tlvs
= tlv_query_short_channel_ids_tlvs_new(tmpctx);
if (!fromwire_query_short_channel_ids(tmpctx, msg, &chain, &encoded,
tlvs)) {
return towire_errorfmt(peer, NULL,
"Bad query_short_channel_ids w/tlvs %s",
tal_hex(tmpctx, msg));
}
if (tlvs->query_flags) {
flags = decode_scid_query_flags(tmpctx, tlvs->query_flags);
if (!flags) {
return towire_errorfmt(peer, NULL,
"Bad query_short_channel_ids query_flags %s",
tal_hex(tmpctx, msg));
}
} else
flags = NULL;
#else
if (!fromwire_query_short_channel_ids(tmpctx, msg, &chain, &encoded)) {
return towire_errorfmt(peer, NULL,
"Bad query_short_channel_ids %s",
tal_hex(tmpctx, msg));
}
flags = NULL;
#endif
if (!bitcoin_blkid_eq(&peer->daemon->chain_hash, &chain)) {
status_trace("%s sent query_short_channel_ids chainhash %s",
type_to_string(tmpctx, struct node_id, &peer->id),
type_to_string(tmpctx, struct bitcoin_blkid, &chain));
return NULL;
}
/* BOLT #7:
*
* - if it has not sent `reply_short_channel_ids_end` to a
* previously received `query_short_channel_ids` from this
* sender:
* - MAY fail the connection.
*/
if (peer->scid_queries || peer->scid_query_nodes) {
return towire_errorfmt(peer, NULL,
"Bad concurrent query_short_channel_ids");
}
scids = decode_short_ids(tmpctx, encoded);
if (!scids) {
return towire_errorfmt(peer, NULL,
"Bad query_short_channel_ids encoding %s",
tal_hex(tmpctx, encoded));
}
/* BOLT-61a1365a45cc8b463ddbbe3429d350f8eac787dd #7:
*
* The receiver:
*...
* - if the incoming message includes `query_short_channel_ids_tlvs`:
* - if `encoded_query_flags` does not decode to exactly one flag per
* `short_channel_id`:
* - MAY fail the connection.
*/
if (!flags) {
/* Pretend they asked for everything. */
flags = tal_arr(tmpctx, bigsize_t, tal_count(scids));
memset(flags, 0xFF, tal_bytelen(flags));
} else {
if (tal_count(flags) != tal_count(scids)) {
return towire_errorfmt(peer, NULL,
"Bad query_short_channel_ids flags count %zu scids %zu",
tal_count(flags), tal_count(scids));
}
}
/* BOLT #7:
*
* - MUST respond to each known `short_channel_id` with a `channel_announcement`
* and the latest `channel_update` for each end
* - SHOULD NOT wait for the next outgoing gossip flush to send
* these.
*/
peer->scid_queries = tal_steal(peer, scids);
peer->scid_query_flags = tal_steal(peer, flags);
peer->scid_query_idx = 0;
peer->scid_query_nodes = tal_arr(peer, struct node_id, 0);
/* Notify the daemon_conn-write loop to invoke create_next_scid_reply */
daemon_conn_wake(peer->dc);
return NULL;
}
/*~ When we compact the gossip store, all the broadcast indexs move.
* We simply offset everyone, which means in theory they could retransmit
* some, but that's a lesser evil than skipping some. */
void update_peers_broadcast_index(struct list_head *peers, u32 offset)
{
struct peer *peer, *next;
list_for_each_safe(peers, peer, next, list) {
int gs_fd;
/*~ Since store has been compacted, they need a new fd for the
* new store. We also tell them how much this is shrunk, so
* they can (approximately) tell where to start in the new store.
*/
gs_fd = gossip_store_readonly_fd(peer->daemon->rstate->gs);
if (gs_fd < 0) {
status_broken("Can't get read-only gossip store fd:"
" killing peer");
tal_free(peer);
} else {
u8 *msg = towire_gossipd_new_store_fd(NULL, offset);
daemon_conn_send(peer->dc, take(msg));
daemon_conn_send_fd(peer->dc, gs_fd);
}
}
}
/*~ We can send multiple replies when the peer queries for all channels in
* a given range of blocks; each one indicates the range of blocks it covers. */
static void reply_channel_range(struct peer *peer,
u32 first_blocknum, u32 number_of_blocks,
const u8 *encoded_scids,
struct tlv_reply_channel_range_tlvs_timestamps_tlv *timestamps,
struct tlv_reply_channel_range_tlvs_checksums_tlv *checksums)
{
/* BOLT #7:
*
* - For each `reply_channel_range`:
* - MUST set with `chain_hash` equal to that of `query_channel_range`,
* - MUST encode a `short_channel_id` for every open channel it
* knows in blocks `first_blocknum` to `first_blocknum` plus
* `number_of_blocks` minus one.
* - MUST limit `number_of_blocks` to the maximum number of blocks
* whose results could fit in `encoded_short_ids`
* - if does not maintain up-to-date channel information for
* `chain_hash`:
* - MUST set `complete` to 0.
* - otherwise:
* - SHOULD set `complete` to 1.
*/
#if EXPERIMENTAL_FEATURES
struct tlv_reply_channel_range_tlvs *tlvs
= tlv_reply_channel_range_tlvs_new(tmpctx);
tlvs->timestamps_tlv = timestamps;
tlvs->checksums_tlv = checksums;
u8 *msg = towire_reply_channel_range(NULL,
&peer->daemon->chain_hash,
first_blocknum,
number_of_blocks,
1, encoded_scids, tlvs);
#else
u8 *msg = towire_reply_channel_range(NULL,
&peer->daemon->chain_hash,
first_blocknum,
number_of_blocks,
1, encoded_scids);
#endif
queue_peer_msg(peer, take(msg));
}
/* BOLT-61a1365a45cc8b463ddbbe3429d350f8eac787dd #7:
*
* `query_option_flags` is a bitfield represented as a minimally-encoded varint.
* Bits have the following meaning:
*
* | Bit Position | Meaning |
* | ------------- | ----------------------- |
* | 0 | Sender wants timestamps |
* | 1 | Sender wants checksums |
*/
enum query_option_flags {
QUERY_ADD_TIMESTAMPS = 0x1,
QUERY_ADD_CHECKSUMS = 0x2,
};
/* BOLT-61a1365a45cc8b463ddbbe3429d350f8eac787dd #7:
*
* The checksum of a `channel_update` is the CRC32C checksum as specified in
* [RFC3720](https://tools.ietf.org/html/rfc3720#appendix-B.4) of this
* `channel_update` without its `signature` and `timestamp` fields.
*/
static u32 crc32_of_update(const u8 *channel_update)
{
u32 sum;
/* BOLT #7:
*
* 1. type: 258 (`channel_update`)
* 2. data:
* * [`signature`:`signature`]
* * [`chain_hash`:`chain_hash`]
* * [`short_channel_id`:`short_channel_id`]
* * [`u32`:`timestamp`]
*...
*/
/* We already checked it's valid before accepting */
assert(tal_count(channel_update) > 64 + 32 + 8 + 4);
sum = crc32c(0, channel_update + 64, 32 + 8);
sum = crc32c(sum, channel_update + 64 + 32 + 8 + 4,
tal_count(channel_update) - (64 + 32 + 8 + 4));
return sum;
}
static void get_checksum_and_timestamp(struct routing_state *rstate,
const struct chan *chan,