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