/
gossip.rs
2887 lines (2597 loc) · 111 KB
/
gossip.rs
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 file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! The top-level network map tracking logic lives here.
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
use bitcoin::secp256k1::PublicKey;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::Hash;
use bitcoin::blockdata::script::Builder;
use bitcoin::blockdata::transaction::TxOut;
use bitcoin::blockdata::opcodes;
use bitcoin::hash_types::BlockHash;
use chain;
use chain::Access;
use ln::features::{ChannelFeatures, NodeFeatures};
use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
use ln::msgs;
use util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
use util::logger::{Logger, Level};
use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
use io;
use prelude::*;
use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
use core::{cmp, fmt};
use sync::{RwLock, RwLockReadGuard};
use core::sync::atomic::{AtomicUsize, Ordering};
use sync::Mutex;
use core::ops::Deref;
use bitcoin::hashes::hex::ToHex;
#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};
/// We remove stale channel directional info two weeks after the last update, per BOLT 7's
/// suggestion.
const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
/// The maximum number of extra bytes which we do not understand in a gossip message before we will
/// refuse to relay the message.
const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
/// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
/// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
const MAX_SCIDS_PER_REPLY: usize = 8000;
/// Represents the compressed public key of a node
#[derive(Clone, Copy)]
pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
impl NodeId {
/// Create a new NodeId from a public key
pub fn from_pubkey(pubkey: &PublicKey) -> Self {
NodeId(pubkey.serialize())
}
/// Get the public key slice from this NodeId
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
impl fmt::Debug for NodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NodeId({})", log_bytes!(self.0))
}
}
impl core::hash::Hash for NodeId {
fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
self.0.hash(hasher);
}
}
impl Eq for NodeId {}
impl PartialEq for NodeId {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
impl cmp::PartialOrd for NodeId {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NodeId {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.0[..].cmp(&other.0[..])
}
}
impl Writeable for NodeId {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
writer.write_all(&self.0)?;
Ok(())
}
}
impl Readable for NodeId {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let mut buf = [0; PUBLIC_KEY_SIZE];
reader.read_exact(&mut buf)?;
Ok(Self(buf))
}
}
/// Represents the network as nodes and channels between them
pub struct NetworkGraph<L: Deref> where L::Target: Logger {
secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
genesis_hash: BlockHash,
logger: L,
// Lock order: channels -> nodes
channels: RwLock<BTreeMap<u64, ChannelInfo>>,
nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
}
/// A read-only view of [`NetworkGraph`].
pub struct ReadOnlyNetworkGraph<'a> {
channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
}
/// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
/// return packet by a node along the route. See [BOLT #4] for details.
///
/// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
#[derive(Clone, Debug, PartialEq)]
pub enum NetworkUpdate {
/// An error indicating a `channel_update` messages should be applied via
/// [`NetworkGraph::update_channel`].
ChannelUpdateMessage {
/// The update to apply via [`NetworkGraph::update_channel`].
msg: ChannelUpdate,
},
/// An error indicating that a channel failed to route a payment, which should be applied via
/// [`NetworkGraph::channel_failed`].
ChannelFailure {
/// The short channel id of the closed channel.
short_channel_id: u64,
/// Whether the channel should be permanently removed or temporarily disabled until a new
/// `channel_update` message is received.
is_permanent: bool,
},
/// An error indicating that a node failed to route a payment, which should be applied via
/// [`NetworkGraph::node_failed`].
NodeFailure {
/// The node id of the failed node.
node_id: PublicKey,
/// Whether the node should be permanently removed from consideration or can be restored
/// when a new `channel_update` message is received.
is_permanent: bool,
}
}
impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
(0, ChannelUpdateMessage) => {
(0, msg, required),
},
(2, ChannelFailure) => {
(0, short_channel_id, required),
(2, is_permanent, required),
},
(4, NodeFailure) => {
(0, node_id, required),
(2, is_permanent, required),
},
);
/// Receives and validates network updates from peers,
/// stores authentic and relevant data as a network graph.
/// This network graph is then used for routing payments.
/// Provides interface to help with initial routing sync by
/// serving historical announcements.
///
/// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentPathFailed`] to the
/// [`NetworkGraph`].
pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref>
where C::Target: chain::Access, L::Target: Logger
{
network_graph: G,
chain_access: Option<C>,
full_syncs_requested: AtomicUsize,
pending_events: Mutex<Vec<MessageSendEvent>>,
logger: L,
}
impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> P2PGossipSync<G, C, L>
where C::Target: chain::Access, L::Target: Logger
{
/// Creates a new tracker of the actual state of the network of channels and nodes,
/// assuming an existing Network Graph.
/// Chain monitor is used to make sure announced channels exist on-chain,
/// channel data is correct, and that the announcement is signed with
/// channel owners' keys.
pub fn new(network_graph: G, chain_access: Option<C>, logger: L) -> Self {
P2PGossipSync {
network_graph,
full_syncs_requested: AtomicUsize::new(0),
chain_access,
pending_events: Mutex::new(vec![]),
logger,
}
}
/// Adds a provider used to check new announcements. Does not affect
/// existing announcements unless they are updated.
/// Add, update or remove the provider would replace the current one.
pub fn add_chain_access(&mut self, chain_access: Option<C>) {
self.chain_access = chain_access;
}
/// Gets a reference to the underlying [`NetworkGraph`] which was provided in
/// [`P2PGossipSync::new`].
///
/// (C-not exported) as bindings don't support a reference-to-a-reference yet
pub fn network_graph(&self) -> &G {
&self.network_graph
}
/// Returns true when a full routing table sync should be performed with a peer.
fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
//TODO: Determine whether to request a full sync based on the network map.
const FULL_SYNCS_TO_REQUEST: usize = 5;
if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
true
} else {
false
}
}
}
impl<L: Deref> EventHandler for NetworkGraph<L> where L::Target: Logger {
fn handle_event(&self, event: &Event) {
if let Event::PaymentPathFailed { network_update, .. } = event {
if let Some(network_update) = network_update {
match *network_update {
NetworkUpdate::ChannelUpdateMessage { ref msg } => {
let short_channel_id = msg.contents.short_channel_id;
let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
let status = if is_enabled { "enabled" } else { "disabled" };
log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
let _ = self.update_channel(msg);
},
NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
let action = if is_permanent { "Removing" } else { "Disabling" };
log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
self.channel_failed(short_channel_id, is_permanent);
},
NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
let action = if is_permanent { "Removing" } else { "Disabling" };
log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
self.node_failed(node_id, is_permanent);
},
}
}
}
}
}
macro_rules! secp_verify_sig {
( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
Ok(_) => {},
Err(_) => {
return Err(LightningError {
err: format!("Invalid signature on {} message", $msg_type),
action: ErrorAction::SendWarningMessage {
msg: msgs::WarningMessage {
channel_id: [0; 32],
data: format!("Invalid signature on {} message", $msg_type),
},
log_level: Level::Trace,
},
});
},
}
};
}
impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, C, L>
where C::Target: chain::Access, L::Target: Logger
{
fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
self.network_graph.update_node_from_announcement(msg)?;
Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
}
fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
self.network_graph.update_channel_from_announcement(msg, &self.chain_access)?;
log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
}
fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
self.network_graph.update_channel(msg)?;
Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
}
fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
let mut result = Vec::with_capacity(batch_amount as usize);
let channels = self.network_graph.channels.read().unwrap();
let mut iter = channels.range(starting_point..);
while result.len() < batch_amount as usize {
if let Some((_, ref chan)) = iter.next() {
if chan.announcement_message.is_some() {
let chan_announcement = chan.announcement_message.clone().unwrap();
let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
if let Some(one_to_two) = chan.one_to_two.as_ref() {
one_to_two_announcement = one_to_two.last_update_message.clone();
}
if let Some(two_to_one) = chan.two_to_one.as_ref() {
two_to_one_announcement = two_to_one.last_update_message.clone();
}
result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
} else {
// TODO: We may end up sending un-announced channel_updates if we are sending
// initial sync data while receiving announce/updates for this channel.
}
} else {
return result;
}
}
result
}
fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
let mut result = Vec::with_capacity(batch_amount as usize);
let nodes = self.network_graph.nodes.read().unwrap();
let mut iter = if let Some(pubkey) = starting_point {
let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
iter.next();
iter
} else {
nodes.range::<NodeId, _>(..)
};
while result.len() < batch_amount as usize {
if let Some((_, ref node)) = iter.next() {
if let Some(node_info) = node.announcement_info.as_ref() {
if node_info.announcement_message.is_some() {
result.push(node_info.announcement_message.clone().unwrap());
}
}
} else {
return result;
}
}
result
}
/// Initiates a stateless sync of routing gossip information with a peer
/// using gossip_queries. The default strategy used by this implementation
/// is to sync the full block range with several peers.
///
/// We should expect one or more reply_channel_range messages in response
/// to our query_channel_range. Each reply will enqueue a query_scid message
/// to request gossip messages for each channel. The sync is considered complete
/// when the final reply_scids_end message is received, though we are not
/// tracking this directly.
fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init) {
// We will only perform a sync with peers that support gossip_queries.
if !init_msg.features.supports_gossip_queries() {
return ();
}
// The lightning network's gossip sync system is completely broken in numerous ways.
//
// Given no broadly-available set-reconciliation protocol, the only reasonable approach is
// to do a full sync from the first few peers we connect to, and then receive gossip
// updates from all our peers normally.
//
// Originally, we could simply tell a peer to dump us the entire gossip table on startup,
// wasting lots of bandwidth but ensuring we have the full network graph. After the initial
// dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
// seen.
//
// In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
// to ask for the SCIDs of all channels in your peer's routing graph, and then only request
// channel data which you are missing. Except there was no way at all to identify which
// `channel_update`s you were missing, so you still had to request everything, just in a
// very complicated way with some queries instead of just getting the dump.
//
// Later, an option was added to fetch the latest timestamps of the `channel_update`s to
// make efficient sync possible, however it has yet to be implemented in lnd, which makes
// relying on it useless.
//
// After gossip queries were introduced, support for receiving a full gossip table dump on
// connection was removed from several nodes, making it impossible to get a full sync
// without using the "gossip queries" messages.
//
// Once you opt into "gossip queries" the only way to receive any gossip updates that a
// peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
// message, as the name implies, tells the peer to not forward any gossip messages with a
// timestamp older than a given value (not the time the peer received the filter, but the
// timestamp in the update message, which is often hours behind when the peer received the
// message).
//
// Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
// your peer to send you the full routing graph (subject to the filter). Thus, in order to
// tell a peer to send you any updates as it sees them, you have to also ask for the full
// routing graph to be synced. If you set a timestamp filter near the current time, peers
// will simply not forward any new updates they see to you which were generated some time
// ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
// ago), you will always get the full routing graph from all your peers.
//
// Most lightning nodes today opt to simply turn off receiving gossip data which only
// propagated some time after it was generated, and, worse, often disable gossiping with
// several peers after their first connection. The second behavior can cause gossip to not
// propagate fully if there are cuts in the gossiping subgraph.
//
// In an attempt to cut a middle ground between always fetching the full graph from all of
// our peers and never receiving gossip from peers at all, we send all of our peers a
// `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
//
// For no-std builds, we bury our head in the sand and do a full sync on each connection.
let should_request_full_sync = self.should_request_full_sync(&their_node_id);
#[allow(unused_mut, unused_assignments)]
let mut gossip_start_time = 0;
#[cfg(feature = "std")]
{
gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
if should_request_full_sync {
gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
} else {
gossip_start_time -= 60 * 60; // an hour ago
}
}
let mut pending_events = self.pending_events.lock().unwrap();
pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
node_id: their_node_id.clone(),
msg: GossipTimestampFilter {
chain_hash: self.network_graph.genesis_hash,
first_timestamp: gossip_start_time as u32, // 2106 issue!
timestamp_range: u32::max_value(),
},
});
}
fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
// We don't make queries, so should never receive replies. If, in the future, the set
// reconciliation extensions to gossip queries become broadly supported, we should revert
// this code to its state pre-0.0.106.
Ok(())
}
fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
// We don't make queries, so should never receive replies. If, in the future, the set
// reconciliation extensions to gossip queries become broadly supported, we should revert
// this code to its state pre-0.0.106.
Ok(())
}
/// Processes a query from a peer by finding announced/public channels whose funding UTXOs
/// are in the specified block range. Due to message size limits, large range
/// queries may result in several reply messages. This implementation enqueues
/// all reply messages into pending events. Each message will allocate just under 65KiB. A full
/// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
/// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
/// memory constrained systems.
fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
log_debug!(self.logger, "Handling query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks);
let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
// We might receive valid queries with end_blocknum that would overflow SCID conversion.
// If so, we manually cap the ending block to avoid this overflow.
let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
// Per spec, we must reply to a query. Send an empty message when things are invalid.
if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
let mut pending_events = self.pending_events.lock().unwrap();
pending_events.push(MessageSendEvent::SendReplyChannelRange {
node_id: their_node_id.clone(),
msg: ReplyChannelRange {
chain_hash: msg.chain_hash.clone(),
first_blocknum: msg.first_blocknum,
number_of_blocks: msg.number_of_blocks,
sync_complete: true,
short_channel_ids: vec![],
}
});
return Err(LightningError {
err: String::from("query_channel_range could not be processed"),
action: ErrorAction::IgnoreError,
});
}
// Creates channel batches. We are not checking if the channel is routable
// (has at least one update). A peer may still want to know the channel
// exists even if its not yet routable.
let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
let channels = self.network_graph.channels.read().unwrap();
for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
if let Some(chan_announcement) = &chan.announcement_message {
// Construct a new batch if last one is full
if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
}
let batch = batches.last_mut().unwrap();
batch.push(chan_announcement.contents.short_channel_id);
}
}
drop(channels);
let mut pending_events = self.pending_events.lock().unwrap();
let batch_count = batches.len();
let mut prev_batch_endblock = msg.first_blocknum;
for (batch_index, batch) in batches.into_iter().enumerate() {
// Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
// and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
//
// Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
// reply is >= the previous reply's `first_blocknum` and either exactly the previous
// reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
// significant diversion from the requirements set by the spec, and, in case of blocks
// with no channel opens (e.g. empty blocks), requires that we use the previous value
// and *not* derive the first_blocknum from the actual first block of the reply.
let first_blocknum = prev_batch_endblock;
// Each message carries the number of blocks (from the `first_blocknum`) its contents
// fit in. Though there is no requirement that we use exactly the number of blocks its
// contents are from, except for the bogus requirements c-lightning enforces, above.
//
// Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
// >= the query's end block. Thus, for the last reply, we calculate the difference
// between the query's end block and the start of the reply.
//
// Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
// first_blocknum will be either msg.first_blocknum or a higher block height.
let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
(true, msg.end_blocknum() - first_blocknum)
}
// Prior replies should use the number of blocks that fit into the reply. Overflow
// safe since first_blocknum is always <= last SCID's block.
else {
(false, block_from_scid(batch.last().unwrap()) - first_blocknum)
};
prev_batch_endblock = first_blocknum + number_of_blocks;
pending_events.push(MessageSendEvent::SendReplyChannelRange {
node_id: their_node_id.clone(),
msg: ReplyChannelRange {
chain_hash: msg.chain_hash.clone(),
first_blocknum,
number_of_blocks,
sync_complete,
short_channel_ids: batch,
}
});
}
Ok(())
}
fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
// TODO
Err(LightningError {
err: String::from("Not implemented"),
action: ErrorAction::IgnoreError,
})
}
}
impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, C, L>
where
C::Target: chain::Access,
L::Target: Logger,
{
fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
let mut ret = Vec::new();
let mut pending_events = self.pending_events.lock().unwrap();
core::mem::swap(&mut ret, &mut pending_events);
ret
}
}
#[derive(Clone, Debug, PartialEq)]
/// Details about one direction of a channel as received within a [`ChannelUpdate`].
pub struct ChannelUpdateInfo {
/// When the last update to the channel direction was issued.
/// Value is opaque, as set in the announcement.
pub last_update: u32,
/// Whether the channel can be currently used for payments (in this one direction).
pub enabled: bool,
/// The difference in CLTV values that you must have when routing through this channel.
pub cltv_expiry_delta: u16,
/// The minimum value, which must be relayed to the next hop via the channel
pub htlc_minimum_msat: u64,
/// The maximum value which may be relayed to the next hop via the channel.
pub htlc_maximum_msat: u64,
/// Fees charged when the channel is used for routing
pub fees: RoutingFees,
/// Most recent update for the channel received from the network
/// Mostly redundant with the data we store in fields explicitly.
/// Everything else is useful only for sending out for initial routing sync.
/// Not stored if contains excess data to prevent DoS.
pub last_update_message: Option<ChannelUpdate>,
}
impl fmt::Display for ChannelUpdateInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
Ok(())
}
}
impl Writeable for ChannelUpdateInfo {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.last_update, required),
(2, self.enabled, required),
(4, self.cltv_expiry_delta, required),
(6, self.htlc_minimum_msat, required),
(8, self.htlc_maximum_msat, required),
(10, self.fees, required),
(12, self.last_update_message, required),
});
Ok(())
}
#[inline]
fn serialized_length(&self) -> usize {
use util::ser::BigSize;
let len = {
#[allow(unused_mut)]
let mut len = ::util::ser::LengthCalculatingWriter(0);
get_varint_length_prefixed_tlv_length!(len, 0, self.last_update, required);
get_varint_length_prefixed_tlv_length!(len, 2, self.enabled, required);
get_varint_length_prefixed_tlv_length!(len, 4, self.cltv_expiry_delta, required);
get_varint_length_prefixed_tlv_length!(len, 6, self.htlc_minimum_msat, required);
get_varint_length_prefixed_tlv_length!(len, 8, self.htlc_maximum_msat, required);
get_varint_length_prefixed_tlv_length!(len, 10, self.fees, required);
get_varint_length_prefixed_tlv_length!(len, 12, self.last_update_message, required);
len.0
};
let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
len + len_calc.0
}
}
impl MaybeReadable for ChannelUpdateInfo {
fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
init_tlv_field_var!(last_update, required);
init_tlv_field_var!(enabled, required);
init_tlv_field_var!(cltv_expiry_delta, required);
init_tlv_field_var!(htlc_minimum_msat, required);
init_tlv_field_var!(htlc_maximum_msat, required);
init_tlv_field_var!(fees, required);
init_tlv_field_var!(last_update_message, required);
read_tlv_fields!(reader, {
(0, last_update, required),
(2, enabled, required),
(4, cltv_expiry_delta, required),
(6, htlc_minimum_msat, required),
(8, htlc_maximum_msat, required),
(10, fees, required),
(12, last_update_message, required)
});
if let Some(htlc_maximum_msat) = htlc_maximum_msat.0 {
Ok(Some(ChannelUpdateInfo {
last_update: init_tlv_based_struct_field!(last_update, required),
enabled: init_tlv_based_struct_field!(enabled, required),
cltv_expiry_delta: init_tlv_based_struct_field!(cltv_expiry_delta, required),
htlc_minimum_msat: init_tlv_based_struct_field!(htlc_minimum_msat, required),
htlc_maximum_msat,
fees: init_tlv_based_struct_field!(fees, required),
last_update_message: init_tlv_based_struct_field!(last_update_message, required),
}))
} else {
Ok(None)
}
}
}
#[derive(Clone, Debug, PartialEq)]
/// Details about a channel (both directions).
/// Received within a channel announcement.
pub struct ChannelInfo {
/// Protocol features of a channel communicated during its announcement
pub features: ChannelFeatures,
/// Source node of the first direction of a channel
pub node_one: NodeId,
/// Details about the first direction of a channel
pub one_to_two: Option<ChannelUpdateInfo>,
/// Source node of the second direction of a channel
pub node_two: NodeId,
/// Details about the second direction of a channel
pub two_to_one: Option<ChannelUpdateInfo>,
/// The channel capacity as seen on-chain, if chain lookup is available.
pub capacity_sats: Option<u64>,
/// An initial announcement of the channel
/// Mostly redundant with the data we store in fields explicitly.
/// Everything else is useful only for sending out for initial routing sync.
/// Not stored if contains excess data to prevent DoS.
pub announcement_message: Option<ChannelAnnouncement>,
/// The timestamp when we received the announcement, if we are running with feature = "std"
/// (which we can probably assume we are - no-std environments probably won't have a full
/// network graph in memory!).
announcement_received_time: u64,
}
impl ChannelInfo {
/// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
/// returned `source`, or `None` if `target` is not one of the channel's counterparties.
pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
let (direction, source) = {
if target == &self.node_one {
(self.two_to_one.as_ref(), &self.node_two)
} else if target == &self.node_two {
(self.one_to_two.as_ref(), &self.node_one)
} else {
return None;
}
};
Some((DirectedChannelInfo::new(self, direction), source))
}
/// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
/// returned `target`, or `None` if `source` is not one of the channel's counterparties.
pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
let (direction, target) = {
if source == &self.node_one {
(self.one_to_two.as_ref(), &self.node_two)
} else if source == &self.node_two {
(self.two_to_one.as_ref(), &self.node_one)
} else {
return None;
}
};
Some((DirectedChannelInfo::new(self, direction), target))
}
/// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
let direction = channel_flags & 1u8;
if direction == 0 {
self.one_to_two.as_ref()
} else {
self.two_to_one.as_ref()
}
}
}
impl fmt::Display for ChannelInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
log_bytes!(self.features.encode()), log_bytes!(self.node_one.as_slice()), self.one_to_two, log_bytes!(self.node_two.as_slice()), self.two_to_one)?;
Ok(())
}
}
impl Writeable for ChannelInfo {
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.features, required),
(1, self.announcement_received_time, (default_value, 0)),
(2, self.node_one, required),
(4, self.one_to_two, required),
(6, self.node_two, required),
(8, self.two_to_one, required),
(10, self.capacity_sats, required),
(12, self.announcement_message, required),
});
Ok(())
}
#[inline]
fn serialized_length(&self) -> usize {
use util::ser::BigSize;
let len = {
#[allow(unused_mut)]
let mut len = ::util::ser::LengthCalculatingWriter(0);
get_varint_length_prefixed_tlv_length!(len, 0, self.features, required);
get_varint_length_prefixed_tlv_length!(len, 1, self.announcement_received_time, (default_value, 0));
get_varint_length_prefixed_tlv_length!(len, 2, self.node_one, required);
get_varint_length_prefixed_tlv_length!(len, 4, self.one_to_two, required);
get_varint_length_prefixed_tlv_length!(len, 6, self.node_two, required);
get_varint_length_prefixed_tlv_length!(len, 8, self.two_to_one, required);
get_varint_length_prefixed_tlv_length!(len, 10, self.capacity_sats, required);
get_varint_length_prefixed_tlv_length!(len, 12, self.announcement_message, required);
len.0
};
let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
len + len_calc.0
}
}
impl Readable for ChannelInfo {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
init_tlv_field_var!(features, required);
init_tlv_field_var!(announcement_received_time, (default_value, 0));
init_tlv_field_var!(node_one, required);
let mut one_to_two = None;
init_tlv_field_var!(node_two, required);
let mut two_to_one = None;
init_tlv_field_var!(capacity_sats, required);
init_tlv_field_var!(announcement_message, required);
read_tlv_fields!(reader, {
(0, features, required),
(1, announcement_received_time, (default_value, 0)),
(2, node_one, required),
(4, one_to_two, ignorable),
(6, node_two, required),
(8, two_to_one, ignorable),
(10, capacity_sats, required),
(12, announcement_message, required),
});
Ok(ChannelInfo {
features: init_tlv_based_struct_field!(features, required),
node_one: init_tlv_based_struct_field!(node_one, required),
one_to_two,
node_two: init_tlv_based_struct_field!(node_two, required),
two_to_one,
capacity_sats: init_tlv_based_struct_field!(capacity_sats, required),
announcement_message: init_tlv_based_struct_field!(announcement_message, required),
announcement_received_time: init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
})
}
}
/// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
/// source node to a target node.
#[derive(Clone)]
pub struct DirectedChannelInfo<'a> {
channel: &'a ChannelInfo,
direction: Option<&'a ChannelUpdateInfo>,
htlc_maximum_msat: u64,
effective_capacity: EffectiveCapacity,
}
impl<'a> DirectedChannelInfo<'a> {
#[inline]
fn new(channel: &'a ChannelInfo, direction: Option<&'a ChannelUpdateInfo>) -> Self {
let htlc_maximum_msat = direction.map(|direction| direction.htlc_maximum_msat);
let capacity_msat = channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
let (htlc_maximum_msat, effective_capacity) = match (htlc_maximum_msat, capacity_msat) {
(Some(amount_msat), Some(capacity_msat)) => {
let htlc_maximum_msat = cmp::min(amount_msat, capacity_msat);
(htlc_maximum_msat, EffectiveCapacity::Total { capacity_msat })
},
(Some(amount_msat), None) => {
(amount_msat, EffectiveCapacity::MaximumHTLC { amount_msat })
},
(None, Some(capacity_msat)) => {
(capacity_msat, EffectiveCapacity::Total { capacity_msat })
},
(None, None) => (EffectiveCapacity::Unknown.as_msat(), EffectiveCapacity::Unknown),
};
Self {
channel, direction, htlc_maximum_msat, effective_capacity
}
}
/// Returns information for the channel.
pub fn channel(&self) -> &'a ChannelInfo { self.channel }
/// Returns information for the direction.
pub fn direction(&self) -> Option<&'a ChannelUpdateInfo> { self.direction }
/// Returns the maximum HTLC amount allowed over the channel in the direction.
pub fn htlc_maximum_msat(&self) -> u64 {
self.htlc_maximum_msat
}
/// Returns the [`EffectiveCapacity`] of the channel in the direction.
///
/// This is either the total capacity from the funding transaction, if known, or the
/// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
/// otherwise.
pub fn effective_capacity(&self) -> EffectiveCapacity {
self.effective_capacity
}
/// Returns `Some` if [`ChannelUpdateInfo`] is available in the direction.
pub(super) fn with_update(self) -> Option<DirectedChannelInfoWithUpdate<'a>> {
match self.direction {
Some(_) => Some(DirectedChannelInfoWithUpdate { inner: self }),
None => None,
}
}
}
impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("DirectedChannelInfo")
.field("channel", &self.channel)
.finish()
}
}
/// A [`DirectedChannelInfo`] with [`ChannelUpdateInfo`] available in its direction.
#[derive(Clone)]
pub(super) struct DirectedChannelInfoWithUpdate<'a> {
inner: DirectedChannelInfo<'a>,
}
impl<'a> DirectedChannelInfoWithUpdate<'a> {
/// Returns information for the channel.
#[inline]
pub(super) fn channel(&self) -> &'a ChannelInfo { &self.inner.channel }
/// Returns information for the direction.
#[inline]
pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.inner.direction.unwrap() }
/// Returns the [`EffectiveCapacity`] of the channel in the direction.
#[inline]
pub(super) fn effective_capacity(&self) -> EffectiveCapacity { self.inner.effective_capacity() }
/// Returns the maximum HTLC amount allowed over the channel in the direction.
#[inline]
pub(super) fn htlc_maximum_msat(&self) -> u64 { self.inner.htlc_maximum_msat() }
}
impl<'a> fmt::Debug for DirectedChannelInfoWithUpdate<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(f)
}
}
/// The effective capacity of a channel for routing purposes.
///
/// While this may be smaller than the actual channel capacity, amounts greater than
/// [`Self::as_msat`] should not be routed through the channel.
#[derive(Clone, Copy)]
pub enum EffectiveCapacity {
/// The available liquidity in the channel known from being a channel counterparty, and thus a
/// direct hop.
ExactLiquidity {
/// Either the inbound or outbound liquidity depending on the direction, denominated in
/// millisatoshi.
liquidity_msat: u64,
},
/// The maximum HTLC amount in one direction as advertised on the gossip network.
MaximumHTLC {
/// The maximum HTLC amount denominated in millisatoshi.
amount_msat: u64,
},
/// The total capacity of the channel as determined by the funding transaction.
Total {
/// The funding amount denominated in millisatoshi.
capacity_msat: u64,
},
/// A capacity sufficient to route any payment, typically used for private channels provided by
/// an invoice.
Infinite,
/// A capacity that is unknown possibly because either the chain state is unavailable to know
/// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
Unknown,
}
/// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
/// use when making routing decisions.
pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
impl EffectiveCapacity {
/// Returns the effective capacity denominated in millisatoshi.
pub fn as_msat(&self) -> u64 {
match self {
EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
EffectiveCapacity::MaximumHTLC { amount_msat } => *amount_msat,
EffectiveCapacity::Total { capacity_msat } => *capacity_msat,
EffectiveCapacity::Infinite => u64::max_value(),
EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
}
}
}