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