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