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