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