Merge pull request #1382 from TheBlueMatt/2022-03-gossip-queries-sucks
[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::key::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($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         /// For an already known node (from channel announcements), update its stored properties from a
1037         /// given node announcement.
1038         ///
1039         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1040         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1041         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1042         pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1043                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1044                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id, "node_announcement");
1045                 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1046         }
1047
1048         /// For an already known node (from channel announcements), update its stored properties from a
1049         /// given node announcement without verifying the associated signatures. Because we aren't
1050         /// given the associated signatures here we cannot relay the node announcement to any of our
1051         /// peers.
1052         pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1053                 self.update_node_from_announcement_intern(msg, None)
1054         }
1055
1056         fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1057                 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
1058                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
1059                         Some(node) => {
1060                                 if let Some(node_info) = node.announcement_info.as_ref() {
1061                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1062                                         // updates to ensure you always have the latest one, only vaguely suggesting
1063                                         // that it be at least the current time.
1064                                         if node_info.last_update  > msg.timestamp {
1065                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1066                                         } else if node_info.last_update  == msg.timestamp {
1067                                                 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1068                                         }
1069                                 }
1070
1071                                 let should_relay =
1072                                         msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1073                                         msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1074                                         msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1075                                 node.announcement_info = Some(NodeAnnouncementInfo {
1076                                         features: msg.features.clone(),
1077                                         last_update: msg.timestamp,
1078                                         rgb: msg.rgb,
1079                                         alias: msg.alias,
1080                                         addresses: msg.addresses.clone(),
1081                                         announcement_message: if should_relay { full_msg.cloned() } else { None },
1082                                 });
1083
1084                                 Ok(())
1085                         }
1086                 }
1087         }
1088
1089         /// Store or update channel info from a channel announcement.
1090         ///
1091         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1092         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1093         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1094         ///
1095         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1096         /// the corresponding UTXO exists on chain and is correctly-formatted.
1097         pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
1098                 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
1099         ) -> Result<(), LightningError>
1100         where
1101                 C::Target: chain::Access,
1102         {
1103                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1104                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1, "channel_announcement");
1105                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2, "channel_announcement");
1106                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1, "channel_announcement");
1107                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2, "channel_announcement");
1108                 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
1109         }
1110
1111         /// Store or update channel info from a channel announcement without verifying the associated
1112         /// signatures. Because we aren't given the associated signatures here we cannot relay the
1113         /// channel announcement to any of our peers.
1114         ///
1115         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1116         /// the corresponding UTXO exists on chain and is correctly-formatted.
1117         pub fn update_channel_from_unsigned_announcement<C: Deref>(
1118                 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
1119         ) -> Result<(), LightningError>
1120         where
1121                 C::Target: chain::Access,
1122         {
1123                 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
1124         }
1125
1126         fn update_channel_from_unsigned_announcement_intern<C: Deref>(
1127                 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
1128         ) -> Result<(), LightningError>
1129         where
1130                 C::Target: chain::Access,
1131         {
1132                 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1133                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1134                 }
1135
1136                 let utxo_value = match &chain_access {
1137                         &None => {
1138                                 // Tentatively accept, potentially exposing us to DoS attacks
1139                                 None
1140                         },
1141                         &Some(ref chain_access) => {
1142                                 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
1143                                         Ok(TxOut { value, script_pubkey }) => {
1144                                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1145                                                                                     .push_slice(&msg.bitcoin_key_1.serialize())
1146                                                                                     .push_slice(&msg.bitcoin_key_2.serialize())
1147                                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
1148                                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1149                                                 if script_pubkey != expected_script {
1150                                                         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});
1151                                                 }
1152                                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
1153                                                 //to the new HTLC max field in channel_update
1154                                                 Some(value)
1155                                         },
1156                                         Err(chain::AccessError::UnknownChain) => {
1157                                                 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
1158                                         },
1159                                         Err(chain::AccessError::UnknownTx) => {
1160                                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
1161                                         },
1162                                 }
1163                         },
1164                 };
1165
1166                 #[allow(unused_mut, unused_assignments)]
1167                 let mut announcement_received_time = 0;
1168                 #[cfg(feature = "std")]
1169                 {
1170                         announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1171                 }
1172
1173                 let chan_info = ChannelInfo {
1174                                 features: msg.features.clone(),
1175                                 node_one: NodeId::from_pubkey(&msg.node_id_1),
1176                                 one_to_two: None,
1177                                 node_two: NodeId::from_pubkey(&msg.node_id_2),
1178                                 two_to_one: None,
1179                                 capacity_sats: utxo_value,
1180                                 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1181                                         { full_msg.cloned() } else { None },
1182                                 announcement_received_time,
1183                         };
1184
1185                 let mut channels = self.channels.write().unwrap();
1186                 let mut nodes = self.nodes.write().unwrap();
1187                 match channels.entry(msg.short_channel_id) {
1188                         BtreeEntry::Occupied(mut entry) => {
1189                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1190                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
1191                                 //exactly how...
1192                                 if utxo_value.is_some() {
1193                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1194                                         // only sometimes returns results. In any case remove the previous entry. Note
1195                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
1196                                         // do that because
1197                                         // a) we don't *require* a UTXO provider that always returns results.
1198                                         // b) we don't track UTXOs of channels we know about and remove them if they
1199                                         //    get reorg'd out.
1200                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1201                                         Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
1202                                         *entry.get_mut() = chan_info;
1203                                 } else {
1204                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1205                                 }
1206                         },
1207                         BtreeEntry::Vacant(entry) => {
1208                                 entry.insert(chan_info);
1209                         }
1210                 };
1211
1212                 macro_rules! add_channel_to_node {
1213                         ( $node_id: expr ) => {
1214                                 match nodes.entry($node_id) {
1215                                         BtreeEntry::Occupied(node_entry) => {
1216                                                 node_entry.into_mut().channels.push(msg.short_channel_id);
1217                                         },
1218                                         BtreeEntry::Vacant(node_entry) => {
1219                                                 node_entry.insert(NodeInfo {
1220                                                         channels: vec!(msg.short_channel_id),
1221                                                         lowest_inbound_channel_fees: None,
1222                                                         announcement_info: None,
1223                                                 });
1224                                         }
1225                                 }
1226                         };
1227                 }
1228
1229                 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_1));
1230                 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_2));
1231
1232                 Ok(())
1233         }
1234
1235         /// Close a channel if a corresponding HTLC fail was sent.
1236         /// If permanent, removes a channel from the local storage.
1237         /// May cause the removal of nodes too, if this was their last channel.
1238         /// If not permanent, makes channels unavailable for routing.
1239         pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
1240                 let mut channels = self.channels.write().unwrap();
1241                 if is_permanent {
1242                         if let Some(chan) = channels.remove(&short_channel_id) {
1243                                 let mut nodes = self.nodes.write().unwrap();
1244                                 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1245                         }
1246                 } else {
1247                         if let Some(chan) = channels.get_mut(&short_channel_id) {
1248                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1249                                         one_to_two.enabled = false;
1250                                 }
1251                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1252                                         two_to_one.enabled = false;
1253                                 }
1254                         }
1255                 }
1256         }
1257
1258         /// Marks a node in the graph as failed.
1259         pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1260                 if is_permanent {
1261                         // TODO: Wholly remove the node
1262                 } else {
1263                         // TODO: downgrade the node
1264                 }
1265         }
1266
1267         #[cfg(feature = "std")]
1268         /// Removes information about channels that we haven't heard any updates about in some time.
1269         /// This can be used regularly to prune the network graph of channels that likely no longer
1270         /// exist.
1271         ///
1272         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1273         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1274         /// pruning occur for updates which are at least two weeks old, which we implement here.
1275         ///
1276         /// Note that for users of the `lightning-background-processor` crate this method may be
1277         /// automatically called regularly for you.
1278         ///
1279         /// This method is only available with the `std` feature. See
1280         /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1281         pub fn remove_stale_channels(&self) {
1282                 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1283                 self.remove_stale_channels_with_time(time);
1284         }
1285
1286         /// Removes information about channels that we haven't heard any updates about in some time.
1287         /// This can be used regularly to prune the network graph of channels that likely no longer
1288         /// exist.
1289         ///
1290         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1291         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1292         /// pruning occur for updates which are at least two weeks old, which we implement here.
1293         ///
1294         /// This function takes the current unix time as an argument. For users with the `std` feature
1295         /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1296         pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1297                 let mut channels = self.channels.write().unwrap();
1298                 // Time out if we haven't received an update in at least 14 days.
1299                 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1300                 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1301                 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1302                 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1303                 // time.
1304                 let mut scids_to_remove = Vec::new();
1305                 for (scid, info) in channels.iter_mut() {
1306                         if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1307                                 info.one_to_two = None;
1308                         }
1309                         if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1310                                 info.two_to_one = None;
1311                         }
1312                         if info.one_to_two.is_none() && info.two_to_one.is_none() {
1313                                 // We check the announcement_received_time here to ensure we don't drop
1314                                 // announcements that we just received and are just waiting for our peer to send a
1315                                 // channel_update for.
1316                                 if info.announcement_received_time < min_time_unix as u64 {
1317                                         scids_to_remove.push(*scid);
1318                                 }
1319                         }
1320                 }
1321                 if !scids_to_remove.is_empty() {
1322                         let mut nodes = self.nodes.write().unwrap();
1323                         for scid in scids_to_remove {
1324                                 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1325                                 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1326                         }
1327                 }
1328         }
1329
1330         /// For an already known (from announcement) channel, update info about one of the directions
1331         /// of the channel.
1332         ///
1333         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1334         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1335         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1336         ///
1337         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1338         /// materially in the future will be rejected.
1339         pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1340                 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1341         }
1342
1343         /// For an already known (from announcement) channel, update info about one of the directions
1344         /// of the channel without verifying the associated signatures. Because we aren't given the
1345         /// associated signatures here we cannot relay the channel update to any of our peers.
1346         ///
1347         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1348         /// materially in the future will be rejected.
1349         pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1350                 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1351         }
1352
1353         fn update_channel_intern<T: secp256k1::Verification>(&self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
1354                 let dest_node_id;
1355                 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1356                 let chan_was_enabled;
1357
1358                 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1359                 {
1360                         // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1361                         // disable this check during tests!
1362                         let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1363                         if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1364                                 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1365                         }
1366                         if msg.timestamp as u64 > time + 60 * 60 * 24 {
1367                                 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1368                         }
1369                 }
1370
1371                 let mut channels = self.channels.write().unwrap();
1372                 match channels.get_mut(&msg.short_channel_id) {
1373                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1374                         Some(channel) => {
1375                                 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1376                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
1377                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1378                                         }
1379
1380                                         if let Some(capacity_sats) = channel.capacity_sats {
1381                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1382                                                 // Don't query UTXO set here to reduce DoS risks.
1383                                                 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1384                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1385                                                 }
1386                                         }
1387                                 }
1388                                 macro_rules! check_update_latest {
1389                                         ($target: expr) => {
1390                                                 if let Some(existing_chan_info) = $target.as_ref() {
1391                                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1392                                                         // order updates to ensure you always have the latest one, only
1393                                                         // suggesting  that it be at least the current time. For
1394                                                         // channel_updates specifically, the BOLTs discuss the possibility of
1395                                                         // pruning based on the timestamp field being more than two weeks old,
1396                                                         // but only in the non-normative section.
1397                                                         if existing_chan_info.last_update > msg.timestamp {
1398                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1399                                                         } else if existing_chan_info.last_update == msg.timestamp {
1400                                                                 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1401                                                         }
1402                                                         chan_was_enabled = existing_chan_info.enabled;
1403                                                 } else {
1404                                                         chan_was_enabled = false;
1405                                                 }
1406                                         }
1407                                 }
1408
1409                                 macro_rules! get_new_channel_info {
1410                                         () => { {
1411                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1412                                                         { full_msg.cloned() } else { None };
1413
1414                                                 let updated_channel_update_info = ChannelUpdateInfo {
1415                                                         enabled: chan_enabled,
1416                                                         last_update: msg.timestamp,
1417                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
1418                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
1419                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1420                                                         fees: RoutingFees {
1421                                                                 base_msat: msg.fee_base_msat,
1422                                                                 proportional_millionths: msg.fee_proportional_millionths,
1423                                                         },
1424                                                         last_update_message
1425                                                 };
1426                                                 Some(updated_channel_update_info)
1427                                         } }
1428                                 }
1429
1430                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1431                                 if msg.flags & 1 == 1 {
1432                                         dest_node_id = channel.node_one.clone();
1433                                         check_update_latest!(channel.two_to_one);
1434                                         if let Some((sig, ctx)) = sig_info {
1435                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1436                                                         err: "Couldn't parse source node pubkey".to_owned(),
1437                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1438                                                 })?, "channel_update");
1439                                         }
1440                                         channel.two_to_one = get_new_channel_info!();
1441                                 } else {
1442                                         dest_node_id = channel.node_two.clone();
1443                                         check_update_latest!(channel.one_to_two);
1444                                         if let Some((sig, ctx)) = sig_info {
1445                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1446                                                         err: "Couldn't parse destination node pubkey".to_owned(),
1447                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1448                                                 })?, "channel_update");
1449                                         }
1450                                         channel.one_to_two = get_new_channel_info!();
1451                                 }
1452                         }
1453                 }
1454
1455                 let mut nodes = self.nodes.write().unwrap();
1456                 if chan_enabled {
1457                         let node = nodes.get_mut(&dest_node_id).unwrap();
1458                         let mut base_msat = msg.fee_base_msat;
1459                         let mut proportional_millionths = msg.fee_proportional_millionths;
1460                         if let Some(fees) = node.lowest_inbound_channel_fees {
1461                                 base_msat = cmp::min(base_msat, fees.base_msat);
1462                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1463                         }
1464                         node.lowest_inbound_channel_fees = Some(RoutingFees {
1465                                 base_msat,
1466                                 proportional_millionths
1467                         });
1468                 } else if chan_was_enabled {
1469                         let node = nodes.get_mut(&dest_node_id).unwrap();
1470                         let mut lowest_inbound_channel_fees = None;
1471
1472                         for chan_id in node.channels.iter() {
1473                                 let chan = channels.get(chan_id).unwrap();
1474                                 let chan_info_opt;
1475                                 if chan.node_one == dest_node_id {
1476                                         chan_info_opt = chan.two_to_one.as_ref();
1477                                 } else {
1478                                         chan_info_opt = chan.one_to_two.as_ref();
1479                                 }
1480                                 if let Some(chan_info) = chan_info_opt {
1481                                         if chan_info.enabled {
1482                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1483                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1484                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1485                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1486                                         }
1487                                 }
1488                         }
1489
1490                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1491                 }
1492
1493                 Ok(())
1494         }
1495
1496         fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1497                 macro_rules! remove_from_node {
1498                         ($node_id: expr) => {
1499                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1500                                         entry.get_mut().channels.retain(|chan_id| {
1501                                                 short_channel_id != *chan_id
1502                                         });
1503                                         if entry.get().channels.is_empty() {
1504                                                 entry.remove_entry();
1505                                         }
1506                                 } else {
1507                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1508                                 }
1509                         }
1510                 }
1511
1512                 remove_from_node!(chan.node_one);
1513                 remove_from_node!(chan.node_two);
1514         }
1515 }
1516
1517 impl ReadOnlyNetworkGraph<'_> {
1518         /// Returns all known valid channels' short ids along with announced channel info.
1519         ///
1520         /// (C-not exported) because we have no mapping for `BTreeMap`s
1521         pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1522                 &*self.channels
1523         }
1524
1525         /// Returns all known nodes' public keys along with announced node info.
1526         ///
1527         /// (C-not exported) because we have no mapping for `BTreeMap`s
1528         pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1529                 &*self.nodes
1530         }
1531
1532         /// Get network addresses by node id.
1533         /// Returns None if the requested node is completely unknown,
1534         /// or if node announcement for the node was never received.
1535         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1536                 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1537                         if let Some(node_info) = node.announcement_info.as_ref() {
1538                                 return Some(node_info.addresses.clone())
1539                         }
1540                 }
1541                 None
1542         }
1543 }
1544
1545 #[cfg(test)]
1546 mod tests {
1547         use chain;
1548         use ln::PaymentHash;
1549         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1550         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1551         use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1552                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, 
1553                 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1554         use util::test_utils;
1555         use util::logger::Logger;
1556         use util::ser::{Readable, Writeable};
1557         use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1558         use util::scid_utils::scid_from_parts;
1559
1560         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1561
1562         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1563         use bitcoin::hashes::Hash;
1564         use bitcoin::network::constants::Network;
1565         use bitcoin::blockdata::constants::genesis_block;
1566         use bitcoin::blockdata::script::{Builder, Script};
1567         use bitcoin::blockdata::transaction::TxOut;
1568         use bitcoin::blockdata::opcodes;
1569
1570         use hex;
1571
1572         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1573         use bitcoin::secp256k1::{All, Secp256k1};
1574
1575         use io;
1576         use prelude::*;
1577         use sync::Arc;
1578
1579         fn create_network_graph() -> NetworkGraph {
1580                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1581                 NetworkGraph::new(genesis_hash)
1582         }
1583
1584         fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1585                 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1586         ) {
1587                 let secp_ctx = Secp256k1::new();
1588                 let logger = Arc::new(test_utils::TestLogger::new());
1589                 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1590                 (secp_ctx, net_graph_msg_handler)
1591         }
1592
1593         #[test]
1594         fn request_full_sync_finite_times() {
1595                 let network_graph = create_network_graph();
1596                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1597                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1598
1599                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1600                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1601                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1602                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1603                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1604                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1605         }
1606
1607         fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1608                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1609                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1610                         features: NodeFeatures::known(),
1611                         timestamp: 100,
1612                         node_id: node_id,
1613                         rgb: [0; 3],
1614                         alias: [0; 32],
1615                         addresses: Vec::new(),
1616                         excess_address_data: Vec::new(),
1617                         excess_data: Vec::new(),
1618                 };
1619                 f(&mut unsigned_announcement);
1620                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1621                 NodeAnnouncement {
1622                         signature: secp_ctx.sign(&msghash, node_key),
1623                         contents: unsigned_announcement
1624                 }
1625         }
1626
1627         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 {
1628                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1629                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1630                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1631                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1632
1633                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1634                         features: ChannelFeatures::known(),
1635                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1636                         short_channel_id: 0,
1637                         node_id_1,
1638                         node_id_2,
1639                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1640                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1641                         excess_data: Vec::new(),
1642                 };
1643                 f(&mut unsigned_announcement);
1644                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1645                 ChannelAnnouncement {
1646                         node_signature_1: secp_ctx.sign(&msghash, node_1_key),
1647                         node_signature_2: secp_ctx.sign(&msghash, node_2_key),
1648                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1649                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1650                         contents: unsigned_announcement,
1651                 }
1652         }
1653
1654         fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1655                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1656                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1657                 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1658                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1659                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1660                               .push_opcode(opcodes::all::OP_PUSHNUM_2)
1661                               .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1662                               .to_v0_p2wsh()
1663         }
1664
1665         fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1666                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1667                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1668                         short_channel_id: 0,
1669                         timestamp: 100,
1670                         flags: 0,
1671                         cltv_expiry_delta: 144,
1672                         htlc_minimum_msat: 1_000_000,
1673                         htlc_maximum_msat: OptionalField::Absent,
1674                         fee_base_msat: 10_000,
1675                         fee_proportional_millionths: 20,
1676                         excess_data: Vec::new()
1677                 };
1678                 f(&mut unsigned_channel_update);
1679                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1680                 ChannelUpdate {
1681                         signature: secp_ctx.sign(&msghash, node_key),
1682                         contents: unsigned_channel_update
1683                 }
1684         }
1685
1686         #[test]
1687         fn handling_node_announcements() {
1688                 let network_graph = create_network_graph();
1689                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1690
1691                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1692                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1693                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1694
1695                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1696                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1697                         Ok(_) => panic!(),
1698                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1699                 };
1700
1701                 {
1702                         // Announce a channel to add a corresponding node.
1703                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1704                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1705                                 Ok(res) => assert!(res),
1706                                 _ => panic!()
1707                         };
1708                 }
1709
1710                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1711                         Ok(res) => assert!(res),
1712                         Err(_) => panic!()
1713                 };
1714
1715                 let fake_msghash = hash_to_message!(&zero_hash);
1716                 match net_graph_msg_handler.handle_node_announcement(
1717                         &NodeAnnouncement {
1718                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1719                                 contents: valid_announcement.contents.clone()
1720                 }) {
1721                         Ok(_) => panic!(),
1722                         Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
1723                 };
1724
1725                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1726                         unsigned_announcement.timestamp += 1000;
1727                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1728                 }, node_1_privkey, &secp_ctx);
1729                 // Return false because contains excess data.
1730                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1731                         Ok(res) => assert!(!res),
1732                         Err(_) => panic!()
1733                 };
1734
1735                 // Even though previous announcement was not relayed further, we still accepted it,
1736                 // so we now won't accept announcements before the previous one.
1737                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1738                         unsigned_announcement.timestamp += 1000 - 10;
1739                 }, node_1_privkey, &secp_ctx);
1740                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1741                         Ok(_) => panic!(),
1742                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1743                 };
1744         }
1745
1746         #[test]
1747         fn handling_channel_announcements() {
1748                 let secp_ctx = Secp256k1::new();
1749                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1750
1751                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1752                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1753
1754                 let good_script = get_channel_script(&secp_ctx);
1755                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1756
1757                 // Test if the UTXO lookups were not supported
1758                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1759                 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1760                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1761                         Ok(res) => assert!(res),
1762                         _ => panic!()
1763                 };
1764
1765                 {
1766                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1767                                 None => panic!(),
1768                                 Some(_) => ()
1769                         };
1770                 }
1771
1772                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1773                 // drop new one on the floor, since we can't see any changes.
1774                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1775                         Ok(_) => panic!(),
1776                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1777                 };
1778
1779                 // Test if an associated transaction were not on-chain (or not confirmed).
1780                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1781                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1782                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1783                 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1784
1785                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1786                         unsigned_announcement.short_channel_id += 1;
1787                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1788                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1789                         Ok(_) => panic!(),
1790                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1791                 };
1792
1793                 // Now test if the transaction is found in the UTXO set and the script is correct.
1794                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1795                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1796                         unsigned_announcement.short_channel_id += 2;
1797                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1798                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1799                         Ok(res) => assert!(res),
1800                         _ => panic!()
1801                 };
1802
1803                 {
1804                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1805                                 None => panic!(),
1806                                 Some(_) => ()
1807                         };
1808                 }
1809
1810                 // If we receive announcement for the same channel (but TX is not confirmed),
1811                 // drop new one on the floor, since we can't see any changes.
1812                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1813                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1814                         Ok(_) => panic!(),
1815                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1816                 };
1817
1818                 // But if it is confirmed, replace the channel
1819                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1820                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1821                         unsigned_announcement.features = ChannelFeatures::empty();
1822                         unsigned_announcement.short_channel_id += 2;
1823                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1824                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1825                         Ok(res) => assert!(res),
1826                         _ => panic!()
1827                 };
1828                 {
1829                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1830                                 Some(channel_entry) => {
1831                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1832                                 },
1833                                 _ => panic!()
1834                         };
1835                 }
1836
1837                 // Don't relay valid channels with excess data
1838                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1839                         unsigned_announcement.short_channel_id += 3;
1840                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1841                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1842                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1843                         Ok(res) => assert!(!res),
1844                         _ => panic!()
1845                 };
1846
1847                 let mut invalid_sig_announcement = valid_announcement.clone();
1848                 invalid_sig_announcement.contents.excess_data = Vec::new();
1849                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1850                         Ok(_) => panic!(),
1851                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
1852                 };
1853
1854                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1855                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1856                         Ok(_) => panic!(),
1857                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1858                 };
1859         }
1860
1861         #[test]
1862         fn handling_channel_update() {
1863                 let secp_ctx = Secp256k1::new();
1864                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1865                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1866                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1867                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1868
1869                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1870                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1871
1872                 let amount_sats = 1000_000;
1873                 let short_channel_id;
1874
1875                 {
1876                         // Announce a channel we will update
1877                         let good_script = get_channel_script(&secp_ctx);
1878                         *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1879
1880                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1881                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1882                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1883                                 Ok(_) => (),
1884                                 Err(_) => panic!()
1885                         };
1886
1887                 }
1888
1889                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1890                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1891                         Ok(res) => assert!(res),
1892                         _ => panic!()
1893                 };
1894
1895                 {
1896                         match network_graph.read_only().channels().get(&short_channel_id) {
1897                                 None => panic!(),
1898                                 Some(channel_info) => {
1899                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1900                                         assert!(channel_info.two_to_one.is_none());
1901                                 }
1902                         };
1903                 }
1904
1905                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1906                         unsigned_channel_update.timestamp += 100;
1907                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1908                 }, node_1_privkey, &secp_ctx);
1909                 // Return false because contains excess data
1910                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1911                         Ok(res) => assert!(!res),
1912                         _ => panic!()
1913                 };
1914
1915                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1916                         unsigned_channel_update.timestamp += 110;
1917                         unsigned_channel_update.short_channel_id += 1;
1918                 }, node_1_privkey, &secp_ctx);
1919                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1920                         Ok(_) => panic!(),
1921                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1922                 };
1923
1924                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1925                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1926                         unsigned_channel_update.timestamp += 110;
1927                 }, node_1_privkey, &secp_ctx);
1928                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1929                         Ok(_) => panic!(),
1930                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1931                 };
1932
1933                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1934                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1935                         unsigned_channel_update.timestamp += 110;
1936                 }, node_1_privkey, &secp_ctx);
1937                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1938                         Ok(_) => panic!(),
1939                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1940                 };
1941
1942                 // Even though previous update was not relayed further, we still accepted it,
1943                 // so we now won't accept update before the previous one.
1944                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1945                         unsigned_channel_update.timestamp += 100;
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, "Update had same timestamp as last processed update")
1950                 };
1951
1952                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1953                         unsigned_channel_update.timestamp += 500;
1954                 }, node_1_privkey, &secp_ctx);
1955                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1956                 let fake_msghash = hash_to_message!(&zero_hash);
1957                 invalid_sig_channel_update.signature = secp_ctx.sign(&fake_msghash, node_1_privkey);
1958                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1959                         Ok(_) => panic!(),
1960                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
1961                 };
1962         }
1963
1964         #[test]
1965         fn handling_network_update() {
1966                 let logger = test_utils::TestLogger::new();
1967                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1968                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1969                 let network_graph = NetworkGraph::new(genesis_hash);
1970                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1971                 let secp_ctx = Secp256k1::new();
1972
1973                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1974                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1975
1976                 {
1977                         // There is no nodes in the table at the beginning.
1978                         assert_eq!(network_graph.read_only().nodes().len(), 0);
1979                 }
1980
1981                 let short_channel_id;
1982                 {
1983                         // Announce a channel we will update
1984                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1985                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1986                         let chain_source: Option<&test_utils::TestChainSource> = None;
1987                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1988                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1989
1990                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1991                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1992
1993                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1994                                 payment_id: None,
1995                                 payment_hash: PaymentHash([0; 32]),
1996                                 rejected_by_dest: false,
1997                                 all_paths_failed: true,
1998                                 path: vec![],
1999                                 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
2000                                         msg: valid_channel_update,
2001                                 }),
2002                                 short_channel_id: None,
2003                                 retry: None,
2004                                 error_code: None,
2005                                 error_data: None,
2006                         });
2007
2008                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2009                 }
2010
2011                 // Non-permanent closing just disables a channel
2012                 {
2013                         match network_graph.read_only().channels().get(&short_channel_id) {
2014                                 None => panic!(),
2015                                 Some(channel_info) => {
2016                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2017                                 }
2018                         };
2019
2020                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2021                                 payment_id: None,
2022                                 payment_hash: PaymentHash([0; 32]),
2023                                 rejected_by_dest: false,
2024                                 all_paths_failed: true,
2025                                 path: vec![],
2026                                 network_update: Some(NetworkUpdate::ChannelClosed {
2027                                         short_channel_id,
2028                                         is_permanent: false,
2029                                 }),
2030                                 short_channel_id: None,
2031                                 retry: None,
2032                                 error_code: None,
2033                                 error_data: None,
2034                         });
2035
2036                         match network_graph.read_only().channels().get(&short_channel_id) {
2037                                 None => panic!(),
2038                                 Some(channel_info) => {
2039                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
2040                                 }
2041                         };
2042                 }
2043
2044                 // Permanent closing deletes a channel
2045                 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2046                         payment_id: None,
2047                         payment_hash: PaymentHash([0; 32]),
2048                         rejected_by_dest: false,
2049                         all_paths_failed: true,
2050                         path: vec![],
2051                         network_update: Some(NetworkUpdate::ChannelClosed {
2052                                 short_channel_id,
2053                                 is_permanent: true,
2054                         }),
2055                         short_channel_id: None,
2056                         retry: None,
2057                         error_code: None,
2058                         error_data: None,
2059                 });
2060
2061                 assert_eq!(network_graph.read_only().channels().len(), 0);
2062                 // Nodes are also deleted because there are no associated channels anymore
2063                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2064                 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
2065         }
2066
2067         #[test]
2068         fn test_channel_timeouts() {
2069                 // Test the removal of channels with `remove_stale_channels`.
2070                 let logger = test_utils::TestLogger::new();
2071                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2072                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2073                 let network_graph = NetworkGraph::new(genesis_hash);
2074                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
2075                 let secp_ctx = Secp256k1::new();
2076
2077                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2078                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2079
2080                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2081                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2082                 let chain_source: Option<&test_utils::TestChainSource> = None;
2083                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
2084                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2085
2086                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2087                 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
2088                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2089
2090                 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2091                 assert_eq!(network_graph.read_only().channels().len(), 1);
2092                 assert_eq!(network_graph.read_only().nodes().len(), 2);
2093
2094                 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2095                 #[cfg(feature = "std")]
2096                 {
2097                         // In std mode, a further check is performed before fully removing the channel -
2098                         // the channel_announcement must have been received at least two weeks ago. We
2099                         // fudge that here by indicating the time has jumped two weeks. Note that the
2100                         // directional channel information will have been removed already..
2101                         assert_eq!(network_graph.read_only().channels().len(), 1);
2102                         assert_eq!(network_graph.read_only().nodes().len(), 2);
2103                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2104
2105                         use std::time::{SystemTime, UNIX_EPOCH};
2106                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2107                         network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2108                 }
2109
2110                 assert_eq!(network_graph.read_only().channels().len(), 0);
2111                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2112         }
2113
2114         #[test]
2115         fn getting_next_channel_announcements() {
2116                 let network_graph = create_network_graph();
2117                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2118                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2119                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2120
2121                 // Channels were not announced yet.
2122                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
2123                 assert_eq!(channels_with_announcements.len(), 0);
2124
2125                 let short_channel_id;
2126                 {
2127                         // Announce a channel we will update
2128                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2129                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2130                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2131                                 Ok(_) => (),
2132                                 Err(_) => panic!()
2133                         };
2134                 }
2135
2136                 // Contains initial channel announcement now.
2137                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2138                 assert_eq!(channels_with_announcements.len(), 1);
2139                 if let Some(channel_announcements) = channels_with_announcements.first() {
2140                         let &(_, ref update_1, ref update_2) = channel_announcements;
2141                         assert_eq!(update_1, &None);
2142                         assert_eq!(update_2, &None);
2143                 } else {
2144                         panic!();
2145                 }
2146
2147
2148                 {
2149                         // Valid channel update
2150                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2151                                 unsigned_channel_update.timestamp = 101;
2152                         }, node_1_privkey, &secp_ctx);
2153                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2154                                 Ok(_) => (),
2155                                 Err(_) => panic!()
2156                         };
2157                 }
2158
2159                 // Now contains an initial announcement and an update.
2160                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2161                 assert_eq!(channels_with_announcements.len(), 1);
2162                 if let Some(channel_announcements) = channels_with_announcements.first() {
2163                         let &(_, ref update_1, ref update_2) = channel_announcements;
2164                         assert_ne!(update_1, &None);
2165                         assert_eq!(update_2, &None);
2166                 } else {
2167                         panic!();
2168                 }
2169
2170                 {
2171                         // Channel update with excess data.
2172                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2173                                 unsigned_channel_update.timestamp = 102;
2174                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2175                         }, node_1_privkey, &secp_ctx);
2176                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2177                                 Ok(_) => (),
2178                                 Err(_) => panic!()
2179                         };
2180                 }
2181
2182                 // Test that announcements with excess data won't be returned
2183                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2184                 assert_eq!(channels_with_announcements.len(), 1);
2185                 if let Some(channel_announcements) = channels_with_announcements.first() {
2186                         let &(_, ref update_1, ref update_2) = channel_announcements;
2187                         assert_eq!(update_1, &None);
2188                         assert_eq!(update_2, &None);
2189                 } else {
2190                         panic!();
2191                 }
2192
2193                 // Further starting point have no channels after it
2194                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
2195                 assert_eq!(channels_with_announcements.len(), 0);
2196         }
2197
2198         #[test]
2199         fn getting_next_node_announcements() {
2200                 let network_graph = create_network_graph();
2201                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2202                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2203                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2204                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2205
2206                 // No nodes yet.
2207                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2208                 assert_eq!(next_announcements.len(), 0);
2209
2210                 {
2211                         // Announce a channel to add 2 nodes
2212                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2213                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2214                                 Ok(_) => (),
2215                                 Err(_) => panic!()
2216                         };
2217                 }
2218
2219
2220                 // Nodes were never announced
2221                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2222                 assert_eq!(next_announcements.len(), 0);
2223
2224                 {
2225                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2226                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2227                                 Ok(_) => (),
2228                                 Err(_) => panic!()
2229                         };
2230
2231                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2232                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2233                                 Ok(_) => (),
2234                                 Err(_) => panic!()
2235                         };
2236                 }
2237
2238                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2239                 assert_eq!(next_announcements.len(), 2);
2240
2241                 // Skip the first node.
2242                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2243                 assert_eq!(next_announcements.len(), 1);
2244
2245                 {
2246                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2247                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2248                                 unsigned_announcement.timestamp += 10;
2249                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2250                         }, node_2_privkey, &secp_ctx);
2251                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2252                                 Ok(res) => assert!(!res),
2253                                 Err(_) => panic!()
2254                         };
2255                 }
2256
2257                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2258                 assert_eq!(next_announcements.len(), 0);
2259         }
2260
2261         #[test]
2262         fn network_graph_serialization() {
2263                 let network_graph = create_network_graph();
2264                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2265
2266                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2267                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2268
2269                 // Announce a channel to add a corresponding node.
2270                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2271                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2272                         Ok(res) => assert!(res),
2273                         _ => panic!()
2274                 };
2275
2276                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2277                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2278                         Ok(_) => (),
2279                         Err(_) => panic!()
2280                 };
2281
2282                 let mut w = test_utils::TestVecWriter(Vec::new());
2283                 assert!(!network_graph.read_only().nodes().is_empty());
2284                 assert!(!network_graph.read_only().channels().is_empty());
2285                 network_graph.write(&mut w).unwrap();
2286                 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2287         }
2288
2289         #[test]
2290         #[cfg(feature = "std")]
2291         fn calling_sync_routing_table() {
2292                 use std::time::{SystemTime, UNIX_EPOCH};
2293
2294                 let network_graph = create_network_graph();
2295                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2296                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2297                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2298
2299                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2300
2301                 // It should ignore if gossip_queries feature is not enabled
2302                 {
2303                         let init_msg = Init { features: InitFeatures::known().clear_gossip_queries(), remote_network_address: None };
2304                         net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2305                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2306                         assert_eq!(events.len(), 0);
2307                 }
2308
2309                 // It should send a gossip_timestamp_filter with the correct information
2310                 {
2311                         let init_msg = Init { features: InitFeatures::known(), remote_network_address: None };
2312                         net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2313                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2314                         assert_eq!(events.len(), 1);
2315                         match &events[0] {
2316                                 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
2317                                         assert_eq!(node_id, &node_id_1);
2318                                         assert_eq!(msg.chain_hash, chain_hash);
2319                                         let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2320                                         assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
2321                                         assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
2322                                         assert_eq!(msg.timestamp_range, u32::max_value());
2323                                 },
2324                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2325                         };
2326                 }
2327         }
2328
2329         #[test]
2330         fn handling_query_channel_range() {
2331                 let network_graph = create_network_graph();
2332                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2333
2334                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2335                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2336                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2337                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2338
2339                 let mut scids: Vec<u64> = vec![
2340                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2341                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2342                 ];
2343
2344                 // used for testing multipart reply across blocks
2345                 for block in 100000..=108001 {
2346                         scids.push(scid_from_parts(block, 0, 0).unwrap());
2347                 }
2348
2349                 // used for testing resumption on same block
2350                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2351
2352                 for scid in scids {
2353                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2354                                 unsigned_announcement.short_channel_id = scid;
2355                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2356                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2357                                 Ok(_) => (),
2358                                 _ => panic!()
2359                         };
2360                 }
2361
2362                 // Error when number_of_blocks=0
2363                 do_handling_query_channel_range(
2364                         &net_graph_msg_handler,
2365                         &node_id_2,
2366                         QueryChannelRange {
2367                                 chain_hash: chain_hash.clone(),
2368                                 first_blocknum: 0,
2369                                 number_of_blocks: 0,
2370                         },
2371                         false,
2372                         vec![ReplyChannelRange {
2373                                 chain_hash: chain_hash.clone(),
2374                                 first_blocknum: 0,
2375                                 number_of_blocks: 0,
2376                                 sync_complete: true,
2377                                 short_channel_ids: vec![]
2378                         }]
2379                 );
2380
2381                 // Error when wrong chain
2382                 do_handling_query_channel_range(
2383                         &net_graph_msg_handler,
2384                         &node_id_2,
2385                         QueryChannelRange {
2386                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2387                                 first_blocknum: 0,
2388                                 number_of_blocks: 0xffff_ffff,
2389                         },
2390                         false,
2391                         vec![ReplyChannelRange {
2392                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2393                                 first_blocknum: 0,
2394                                 number_of_blocks: 0xffff_ffff,
2395                                 sync_complete: true,
2396                                 short_channel_ids: vec![],
2397                         }]
2398                 );
2399
2400                 // Error when first_blocknum > 0xffffff
2401                 do_handling_query_channel_range(
2402                         &net_graph_msg_handler,
2403                         &node_id_2,
2404                         QueryChannelRange {
2405                                 chain_hash: chain_hash.clone(),
2406                                 first_blocknum: 0x01000000,
2407                                 number_of_blocks: 0xffff_ffff,
2408                         },
2409                         false,
2410                         vec![ReplyChannelRange {
2411                                 chain_hash: chain_hash.clone(),
2412                                 first_blocknum: 0x01000000,
2413                                 number_of_blocks: 0xffff_ffff,
2414                                 sync_complete: true,
2415                                 short_channel_ids: vec![]
2416                         }]
2417                 );
2418
2419                 // Empty reply when max valid SCID block num
2420                 do_handling_query_channel_range(
2421                         &net_graph_msg_handler,
2422                         &node_id_2,
2423                         QueryChannelRange {
2424                                 chain_hash: chain_hash.clone(),
2425                                 first_blocknum: 0xffffff,
2426                                 number_of_blocks: 1,
2427                         },
2428                         true,
2429                         vec![
2430                                 ReplyChannelRange {
2431                                         chain_hash: chain_hash.clone(),
2432                                         first_blocknum: 0xffffff,
2433                                         number_of_blocks: 1,
2434                                         sync_complete: true,
2435                                         short_channel_ids: vec![]
2436                                 },
2437                         ]
2438                 );
2439
2440                 // No results in valid query range
2441                 do_handling_query_channel_range(
2442                         &net_graph_msg_handler,
2443                         &node_id_2,
2444                         QueryChannelRange {
2445                                 chain_hash: chain_hash.clone(),
2446                                 first_blocknum: 1000,
2447                                 number_of_blocks: 1000,
2448                         },
2449                         true,
2450                         vec![
2451                                 ReplyChannelRange {
2452                                         chain_hash: chain_hash.clone(),
2453                                         first_blocknum: 1000,
2454                                         number_of_blocks: 1000,
2455                                         sync_complete: true,
2456                                         short_channel_ids: vec![],
2457                                 }
2458                         ]
2459                 );
2460
2461                 // Overflow first_blocknum + number_of_blocks
2462                 do_handling_query_channel_range(
2463                         &net_graph_msg_handler,
2464                         &node_id_2,
2465                         QueryChannelRange {
2466                                 chain_hash: chain_hash.clone(),
2467                                 first_blocknum: 0xfe0000,
2468                                 number_of_blocks: 0xffffffff,
2469                         },
2470                         true,
2471                         vec![
2472                                 ReplyChannelRange {
2473                                         chain_hash: chain_hash.clone(),
2474                                         first_blocknum: 0xfe0000,
2475                                         number_of_blocks: 0xffffffff - 0xfe0000,
2476                                         sync_complete: true,
2477                                         short_channel_ids: vec![
2478                                                 0xfffffe_ffffff_ffff, // max
2479                                         ]
2480                                 }
2481                         ]
2482                 );
2483
2484                 // Single block exactly full
2485                 do_handling_query_channel_range(
2486                         &net_graph_msg_handler,
2487                         &node_id_2,
2488                         QueryChannelRange {
2489                                 chain_hash: chain_hash.clone(),
2490                                 first_blocknum: 100000,
2491                                 number_of_blocks: 8000,
2492                         },
2493                         true,
2494                         vec![
2495                                 ReplyChannelRange {
2496                                         chain_hash: chain_hash.clone(),
2497                                         first_blocknum: 100000,
2498                                         number_of_blocks: 8000,
2499                                         sync_complete: true,
2500                                         short_channel_ids: (100000..=107999)
2501                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2502                                                 .collect(),
2503                                 },
2504                         ]
2505                 );
2506
2507                 // Multiple split on new block
2508                 do_handling_query_channel_range(
2509                         &net_graph_msg_handler,
2510                         &node_id_2,
2511                         QueryChannelRange {
2512                                 chain_hash: chain_hash.clone(),
2513                                 first_blocknum: 100000,
2514                                 number_of_blocks: 8001,
2515                         },
2516                         true,
2517                         vec![
2518                                 ReplyChannelRange {
2519                                         chain_hash: chain_hash.clone(),
2520                                         first_blocknum: 100000,
2521                                         number_of_blocks: 7999,
2522                                         sync_complete: false,
2523                                         short_channel_ids: (100000..=107999)
2524                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2525                                                 .collect(),
2526                                 },
2527                                 ReplyChannelRange {
2528                                         chain_hash: chain_hash.clone(),
2529                                         first_blocknum: 107999,
2530                                         number_of_blocks: 2,
2531                                         sync_complete: true,
2532                                         short_channel_ids: vec![
2533                                                 scid_from_parts(108000, 0, 0).unwrap(),
2534                                         ],
2535                                 }
2536                         ]
2537                 );
2538
2539                 // Multiple split on same block
2540                 do_handling_query_channel_range(
2541                         &net_graph_msg_handler,
2542                         &node_id_2,
2543                         QueryChannelRange {
2544                                 chain_hash: chain_hash.clone(),
2545                                 first_blocknum: 100002,
2546                                 number_of_blocks: 8000,
2547                         },
2548                         true,
2549                         vec![
2550                                 ReplyChannelRange {
2551                                         chain_hash: chain_hash.clone(),
2552                                         first_blocknum: 100002,
2553                                         number_of_blocks: 7999,
2554                                         sync_complete: false,
2555                                         short_channel_ids: (100002..=108001)
2556                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2557                                                 .collect(),
2558                                 },
2559                                 ReplyChannelRange {
2560                                         chain_hash: chain_hash.clone(),
2561                                         first_blocknum: 108001,
2562                                         number_of_blocks: 1,
2563                                         sync_complete: true,
2564                                         short_channel_ids: vec![
2565                                                 scid_from_parts(108001, 1, 0).unwrap(),
2566                                         ],
2567                                 }
2568                         ]
2569                 );
2570         }
2571
2572         fn do_handling_query_channel_range(
2573                 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2574                 test_node_id: &PublicKey,
2575                 msg: QueryChannelRange,
2576                 expected_ok: bool,
2577                 expected_replies: Vec<ReplyChannelRange>
2578         ) {
2579                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2580                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2581                 let query_end_blocknum = msg.end_blocknum();
2582                 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2583
2584                 if expected_ok {
2585                         assert!(result.is_ok());
2586                 } else {
2587                         assert!(result.is_err());
2588                 }
2589
2590                 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2591                 assert_eq!(events.len(), expected_replies.len());
2592
2593                 for i in 0..events.len() {
2594                         let expected_reply = &expected_replies[i];
2595                         match &events[i] {
2596                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2597                                         assert_eq!(node_id, test_node_id);
2598                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2599                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2600                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2601                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2602                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2603
2604                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2605                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2606                                         assert!(msg.first_blocknum >= max_firstblocknum);
2607                                         max_firstblocknum = msg.first_blocknum;
2608                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2609
2610                                         // Check that the last block count is >= the query's end_blocknum
2611                                         if i == events.len() - 1 {
2612                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2613                                         }
2614                                 },
2615                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2616                         }
2617                 }
2618         }
2619
2620         #[test]
2621         fn handling_query_short_channel_ids() {
2622                 let network_graph = create_network_graph();
2623                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2624                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2625                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2626
2627                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2628
2629                 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2630                         chain_hash,
2631                         short_channel_ids: vec![0x0003e8_000000_0000],
2632                 });
2633                 assert!(result.is_err());
2634         }
2635 }
2636
2637 #[cfg(all(test, feature = "_bench_unstable"))]
2638 mod benches {
2639         use super::*;
2640
2641         use test::Bencher;
2642         use std::io::Read;
2643
2644         #[bench]
2645         fn read_network_graph(bench: &mut Bencher) {
2646                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2647                 let mut v = Vec::new();
2648                 d.read_to_end(&mut v).unwrap();
2649                 bench.iter(|| {
2650                         let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2651                 });
2652         }
2653
2654         #[bench]
2655         fn write_network_graph(bench: &mut Bencher) {
2656                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2657                 let net_graph = NetworkGraph::read(&mut d).unwrap();
2658                 bench.iter(|| {
2659                         let _ = net_graph.encode();
2660                 });
2661         }
2662 }