Parameterize NetworkGraph with Logger
[rust-lightning] / lightning / src / routing / gossip.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level network map tracking logic lives here.
11
12 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
13 use bitcoin::secp256k1::PublicKey;
14 use bitcoin::secp256k1::Secp256k1;
15 use bitcoin::secp256k1;
16
17 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::hashes::Hash;
19 use bitcoin::blockdata::script::Builder;
20 use bitcoin::blockdata::transaction::TxOut;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::hash_types::BlockHash;
23
24 use chain;
25 use chain::Access;
26 use ln::features::{ChannelFeatures, NodeFeatures};
27 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
28 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField, GossipTimestampFilter};
29 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use ln::msgs;
31 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
32 use util::logger::{Logger, Level};
33 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
34 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
35
36 use io;
37 use prelude::*;
38 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
39 use core::{cmp, fmt};
40 use sync::{RwLock, RwLockReadGuard};
41 use core::sync::atomic::{AtomicUsize, Ordering};
42 use sync::Mutex;
43 use core::ops::Deref;
44 use bitcoin::hashes::hex::ToHex;
45
46 #[cfg(feature = "std")]
47 use std::time::{SystemTime, UNIX_EPOCH};
48
49 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
50 /// suggestion.
51 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
52
53 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
54 /// refuse to relay the message.
55 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
56
57 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
58 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
59 const MAX_SCIDS_PER_REPLY: usize = 8000;
60
61 /// Represents the compressed public key of a node
62 #[derive(Clone, Copy)]
63 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
64
65 impl NodeId {
66         /// Create a new NodeId from a public key
67         pub fn from_pubkey(pubkey: &PublicKey) -> Self {
68                 NodeId(pubkey.serialize())
69         }
70
71         /// Get the public key slice from this NodeId
72         pub fn as_slice(&self) -> &[u8] {
73                 &self.0
74         }
75 }
76
77 impl fmt::Debug for NodeId {
78         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79                 write!(f, "NodeId({})", log_bytes!(self.0))
80         }
81 }
82
83 impl core::hash::Hash for NodeId {
84         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
85                 self.0.hash(hasher);
86         }
87 }
88
89 impl Eq for NodeId {}
90
91 impl PartialEq for NodeId {
92         fn eq(&self, other: &Self) -> bool {
93                 self.0[..] == other.0[..]
94         }
95 }
96
97 impl cmp::PartialOrd for NodeId {
98         fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
99                 Some(self.cmp(other))
100         }
101 }
102
103 impl Ord for NodeId {
104         fn cmp(&self, other: &Self) -> cmp::Ordering {
105                 self.0[..].cmp(&other.0[..])
106         }
107 }
108
109 impl Writeable for NodeId {
110         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
111                 writer.write_all(&self.0)?;
112                 Ok(())
113         }
114 }
115
116 impl Readable for NodeId {
117         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
118                 let mut buf = [0; PUBLIC_KEY_SIZE];
119                 reader.read_exact(&mut buf)?;
120                 Ok(Self(buf))
121         }
122 }
123
124 /// Represents the network as nodes and channels between them
125 pub struct NetworkGraph<L: Deref> where L::Target: Logger {
126         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
127         last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
128         genesis_hash: BlockHash,
129         _logger: L,
130         // Lock order: channels -> nodes
131         channels: RwLock<BTreeMap<u64, ChannelInfo>>,
132         nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
133 }
134
135 /// A read-only view of [`NetworkGraph`].
136 pub struct ReadOnlyNetworkGraph<'a> {
137         channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
138         nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
139 }
140
141 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
142 /// return packet by a node along the route. See [BOLT #4] for details.
143 ///
144 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
145 #[derive(Clone, Debug, PartialEq)]
146 pub enum NetworkUpdate {
147         /// An error indicating a `channel_update` messages should be applied via
148         /// [`NetworkGraph::update_channel`].
149         ChannelUpdateMessage {
150                 /// The update to apply via [`NetworkGraph::update_channel`].
151                 msg: ChannelUpdate,
152         },
153         /// An error indicating that a channel failed to route a payment, which should be applied via
154         /// [`NetworkGraph::channel_failed`].
155         ChannelFailure {
156                 /// The short channel id of the closed channel.
157                 short_channel_id: u64,
158                 /// Whether the channel should be permanently removed or temporarily disabled until a new
159                 /// `channel_update` message is received.
160                 is_permanent: bool,
161         },
162         /// An error indicating that a node failed to route a payment, which should be applied via
163         /// [`NetworkGraph::node_failed`].
164         NodeFailure {
165                 /// The node id of the failed node.
166                 node_id: PublicKey,
167                 /// Whether the node should be permanently removed from consideration or can be restored
168                 /// when a new `channel_update` message is received.
169                 is_permanent: bool,
170         }
171 }
172
173 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
174         (0, ChannelUpdateMessage) => {
175                 (0, msg, required),
176         },
177         (2, ChannelFailure) => {
178                 (0, short_channel_id, required),
179                 (2, is_permanent, required),
180         },
181         (4, NodeFailure) => {
182                 (0, node_id, required),
183                 (2, is_permanent, required),
184         },
185 );
186
187 impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> EventHandler for P2PGossipSync<G, C, L>
188 where C::Target: chain::Access, L::Target: Logger {
189         fn handle_event(&self, event: &Event) {
190                 if let Event::PaymentPathFailed { payment_hash: _, rejected_by_dest: _, network_update, .. } = event {
191                         if let Some(network_update) = network_update {
192                                 self.handle_network_update(network_update);
193                         }
194                 }
195         }
196 }
197
198 /// Receives and validates network updates from peers,
199 /// stores authentic and relevant data as a network graph.
200 /// This network graph is then used for routing payments.
201 /// Provides interface to help with initial routing sync by
202 /// serving historical announcements.
203 ///
204 /// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentPathFailed`] to the
205 /// [`NetworkGraph`].
206 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref>
207 where C::Target: chain::Access, L::Target: Logger
208 {
209         network_graph: G,
210         chain_access: Option<C>,
211         full_syncs_requested: AtomicUsize,
212         pending_events: Mutex<Vec<MessageSendEvent>>,
213         logger: L,
214 }
215
216 impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> P2PGossipSync<G, C, L>
217 where C::Target: chain::Access, L::Target: Logger
218 {
219         /// Creates a new tracker of the actual state of the network of channels and nodes,
220         /// assuming an existing Network Graph.
221         /// Chain monitor is used to make sure announced channels exist on-chain,
222         /// channel data is correct, and that the announcement is signed with
223         /// channel owners' keys.
224         pub fn new(network_graph: G, chain_access: Option<C>, logger: L) -> Self {
225                 P2PGossipSync {
226                         network_graph,
227                         full_syncs_requested: AtomicUsize::new(0),
228                         chain_access,
229                         pending_events: Mutex::new(vec![]),
230                         logger,
231                 }
232         }
233
234         /// Adds a provider used to check new announcements. Does not affect
235         /// existing announcements unless they are updated.
236         /// Add, update or remove the provider would replace the current one.
237         pub fn add_chain_access(&mut self, chain_access: Option<C>) {
238                 self.chain_access = chain_access;
239         }
240
241         /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
242         /// [`P2PGossipSync::new`].
243         ///
244         /// (C-not exported) as bindings don't support a reference-to-a-reference yet
245         pub fn network_graph(&self) -> &G {
246                 &self.network_graph
247         }
248
249         /// Returns true when a full routing table sync should be performed with a peer.
250         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
251                 //TODO: Determine whether to request a full sync based on the network map.
252                 const FULL_SYNCS_TO_REQUEST: usize = 5;
253                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
254                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
255                         true
256                 } else {
257                         false
258                 }
259         }
260
261         /// Applies changes to the [`NetworkGraph`] from the given update.
262         fn handle_network_update(&self, update: &NetworkUpdate) {
263                 match *update {
264                         NetworkUpdate::ChannelUpdateMessage { ref msg } => {
265                                 let short_channel_id = msg.contents.short_channel_id;
266                                 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
267                                 let status = if is_enabled { "enabled" } else { "disabled" };
268                                 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
269                                 let _ = self.network_graph.update_channel(msg);
270                         },
271                         NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
272                                 let action = if is_permanent { "Removing" } else { "Disabling" };
273                                 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
274                                 self.network_graph.channel_failed(short_channel_id, is_permanent);
275                         },
276                         NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
277                                 let action = if is_permanent { "Removing" } else { "Disabling" };
278                                 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
279                                 self.network_graph.node_failed(node_id, is_permanent);
280                         },
281                 }
282         }
283 }
284
285 macro_rules! secp_verify_sig {
286         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
287                 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
288                         Ok(_) => {},
289                         Err(_) => {
290                                 return Err(LightningError {
291                                         err: format!("Invalid signature on {} message", $msg_type),
292                                         action: ErrorAction::SendWarningMessage {
293                                                 msg: msgs::WarningMessage {
294                                                         channel_id: [0; 32],
295                                                         data: format!("Invalid signature on {} message", $msg_type),
296                                                 },
297                                                 log_level: Level::Trace,
298                                         },
299                                 });
300                         },
301                 }
302         };
303 }
304
305 impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, C, L>
306 where C::Target: chain::Access, L::Target: Logger
307 {
308         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
309                 self.network_graph.update_node_from_announcement(msg)?;
310                 Ok(msg.contents.excess_data.len() <=  MAX_EXCESS_BYTES_FOR_RELAY &&
311                    msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
312                    msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
313         }
314
315         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
316                 self.network_graph.update_channel_from_announcement(msg, &self.chain_access)?;
317                 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 { "" });
318                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
319         }
320
321         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
322                 self.network_graph.update_channel(msg)?;
323                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
324         }
325
326         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
327                 let mut result = Vec::with_capacity(batch_amount as usize);
328                 let channels = self.network_graph.channels.read().unwrap();
329                 let mut iter = channels.range(starting_point..);
330                 while result.len() < batch_amount as usize {
331                         if let Some((_, ref chan)) = iter.next() {
332                                 if chan.announcement_message.is_some() {
333                                         let chan_announcement = chan.announcement_message.clone().unwrap();
334                                         let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
335                                         let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
336                                         if let Some(one_to_two) = chan.one_to_two.as_ref() {
337                                                 one_to_two_announcement = one_to_two.last_update_message.clone();
338                                         }
339                                         if let Some(two_to_one) = chan.two_to_one.as_ref() {
340                                                 two_to_one_announcement = two_to_one.last_update_message.clone();
341                                         }
342                                         result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
343                                 } else {
344                                         // TODO: We may end up sending un-announced channel_updates if we are sending
345                                         // initial sync data while receiving announce/updates for this channel.
346                                 }
347                         } else {
348                                 return result;
349                         }
350                 }
351                 result
352         }
353
354         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
355                 let mut result = Vec::with_capacity(batch_amount as usize);
356                 let nodes = self.network_graph.nodes.read().unwrap();
357                 let mut iter = if let Some(pubkey) = starting_point {
358                                 let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
359                                 iter.next();
360                                 iter
361                         } else {
362                                 nodes.range::<NodeId, _>(..)
363                         };
364                 while result.len() < batch_amount as usize {
365                         if let Some((_, ref node)) = iter.next() {
366                                 if let Some(node_info) = node.announcement_info.as_ref() {
367                                         if node_info.announcement_message.is_some() {
368                                                 result.push(node_info.announcement_message.clone().unwrap());
369                                         }
370                                 }
371                         } else {
372                                 return result;
373                         }
374                 }
375                 result
376         }
377
378         /// Initiates a stateless sync of routing gossip information with a peer
379         /// using gossip_queries. The default strategy used by this implementation
380         /// is to sync the full block range with several peers.
381         ///
382         /// We should expect one or more reply_channel_range messages in response
383         /// to our query_channel_range. Each reply will enqueue a query_scid message
384         /// to request gossip messages for each channel. The sync is considered complete
385         /// when the final reply_scids_end message is received, though we are not
386         /// tracking this directly.
387         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init) {
388                 // We will only perform a sync with peers that support gossip_queries.
389                 if !init_msg.features.supports_gossip_queries() {
390                         return ();
391                 }
392
393                 // The lightning network's gossip sync system is completely broken in numerous ways.
394                 //
395                 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
396                 // to do a full sync from the first few peers we connect to, and then receive gossip
397                 // updates from all our peers normally.
398                 //
399                 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
400                 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
401                 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
402                 // seen.
403                 //
404                 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
405                 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
406                 // channel data which you are missing. Except there was no way at all to identify which
407                 // `channel_update`s you were missing, so you still had to request everything, just in a
408                 // very complicated way with some queries instead of just getting the dump.
409                 //
410                 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
411                 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
412                 // relying on it useless.
413                 //
414                 // After gossip queries were introduced, support for receiving a full gossip table dump on
415                 // connection was removed from several nodes, making it impossible to get a full sync
416                 // without using the "gossip queries" messages.
417                 //
418                 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
419                 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
420                 // message, as the name implies, tells the peer to not forward any gossip messages with a
421                 // timestamp older than a given value (not the time the peer received the filter, but the
422                 // timestamp in the update message, which is often hours behind when the peer received the
423                 // message).
424                 //
425                 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
426                 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
427                 // tell a peer to send you any updates as it sees them, you have to also ask for the full
428                 // routing graph to be synced. If you set a timestamp filter near the current time, peers
429                 // will simply not forward any new updates they see to you which were generated some time
430                 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
431                 // ago), you will always get the full routing graph from all your peers.
432                 //
433                 // Most lightning nodes today opt to simply turn off receiving gossip data which only
434                 // propagated some time after it was generated, and, worse, often disable gossiping with
435                 // several peers after their first connection. The second behavior can cause gossip to not
436                 // propagate fully if there are cuts in the gossiping subgraph.
437                 //
438                 // In an attempt to cut a middle ground between always fetching the full graph from all of
439                 // our peers and never receiving gossip from peers at all, we send all of our peers a
440                 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
441                 //
442                 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
443                 let should_request_full_sync = self.should_request_full_sync(&their_node_id);
444                 #[allow(unused_mut, unused_assignments)]
445                 let mut gossip_start_time = 0;
446                 #[cfg(feature = "std")]
447                 {
448                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
449                         if should_request_full_sync {
450                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
451                         } else {
452                                 gossip_start_time -= 60 * 60; // an hour ago
453                         }
454                 }
455
456                 let mut pending_events = self.pending_events.lock().unwrap();
457                 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
458                         node_id: their_node_id.clone(),
459                         msg: GossipTimestampFilter {
460                                 chain_hash: self.network_graph.genesis_hash,
461                                 first_timestamp: gossip_start_time as u32, // 2106 issue!
462                                 timestamp_range: u32::max_value(),
463                         },
464                 });
465         }
466
467         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
468                 // We don't make queries, so should never receive replies. If, in the future, the set
469                 // reconciliation extensions to gossip queries become broadly supported, we should revert
470                 // this code to its state pre-0.0.106.
471                 Ok(())
472         }
473
474         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
475                 // We don't make queries, so should never receive replies. If, in the future, the set
476                 // reconciliation extensions to gossip queries become broadly supported, we should revert
477                 // this code to its state pre-0.0.106.
478                 Ok(())
479         }
480
481         /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
482         /// are in the specified block range. Due to message size limits, large range
483         /// queries may result in several reply messages. This implementation enqueues
484         /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
485         /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
486         /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
487         /// memory constrained systems.
488         fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
489                 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);
490
491                 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
492
493                 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
494                 // If so, we manually cap the ending block to avoid this overflow.
495                 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
496
497                 // Per spec, we must reply to a query. Send an empty message when things are invalid.
498                 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
499                         let mut pending_events = self.pending_events.lock().unwrap();
500                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
501                                 node_id: their_node_id.clone(),
502                                 msg: ReplyChannelRange {
503                                         chain_hash: msg.chain_hash.clone(),
504                                         first_blocknum: msg.first_blocknum,
505                                         number_of_blocks: msg.number_of_blocks,
506                                         sync_complete: true,
507                                         short_channel_ids: vec![],
508                                 }
509                         });
510                         return Err(LightningError {
511                                 err: String::from("query_channel_range could not be processed"),
512                                 action: ErrorAction::IgnoreError,
513                         });
514                 }
515
516                 // Creates channel batches. We are not checking if the channel is routable
517                 // (has at least one update). A peer may still want to know the channel
518                 // exists even if its not yet routable.
519                 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
520                 let channels = self.network_graph.channels.read().unwrap();
521                 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
522                         if let Some(chan_announcement) = &chan.announcement_message {
523                                 // Construct a new batch if last one is full
524                                 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
525                                         batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
526                                 }
527
528                                 let batch = batches.last_mut().unwrap();
529                                 batch.push(chan_announcement.contents.short_channel_id);
530                         }
531                 }
532                 drop(channels);
533
534                 let mut pending_events = self.pending_events.lock().unwrap();
535                 let batch_count = batches.len();
536                 let mut prev_batch_endblock = msg.first_blocknum;
537                 for (batch_index, batch) in batches.into_iter().enumerate() {
538                         // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
539                         // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
540                         //
541                         // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
542                         // reply is >= the previous reply's `first_blocknum` and either exactly the previous
543                         // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
544                         // significant diversion from the requirements set by the spec, and, in case of blocks
545                         // with no channel opens (e.g. empty blocks), requires that we use the previous value
546                         // and *not* derive the first_blocknum from the actual first block of the reply.
547                         let first_blocknum = prev_batch_endblock;
548
549                         // Each message carries the number of blocks (from the `first_blocknum`) its contents
550                         // fit in. Though there is no requirement that we use exactly the number of blocks its
551                         // contents are from, except for the bogus requirements c-lightning enforces, above.
552                         //
553                         // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
554                         // >= the query's end block. Thus, for the last reply, we calculate the difference
555                         // between the query's end block and the start of the reply.
556                         //
557                         // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
558                         // first_blocknum will be either msg.first_blocknum or a higher block height.
559                         let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
560                                 (true, msg.end_blocknum() - first_blocknum)
561                         }
562                         // Prior replies should use the number of blocks that fit into the reply. Overflow
563                         // safe since first_blocknum is always <= last SCID's block.
564                         else {
565                                 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
566                         };
567
568                         prev_batch_endblock = first_blocknum + number_of_blocks;
569
570                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
571                                 node_id: their_node_id.clone(),
572                                 msg: ReplyChannelRange {
573                                         chain_hash: msg.chain_hash.clone(),
574                                         first_blocknum,
575                                         number_of_blocks,
576                                         sync_complete,
577                                         short_channel_ids: batch,
578                                 }
579                         });
580                 }
581
582                 Ok(())
583         }
584
585         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
586                 // TODO
587                 Err(LightningError {
588                         err: String::from("Not implemented"),
589                         action: ErrorAction::IgnoreError,
590                 })
591         }
592 }
593
594 impl<G: Deref<Target=NetworkGraph<L>>, C: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, C, L>
595 where
596         C::Target: chain::Access,
597         L::Target: Logger,
598 {
599         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
600                 let mut ret = Vec::new();
601                 let mut pending_events = self.pending_events.lock().unwrap();
602                 core::mem::swap(&mut ret, &mut pending_events);
603                 ret
604         }
605 }
606
607 #[derive(Clone, Debug, PartialEq)]
608 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
609 pub struct ChannelUpdateInfo {
610         /// When the last update to the channel direction was issued.
611         /// Value is opaque, as set in the announcement.
612         pub last_update: u32,
613         /// Whether the channel can be currently used for payments (in this one direction).
614         pub enabled: bool,
615         /// The difference in CLTV values that you must have when routing through this channel.
616         pub cltv_expiry_delta: u16,
617         /// The minimum value, which must be relayed to the next hop via the channel
618         pub htlc_minimum_msat: u64,
619         /// The maximum value which may be relayed to the next hop via the channel.
620         pub htlc_maximum_msat: Option<u64>,
621         /// Fees charged when the channel is used for routing
622         pub fees: RoutingFees,
623         /// Most recent update for the channel received from the network
624         /// Mostly redundant with the data we store in fields explicitly.
625         /// Everything else is useful only for sending out for initial routing sync.
626         /// Not stored if contains excess data to prevent DoS.
627         pub last_update_message: Option<ChannelUpdate>,
628 }
629
630 impl fmt::Display for ChannelUpdateInfo {
631         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
632                 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)?;
633                 Ok(())
634         }
635 }
636
637 impl_writeable_tlv_based!(ChannelUpdateInfo, {
638         (0, last_update, required),
639         (2, enabled, required),
640         (4, cltv_expiry_delta, required),
641         (6, htlc_minimum_msat, required),
642         (8, htlc_maximum_msat, required),
643         (10, fees, required),
644         (12, last_update_message, required),
645 });
646
647 #[derive(Clone, Debug, PartialEq)]
648 /// Details about a channel (both directions).
649 /// Received within a channel announcement.
650 pub struct ChannelInfo {
651         /// Protocol features of a channel communicated during its announcement
652         pub features: ChannelFeatures,
653         /// Source node of the first direction of a channel
654         pub node_one: NodeId,
655         /// Details about the first direction of a channel
656         pub one_to_two: Option<ChannelUpdateInfo>,
657         /// Source node of the second direction of a channel
658         pub node_two: NodeId,
659         /// Details about the second direction of a channel
660         pub two_to_one: Option<ChannelUpdateInfo>,
661         /// The channel capacity as seen on-chain, if chain lookup is available.
662         pub capacity_sats: Option<u64>,
663         /// An initial announcement of the channel
664         /// Mostly redundant with the data we store in fields explicitly.
665         /// Everything else is useful only for sending out for initial routing sync.
666         /// Not stored if contains excess data to prevent DoS.
667         pub announcement_message: Option<ChannelAnnouncement>,
668         /// The timestamp when we received the announcement, if we are running with feature = "std"
669         /// (which we can probably assume we are - no-std environments probably won't have a full
670         /// network graph in memory!).
671         announcement_received_time: u64,
672 }
673
674 impl ChannelInfo {
675         /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
676         /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
677         pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
678                 let (direction, source) = {
679                         if target == &self.node_one {
680                                 (self.two_to_one.as_ref(), &self.node_two)
681                         } else if target == &self.node_two {
682                                 (self.one_to_two.as_ref(), &self.node_one)
683                         } else {
684                                 return None;
685                         }
686                 };
687                 Some((DirectedChannelInfo::new(self, direction), source))
688         }
689
690         /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
691         /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
692         pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
693                 let (direction, target) = {
694                         if source == &self.node_one {
695                                 (self.one_to_two.as_ref(), &self.node_two)
696                         } else if source == &self.node_two {
697                                 (self.two_to_one.as_ref(), &self.node_one)
698                         } else {
699                                 return None;
700                         }
701                 };
702                 Some((DirectedChannelInfo::new(self, direction), target))
703         }
704
705         /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
706         pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
707                 let direction = channel_flags & 1u8;
708                 if direction == 0 {
709                         self.one_to_two.as_ref()
710                 } else {
711                         self.two_to_one.as_ref()
712                 }
713         }
714 }
715
716 impl fmt::Display for ChannelInfo {
717         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
718                 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
719                    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)?;
720                 Ok(())
721         }
722 }
723
724 impl_writeable_tlv_based!(ChannelInfo, {
725         (0, features, required),
726         (1, announcement_received_time, (default_value, 0)),
727         (2, node_one, required),
728         (4, one_to_two, required),
729         (6, node_two, required),
730         (8, two_to_one, required),
731         (10, capacity_sats, required),
732         (12, announcement_message, required),
733 });
734
735 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
736 /// source node to a target node.
737 #[derive(Clone)]
738 pub struct DirectedChannelInfo<'a> {
739         channel: &'a ChannelInfo,
740         direction: Option<&'a ChannelUpdateInfo>,
741         htlc_maximum_msat: u64,
742         effective_capacity: EffectiveCapacity,
743 }
744
745 impl<'a> DirectedChannelInfo<'a> {
746         #[inline]
747         fn new(channel: &'a ChannelInfo, direction: Option<&'a ChannelUpdateInfo>) -> Self {
748                 let htlc_maximum_msat = direction.and_then(|direction| direction.htlc_maximum_msat);
749                 let capacity_msat = channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
750
751                 let (htlc_maximum_msat, effective_capacity) = match (htlc_maximum_msat, capacity_msat) {
752                         (Some(amount_msat), Some(capacity_msat)) => {
753                                 let htlc_maximum_msat = cmp::min(amount_msat, capacity_msat);
754                                 (htlc_maximum_msat, EffectiveCapacity::Total { capacity_msat })
755                         },
756                         (Some(amount_msat), None) => {
757                                 (amount_msat, EffectiveCapacity::MaximumHTLC { amount_msat })
758                         },
759                         (None, Some(capacity_msat)) => {
760                                 (capacity_msat, EffectiveCapacity::Total { capacity_msat })
761                         },
762                         (None, None) => (EffectiveCapacity::Unknown.as_msat(), EffectiveCapacity::Unknown),
763                 };
764
765                 Self {
766                         channel, direction, htlc_maximum_msat, effective_capacity
767                 }
768         }
769
770         /// Returns information for the channel.
771         pub fn channel(&self) -> &'a ChannelInfo { self.channel }
772
773         /// Returns information for the direction.
774         pub fn direction(&self) -> Option<&'a ChannelUpdateInfo> { self.direction }
775
776         /// Returns the maximum HTLC amount allowed over the channel in the direction.
777         pub fn htlc_maximum_msat(&self) -> u64 {
778                 self.htlc_maximum_msat
779         }
780
781         /// Returns the [`EffectiveCapacity`] of the channel in the direction.
782         ///
783         /// This is either the total capacity from the funding transaction, if known, or the
784         /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
785         /// otherwise.
786         pub fn effective_capacity(&self) -> EffectiveCapacity {
787                 self.effective_capacity
788         }
789
790         /// Returns `Some` if [`ChannelUpdateInfo`] is available in the direction.
791         pub(super) fn with_update(self) -> Option<DirectedChannelInfoWithUpdate<'a>> {
792                 match self.direction {
793                         Some(_) => Some(DirectedChannelInfoWithUpdate { inner: self }),
794                         None => None,
795                 }
796         }
797 }
798
799 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
800         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
801                 f.debug_struct("DirectedChannelInfo")
802                         .field("channel", &self.channel)
803                         .finish()
804         }
805 }
806
807 /// A [`DirectedChannelInfo`] with [`ChannelUpdateInfo`] available in its direction.
808 #[derive(Clone)]
809 pub(super) struct DirectedChannelInfoWithUpdate<'a> {
810         inner: DirectedChannelInfo<'a>,
811 }
812
813 impl<'a> DirectedChannelInfoWithUpdate<'a> {
814         /// Returns information for the channel.
815         #[inline]
816         pub(super) fn channel(&self) -> &'a ChannelInfo { &self.inner.channel }
817
818         /// Returns information for the direction.
819         #[inline]
820         pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.inner.direction.unwrap() }
821
822         /// Returns the [`EffectiveCapacity`] of the channel in the direction.
823         #[inline]
824         pub(super) fn effective_capacity(&self) -> EffectiveCapacity { self.inner.effective_capacity() }
825
826         /// Returns the maximum HTLC amount allowed over the channel in the direction.
827         #[inline]
828         pub(super) fn htlc_maximum_msat(&self) -> u64 { self.inner.htlc_maximum_msat() }
829 }
830
831 impl<'a> fmt::Debug for DirectedChannelInfoWithUpdate<'a> {
832         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
833                 self.inner.fmt(f)
834         }
835 }
836
837 /// The effective capacity of a channel for routing purposes.
838 ///
839 /// While this may be smaller than the actual channel capacity, amounts greater than
840 /// [`Self::as_msat`] should not be routed through the channel.
841 #[derive(Clone, Copy)]
842 pub enum EffectiveCapacity {
843         /// The available liquidity in the channel known from being a channel counterparty, and thus a
844         /// direct hop.
845         ExactLiquidity {
846                 /// Either the inbound or outbound liquidity depending on the direction, denominated in
847                 /// millisatoshi.
848                 liquidity_msat: u64,
849         },
850         /// The maximum HTLC amount in one direction as advertised on the gossip network.
851         MaximumHTLC {
852                 /// The maximum HTLC amount denominated in millisatoshi.
853                 amount_msat: u64,
854         },
855         /// The total capacity of the channel as determined by the funding transaction.
856         Total {
857                 /// The funding amount denominated in millisatoshi.
858                 capacity_msat: u64,
859         },
860         /// A capacity sufficient to route any payment, typically used for private channels provided by
861         /// an invoice.
862         Infinite,
863         /// A capacity that is unknown possibly because either the chain state is unavailable to know
864         /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
865         Unknown,
866 }
867
868 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
869 /// use when making routing decisions.
870 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
871
872 impl EffectiveCapacity {
873         /// Returns the effective capacity denominated in millisatoshi.
874         pub fn as_msat(&self) -> u64 {
875                 match self {
876                         EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
877                         EffectiveCapacity::MaximumHTLC { amount_msat } => *amount_msat,
878                         EffectiveCapacity::Total { capacity_msat } => *capacity_msat,
879                         EffectiveCapacity::Infinite => u64::max_value(),
880                         EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
881                 }
882         }
883 }
884
885 /// Fees for routing via a given channel or a node
886 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
887 pub struct RoutingFees {
888         /// Flat routing fee in satoshis
889         pub base_msat: u32,
890         /// Liquidity-based routing fee in millionths of a routed amount.
891         /// In other words, 10000 is 1%.
892         pub proportional_millionths: u32,
893 }
894
895 impl_writeable_tlv_based!(RoutingFees, {
896         (0, base_msat, required),
897         (2, proportional_millionths, required)
898 });
899
900 #[derive(Clone, Debug, PartialEq)]
901 /// Information received in the latest node_announcement from this node.
902 pub struct NodeAnnouncementInfo {
903         /// Protocol features the node announced support for
904         pub features: NodeFeatures,
905         /// When the last known update to the node state was issued.
906         /// Value is opaque, as set in the announcement.
907         pub last_update: u32,
908         /// Color assigned to the node
909         pub rgb: [u8; 3],
910         /// Moniker assigned to the node.
911         /// May be invalid or malicious (eg control chars),
912         /// should not be exposed to the user.
913         pub alias: [u8; 32],
914         /// Internet-level addresses via which one can connect to the node
915         pub addresses: Vec<NetAddress>,
916         /// An initial announcement of the node
917         /// Mostly redundant with the data we store in fields explicitly.
918         /// Everything else is useful only for sending out for initial routing sync.
919         /// Not stored if contains excess data to prevent DoS.
920         pub announcement_message: Option<NodeAnnouncement>
921 }
922
923 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
924         (0, features, required),
925         (2, last_update, required),
926         (4, rgb, required),
927         (6, alias, required),
928         (8, announcement_message, option),
929         (10, addresses, vec_type),
930 });
931
932 #[derive(Clone, Debug, PartialEq)]
933 /// Details about a node in the network, known from the network announcement.
934 pub struct NodeInfo {
935         /// All valid channels a node has announced
936         pub channels: Vec<u64>,
937         /// Lowest fees enabling routing via any of the enabled, known channels to a node.
938         /// The two fields (flat and proportional fee) are independent,
939         /// meaning they don't have to refer to the same channel.
940         pub lowest_inbound_channel_fees: Option<RoutingFees>,
941         /// More information about a node from node_announcement.
942         /// Optional because we store a Node entry after learning about it from
943         /// a channel announcement, but before receiving a node announcement.
944         pub announcement_info: Option<NodeAnnouncementInfo>
945 }
946
947 impl fmt::Display for NodeInfo {
948         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
949                 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
950                    self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
951                 Ok(())
952         }
953 }
954
955 impl_writeable_tlv_based!(NodeInfo, {
956         (0, lowest_inbound_channel_fees, option),
957         (2, announcement_info, option),
958         (4, channels, vec_type),
959 });
960
961 const SERIALIZATION_VERSION: u8 = 1;
962 const MIN_SERIALIZATION_VERSION: u8 = 1;
963
964 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
965         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
966                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
967
968                 self.genesis_hash.write(writer)?;
969                 let channels = self.channels.read().unwrap();
970                 (channels.len() as u64).write(writer)?;
971                 for (ref chan_id, ref chan_info) in channels.iter() {
972                         (*chan_id).write(writer)?;
973                         chan_info.write(writer)?;
974                 }
975                 let nodes = self.nodes.read().unwrap();
976                 (nodes.len() as u64).write(writer)?;
977                 for (ref node_id, ref node_info) in nodes.iter() {
978                         node_id.write(writer)?;
979                         node_info.write(writer)?;
980                 }
981
982                 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
983                 write_tlv_fields!(writer, {
984                         (1, last_rapid_gossip_sync_timestamp, option),
985                 });
986                 Ok(())
987         }
988 }
989
990 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
991         fn read<R: io::Read>(reader: &mut R, _logger: L) -> Result<NetworkGraph<L>, DecodeError> {
992                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
993
994                 let genesis_hash: BlockHash = Readable::read(reader)?;
995                 let channels_count: u64 = Readable::read(reader)?;
996                 let mut channels = BTreeMap::new();
997                 for _ in 0..channels_count {
998                         let chan_id: u64 = Readable::read(reader)?;
999                         let chan_info = Readable::read(reader)?;
1000                         channels.insert(chan_id, chan_info);
1001                 }
1002                 let nodes_count: u64 = Readable::read(reader)?;
1003                 let mut nodes = BTreeMap::new();
1004                 for _ in 0..nodes_count {
1005                         let node_id = Readable::read(reader)?;
1006                         let node_info = Readable::read(reader)?;
1007                         nodes.insert(node_id, node_info);
1008                 }
1009
1010                 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1011                 read_tlv_fields!(reader, {
1012                         (1, last_rapid_gossip_sync_timestamp, option),
1013                 });
1014
1015                 Ok(NetworkGraph {
1016                         secp_ctx: Secp256k1::verification_only(),
1017                         genesis_hash,
1018                         _logger,
1019                         channels: RwLock::new(channels),
1020                         nodes: RwLock::new(nodes),
1021                         last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1022                 })
1023         }
1024 }
1025
1026 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1027         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1028                 writeln!(f, "Network map\n[Channels]")?;
1029                 for (key, val) in self.channels.read().unwrap().iter() {
1030                         writeln!(f, " {}: {}", key, val)?;
1031                 }
1032                 writeln!(f, "[Nodes]")?;
1033                 for (&node_id, val) in self.nodes.read().unwrap().iter() {
1034                         writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
1035                 }
1036                 Ok(())
1037         }
1038 }
1039
1040 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1041         fn eq(&self, other: &Self) -> bool {
1042                 self.genesis_hash == other.genesis_hash &&
1043                         *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
1044                         *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
1045         }
1046 }
1047
1048 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1049         /// Creates a new, empty, network graph.
1050         pub fn new(genesis_hash: BlockHash, _logger: L) -> NetworkGraph<L> {
1051                 Self {
1052                         secp_ctx: Secp256k1::verification_only(),
1053                         genesis_hash,
1054                         _logger,
1055                         channels: RwLock::new(BTreeMap::new()),
1056                         nodes: RwLock::new(BTreeMap::new()),
1057                         last_rapid_gossip_sync_timestamp: Mutex::new(None),
1058                 }
1059         }
1060
1061         /// Returns a read-only view of the network graph.
1062         pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1063                 let channels = self.channels.read().unwrap();
1064                 let nodes = self.nodes.read().unwrap();
1065                 ReadOnlyNetworkGraph {
1066                         channels,
1067                         nodes,
1068                 }
1069         }
1070
1071         /// The unix timestamp provided by the most recent rapid gossip sync.
1072         /// It will be set by the rapid sync process after every sync completion.
1073         pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1074                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1075         }
1076
1077         /// Update the unix timestamp provided by the most recent rapid gossip sync.
1078         /// This should be done automatically by the rapid sync process after every sync completion.
1079         pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1080                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1081         }
1082
1083         /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1084         /// purposes.
1085         #[cfg(test)]
1086         pub fn clear_nodes_announcement_info(&self) {
1087                 for node in self.nodes.write().unwrap().iter_mut() {
1088                         node.1.announcement_info = None;
1089                 }
1090         }
1091
1092         /// For an already known node (from channel announcements), update its stored properties from a
1093         /// given node announcement.
1094         ///
1095         /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1096         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1097         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1098         pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1099                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1100                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id, "node_announcement");
1101                 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1102         }
1103
1104         /// For an already known node (from channel announcements), update its stored properties from a
1105         /// given node announcement without verifying the associated signatures. Because we aren't
1106         /// given the associated signatures here we cannot relay the node announcement to any of our
1107         /// peers.
1108         pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1109                 self.update_node_from_announcement_intern(msg, None)
1110         }
1111
1112         fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1113                 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
1114                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
1115                         Some(node) => {
1116                                 if let Some(node_info) = node.announcement_info.as_ref() {
1117                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1118                                         // updates to ensure you always have the latest one, only vaguely suggesting
1119                                         // that it be at least the current time.
1120                                         if node_info.last_update  > msg.timestamp {
1121                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1122                                         } else if node_info.last_update  == msg.timestamp {
1123                                                 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1124                                         }
1125                                 }
1126
1127                                 let should_relay =
1128                                         msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1129                                         msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1130                                         msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1131                                 node.announcement_info = Some(NodeAnnouncementInfo {
1132                                         features: msg.features.clone(),
1133                                         last_update: msg.timestamp,
1134                                         rgb: msg.rgb,
1135                                         alias: msg.alias,
1136                                         addresses: msg.addresses.clone(),
1137                                         announcement_message: if should_relay { full_msg.cloned() } else { None },
1138                                 });
1139
1140                                 Ok(())
1141                         }
1142                 }
1143         }
1144
1145         /// Store or update channel info from a channel announcement.
1146         ///
1147         /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1148         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1149         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1150         ///
1151         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1152         /// the corresponding UTXO exists on chain and is correctly-formatted.
1153         pub fn update_channel_from_announcement<C: Deref>(
1154                 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>,
1155         ) -> Result<(), LightningError>
1156         where
1157                 C::Target: chain::Access,
1158         {
1159                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1160                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1, "channel_announcement");
1161                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2, "channel_announcement");
1162                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1, "channel_announcement");
1163                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2, "channel_announcement");
1164                 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
1165         }
1166
1167         /// Store or update channel info from a channel announcement without verifying the associated
1168         /// signatures. Because we aren't given the associated signatures here we cannot relay the
1169         /// channel announcement to any of our peers.
1170         ///
1171         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1172         /// the corresponding UTXO exists on chain and is correctly-formatted.
1173         pub fn update_channel_from_unsigned_announcement<C: Deref>(
1174                 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
1175         ) -> Result<(), LightningError>
1176         where
1177                 C::Target: chain::Access,
1178         {
1179                 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
1180         }
1181
1182         /// Update channel from partial announcement data received via rapid gossip sync
1183         ///
1184         /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1185         /// rapid gossip sync server)
1186         ///
1187         /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1188         pub fn add_channel_from_partial_announcement(&self, short_channel_id: u64, timestamp: u64, features: ChannelFeatures, node_id_1: PublicKey, node_id_2: PublicKey) -> Result<(), LightningError> {
1189                 if node_id_1 == node_id_2 {
1190                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1191                 };
1192
1193                 let node_1 = NodeId::from_pubkey(&node_id_1);
1194                 let node_2 = NodeId::from_pubkey(&node_id_2);
1195                 let channel_info = ChannelInfo {
1196                         features,
1197                         node_one: node_1.clone(),
1198                         one_to_two: None,
1199                         node_two: node_2.clone(),
1200                         two_to_one: None,
1201                         capacity_sats: None,
1202                         announcement_message: None,
1203                         announcement_received_time: timestamp,
1204                 };
1205
1206                 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1207         }
1208
1209         fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1210                 let mut channels = self.channels.write().unwrap();
1211                 let mut nodes = self.nodes.write().unwrap();
1212
1213                 let node_id_a = channel_info.node_one.clone();
1214                 let node_id_b = channel_info.node_two.clone();
1215
1216                 match channels.entry(short_channel_id) {
1217                         BtreeEntry::Occupied(mut entry) => {
1218                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1219                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
1220                                 //exactly how...
1221                                 if utxo_value.is_some() {
1222                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1223                                         // only sometimes returns results. In any case remove the previous entry. Note
1224                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
1225                                         // do that because
1226                                         // a) we don't *require* a UTXO provider that always returns results.
1227                                         // b) we don't track UTXOs of channels we know about and remove them if they
1228                                         //    get reorg'd out.
1229                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1230                                         Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1231                                         *entry.get_mut() = channel_info;
1232                                 } else {
1233                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1234                                 }
1235                         },
1236                         BtreeEntry::Vacant(entry) => {
1237                                 entry.insert(channel_info);
1238                         }
1239                 };
1240
1241                 for current_node_id in [node_id_a, node_id_b].iter() {
1242                         match nodes.entry(current_node_id.clone()) {
1243                                 BtreeEntry::Occupied(node_entry) => {
1244                                         node_entry.into_mut().channels.push(short_channel_id);
1245                                 },
1246                                 BtreeEntry::Vacant(node_entry) => {
1247                                         node_entry.insert(NodeInfo {
1248                                                 channels: vec!(short_channel_id),
1249                                                 lowest_inbound_channel_fees: None,
1250                                                 announcement_info: None,
1251                                         });
1252                                 }
1253                         };
1254                 };
1255
1256                 Ok(())
1257         }
1258
1259         fn update_channel_from_unsigned_announcement_intern<C: Deref>(
1260                 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
1261         ) -> Result<(), LightningError>
1262         where
1263                 C::Target: chain::Access,
1264         {
1265                 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1266                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1267                 }
1268
1269                 let utxo_value = match &chain_access {
1270                         &None => {
1271                                 // Tentatively accept, potentially exposing us to DoS attacks
1272                                 None
1273                         },
1274                         &Some(ref chain_access) => {
1275                                 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
1276                                         Ok(TxOut { value, script_pubkey }) => {
1277                                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1278                                                                                     .push_slice(&msg.bitcoin_key_1.serialize())
1279                                                                                     .push_slice(&msg.bitcoin_key_2.serialize())
1280                                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
1281                                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1282                                                 if script_pubkey != expected_script {
1283                                                         return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
1284                                                 }
1285                                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
1286                                                 //to the new HTLC max field in channel_update
1287                                                 Some(value)
1288                                         },
1289                                         Err(chain::AccessError::UnknownChain) => {
1290                                                 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
1291                                         },
1292                                         Err(chain::AccessError::UnknownTx) => {
1293                                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
1294                                         },
1295                                 }
1296                         },
1297                 };
1298
1299                 #[allow(unused_mut, unused_assignments)]
1300                 let mut announcement_received_time = 0;
1301                 #[cfg(feature = "std")]
1302                 {
1303                         announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1304                 }
1305
1306                 let chan_info = ChannelInfo {
1307                         features: msg.features.clone(),
1308                         node_one: NodeId::from_pubkey(&msg.node_id_1),
1309                         one_to_two: None,
1310                         node_two: NodeId::from_pubkey(&msg.node_id_2),
1311                         two_to_one: None,
1312                         capacity_sats: utxo_value,
1313                         announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1314                                 { full_msg.cloned() } else { None },
1315                         announcement_received_time,
1316                 };
1317
1318                 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)
1319         }
1320
1321         /// Marks a channel in the graph as failed if a corresponding HTLC fail was sent.
1322         /// If permanent, removes a channel from the local storage.
1323         /// May cause the removal of nodes too, if this was their last channel.
1324         /// If not permanent, makes channels unavailable for routing.
1325         pub fn channel_failed(&self, short_channel_id: u64, is_permanent: bool) {
1326                 let mut channels = self.channels.write().unwrap();
1327                 if is_permanent {
1328                         if let Some(chan) = channels.remove(&short_channel_id) {
1329                                 let mut nodes = self.nodes.write().unwrap();
1330                                 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1331                         }
1332                 } else {
1333                         if let Some(chan) = channels.get_mut(&short_channel_id) {
1334                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1335                                         one_to_two.enabled = false;
1336                                 }
1337                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1338                                         two_to_one.enabled = false;
1339                                 }
1340                         }
1341                 }
1342         }
1343
1344         /// Marks a node in the graph as failed.
1345         pub fn node_failed(&self, _node_id: &PublicKey, is_permanent: bool) {
1346                 if is_permanent {
1347                         // TODO: Wholly remove the node
1348                 } else {
1349                         // TODO: downgrade the node
1350                 }
1351         }
1352
1353         #[cfg(feature = "std")]
1354         /// Removes information about channels that we haven't heard any updates about in some time.
1355         /// This can be used regularly to prune the network graph of channels that likely no longer
1356         /// exist.
1357         ///
1358         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1359         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1360         /// pruning occur for updates which are at least two weeks old, which we implement here.
1361         ///
1362         /// Note that for users of the `lightning-background-processor` crate this method may be
1363         /// automatically called regularly for you.
1364         ///
1365         /// This method is only available with the `std` feature. See
1366         /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1367         pub fn remove_stale_channels(&self) {
1368                 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1369                 self.remove_stale_channels_with_time(time);
1370         }
1371
1372         /// Removes information about channels that we haven't heard any updates about in some time.
1373         /// This can be used regularly to prune the network graph of channels that likely no longer
1374         /// exist.
1375         ///
1376         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1377         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1378         /// pruning occur for updates which are at least two weeks old, which we implement here.
1379         ///
1380         /// This function takes the current unix time as an argument. For users with the `std` feature
1381         /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1382         pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1383                 let mut channels = self.channels.write().unwrap();
1384                 // Time out if we haven't received an update in at least 14 days.
1385                 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1386                 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1387                 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1388                 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1389                 // time.
1390                 let mut scids_to_remove = Vec::new();
1391                 for (scid, info) in channels.iter_mut() {
1392                         if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1393                                 info.one_to_two = None;
1394                         }
1395                         if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1396                                 info.two_to_one = None;
1397                         }
1398                         if info.one_to_two.is_none() && info.two_to_one.is_none() {
1399                                 // We check the announcement_received_time here to ensure we don't drop
1400                                 // announcements that we just received and are just waiting for our peer to send a
1401                                 // channel_update for.
1402                                 if info.announcement_received_time < min_time_unix as u64 {
1403                                         scids_to_remove.push(*scid);
1404                                 }
1405                         }
1406                 }
1407                 if !scids_to_remove.is_empty() {
1408                         let mut nodes = self.nodes.write().unwrap();
1409                         for scid in scids_to_remove {
1410                                 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1411                                 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1412                         }
1413                 }
1414         }
1415
1416         /// For an already known (from announcement) channel, update info about one of the directions
1417         /// of the channel.
1418         ///
1419         /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1420         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1421         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1422         ///
1423         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1424         /// materially in the future will be rejected.
1425         pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1426                 self.update_channel_intern(&msg.contents, Some(&msg), Some(&msg.signature))
1427         }
1428
1429         /// For an already known (from announcement) channel, update info about one of the directions
1430         /// of the channel without verifying the associated signatures. Because we aren't given the
1431         /// associated signatures here we cannot relay the channel update to any of our peers.
1432         ///
1433         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1434         /// materially in the future will be rejected.
1435         pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1436                 self.update_channel_intern(msg, None, None)
1437         }
1438
1439         fn update_channel_intern(&self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>) -> Result<(), LightningError> {
1440                 let dest_node_id;
1441                 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1442                 let chan_was_enabled;
1443
1444                 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1445                 {
1446                         // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1447                         // disable this check during tests!
1448                         let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1449                         if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1450                                 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1451                         }
1452                         if msg.timestamp as u64 > time + 60 * 60 * 24 {
1453                                 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1454                         }
1455                 }
1456
1457                 let mut channels = self.channels.write().unwrap();
1458                 match channels.get_mut(&msg.short_channel_id) {
1459                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1460                         Some(channel) => {
1461                                 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1462                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
1463                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1464                                         }
1465
1466                                         if let Some(capacity_sats) = channel.capacity_sats {
1467                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1468                                                 // Don't query UTXO set here to reduce DoS risks.
1469                                                 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1470                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1471                                                 }
1472                                         }
1473                                 }
1474                                 macro_rules! check_update_latest {
1475                                         ($target: expr) => {
1476                                                 if let Some(existing_chan_info) = $target.as_ref() {
1477                                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1478                                                         // order updates to ensure you always have the latest one, only
1479                                                         // suggesting  that it be at least the current time. For
1480                                                         // channel_updates specifically, the BOLTs discuss the possibility of
1481                                                         // pruning based on the timestamp field being more than two weeks old,
1482                                                         // but only in the non-normative section.
1483                                                         if existing_chan_info.last_update > msg.timestamp {
1484                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1485                                                         } else if existing_chan_info.last_update == msg.timestamp {
1486                                                                 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1487                                                         }
1488                                                         chan_was_enabled = existing_chan_info.enabled;
1489                                                 } else {
1490                                                         chan_was_enabled = false;
1491                                                 }
1492                                         }
1493                                 }
1494
1495                                 macro_rules! get_new_channel_info {
1496                                         () => { {
1497                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1498                                                         { full_msg.cloned() } else { None };
1499
1500                                                 let updated_channel_update_info = ChannelUpdateInfo {
1501                                                         enabled: chan_enabled,
1502                                                         last_update: msg.timestamp,
1503                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
1504                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
1505                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1506                                                         fees: RoutingFees {
1507                                                                 base_msat: msg.fee_base_msat,
1508                                                                 proportional_millionths: msg.fee_proportional_millionths,
1509                                                         },
1510                                                         last_update_message
1511                                                 };
1512                                                 Some(updated_channel_update_info)
1513                                         } }
1514                                 }
1515
1516                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1517                                 if msg.flags & 1 == 1 {
1518                                         dest_node_id = channel.node_one.clone();
1519                                         check_update_latest!(channel.two_to_one);
1520                                         if let Some(sig) = sig {
1521                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1522                                                         err: "Couldn't parse source node pubkey".to_owned(),
1523                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1524                                                 })?, "channel_update");
1525                                         }
1526                                         channel.two_to_one = get_new_channel_info!();
1527                                 } else {
1528                                         dest_node_id = channel.node_two.clone();
1529                                         check_update_latest!(channel.one_to_two);
1530                                         if let Some(sig) = sig {
1531                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1532                                                         err: "Couldn't parse destination node pubkey".to_owned(),
1533                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1534                                                 })?, "channel_update");
1535                                         }
1536                                         channel.one_to_two = get_new_channel_info!();
1537                                 }
1538                         }
1539                 }
1540
1541                 let mut nodes = self.nodes.write().unwrap();
1542                 if chan_enabled {
1543                         let node = nodes.get_mut(&dest_node_id).unwrap();
1544                         let mut base_msat = msg.fee_base_msat;
1545                         let mut proportional_millionths = msg.fee_proportional_millionths;
1546                         if let Some(fees) = node.lowest_inbound_channel_fees {
1547                                 base_msat = cmp::min(base_msat, fees.base_msat);
1548                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1549                         }
1550                         node.lowest_inbound_channel_fees = Some(RoutingFees {
1551                                 base_msat,
1552                                 proportional_millionths
1553                         });
1554                 } else if chan_was_enabled {
1555                         let node = nodes.get_mut(&dest_node_id).unwrap();
1556                         let mut lowest_inbound_channel_fees = None;
1557
1558                         for chan_id in node.channels.iter() {
1559                                 let chan = channels.get(chan_id).unwrap();
1560                                 let chan_info_opt;
1561                                 if chan.node_one == dest_node_id {
1562                                         chan_info_opt = chan.two_to_one.as_ref();
1563                                 } else {
1564                                         chan_info_opt = chan.one_to_two.as_ref();
1565                                 }
1566                                 if let Some(chan_info) = chan_info_opt {
1567                                         if chan_info.enabled {
1568                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1569                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1570                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1571                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1572                                         }
1573                                 }
1574                         }
1575
1576                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1577                 }
1578
1579                 Ok(())
1580         }
1581
1582         fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1583                 macro_rules! remove_from_node {
1584                         ($node_id: expr) => {
1585                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1586                                         entry.get_mut().channels.retain(|chan_id| {
1587                                                 short_channel_id != *chan_id
1588                                         });
1589                                         if entry.get().channels.is_empty() {
1590                                                 entry.remove_entry();
1591                                         }
1592                                 } else {
1593                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1594                                 }
1595                         }
1596                 }
1597
1598                 remove_from_node!(chan.node_one);
1599                 remove_from_node!(chan.node_two);
1600         }
1601 }
1602
1603 impl ReadOnlyNetworkGraph<'_> {
1604         /// Returns all known valid channels' short ids along with announced channel info.
1605         ///
1606         /// (C-not exported) because we have no mapping for `BTreeMap`s
1607         pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1608                 &*self.channels
1609         }
1610
1611         /// Returns all known nodes' public keys along with announced node info.
1612         ///
1613         /// (C-not exported) because we have no mapping for `BTreeMap`s
1614         pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1615                 &*self.nodes
1616         }
1617
1618         /// Get network addresses by node id.
1619         /// Returns None if the requested node is completely unknown,
1620         /// or if node announcement for the node was never received.
1621         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1622                 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1623                         if let Some(node_info) = node.announcement_info.as_ref() {
1624                                 return Some(node_info.addresses.clone())
1625                         }
1626                 }
1627                 None
1628         }
1629 }
1630
1631 #[cfg(test)]
1632 mod tests {
1633         use chain;
1634         use ln::PaymentHash;
1635         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1636         use routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1637         use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1638                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1639                 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1640         use util::test_utils;
1641         use util::logger::Logger;
1642         use util::ser::{ReadableArgs, Writeable};
1643         use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1644         use util::scid_utils::scid_from_parts;
1645
1646         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1647
1648         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1649         use bitcoin::hashes::Hash;
1650         use bitcoin::network::constants::Network;
1651         use bitcoin::blockdata::constants::genesis_block;
1652         use bitcoin::blockdata::script::{Builder, Script};
1653         use bitcoin::blockdata::transaction::TxOut;
1654         use bitcoin::blockdata::opcodes;
1655
1656         use hex;
1657
1658         use bitcoin::secp256k1::{PublicKey, SecretKey};
1659         use bitcoin::secp256k1::{All, Secp256k1};
1660
1661         use io;
1662         use bitcoin::secp256k1;
1663         use prelude::*;
1664         use sync::Arc;
1665
1666         fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
1667                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1668                 let logger = Arc::new(test_utils::TestLogger::new());
1669                 NetworkGraph::new(genesis_hash, logger)
1670         }
1671
1672         fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
1673                 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
1674                 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1675         ) {
1676                 let secp_ctx = Secp256k1::new();
1677                 let logger = Arc::new(test_utils::TestLogger::new());
1678                 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
1679                 (secp_ctx, gossip_sync)
1680         }
1681
1682         #[test]
1683         fn request_full_sync_finite_times() {
1684                 let network_graph = create_network_graph();
1685                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
1686                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1687
1688                 assert!(gossip_sync.should_request_full_sync(&node_id));
1689                 assert!(gossip_sync.should_request_full_sync(&node_id));
1690                 assert!(gossip_sync.should_request_full_sync(&node_id));
1691                 assert!(gossip_sync.should_request_full_sync(&node_id));
1692                 assert!(gossip_sync.should_request_full_sync(&node_id));
1693                 assert!(!gossip_sync.should_request_full_sync(&node_id));
1694         }
1695
1696         fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1697                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1698                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1699                         features: NodeFeatures::known(),
1700                         timestamp: 100,
1701                         node_id: node_id,
1702                         rgb: [0; 3],
1703                         alias: [0; 32],
1704                         addresses: Vec::new(),
1705                         excess_address_data: Vec::new(),
1706                         excess_data: Vec::new(),
1707                 };
1708                 f(&mut unsigned_announcement);
1709                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1710                 NodeAnnouncement {
1711                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
1712                         contents: unsigned_announcement
1713                 }
1714         }
1715
1716         fn get_signed_channel_announcement<F: Fn(&mut UnsignedChannelAnnouncement)>(f: F, node_1_key: &SecretKey, node_2_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelAnnouncement {
1717                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1718                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1719                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1720                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1721
1722                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1723                         features: ChannelFeatures::known(),
1724                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1725                         short_channel_id: 0,
1726                         node_id_1,
1727                         node_id_2,
1728                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1729                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1730                         excess_data: Vec::new(),
1731                 };
1732                 f(&mut unsigned_announcement);
1733                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1734                 ChannelAnnouncement {
1735                         node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
1736                         node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
1737                         bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
1738                         bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
1739                         contents: unsigned_announcement,
1740                 }
1741         }
1742
1743         fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1744                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1745                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1746                 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1747                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1748                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1749                               .push_opcode(opcodes::all::OP_PUSHNUM_2)
1750                               .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1751                               .to_v0_p2wsh()
1752         }
1753
1754         fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1755                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1756                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1757                         short_channel_id: 0,
1758                         timestamp: 100,
1759                         flags: 0,
1760                         cltv_expiry_delta: 144,
1761                         htlc_minimum_msat: 1_000_000,
1762                         htlc_maximum_msat: OptionalField::Absent,
1763                         fee_base_msat: 10_000,
1764                         fee_proportional_millionths: 20,
1765                         excess_data: Vec::new()
1766                 };
1767                 f(&mut unsigned_channel_update);
1768                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1769                 ChannelUpdate {
1770                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
1771                         contents: unsigned_channel_update
1772                 }
1773         }
1774
1775         #[test]
1776         fn handling_node_announcements() {
1777                 let network_graph = create_network_graph();
1778                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
1779
1780                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1781                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1782                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1783
1784                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1785                 match gossip_sync.handle_node_announcement(&valid_announcement) {
1786                         Ok(_) => panic!(),
1787                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1788                 };
1789
1790                 {
1791                         // Announce a channel to add a corresponding node.
1792                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1793                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
1794                                 Ok(res) => assert!(res),
1795                                 _ => panic!()
1796                         };
1797                 }
1798
1799                 match gossip_sync.handle_node_announcement(&valid_announcement) {
1800                         Ok(res) => assert!(res),
1801                         Err(_) => panic!()
1802                 };
1803
1804                 let fake_msghash = hash_to_message!(&zero_hash);
1805                 match gossip_sync.handle_node_announcement(
1806                         &NodeAnnouncement {
1807                                 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
1808                                 contents: valid_announcement.contents.clone()
1809                 }) {
1810                         Ok(_) => panic!(),
1811                         Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
1812                 };
1813
1814                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1815                         unsigned_announcement.timestamp += 1000;
1816                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1817                 }, node_1_privkey, &secp_ctx);
1818                 // Return false because contains excess data.
1819                 match gossip_sync.handle_node_announcement(&announcement_with_data) {
1820                         Ok(res) => assert!(!res),
1821                         Err(_) => panic!()
1822                 };
1823
1824                 // Even though previous announcement was not relayed further, we still accepted it,
1825                 // so we now won't accept announcements before the previous one.
1826                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1827                         unsigned_announcement.timestamp += 1000 - 10;
1828                 }, node_1_privkey, &secp_ctx);
1829                 match gossip_sync.handle_node_announcement(&outdated_announcement) {
1830                         Ok(_) => panic!(),
1831                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1832                 };
1833         }
1834
1835         #[test]
1836         fn handling_channel_announcements() {
1837                 let secp_ctx = Secp256k1::new();
1838                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1839
1840                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1841                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1842
1843                 let good_script = get_channel_script(&secp_ctx);
1844                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1845
1846                 // Test if the UTXO lookups were not supported
1847                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1848                 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
1849                 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, Arc::clone(&logger));
1850                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1851                         Ok(res) => assert!(res),
1852                         _ => panic!()
1853                 };
1854
1855                 {
1856                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1857                                 None => panic!(),
1858                                 Some(_) => ()
1859                         };
1860                 }
1861
1862                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1863                 // drop new one on the floor, since we can't see any changes.
1864                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1865                         Ok(_) => panic!(),
1866                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1867                 };
1868
1869                 // Test if an associated transaction were not on-chain (or not confirmed).
1870                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1871                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1872                 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
1873                 gossip_sync = P2PGossipSync::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1874
1875                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1876                         unsigned_announcement.short_channel_id += 1;
1877                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1878                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1879                         Ok(_) => panic!(),
1880                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1881                 };
1882
1883                 // Now test if the transaction is found in the UTXO set and the script is correct.
1884                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1885                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1886                         unsigned_announcement.short_channel_id += 2;
1887                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1888                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1889                         Ok(res) => assert!(res),
1890                         _ => panic!()
1891                 };
1892
1893                 {
1894                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1895                                 None => panic!(),
1896                                 Some(_) => ()
1897                         };
1898                 }
1899
1900                 // If we receive announcement for the same channel (but TX is not confirmed),
1901                 // drop new one on the floor, since we can't see any changes.
1902                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1903                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1904                         Ok(_) => panic!(),
1905                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1906                 };
1907
1908                 // But if it is confirmed, replace the channel
1909                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1910                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1911                         unsigned_announcement.features = ChannelFeatures::empty();
1912                         unsigned_announcement.short_channel_id += 2;
1913                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1914                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1915                         Ok(res) => assert!(res),
1916                         _ => panic!()
1917                 };
1918                 {
1919                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1920                                 Some(channel_entry) => {
1921                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1922                                 },
1923                                 _ => panic!()
1924                         };
1925                 }
1926
1927                 // Don't relay valid channels with excess data
1928                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1929                         unsigned_announcement.short_channel_id += 3;
1930                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1931                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1932                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
1933                         Ok(res) => assert!(!res),
1934                         _ => panic!()
1935                 };
1936
1937                 let mut invalid_sig_announcement = valid_announcement.clone();
1938                 invalid_sig_announcement.contents.excess_data = Vec::new();
1939                 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
1940                         Ok(_) => panic!(),
1941                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
1942                 };
1943
1944                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1945                 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
1946                         Ok(_) => panic!(),
1947                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1948                 };
1949         }
1950
1951         #[test]
1952         fn handling_channel_update() {
1953                 let secp_ctx = Secp256k1::new();
1954                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1955                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1956                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1957                 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
1958                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1959
1960                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1961                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1962
1963                 let amount_sats = 1000_000;
1964                 let short_channel_id;
1965
1966                 {
1967                         // Announce a channel we will update
1968                         let good_script = get_channel_script(&secp_ctx);
1969                         *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1970
1971                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1972                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1973                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
1974                                 Ok(_) => (),
1975                                 Err(_) => panic!()
1976                         };
1977
1978                 }
1979
1980                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1981                 match gossip_sync.handle_channel_update(&valid_channel_update) {
1982                         Ok(res) => assert!(res),
1983                         _ => panic!()
1984                 };
1985
1986                 {
1987                         match network_graph.read_only().channels().get(&short_channel_id) {
1988                                 None => panic!(),
1989                                 Some(channel_info) => {
1990                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1991                                         assert!(channel_info.two_to_one.is_none());
1992                                 }
1993                         };
1994                 }
1995
1996                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1997                         unsigned_channel_update.timestamp += 100;
1998                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1999                 }, node_1_privkey, &secp_ctx);
2000                 // Return false because contains excess data
2001                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2002                         Ok(res) => assert!(!res),
2003                         _ => panic!()
2004                 };
2005
2006                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2007                         unsigned_channel_update.timestamp += 110;
2008                         unsigned_channel_update.short_channel_id += 1;
2009                 }, node_1_privkey, &secp_ctx);
2010                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2011                         Ok(_) => panic!(),
2012                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2013                 };
2014
2015                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2016                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
2017                         unsigned_channel_update.timestamp += 110;
2018                 }, node_1_privkey, &secp_ctx);
2019                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2020                         Ok(_) => panic!(),
2021                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2022                 };
2023
2024                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2025                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
2026                         unsigned_channel_update.timestamp += 110;
2027                 }, node_1_privkey, &secp_ctx);
2028                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2029                         Ok(_) => panic!(),
2030                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2031                 };
2032
2033                 // Even though previous update was not relayed further, we still accepted it,
2034                 // so we now won't accept update before the previous one.
2035                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2036                         unsigned_channel_update.timestamp += 100;
2037                 }, node_1_privkey, &secp_ctx);
2038                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2039                         Ok(_) => panic!(),
2040                         Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2041                 };
2042
2043                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2044                         unsigned_channel_update.timestamp += 500;
2045                 }, node_1_privkey, &secp_ctx);
2046                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2047                 let fake_msghash = hash_to_message!(&zero_hash);
2048                 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2049                 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2050                         Ok(_) => panic!(),
2051                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2052                 };
2053         }
2054
2055         #[test]
2056         fn handling_network_update() {
2057                 let logger = test_utils::TestLogger::new();
2058                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2059                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2060                 let network_graph = NetworkGraph::new(genesis_hash, &logger);
2061                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(chain_source.clone()), &logger);
2062                 let secp_ctx = Secp256k1::new();
2063
2064                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2065                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2066
2067                 {
2068                         // There is no nodes in the table at the beginning.
2069                         assert_eq!(network_graph.read_only().nodes().len(), 0);
2070                 }
2071
2072                 let short_channel_id;
2073                 {
2074                         // Announce a channel we will update
2075                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2076                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2077                         let chain_source: Option<&test_utils::TestChainSource> = None;
2078                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2079                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2080
2081                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2082                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2083
2084                         gossip_sync.handle_event(&Event::PaymentPathFailed {
2085                                 payment_id: None,
2086                                 payment_hash: PaymentHash([0; 32]),
2087                                 rejected_by_dest: false,
2088                                 all_paths_failed: true,
2089                                 path: vec![],
2090                                 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
2091                                         msg: valid_channel_update,
2092                                 }),
2093                                 short_channel_id: None,
2094                                 retry: None,
2095                                 error_code: None,
2096                                 error_data: None,
2097                         });
2098
2099                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2100                 }
2101
2102                 // Non-permanent closing just disables a channel
2103                 {
2104                         match network_graph.read_only().channels().get(&short_channel_id) {
2105                                 None => panic!(),
2106                                 Some(channel_info) => {
2107                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2108                                 }
2109                         };
2110
2111                         gossip_sync.handle_event(&Event::PaymentPathFailed {
2112                                 payment_id: None,
2113                                 payment_hash: PaymentHash([0; 32]),
2114                                 rejected_by_dest: false,
2115                                 all_paths_failed: true,
2116                                 path: vec![],
2117                                 network_update: Some(NetworkUpdate::ChannelFailure {
2118                                         short_channel_id,
2119                                         is_permanent: false,
2120                                 }),
2121                                 short_channel_id: None,
2122                                 retry: None,
2123                                 error_code: None,
2124                                 error_data: None,
2125                         });
2126
2127                         match network_graph.read_only().channels().get(&short_channel_id) {
2128                                 None => panic!(),
2129                                 Some(channel_info) => {
2130                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
2131                                 }
2132                         };
2133                 }
2134
2135                 // Permanent closing deletes a channel
2136                 gossip_sync.handle_event(&Event::PaymentPathFailed {
2137                         payment_id: None,
2138                         payment_hash: PaymentHash([0; 32]),
2139                         rejected_by_dest: false,
2140                         all_paths_failed: true,
2141                         path: vec![],
2142                         network_update: Some(NetworkUpdate::ChannelFailure {
2143                                 short_channel_id,
2144                                 is_permanent: true,
2145                         }),
2146                         short_channel_id: None,
2147                         retry: None,
2148                         error_code: None,
2149                         error_data: None,
2150                 });
2151
2152                 assert_eq!(network_graph.read_only().channels().len(), 0);
2153                 // Nodes are also deleted because there are no associated channels anymore
2154                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2155                 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
2156         }
2157
2158         #[test]
2159         fn test_channel_timeouts() {
2160                 // Test the removal of channels with `remove_stale_channels`.
2161                 let logger = test_utils::TestLogger::new();
2162                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2163                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2164                 let network_graph = NetworkGraph::new(genesis_hash, &logger);
2165                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(chain_source.clone()), &logger);
2166                 let secp_ctx = Secp256k1::new();
2167
2168                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2169                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2170
2171                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2172                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2173                 let chain_source: Option<&test_utils::TestChainSource> = None;
2174                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2175                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2176
2177                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2178                 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2179                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2180
2181                 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2182                 assert_eq!(network_graph.read_only().channels().len(), 1);
2183                 assert_eq!(network_graph.read_only().nodes().len(), 2);
2184
2185                 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2186                 #[cfg(feature = "std")]
2187                 {
2188                         // In std mode, a further check is performed before fully removing the channel -
2189                         // the channel_announcement must have been received at least two weeks ago. We
2190                         // fudge that here by indicating the time has jumped two weeks. Note that the
2191                         // directional channel information will have been removed already..
2192                         assert_eq!(network_graph.read_only().channels().len(), 1);
2193                         assert_eq!(network_graph.read_only().nodes().len(), 2);
2194                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2195
2196                         use std::time::{SystemTime, UNIX_EPOCH};
2197                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2198                         network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2199                 }
2200
2201                 assert_eq!(network_graph.read_only().channels().len(), 0);
2202                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2203         }
2204
2205         #[test]
2206         fn getting_next_channel_announcements() {
2207                 let network_graph = create_network_graph();
2208                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2209                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2210                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2211
2212                 // Channels were not announced yet.
2213                 let channels_with_announcements = gossip_sync.get_next_channel_announcements(0, 1);
2214                 assert_eq!(channels_with_announcements.len(), 0);
2215
2216                 let short_channel_id;
2217                 {
2218                         // Announce a channel we will update
2219                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2220                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2221                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2222                                 Ok(_) => (),
2223                                 Err(_) => panic!()
2224                         };
2225                 }
2226
2227                 // Contains initial channel announcement now.
2228                 let channels_with_announcements = gossip_sync.get_next_channel_announcements(short_channel_id, 1);
2229                 assert_eq!(channels_with_announcements.len(), 1);
2230                 if let Some(channel_announcements) = channels_with_announcements.first() {
2231                         let &(_, ref update_1, ref update_2) = channel_announcements;
2232                         assert_eq!(update_1, &None);
2233                         assert_eq!(update_2, &None);
2234                 } else {
2235                         panic!();
2236                 }
2237
2238
2239                 {
2240                         // Valid channel update
2241                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2242                                 unsigned_channel_update.timestamp = 101;
2243                         }, node_1_privkey, &secp_ctx);
2244                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2245                                 Ok(_) => (),
2246                                 Err(_) => panic!()
2247                         };
2248                 }
2249
2250                 // Now contains an initial announcement and an update.
2251                 let channels_with_announcements = gossip_sync.get_next_channel_announcements(short_channel_id, 1);
2252                 assert_eq!(channels_with_announcements.len(), 1);
2253                 if let Some(channel_announcements) = channels_with_announcements.first() {
2254                         let &(_, ref update_1, ref update_2) = channel_announcements;
2255                         assert_ne!(update_1, &None);
2256                         assert_eq!(update_2, &None);
2257                 } else {
2258                         panic!();
2259                 }
2260
2261                 {
2262                         // Channel update with excess data.
2263                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2264                                 unsigned_channel_update.timestamp = 102;
2265                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2266                         }, node_1_privkey, &secp_ctx);
2267                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2268                                 Ok(_) => (),
2269                                 Err(_) => panic!()
2270                         };
2271                 }
2272
2273                 // Test that announcements with excess data won't be returned
2274                 let channels_with_announcements = gossip_sync.get_next_channel_announcements(short_channel_id, 1);
2275                 assert_eq!(channels_with_announcements.len(), 1);
2276                 if let Some(channel_announcements) = channels_with_announcements.first() {
2277                         let &(_, ref update_1, ref update_2) = channel_announcements;
2278                         assert_eq!(update_1, &None);
2279                         assert_eq!(update_2, &None);
2280                 } else {
2281                         panic!();
2282                 }
2283
2284                 // Further starting point have no channels after it
2285                 let channels_with_announcements = gossip_sync.get_next_channel_announcements(short_channel_id + 1000, 1);
2286                 assert_eq!(channels_with_announcements.len(), 0);
2287         }
2288
2289         #[test]
2290         fn getting_next_node_announcements() {
2291                 let network_graph = create_network_graph();
2292                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2293                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2294                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2295                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2296
2297                 // No nodes yet.
2298                 let next_announcements = gossip_sync.get_next_node_announcements(None, 10);
2299                 assert_eq!(next_announcements.len(), 0);
2300
2301                 {
2302                         // Announce a channel to add 2 nodes
2303                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2304                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2305                                 Ok(_) => (),
2306                                 Err(_) => panic!()
2307                         };
2308                 }
2309
2310
2311                 // Nodes were never announced
2312                 let next_announcements = gossip_sync.get_next_node_announcements(None, 3);
2313                 assert_eq!(next_announcements.len(), 0);
2314
2315                 {
2316                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2317                         match gossip_sync.handle_node_announcement(&valid_announcement) {
2318                                 Ok(_) => (),
2319                                 Err(_) => panic!()
2320                         };
2321
2322                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2323                         match gossip_sync.handle_node_announcement(&valid_announcement) {
2324                                 Ok(_) => (),
2325                                 Err(_) => panic!()
2326                         };
2327                 }
2328
2329                 let next_announcements = gossip_sync.get_next_node_announcements(None, 3);
2330                 assert_eq!(next_announcements.len(), 2);
2331
2332                 // Skip the first node.
2333                 let next_announcements = gossip_sync.get_next_node_announcements(Some(&node_id_1), 2);
2334                 assert_eq!(next_announcements.len(), 1);
2335
2336                 {
2337                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2338                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2339                                 unsigned_announcement.timestamp += 10;
2340                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2341                         }, node_2_privkey, &secp_ctx);
2342                         match gossip_sync.handle_node_announcement(&valid_announcement) {
2343                                 Ok(res) => assert!(!res),
2344                                 Err(_) => panic!()
2345                         };
2346                 }
2347
2348                 let next_announcements = gossip_sync.get_next_node_announcements(Some(&node_id_1), 2);
2349                 assert_eq!(next_announcements.len(), 0);
2350         }
2351
2352         #[test]
2353         fn network_graph_serialization() {
2354                 let network_graph = create_network_graph();
2355                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2356
2357                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2358                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2359
2360                 // Announce a channel to add a corresponding node.
2361                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2362                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2363                         Ok(res) => assert!(res),
2364                         _ => panic!()
2365                 };
2366
2367                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2368                 match gossip_sync.handle_node_announcement(&valid_announcement) {
2369                         Ok(_) => (),
2370                         Err(_) => panic!()
2371                 };
2372
2373                 let mut w = test_utils::TestVecWriter(Vec::new());
2374                 assert!(!network_graph.read_only().nodes().is_empty());
2375                 assert!(!network_graph.read_only().channels().is_empty());
2376                 network_graph.write(&mut w).unwrap();
2377
2378                 let logger = Arc::new(test_utils::TestLogger::new());
2379                 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
2380         }
2381
2382         #[test]
2383         fn network_graph_tlv_serialization() {
2384                 let network_graph = create_network_graph();
2385                 network_graph.set_last_rapid_gossip_sync_timestamp(42);
2386
2387                 let mut w = test_utils::TestVecWriter(Vec::new());
2388                 network_graph.write(&mut w).unwrap();
2389
2390                 let logger = Arc::new(test_utils::TestLogger::new());
2391                 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
2392                 assert!(reassembled_network_graph == network_graph);
2393                 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
2394         }
2395
2396         #[test]
2397         #[cfg(feature = "std")]
2398         fn calling_sync_routing_table() {
2399                 use std::time::{SystemTime, UNIX_EPOCH};
2400
2401                 let network_graph = create_network_graph();
2402                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2403                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2404                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2405
2406                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2407
2408                 // It should ignore if gossip_queries feature is not enabled
2409                 {
2410                         let init_msg = Init { features: InitFeatures::known().clear_gossip_queries(), remote_network_address: None };
2411                         gossip_sync.peer_connected(&node_id_1, &init_msg);
2412                         let events = gossip_sync.get_and_clear_pending_msg_events();
2413                         assert_eq!(events.len(), 0);
2414                 }
2415
2416                 // It should send a gossip_timestamp_filter with the correct information
2417                 {
2418                         let init_msg = Init { features: InitFeatures::known(), remote_network_address: None };
2419                         gossip_sync.peer_connected(&node_id_1, &init_msg);
2420                         let events = gossip_sync.get_and_clear_pending_msg_events();
2421                         assert_eq!(events.len(), 1);
2422                         match &events[0] {
2423                                 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
2424                                         assert_eq!(node_id, &node_id_1);
2425                                         assert_eq!(msg.chain_hash, chain_hash);
2426                                         let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2427                                         assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
2428                                         assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
2429                                         assert_eq!(msg.timestamp_range, u32::max_value());
2430                                 },
2431                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2432                         };
2433                 }
2434         }
2435
2436         #[test]
2437         fn handling_query_channel_range() {
2438                 let network_graph = create_network_graph();
2439                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2440
2441                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2442                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2443                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2444                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2445
2446                 let mut scids: Vec<u64> = vec![
2447                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2448                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2449                 ];
2450
2451                 // used for testing multipart reply across blocks
2452                 for block in 100000..=108001 {
2453                         scids.push(scid_from_parts(block, 0, 0).unwrap());
2454                 }
2455
2456                 // used for testing resumption on same block
2457                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2458
2459                 for scid in scids {
2460                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2461                                 unsigned_announcement.short_channel_id = scid;
2462                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2463                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2464                                 Ok(_) => (),
2465                                 _ => panic!()
2466                         };
2467                 }
2468
2469                 // Error when number_of_blocks=0
2470                 do_handling_query_channel_range(
2471                         &gossip_sync,
2472                         &node_id_2,
2473                         QueryChannelRange {
2474                                 chain_hash: chain_hash.clone(),
2475                                 first_blocknum: 0,
2476                                 number_of_blocks: 0,
2477                         },
2478                         false,
2479                         vec![ReplyChannelRange {
2480                                 chain_hash: chain_hash.clone(),
2481                                 first_blocknum: 0,
2482                                 number_of_blocks: 0,
2483                                 sync_complete: true,
2484                                 short_channel_ids: vec![]
2485                         }]
2486                 );
2487
2488                 // Error when wrong chain
2489                 do_handling_query_channel_range(
2490                         &gossip_sync,
2491                         &node_id_2,
2492                         QueryChannelRange {
2493                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2494                                 first_blocknum: 0,
2495                                 number_of_blocks: 0xffff_ffff,
2496                         },
2497                         false,
2498                         vec![ReplyChannelRange {
2499                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2500                                 first_blocknum: 0,
2501                                 number_of_blocks: 0xffff_ffff,
2502                                 sync_complete: true,
2503                                 short_channel_ids: vec![],
2504                         }]
2505                 );
2506
2507                 // Error when first_blocknum > 0xffffff
2508                 do_handling_query_channel_range(
2509                         &gossip_sync,
2510                         &node_id_2,
2511                         QueryChannelRange {
2512                                 chain_hash: chain_hash.clone(),
2513                                 first_blocknum: 0x01000000,
2514                                 number_of_blocks: 0xffff_ffff,
2515                         },
2516                         false,
2517                         vec![ReplyChannelRange {
2518                                 chain_hash: chain_hash.clone(),
2519                                 first_blocknum: 0x01000000,
2520                                 number_of_blocks: 0xffff_ffff,
2521                                 sync_complete: true,
2522                                 short_channel_ids: vec![]
2523                         }]
2524                 );
2525
2526                 // Empty reply when max valid SCID block num
2527                 do_handling_query_channel_range(
2528                         &gossip_sync,
2529                         &node_id_2,
2530                         QueryChannelRange {
2531                                 chain_hash: chain_hash.clone(),
2532                                 first_blocknum: 0xffffff,
2533                                 number_of_blocks: 1,
2534                         },
2535                         true,
2536                         vec![
2537                                 ReplyChannelRange {
2538                                         chain_hash: chain_hash.clone(),
2539                                         first_blocknum: 0xffffff,
2540                                         number_of_blocks: 1,
2541                                         sync_complete: true,
2542                                         short_channel_ids: vec![]
2543                                 },
2544                         ]
2545                 );
2546
2547                 // No results in valid query range
2548                 do_handling_query_channel_range(
2549                         &gossip_sync,
2550                         &node_id_2,
2551                         QueryChannelRange {
2552                                 chain_hash: chain_hash.clone(),
2553                                 first_blocknum: 1000,
2554                                 number_of_blocks: 1000,
2555                         },
2556                         true,
2557                         vec![
2558                                 ReplyChannelRange {
2559                                         chain_hash: chain_hash.clone(),
2560                                         first_blocknum: 1000,
2561                                         number_of_blocks: 1000,
2562                                         sync_complete: true,
2563                                         short_channel_ids: vec![],
2564                                 }
2565                         ]
2566                 );
2567
2568                 // Overflow first_blocknum + number_of_blocks
2569                 do_handling_query_channel_range(
2570                         &gossip_sync,
2571                         &node_id_2,
2572                         QueryChannelRange {
2573                                 chain_hash: chain_hash.clone(),
2574                                 first_blocknum: 0xfe0000,
2575                                 number_of_blocks: 0xffffffff,
2576                         },
2577                         true,
2578                         vec![
2579                                 ReplyChannelRange {
2580                                         chain_hash: chain_hash.clone(),
2581                                         first_blocknum: 0xfe0000,
2582                                         number_of_blocks: 0xffffffff - 0xfe0000,
2583                                         sync_complete: true,
2584                                         short_channel_ids: vec![
2585                                                 0xfffffe_ffffff_ffff, // max
2586                                         ]
2587                                 }
2588                         ]
2589                 );
2590
2591                 // Single block exactly full
2592                 do_handling_query_channel_range(
2593                         &gossip_sync,
2594                         &node_id_2,
2595                         QueryChannelRange {
2596                                 chain_hash: chain_hash.clone(),
2597                                 first_blocknum: 100000,
2598                                 number_of_blocks: 8000,
2599                         },
2600                         true,
2601                         vec![
2602                                 ReplyChannelRange {
2603                                         chain_hash: chain_hash.clone(),
2604                                         first_blocknum: 100000,
2605                                         number_of_blocks: 8000,
2606                                         sync_complete: true,
2607                                         short_channel_ids: (100000..=107999)
2608                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2609                                                 .collect(),
2610                                 },
2611                         ]
2612                 );
2613
2614                 // Multiple split on new block
2615                 do_handling_query_channel_range(
2616                         &gossip_sync,
2617                         &node_id_2,
2618                         QueryChannelRange {
2619                                 chain_hash: chain_hash.clone(),
2620                                 first_blocknum: 100000,
2621                                 number_of_blocks: 8001,
2622                         },
2623                         true,
2624                         vec![
2625                                 ReplyChannelRange {
2626                                         chain_hash: chain_hash.clone(),
2627                                         first_blocknum: 100000,
2628                                         number_of_blocks: 7999,
2629                                         sync_complete: false,
2630                                         short_channel_ids: (100000..=107999)
2631                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2632                                                 .collect(),
2633                                 },
2634                                 ReplyChannelRange {
2635                                         chain_hash: chain_hash.clone(),
2636                                         first_blocknum: 107999,
2637                                         number_of_blocks: 2,
2638                                         sync_complete: true,
2639                                         short_channel_ids: vec![
2640                                                 scid_from_parts(108000, 0, 0).unwrap(),
2641                                         ],
2642                                 }
2643                         ]
2644                 );
2645
2646                 // Multiple split on same block
2647                 do_handling_query_channel_range(
2648                         &gossip_sync,
2649                         &node_id_2,
2650                         QueryChannelRange {
2651                                 chain_hash: chain_hash.clone(),
2652                                 first_blocknum: 100002,
2653                                 number_of_blocks: 8000,
2654                         },
2655                         true,
2656                         vec![
2657                                 ReplyChannelRange {
2658                                         chain_hash: chain_hash.clone(),
2659                                         first_blocknum: 100002,
2660                                         number_of_blocks: 7999,
2661                                         sync_complete: false,
2662                                         short_channel_ids: (100002..=108001)
2663                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2664                                                 .collect(),
2665                                 },
2666                                 ReplyChannelRange {
2667                                         chain_hash: chain_hash.clone(),
2668                                         first_blocknum: 108001,
2669                                         number_of_blocks: 1,
2670                                         sync_complete: true,
2671                                         short_channel_ids: vec![
2672                                                 scid_from_parts(108001, 1, 0).unwrap(),
2673                                         ],
2674                                 }
2675                         ]
2676                 );
2677         }
2678
2679         fn do_handling_query_channel_range(
2680                 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2681                 test_node_id: &PublicKey,
2682                 msg: QueryChannelRange,
2683                 expected_ok: bool,
2684                 expected_replies: Vec<ReplyChannelRange>
2685         ) {
2686                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2687                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2688                 let query_end_blocknum = msg.end_blocknum();
2689                 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
2690
2691                 if expected_ok {
2692                         assert!(result.is_ok());
2693                 } else {
2694                         assert!(result.is_err());
2695                 }
2696
2697                 let events = gossip_sync.get_and_clear_pending_msg_events();
2698                 assert_eq!(events.len(), expected_replies.len());
2699
2700                 for i in 0..events.len() {
2701                         let expected_reply = &expected_replies[i];
2702                         match &events[i] {
2703                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2704                                         assert_eq!(node_id, test_node_id);
2705                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2706                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2707                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2708                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2709                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2710
2711                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2712                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2713                                         assert!(msg.first_blocknum >= max_firstblocknum);
2714                                         max_firstblocknum = msg.first_blocknum;
2715                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2716
2717                                         // Check that the last block count is >= the query's end_blocknum
2718                                         if i == events.len() - 1 {
2719                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2720                                         }
2721                                 },
2722                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2723                         }
2724                 }
2725         }
2726
2727         #[test]
2728         fn handling_query_short_channel_ids() {
2729                 let network_graph = create_network_graph();
2730                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2731                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2732                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2733
2734                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2735
2736                 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2737                         chain_hash,
2738                         short_channel_ids: vec![0x0003e8_000000_0000],
2739                 });
2740                 assert!(result.is_err());
2741         }
2742 }
2743
2744 #[cfg(all(test, feature = "_bench_unstable"))]
2745 mod benches {
2746         use super::*;
2747
2748         use test::Bencher;
2749         use std::io::Read;
2750
2751         #[bench]
2752         fn read_network_graph(bench: &mut Bencher) {
2753                 let logger = ::util::test_utils::TestLogger::new();
2754                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2755                 let mut v = Vec::new();
2756                 d.read_to_end(&mut v).unwrap();
2757                 bench.iter(|| {
2758                         let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v), &logger).unwrap();
2759                 });
2760         }
2761
2762         #[bench]
2763         fn write_network_graph(bench: &mut Bencher) {
2764                 let logger = ::util::test_utils::TestLogger::new();
2765                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2766                 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
2767                 bench.iter(|| {
2768                         let _ = net_graph.encode();
2769                 });
2770         }
2771 }