Fix gossip using `gossip_timestamp_filter` instead of queries
[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! maybe_update_channel_info {
1389                                         ( $target: expr, $src_node: 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                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1408                                                         { full_msg.cloned() } else { None };
1409
1410                                                 let updated_channel_update_info = ChannelUpdateInfo {
1411                                                         enabled: chan_enabled,
1412                                                         last_update: msg.timestamp,
1413                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
1414                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
1415                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1416                                                         fees: RoutingFees {
1417                                                                 base_msat: msg.fee_base_msat,
1418                                                                 proportional_millionths: msg.fee_proportional_millionths,
1419                                                         },
1420                                                         last_update_message
1421                                                 };
1422                                                 $target = Some(updated_channel_update_info);
1423                                         }
1424                                 }
1425
1426                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1427                                 if msg.flags & 1 == 1 {
1428                                         dest_node_id = channel.node_one.clone();
1429                                         if let Some((sig, ctx)) = sig_info {
1430                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1431                                                         err: "Couldn't parse source node pubkey".to_owned(),
1432                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1433                                                 })?, "channel_update");
1434                                         }
1435                                         maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1436                                 } else {
1437                                         dest_node_id = channel.node_two.clone();
1438                                         if let Some((sig, ctx)) = sig_info {
1439                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1440                                                         err: "Couldn't parse destination node pubkey".to_owned(),
1441                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1442                                                 })?, "channel_update");
1443                                         }
1444                                         maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1445                                 }
1446                         }
1447                 }
1448
1449                 let mut nodes = self.nodes.write().unwrap();
1450                 if chan_enabled {
1451                         let node = nodes.get_mut(&dest_node_id).unwrap();
1452                         let mut base_msat = msg.fee_base_msat;
1453                         let mut proportional_millionths = msg.fee_proportional_millionths;
1454                         if let Some(fees) = node.lowest_inbound_channel_fees {
1455                                 base_msat = cmp::min(base_msat, fees.base_msat);
1456                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1457                         }
1458                         node.lowest_inbound_channel_fees = Some(RoutingFees {
1459                                 base_msat,
1460                                 proportional_millionths
1461                         });
1462                 } else if chan_was_enabled {
1463                         let node = nodes.get_mut(&dest_node_id).unwrap();
1464                         let mut lowest_inbound_channel_fees = None;
1465
1466                         for chan_id in node.channels.iter() {
1467                                 let chan = channels.get(chan_id).unwrap();
1468                                 let chan_info_opt;
1469                                 if chan.node_one == dest_node_id {
1470                                         chan_info_opt = chan.two_to_one.as_ref();
1471                                 } else {
1472                                         chan_info_opt = chan.one_to_two.as_ref();
1473                                 }
1474                                 if let Some(chan_info) = chan_info_opt {
1475                                         if chan_info.enabled {
1476                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1477                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1478                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1479                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1480                                         }
1481                                 }
1482                         }
1483
1484                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1485                 }
1486
1487                 Ok(())
1488         }
1489
1490         fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1491                 macro_rules! remove_from_node {
1492                         ($node_id: expr) => {
1493                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1494                                         entry.get_mut().channels.retain(|chan_id| {
1495                                                 short_channel_id != *chan_id
1496                                         });
1497                                         if entry.get().channels.is_empty() {
1498                                                 entry.remove_entry();
1499                                         }
1500                                 } else {
1501                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1502                                 }
1503                         }
1504                 }
1505
1506                 remove_from_node!(chan.node_one);
1507                 remove_from_node!(chan.node_two);
1508         }
1509 }
1510
1511 impl ReadOnlyNetworkGraph<'_> {
1512         /// Returns all known valid channels' short ids along with announced channel info.
1513         ///
1514         /// (C-not exported) because we have no mapping for `BTreeMap`s
1515         pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1516                 &*self.channels
1517         }
1518
1519         /// Returns all known nodes' public keys along with announced node info.
1520         ///
1521         /// (C-not exported) because we have no mapping for `BTreeMap`s
1522         pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1523                 &*self.nodes
1524         }
1525
1526         /// Get network addresses by node id.
1527         /// Returns None if the requested node is completely unknown,
1528         /// or if node announcement for the node was never received.
1529         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1530                 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1531                         if let Some(node_info) = node.announcement_info.as_ref() {
1532                                 return Some(node_info.addresses.clone())
1533                         }
1534                 }
1535                 None
1536         }
1537 }
1538
1539 #[cfg(test)]
1540 mod tests {
1541         use chain;
1542         use ln::PaymentHash;
1543         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1544         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1545         use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1546                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, 
1547                 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1548         use util::test_utils;
1549         use util::logger::Logger;
1550         use util::ser::{Readable, Writeable};
1551         use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1552         use util::scid_utils::scid_from_parts;
1553
1554         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1555
1556         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1557         use bitcoin::hashes::Hash;
1558         use bitcoin::network::constants::Network;
1559         use bitcoin::blockdata::constants::genesis_block;
1560         use bitcoin::blockdata::script::{Builder, Script};
1561         use bitcoin::blockdata::transaction::TxOut;
1562         use bitcoin::blockdata::opcodes;
1563
1564         use hex;
1565
1566         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1567         use bitcoin::secp256k1::{All, Secp256k1};
1568
1569         use io;
1570         use prelude::*;
1571         use sync::Arc;
1572
1573         fn create_network_graph() -> NetworkGraph {
1574                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1575                 NetworkGraph::new(genesis_hash)
1576         }
1577
1578         fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1579                 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1580         ) {
1581                 let secp_ctx = Secp256k1::new();
1582                 let logger = Arc::new(test_utils::TestLogger::new());
1583                 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1584                 (secp_ctx, net_graph_msg_handler)
1585         }
1586
1587         #[test]
1588         fn request_full_sync_finite_times() {
1589                 let network_graph = create_network_graph();
1590                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1591                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1592
1593                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1594                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1595                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1596                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1597                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1598                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1599         }
1600
1601         fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1602                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1603                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1604                         features: NodeFeatures::known(),
1605                         timestamp: 100,
1606                         node_id: node_id,
1607                         rgb: [0; 3],
1608                         alias: [0; 32],
1609                         addresses: Vec::new(),
1610                         excess_address_data: Vec::new(),
1611                         excess_data: Vec::new(),
1612                 };
1613                 f(&mut unsigned_announcement);
1614                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1615                 NodeAnnouncement {
1616                         signature: secp_ctx.sign(&msghash, node_key),
1617                         contents: unsigned_announcement
1618                 }
1619         }
1620
1621         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 {
1622                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1623                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1624                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1625                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1626
1627                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1628                         features: ChannelFeatures::known(),
1629                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1630                         short_channel_id: 0,
1631                         node_id_1,
1632                         node_id_2,
1633                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1634                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1635                         excess_data: Vec::new(),
1636                 };
1637                 f(&mut unsigned_announcement);
1638                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1639                 ChannelAnnouncement {
1640                         node_signature_1: secp_ctx.sign(&msghash, node_1_key),
1641                         node_signature_2: secp_ctx.sign(&msghash, node_2_key),
1642                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1643                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1644                         contents: unsigned_announcement,
1645                 }
1646         }
1647
1648         fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1649                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1650                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1651                 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1652                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1653                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1654                               .push_opcode(opcodes::all::OP_PUSHNUM_2)
1655                               .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1656                               .to_v0_p2wsh()
1657         }
1658
1659         fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1660                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1661                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1662                         short_channel_id: 0,
1663                         timestamp: 100,
1664                         flags: 0,
1665                         cltv_expiry_delta: 144,
1666                         htlc_minimum_msat: 1_000_000,
1667                         htlc_maximum_msat: OptionalField::Absent,
1668                         fee_base_msat: 10_000,
1669                         fee_proportional_millionths: 20,
1670                         excess_data: Vec::new()
1671                 };
1672                 f(&mut unsigned_channel_update);
1673                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1674                 ChannelUpdate {
1675                         signature: secp_ctx.sign(&msghash, node_key),
1676                         contents: unsigned_channel_update
1677                 }
1678         }
1679
1680         #[test]
1681         fn handling_node_announcements() {
1682                 let network_graph = create_network_graph();
1683                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1684
1685                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1686                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1687                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1688
1689                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1690                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1691                         Ok(_) => panic!(),
1692                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1693                 };
1694
1695                 {
1696                         // Announce a channel to add a corresponding node.
1697                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1698                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1699                                 Ok(res) => assert!(res),
1700                                 _ => panic!()
1701                         };
1702                 }
1703
1704                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1705                         Ok(res) => assert!(res),
1706                         Err(_) => panic!()
1707                 };
1708
1709                 let fake_msghash = hash_to_message!(&zero_hash);
1710                 match net_graph_msg_handler.handle_node_announcement(
1711                         &NodeAnnouncement {
1712                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1713                                 contents: valid_announcement.contents.clone()
1714                 }) {
1715                         Ok(_) => panic!(),
1716                         Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
1717                 };
1718
1719                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1720                         unsigned_announcement.timestamp += 1000;
1721                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1722                 }, node_1_privkey, &secp_ctx);
1723                 // Return false because contains excess data.
1724                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1725                         Ok(res) => assert!(!res),
1726                         Err(_) => panic!()
1727                 };
1728
1729                 // Even though previous announcement was not relayed further, we still accepted it,
1730                 // so we now won't accept announcements before the previous one.
1731                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1732                         unsigned_announcement.timestamp += 1000 - 10;
1733                 }, node_1_privkey, &secp_ctx);
1734                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1735                         Ok(_) => panic!(),
1736                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1737                 };
1738         }
1739
1740         #[test]
1741         fn handling_channel_announcements() {
1742                 let secp_ctx = Secp256k1::new();
1743                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1744
1745                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1746                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1747
1748                 let good_script = get_channel_script(&secp_ctx);
1749                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1750
1751                 // Test if the UTXO lookups were not supported
1752                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1753                 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1754                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1755                         Ok(res) => assert!(res),
1756                         _ => panic!()
1757                 };
1758
1759                 {
1760                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1761                                 None => panic!(),
1762                                 Some(_) => ()
1763                         };
1764                 }
1765
1766                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1767                 // drop new one on the floor, since we can't see any changes.
1768                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1769                         Ok(_) => panic!(),
1770                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1771                 };
1772
1773                 // Test if an associated transaction were not on-chain (or not confirmed).
1774                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1775                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1776                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1777                 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1778
1779                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1780                         unsigned_announcement.short_channel_id += 1;
1781                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1782                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1783                         Ok(_) => panic!(),
1784                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1785                 };
1786
1787                 // Now test if the transaction is found in the UTXO set and the script is correct.
1788                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1789                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1790                         unsigned_announcement.short_channel_id += 2;
1791                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1792                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1793                         Ok(res) => assert!(res),
1794                         _ => panic!()
1795                 };
1796
1797                 {
1798                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1799                                 None => panic!(),
1800                                 Some(_) => ()
1801                         };
1802                 }
1803
1804                 // If we receive announcement for the same channel (but TX is not confirmed),
1805                 // drop new one on the floor, since we can't see any changes.
1806                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1807                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1808                         Ok(_) => panic!(),
1809                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1810                 };
1811
1812                 // But if it is confirmed, replace the channel
1813                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1814                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1815                         unsigned_announcement.features = ChannelFeatures::empty();
1816                         unsigned_announcement.short_channel_id += 2;
1817                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1818                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1819                         Ok(res) => assert!(res),
1820                         _ => panic!()
1821                 };
1822                 {
1823                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1824                                 Some(channel_entry) => {
1825                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1826                                 },
1827                                 _ => panic!()
1828                         };
1829                 }
1830
1831                 // Don't relay valid channels with excess data
1832                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1833                         unsigned_announcement.short_channel_id += 3;
1834                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1835                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1836                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1837                         Ok(res) => assert!(!res),
1838                         _ => panic!()
1839                 };
1840
1841                 let mut invalid_sig_announcement = valid_announcement.clone();
1842                 invalid_sig_announcement.contents.excess_data = Vec::new();
1843                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1844                         Ok(_) => panic!(),
1845                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
1846                 };
1847
1848                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1849                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1850                         Ok(_) => panic!(),
1851                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1852                 };
1853         }
1854
1855         #[test]
1856         fn handling_channel_update() {
1857                 let secp_ctx = Secp256k1::new();
1858                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1859                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1860                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1861                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1862
1863                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1864                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1865
1866                 let amount_sats = 1000_000;
1867                 let short_channel_id;
1868
1869                 {
1870                         // Announce a channel we will update
1871                         let good_script = get_channel_script(&secp_ctx);
1872                         *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1873
1874                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1875                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1876                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1877                                 Ok(_) => (),
1878                                 Err(_) => panic!()
1879                         };
1880
1881                 }
1882
1883                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1884                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1885                         Ok(res) => assert!(res),
1886                         _ => panic!()
1887                 };
1888
1889                 {
1890                         match network_graph.read_only().channels().get(&short_channel_id) {
1891                                 None => panic!(),
1892                                 Some(channel_info) => {
1893                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1894                                         assert!(channel_info.two_to_one.is_none());
1895                                 }
1896                         };
1897                 }
1898
1899                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1900                         unsigned_channel_update.timestamp += 100;
1901                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1902                 }, node_1_privkey, &secp_ctx);
1903                 // Return false because contains excess data
1904                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1905                         Ok(res) => assert!(!res),
1906                         _ => panic!()
1907                 };
1908
1909                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1910                         unsigned_channel_update.timestamp += 110;
1911                         unsigned_channel_update.short_channel_id += 1;
1912                 }, node_1_privkey, &secp_ctx);
1913                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1914                         Ok(_) => panic!(),
1915                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1916                 };
1917
1918                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1919                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1920                         unsigned_channel_update.timestamp += 110;
1921                 }, node_1_privkey, &secp_ctx);
1922                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1923                         Ok(_) => panic!(),
1924                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1925                 };
1926
1927                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1928                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1929                         unsigned_channel_update.timestamp += 110;
1930                 }, node_1_privkey, &secp_ctx);
1931                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1932                         Ok(_) => panic!(),
1933                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1934                 };
1935
1936                 // Even though previous update was not relayed further, we still accepted it,
1937                 // so we now won't accept update before the previous one.
1938                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1939                         unsigned_channel_update.timestamp += 100;
1940                 }, node_1_privkey, &secp_ctx);
1941                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1942                         Ok(_) => panic!(),
1943                         Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
1944                 };
1945
1946                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1947                         unsigned_channel_update.timestamp += 500;
1948                 }, node_1_privkey, &secp_ctx);
1949                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1950                 let fake_msghash = hash_to_message!(&zero_hash);
1951                 invalid_sig_channel_update.signature = secp_ctx.sign(&fake_msghash, node_1_privkey);
1952                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1953                         Ok(_) => panic!(),
1954                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
1955                 };
1956         }
1957
1958         #[test]
1959         fn handling_network_update() {
1960                 let logger = test_utils::TestLogger::new();
1961                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1962                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1963                 let network_graph = NetworkGraph::new(genesis_hash);
1964                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1965                 let secp_ctx = Secp256k1::new();
1966
1967                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1968                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1969
1970                 {
1971                         // There is no nodes in the table at the beginning.
1972                         assert_eq!(network_graph.read_only().nodes().len(), 0);
1973                 }
1974
1975                 let short_channel_id;
1976                 {
1977                         // Announce a channel we will update
1978                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1979                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1980                         let chain_source: Option<&test_utils::TestChainSource> = None;
1981                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1982                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1983
1984                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1985                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1986
1987                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1988                                 payment_id: None,
1989                                 payment_hash: PaymentHash([0; 32]),
1990                                 rejected_by_dest: false,
1991                                 all_paths_failed: true,
1992                                 path: vec![],
1993                                 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
1994                                         msg: valid_channel_update,
1995                                 }),
1996                                 short_channel_id: None,
1997                                 retry: None,
1998                                 error_code: None,
1999                                 error_data: None,
2000                         });
2001
2002                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2003                 }
2004
2005                 // Non-permanent closing just disables a channel
2006                 {
2007                         match network_graph.read_only().channels().get(&short_channel_id) {
2008                                 None => panic!(),
2009                                 Some(channel_info) => {
2010                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2011                                 }
2012                         };
2013
2014                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2015                                 payment_id: None,
2016                                 payment_hash: PaymentHash([0; 32]),
2017                                 rejected_by_dest: false,
2018                                 all_paths_failed: true,
2019                                 path: vec![],
2020                                 network_update: Some(NetworkUpdate::ChannelClosed {
2021                                         short_channel_id,
2022                                         is_permanent: false,
2023                                 }),
2024                                 short_channel_id: None,
2025                                 retry: None,
2026                                 error_code: None,
2027                                 error_data: None,
2028                         });
2029
2030                         match network_graph.read_only().channels().get(&short_channel_id) {
2031                                 None => panic!(),
2032                                 Some(channel_info) => {
2033                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
2034                                 }
2035                         };
2036                 }
2037
2038                 // Permanent closing deletes a channel
2039                 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2040                         payment_id: None,
2041                         payment_hash: PaymentHash([0; 32]),
2042                         rejected_by_dest: false,
2043                         all_paths_failed: true,
2044                         path: vec![],
2045                         network_update: Some(NetworkUpdate::ChannelClosed {
2046                                 short_channel_id,
2047                                 is_permanent: true,
2048                         }),
2049                         short_channel_id: None,
2050                         retry: None,
2051                         error_code: None,
2052                         error_data: None,
2053                 });
2054
2055                 assert_eq!(network_graph.read_only().channels().len(), 0);
2056                 // Nodes are also deleted because there are no associated channels anymore
2057                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2058                 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
2059         }
2060
2061         #[test]
2062         fn test_channel_timeouts() {
2063                 // Test the removal of channels with `remove_stale_channels`.
2064                 let logger = test_utils::TestLogger::new();
2065                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2066                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2067                 let network_graph = NetworkGraph::new(genesis_hash);
2068                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
2069                 let secp_ctx = Secp256k1::new();
2070
2071                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2072                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2073
2074                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2075                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2076                 let chain_source: Option<&test_utils::TestChainSource> = None;
2077                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
2078                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2079
2080                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2081                 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
2082                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2083
2084                 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2085                 assert_eq!(network_graph.read_only().channels().len(), 1);
2086                 assert_eq!(network_graph.read_only().nodes().len(), 2);
2087
2088                 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2089                 #[cfg(feature = "std")]
2090                 {
2091                         // In std mode, a further check is performed before fully removing the channel -
2092                         // the channel_announcement must have been received at least two weeks ago. We
2093                         // fudge that here by indicating the time has jumped two weeks. Note that the
2094                         // directional channel information will have been removed already..
2095                         assert_eq!(network_graph.read_only().channels().len(), 1);
2096                         assert_eq!(network_graph.read_only().nodes().len(), 2);
2097                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2098
2099                         use std::time::{SystemTime, UNIX_EPOCH};
2100                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2101                         network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2102                 }
2103
2104                 assert_eq!(network_graph.read_only().channels().len(), 0);
2105                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2106         }
2107
2108         #[test]
2109         fn getting_next_channel_announcements() {
2110                 let network_graph = create_network_graph();
2111                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2112                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2113                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2114
2115                 // Channels were not announced yet.
2116                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
2117                 assert_eq!(channels_with_announcements.len(), 0);
2118
2119                 let short_channel_id;
2120                 {
2121                         // Announce a channel we will update
2122                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2123                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2124                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2125                                 Ok(_) => (),
2126                                 Err(_) => panic!()
2127                         };
2128                 }
2129
2130                 // Contains initial channel announcement now.
2131                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2132                 assert_eq!(channels_with_announcements.len(), 1);
2133                 if let Some(channel_announcements) = channels_with_announcements.first() {
2134                         let &(_, ref update_1, ref update_2) = channel_announcements;
2135                         assert_eq!(update_1, &None);
2136                         assert_eq!(update_2, &None);
2137                 } else {
2138                         panic!();
2139                 }
2140
2141
2142                 {
2143                         // Valid channel update
2144                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2145                                 unsigned_channel_update.timestamp = 101;
2146                         }, node_1_privkey, &secp_ctx);
2147                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2148                                 Ok(_) => (),
2149                                 Err(_) => panic!()
2150                         };
2151                 }
2152
2153                 // Now contains an initial announcement and an update.
2154                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2155                 assert_eq!(channels_with_announcements.len(), 1);
2156                 if let Some(channel_announcements) = channels_with_announcements.first() {
2157                         let &(_, ref update_1, ref update_2) = channel_announcements;
2158                         assert_ne!(update_1, &None);
2159                         assert_eq!(update_2, &None);
2160                 } else {
2161                         panic!();
2162                 }
2163
2164                 {
2165                         // Channel update with excess data.
2166                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2167                                 unsigned_channel_update.timestamp = 102;
2168                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2169                         }, node_1_privkey, &secp_ctx);
2170                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2171                                 Ok(_) => (),
2172                                 Err(_) => panic!()
2173                         };
2174                 }
2175
2176                 // Test that announcements with excess data won't be returned
2177                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2178                 assert_eq!(channels_with_announcements.len(), 1);
2179                 if let Some(channel_announcements) = channels_with_announcements.first() {
2180                         let &(_, ref update_1, ref update_2) = channel_announcements;
2181                         assert_eq!(update_1, &None);
2182                         assert_eq!(update_2, &None);
2183                 } else {
2184                         panic!();
2185                 }
2186
2187                 // Further starting point have no channels after it
2188                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
2189                 assert_eq!(channels_with_announcements.len(), 0);
2190         }
2191
2192         #[test]
2193         fn getting_next_node_announcements() {
2194                 let network_graph = create_network_graph();
2195                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2196                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2197                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2198                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2199
2200                 // No nodes yet.
2201                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2202                 assert_eq!(next_announcements.len(), 0);
2203
2204                 {
2205                         // Announce a channel to add 2 nodes
2206                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2207                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2208                                 Ok(_) => (),
2209                                 Err(_) => panic!()
2210                         };
2211                 }
2212
2213
2214                 // Nodes were never announced
2215                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2216                 assert_eq!(next_announcements.len(), 0);
2217
2218                 {
2219                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2220                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2221                                 Ok(_) => (),
2222                                 Err(_) => panic!()
2223                         };
2224
2225                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2226                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2227                                 Ok(_) => (),
2228                                 Err(_) => panic!()
2229                         };
2230                 }
2231
2232                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2233                 assert_eq!(next_announcements.len(), 2);
2234
2235                 // Skip the first node.
2236                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2237                 assert_eq!(next_announcements.len(), 1);
2238
2239                 {
2240                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2241                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2242                                 unsigned_announcement.timestamp += 10;
2243                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2244                         }, node_2_privkey, &secp_ctx);
2245                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2246                                 Ok(res) => assert!(!res),
2247                                 Err(_) => panic!()
2248                         };
2249                 }
2250
2251                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2252                 assert_eq!(next_announcements.len(), 0);
2253         }
2254
2255         #[test]
2256         fn network_graph_serialization() {
2257                 let network_graph = create_network_graph();
2258                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2259
2260                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2261                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2262
2263                 // Announce a channel to add a corresponding node.
2264                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2265                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2266                         Ok(res) => assert!(res),
2267                         _ => panic!()
2268                 };
2269
2270                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2271                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2272                         Ok(_) => (),
2273                         Err(_) => panic!()
2274                 };
2275
2276                 let mut w = test_utils::TestVecWriter(Vec::new());
2277                 assert!(!network_graph.read_only().nodes().is_empty());
2278                 assert!(!network_graph.read_only().channels().is_empty());
2279                 network_graph.write(&mut w).unwrap();
2280                 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2281         }
2282
2283         #[test]
2284         #[cfg(feature = "std")]
2285         fn calling_sync_routing_table() {
2286                 use std::time::{SystemTime, UNIX_EPOCH};
2287
2288                 let network_graph = create_network_graph();
2289                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2290                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2291                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2292
2293                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2294
2295                 // It should ignore if gossip_queries feature is not enabled
2296                 {
2297                         let init_msg = Init { features: InitFeatures::known().clear_gossip_queries(), remote_network_address: None };
2298                         net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2299                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2300                         assert_eq!(events.len(), 0);
2301                 }
2302
2303                 // It should send a gossip_timestamp_filter with the correct information
2304                 {
2305                         let init_msg = Init { features: InitFeatures::known(), remote_network_address: None };
2306                         net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2307                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2308                         assert_eq!(events.len(), 1);
2309                         match &events[0] {
2310                                 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
2311                                         assert_eq!(node_id, &node_id_1);
2312                                         assert_eq!(msg.chain_hash, chain_hash);
2313                                         let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2314                                         assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
2315                                         assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
2316                                         assert_eq!(msg.timestamp_range, u32::max_value());
2317                                 },
2318                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2319                         };
2320                 }
2321         }
2322
2323         #[test]
2324         fn handling_query_channel_range() {
2325                 let network_graph = create_network_graph();
2326                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2327
2328                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2329                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2330                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2331                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2332
2333                 let mut scids: Vec<u64> = vec![
2334                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2335                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2336                 ];
2337
2338                 // used for testing multipart reply across blocks
2339                 for block in 100000..=108001 {
2340                         scids.push(scid_from_parts(block, 0, 0).unwrap());
2341                 }
2342
2343                 // used for testing resumption on same block
2344                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2345
2346                 for scid in scids {
2347                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2348                                 unsigned_announcement.short_channel_id = scid;
2349                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2350                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2351                                 Ok(_) => (),
2352                                 _ => panic!()
2353                         };
2354                 }
2355
2356                 // Error when number_of_blocks=0
2357                 do_handling_query_channel_range(
2358                         &net_graph_msg_handler,
2359                         &node_id_2,
2360                         QueryChannelRange {
2361                                 chain_hash: chain_hash.clone(),
2362                                 first_blocknum: 0,
2363                                 number_of_blocks: 0,
2364                         },
2365                         false,
2366                         vec![ReplyChannelRange {
2367                                 chain_hash: chain_hash.clone(),
2368                                 first_blocknum: 0,
2369                                 number_of_blocks: 0,
2370                                 sync_complete: true,
2371                                 short_channel_ids: vec![]
2372                         }]
2373                 );
2374
2375                 // Error when wrong chain
2376                 do_handling_query_channel_range(
2377                         &net_graph_msg_handler,
2378                         &node_id_2,
2379                         QueryChannelRange {
2380                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2381                                 first_blocknum: 0,
2382                                 number_of_blocks: 0xffff_ffff,
2383                         },
2384                         false,
2385                         vec![ReplyChannelRange {
2386                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2387                                 first_blocknum: 0,
2388                                 number_of_blocks: 0xffff_ffff,
2389                                 sync_complete: true,
2390                                 short_channel_ids: vec![],
2391                         }]
2392                 );
2393
2394                 // Error when first_blocknum > 0xffffff
2395                 do_handling_query_channel_range(
2396                         &net_graph_msg_handler,
2397                         &node_id_2,
2398                         QueryChannelRange {
2399                                 chain_hash: chain_hash.clone(),
2400                                 first_blocknum: 0x01000000,
2401                                 number_of_blocks: 0xffff_ffff,
2402                         },
2403                         false,
2404                         vec![ReplyChannelRange {
2405                                 chain_hash: chain_hash.clone(),
2406                                 first_blocknum: 0x01000000,
2407                                 number_of_blocks: 0xffff_ffff,
2408                                 sync_complete: true,
2409                                 short_channel_ids: vec![]
2410                         }]
2411                 );
2412
2413                 // Empty reply when max valid SCID block num
2414                 do_handling_query_channel_range(
2415                         &net_graph_msg_handler,
2416                         &node_id_2,
2417                         QueryChannelRange {
2418                                 chain_hash: chain_hash.clone(),
2419                                 first_blocknum: 0xffffff,
2420                                 number_of_blocks: 1,
2421                         },
2422                         true,
2423                         vec![
2424                                 ReplyChannelRange {
2425                                         chain_hash: chain_hash.clone(),
2426                                         first_blocknum: 0xffffff,
2427                                         number_of_blocks: 1,
2428                                         sync_complete: true,
2429                                         short_channel_ids: vec![]
2430                                 },
2431                         ]
2432                 );
2433
2434                 // No results in valid query range
2435                 do_handling_query_channel_range(
2436                         &net_graph_msg_handler,
2437                         &node_id_2,
2438                         QueryChannelRange {
2439                                 chain_hash: chain_hash.clone(),
2440                                 first_blocknum: 1000,
2441                                 number_of_blocks: 1000,
2442                         },
2443                         true,
2444                         vec![
2445                                 ReplyChannelRange {
2446                                         chain_hash: chain_hash.clone(),
2447                                         first_blocknum: 1000,
2448                                         number_of_blocks: 1000,
2449                                         sync_complete: true,
2450                                         short_channel_ids: vec![],
2451                                 }
2452                         ]
2453                 );
2454
2455                 // Overflow first_blocknum + number_of_blocks
2456                 do_handling_query_channel_range(
2457                         &net_graph_msg_handler,
2458                         &node_id_2,
2459                         QueryChannelRange {
2460                                 chain_hash: chain_hash.clone(),
2461                                 first_blocknum: 0xfe0000,
2462                                 number_of_blocks: 0xffffffff,
2463                         },
2464                         true,
2465                         vec![
2466                                 ReplyChannelRange {
2467                                         chain_hash: chain_hash.clone(),
2468                                         first_blocknum: 0xfe0000,
2469                                         number_of_blocks: 0xffffffff - 0xfe0000,
2470                                         sync_complete: true,
2471                                         short_channel_ids: vec![
2472                                                 0xfffffe_ffffff_ffff, // max
2473                                         ]
2474                                 }
2475                         ]
2476                 );
2477
2478                 // Single block exactly full
2479                 do_handling_query_channel_range(
2480                         &net_graph_msg_handler,
2481                         &node_id_2,
2482                         QueryChannelRange {
2483                                 chain_hash: chain_hash.clone(),
2484                                 first_blocknum: 100000,
2485                                 number_of_blocks: 8000,
2486                         },
2487                         true,
2488                         vec![
2489                                 ReplyChannelRange {
2490                                         chain_hash: chain_hash.clone(),
2491                                         first_blocknum: 100000,
2492                                         number_of_blocks: 8000,
2493                                         sync_complete: true,
2494                                         short_channel_ids: (100000..=107999)
2495                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2496                                                 .collect(),
2497                                 },
2498                         ]
2499                 );
2500
2501                 // Multiple split on new block
2502                 do_handling_query_channel_range(
2503                         &net_graph_msg_handler,
2504                         &node_id_2,
2505                         QueryChannelRange {
2506                                 chain_hash: chain_hash.clone(),
2507                                 first_blocknum: 100000,
2508                                 number_of_blocks: 8001,
2509                         },
2510                         true,
2511                         vec![
2512                                 ReplyChannelRange {
2513                                         chain_hash: chain_hash.clone(),
2514                                         first_blocknum: 100000,
2515                                         number_of_blocks: 7999,
2516                                         sync_complete: false,
2517                                         short_channel_ids: (100000..=107999)
2518                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2519                                                 .collect(),
2520                                 },
2521                                 ReplyChannelRange {
2522                                         chain_hash: chain_hash.clone(),
2523                                         first_blocknum: 107999,
2524                                         number_of_blocks: 2,
2525                                         sync_complete: true,
2526                                         short_channel_ids: vec![
2527                                                 scid_from_parts(108000, 0, 0).unwrap(),
2528                                         ],
2529                                 }
2530                         ]
2531                 );
2532
2533                 // Multiple split on same block
2534                 do_handling_query_channel_range(
2535                         &net_graph_msg_handler,
2536                         &node_id_2,
2537                         QueryChannelRange {
2538                                 chain_hash: chain_hash.clone(),
2539                                 first_blocknum: 100002,
2540                                 number_of_blocks: 8000,
2541                         },
2542                         true,
2543                         vec![
2544                                 ReplyChannelRange {
2545                                         chain_hash: chain_hash.clone(),
2546                                         first_blocknum: 100002,
2547                                         number_of_blocks: 7999,
2548                                         sync_complete: false,
2549                                         short_channel_ids: (100002..=108001)
2550                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2551                                                 .collect(),
2552                                 },
2553                                 ReplyChannelRange {
2554                                         chain_hash: chain_hash.clone(),
2555                                         first_blocknum: 108001,
2556                                         number_of_blocks: 1,
2557                                         sync_complete: true,
2558                                         short_channel_ids: vec![
2559                                                 scid_from_parts(108001, 1, 0).unwrap(),
2560                                         ],
2561                                 }
2562                         ]
2563                 );
2564         }
2565
2566         fn do_handling_query_channel_range(
2567                 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2568                 test_node_id: &PublicKey,
2569                 msg: QueryChannelRange,
2570                 expected_ok: bool,
2571                 expected_replies: Vec<ReplyChannelRange>
2572         ) {
2573                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2574                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2575                 let query_end_blocknum = msg.end_blocknum();
2576                 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2577
2578                 if expected_ok {
2579                         assert!(result.is_ok());
2580                 } else {
2581                         assert!(result.is_err());
2582                 }
2583
2584                 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2585                 assert_eq!(events.len(), expected_replies.len());
2586
2587                 for i in 0..events.len() {
2588                         let expected_reply = &expected_replies[i];
2589                         match &events[i] {
2590                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2591                                         assert_eq!(node_id, test_node_id);
2592                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2593                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2594                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2595                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2596                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2597
2598                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2599                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2600                                         assert!(msg.first_blocknum >= max_firstblocknum);
2601                                         max_firstblocknum = msg.first_blocknum;
2602                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2603
2604                                         // Check that the last block count is >= the query's end_blocknum
2605                                         if i == events.len() - 1 {
2606                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2607                                         }
2608                                 },
2609                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2610                         }
2611                 }
2612         }
2613
2614         #[test]
2615         fn handling_query_short_channel_ids() {
2616                 let network_graph = create_network_graph();
2617                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2618                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2619                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2620
2621                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2622
2623                 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2624                         chain_hash,
2625                         short_channel_ids: vec![0x0003e8_000000_0000],
2626                 });
2627                 assert!(result.is_err());
2628         }
2629 }
2630
2631 #[cfg(all(test, feature = "_bench_unstable"))]
2632 mod benches {
2633         use super::*;
2634
2635         use test::Bencher;
2636         use std::io::Read;
2637
2638         #[bench]
2639         fn read_network_graph(bench: &mut Bencher) {
2640                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2641                 let mut v = Vec::new();
2642                 d.read_to_end(&mut v).unwrap();
2643                 bench.iter(|| {
2644                         let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2645                 });
2646         }
2647
2648         #[bench]
2649         fn write_network_graph(bench: &mut Bencher) {
2650                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2651                 let net_graph = NetworkGraph::read(&mut d).unwrap();
2652                 bench.iter(|| {
2653                         let _ = net_graph.encode();
2654                 });
2655         }
2656 }