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