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