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