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