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