Add annotations for things which we cannot (yet) expose
[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::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
15
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::opcodes;
20
21 use chain::chaininterface::{ChainError, ChainWatchInterface};
22 use ln::features::{ChannelFeatures, NodeFeatures};
23 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
24 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
25 use ln::msgs;
26 use util::ser::{Writeable, Readable, Writer};
27 use util::logger::Logger;
28
29 use std::{cmp, fmt};
30 use std::sync::{RwLock, RwLockReadGuard};
31 use std::sync::atomic::{AtomicUsize, Ordering};
32 use std::collections::BTreeMap;
33 use std::collections::btree_map::Entry as BtreeEntry;
34 use std::ops::Deref;
35 use bitcoin::hashes::hex::ToHex;
36
37 /// Represents the network as nodes and channels between them
38 #[derive(PartialEq)]
39 pub struct NetworkGraph {
40         channels: BTreeMap<u64, ChannelInfo>,
41         nodes: BTreeMap<PublicKey, NodeInfo>,
42 }
43
44 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
45 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
46 /// the C bindings, as it can be done directly in Rust code.
47 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
48
49 /// Receives and validates network updates from peers,
50 /// stores authentic and relevant data as a network graph.
51 /// This network graph is then used for routing payments.
52 /// Provides interface to help with initial routing sync by
53 /// serving historical announcements.
54 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
55         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
56         /// Representation of the payment channel network
57         pub network_graph: RwLock<NetworkGraph>,
58         chain_monitor: C,
59         full_syncs_requested: AtomicUsize,
60         logger: L,
61 }
62
63 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
64         /// Creates a new tracker of the actual state of the network of channels and nodes,
65         /// assuming a fresh network graph.
66         /// Chain monitor is used to make sure announced channels exist on-chain,
67         /// channel data is correct, and that the announcement is signed with
68         /// channel owners' keys.
69         pub fn new(chain_monitor: C, logger: L) -> Self {
70                 NetGraphMsgHandler {
71                         secp_ctx: Secp256k1::verification_only(),
72                         network_graph: RwLock::new(NetworkGraph {
73                                 channels: BTreeMap::new(),
74                                 nodes: BTreeMap::new(),
75                         }),
76                         full_syncs_requested: AtomicUsize::new(0),
77                         chain_monitor,
78                         logger,
79                 }
80         }
81
82         /// Creates a new tracker of the actual state of the network of channels and nodes,
83         /// assuming an existing Network Graph.
84         pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
85                 NetGraphMsgHandler {
86                         secp_ctx: Secp256k1::verification_only(),
87                         network_graph: RwLock::new(network_graph),
88                         full_syncs_requested: AtomicUsize::new(0),
89                         chain_monitor,
90                         logger,
91                 }
92         }
93
94         /// Take a read lock on the network_graph and return it in the C-bindings
95         /// newtype helper. This is likely only useful when called via the C
96         /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
97         /// yourself.
98         pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
99                 LockedNetworkGraph(self.network_graph.read().unwrap())
100         }
101 }
102
103 impl<'a> LockedNetworkGraph<'a> {
104         /// Get a reference to the NetworkGraph which this read-lock contains.
105         pub fn graph(&self) -> &NetworkGraph {
106                 &*self.0
107         }
108 }
109
110
111 macro_rules! secp_verify_sig {
112         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
113                 match $secp_ctx.verify($msg, $sig, $pubkey) {
114                         Ok(_) => {},
115                         Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
116                 }
117         };
118 }
119
120 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
121         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
122                 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
123         }
124
125         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
126                 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
127                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
128                 }
129
130                 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
131                         Ok((script_pubkey, value)) => {
132                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
133                                                                     .push_slice(&msg.contents.bitcoin_key_1.serialize())
134                                                                     .push_slice(&msg.contents.bitcoin_key_2.serialize())
135                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
136                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
137                                 if script_pubkey != expected_script {
138                                         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});
139                                 }
140                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
141                                 //to the new HTLC max field in channel_update
142                                 Some(value)
143                         },
144                         Err(ChainError::NotSupported) => {
145                                 // Tentatively accept, potentially exposing us to DoS attacks
146                                 None
147                         },
148                         Err(ChainError::NotWatched) => {
149                                 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
150                         },
151                         Err(ChainError::UnknownTx) => {
152                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
153                         },
154                 };
155                 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
156                 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
157                 result
158         }
159
160         fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
161                 match update {
162                         &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
163                                 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
164                         },
165                         &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
166                                 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
167                         },
168                         &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
169                                 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
170                         },
171                 }
172         }
173
174         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
175                 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
176         }
177
178         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
179                 let network_graph = self.network_graph.read().unwrap();
180                 let mut result = Vec::with_capacity(batch_amount as usize);
181                 let mut iter = network_graph.get_channels().range(starting_point..);
182                 while result.len() < batch_amount as usize {
183                         if let Some((_, ref chan)) = iter.next() {
184                                 if chan.announcement_message.is_some() {
185                                         let chan_announcement = chan.announcement_message.clone().unwrap();
186                                         let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
187                                         let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
188                                         if let Some(one_to_two) = chan.one_to_two.as_ref() {
189                                                 one_to_two_announcement = one_to_two.last_update_message.clone();
190                                         }
191                                         if let Some(two_to_one) = chan.two_to_one.as_ref() {
192                                                 two_to_one_announcement = two_to_one.last_update_message.clone();
193                                         }
194                                         result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
195                                 } else {
196                                         // TODO: We may end up sending un-announced channel_updates if we are sending
197                                         // initial sync data while receiving announce/updates for this channel.
198                                 }
199                         } else {
200                                 return result;
201                         }
202                 }
203                 result
204         }
205
206         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
207                 let network_graph = self.network_graph.read().unwrap();
208                 let mut result = Vec::with_capacity(batch_amount as usize);
209                 let mut iter = if let Some(pubkey) = starting_point {
210                                 let mut iter = network_graph.get_nodes().range((*pubkey)..);
211                                 iter.next();
212                                 iter
213                         } else {
214                                 network_graph.get_nodes().range(..)
215                         };
216                 while result.len() < batch_amount as usize {
217                         if let Some((_, ref node)) = iter.next() {
218                                 if let Some(node_info) = node.announcement_info.as_ref() {
219                                         if node_info.announcement_message.is_some() {
220                                                 result.push(node_info.announcement_message.clone().unwrap());
221                                         }
222                                 }
223                         } else {
224                                 return result;
225                         }
226                 }
227                 result
228         }
229
230         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
231                 //TODO: Determine whether to request a full sync based on the network map.
232                 const FULL_SYNCS_TO_REQUEST: usize = 5;
233                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
234                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
235                         true
236                 } else {
237                         false
238                 }
239         }
240 }
241
242 #[derive(PartialEq, Debug)]
243 /// Details about one direction of a channel. Received
244 /// within a channel update.
245 pub struct DirectionalChannelInfo {
246         /// When the last update to the channel direction was issued.
247         /// Value is opaque, as set in the announcement.
248         pub last_update: u32,
249         /// Whether the channel can be currently used for payments (in this one direction).
250         pub enabled: bool,
251         /// The difference in CLTV values that you must have when routing through this channel.
252         pub cltv_expiry_delta: u16,
253         /// The minimum value, which must be relayed to the next hop via the channel
254         pub htlc_minimum_msat: u64,
255         /// The maximum value which may be relayed to the next hop via the channel.
256         pub htlc_maximum_msat: Option<u64>,
257         /// Fees charged when the channel is used for routing
258         pub fees: RoutingFees,
259         /// Most recent update for the channel received from the network
260         /// Mostly redundant with the data we store in fields explicitly.
261         /// Everything else is useful only for sending out for initial routing sync.
262         /// Not stored if contains excess data to prevent DoS.
263         pub last_update_message: Option<ChannelUpdate>,
264 }
265
266 impl fmt::Display for DirectionalChannelInfo {
267         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
268                 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)?;
269                 Ok(())
270         }
271 }
272
273 impl_writeable!(DirectionalChannelInfo, 0, {
274         last_update,
275         enabled,
276         cltv_expiry_delta,
277         htlc_minimum_msat,
278         htlc_maximum_msat,
279         fees,
280         last_update_message
281 });
282
283 #[derive(PartialEq)]
284 /// Details about a channel (both directions).
285 /// Received within a channel announcement.
286 pub struct ChannelInfo {
287         /// Protocol features of a channel communicated during its announcement
288         pub features: ChannelFeatures,
289         /// Source node of the first direction of a channel
290         pub node_one: PublicKey,
291         /// Details about the first direction of a channel
292         pub one_to_two: Option<DirectionalChannelInfo>,
293         /// Source node of the second direction of a channel
294         pub node_two: PublicKey,
295         /// Details about the second direction of a channel
296         pub two_to_one: Option<DirectionalChannelInfo>,
297         /// The channel capacity as seen on-chain, if chain lookup is available.
298         pub capacity_sats: Option<u64>,
299         /// An initial announcement of the channel
300         /// Mostly redundant with the data we store in fields explicitly.
301         /// Everything else is useful only for sending out for initial routing sync.
302         /// Not stored if contains excess data to prevent DoS.
303         pub announcement_message: Option<ChannelAnnouncement>,
304 }
305
306 impl fmt::Display for ChannelInfo {
307         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
308                 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
309                    log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
310                 Ok(())
311         }
312 }
313
314 impl_writeable!(ChannelInfo, 0, {
315         features,
316         node_one,
317         one_to_two,
318         node_two,
319         two_to_one,
320         capacity_sats,
321         announcement_message
322 });
323
324
325 /// Fees for routing via a given channel or a node
326 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
327 pub struct RoutingFees {
328         /// Flat routing fee in satoshis
329         pub base_msat: u32,
330         /// Liquidity-based routing fee in millionths of a routed amount.
331         /// In other words, 10000 is 1%.
332         pub proportional_millionths: u32,
333 }
334
335 impl Readable for RoutingFees{
336         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
337                 let base_msat: u32 = Readable::read(reader)?;
338                 let proportional_millionths: u32 = Readable::read(reader)?;
339                 Ok(RoutingFees {
340                         base_msat,
341                         proportional_millionths,
342                 })
343         }
344 }
345
346 impl Writeable for RoutingFees {
347         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
348                 self.base_msat.write(writer)?;
349                 self.proportional_millionths.write(writer)?;
350                 Ok(())
351         }
352 }
353
354 #[derive(PartialEq, Debug)]
355 /// Information received in the latest node_announcement from this node.
356 pub struct NodeAnnouncementInfo {
357         /// Protocol features the node announced support for
358         pub features: NodeFeatures,
359         /// When the last known update to the node state was issued.
360         /// Value is opaque, as set in the announcement.
361         pub last_update: u32,
362         /// Color assigned to the node
363         pub rgb: [u8; 3],
364         /// Moniker assigned to the node.
365         /// May be invalid or malicious (eg control chars),
366         /// should not be exposed to the user.
367         pub alias: [u8; 32],
368         /// Internet-level addresses via which one can connect to the node
369         pub addresses: Vec<NetAddress>,
370         /// An initial announcement of the node
371         /// Mostly redundant with the data we store in fields explicitly.
372         /// Everything else is useful only for sending out for initial routing sync.
373         /// Not stored if contains excess data to prevent DoS.
374         pub announcement_message: Option<NodeAnnouncement>
375 }
376
377 impl Writeable for NodeAnnouncementInfo {
378         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
379                 self.features.write(writer)?;
380                 self.last_update.write(writer)?;
381                 self.rgb.write(writer)?;
382                 self.alias.write(writer)?;
383                 (self.addresses.len() as u64).write(writer)?;
384                 for ref addr in &self.addresses {
385                         addr.write(writer)?;
386                 }
387                 self.announcement_message.write(writer)?;
388                 Ok(())
389         }
390 }
391
392 impl Readable for NodeAnnouncementInfo {
393         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
394                 let features = Readable::read(reader)?;
395                 let last_update = Readable::read(reader)?;
396                 let rgb = Readable::read(reader)?;
397                 let alias = Readable::read(reader)?;
398                 let addresses_count: u64 = Readable::read(reader)?;
399                 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
400                 for _ in 0..addresses_count {
401                         match Readable::read(reader) {
402                                 Ok(Ok(addr)) => { addresses.push(addr); },
403                                 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
404                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
405                                 _ => unreachable!(),
406                         }
407                 }
408                 let announcement_message = Readable::read(reader)?;
409                 Ok(NodeAnnouncementInfo {
410                         features,
411                         last_update,
412                         rgb,
413                         alias,
414                         addresses,
415                         announcement_message
416                 })
417         }
418 }
419
420 #[derive(PartialEq)]
421 /// Details about a node in the network, known from the network announcement.
422 pub struct NodeInfo {
423         /// All valid channels a node has announced
424         pub channels: Vec<u64>,
425         /// Lowest fees enabling routing via any of the enabled, known channels to a node.
426         /// The two fields (flat and proportional fee) are independent,
427         /// meaning they don't have to refer to the same channel.
428         pub lowest_inbound_channel_fees: Option<RoutingFees>,
429         /// More information about a node from node_announcement.
430         /// Optional because we store a Node entry after learning about it from
431         /// a channel announcement, but before receiving a node announcement.
432         pub announcement_info: Option<NodeAnnouncementInfo>
433 }
434
435 impl fmt::Display for NodeInfo {
436         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
437                 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
438                    self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
439                 Ok(())
440         }
441 }
442
443 impl Writeable for NodeInfo {
444         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
445                 (self.channels.len() as u64).write(writer)?;
446                 for ref chan in self.channels.iter() {
447                         chan.write(writer)?;
448                 }
449                 self.lowest_inbound_channel_fees.write(writer)?;
450                 self.announcement_info.write(writer)?;
451                 Ok(())
452         }
453 }
454
455 const MAX_ALLOC_SIZE: u64 = 64*1024;
456
457 impl Readable for NodeInfo {
458         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
459                 let channels_count: u64 = Readable::read(reader)?;
460                 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
461                 for _ in 0..channels_count {
462                         channels.push(Readable::read(reader)?);
463                 }
464                 let lowest_inbound_channel_fees = Readable::read(reader)?;
465                 let announcement_info = Readable::read(reader)?;
466                 Ok(NodeInfo {
467                         channels,
468                         lowest_inbound_channel_fees,
469                         announcement_info,
470                 })
471         }
472 }
473
474 impl Writeable for NetworkGraph {
475         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
476                 (self.channels.len() as u64).write(writer)?;
477                 for (ref chan_id, ref chan_info) in self.channels.iter() {
478                         (*chan_id).write(writer)?;
479                         chan_info.write(writer)?;
480                 }
481                 (self.nodes.len() as u64).write(writer)?;
482                 for (ref node_id, ref node_info) in self.nodes.iter() {
483                         node_id.write(writer)?;
484                         node_info.write(writer)?;
485                 }
486                 Ok(())
487         }
488 }
489
490 impl Readable for NetworkGraph {
491         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
492                 let channels_count: u64 = Readable::read(reader)?;
493                 let mut channels = BTreeMap::new();
494                 for _ in 0..channels_count {
495                         let chan_id: u64 = Readable::read(reader)?;
496                         let chan_info = Readable::read(reader)?;
497                         channels.insert(chan_id, chan_info);
498                 }
499                 let nodes_count: u64 = Readable::read(reader)?;
500                 let mut nodes = BTreeMap::new();
501                 for _ in 0..nodes_count {
502                         let node_id = Readable::read(reader)?;
503                         let node_info = Readable::read(reader)?;
504                         nodes.insert(node_id, node_info);
505                 }
506                 Ok(NetworkGraph {
507                         channels,
508                         nodes,
509                 })
510         }
511 }
512
513 impl fmt::Display for NetworkGraph {
514         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
515                 write!(f, "Network map\n[Channels]\n")?;
516                 for (key, val) in self.channels.iter() {
517                         write!(f, " {}: {}\n", key, val)?;
518                 }
519                 write!(f, "[Nodes]\n")?;
520                 for (key, val) in self.nodes.iter() {
521                         write!(f, " {}: {}\n", log_pubkey!(key), val)?;
522                 }
523                 Ok(())
524         }
525 }
526
527 impl NetworkGraph {
528         /// Returns all known valid channels' short ids along with announced channel info.
529         ///
530         /// (C-not exported) because we have no mapping for `BTreeMap`s
531         pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
532         /// Returns all known nodes' public keys along with announced node info.
533         ///
534         /// (C-not exported) because we have no mapping for `BTreeMap`s
535         pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
536
537         /// Get network addresses by node id.
538         /// Returns None if the requested node is completely unknown,
539         /// or if node announcement for the node was never received.
540         ///
541         /// (C-not exported) as there is no practical way to track lifetimes of returned values.
542         pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
543                 if let Some(node) = self.nodes.get(pubkey) {
544                         if let Some(node_info) = node.announcement_info.as_ref() {
545                                 return Some(&node_info.addresses)
546                         }
547                 }
548                 None
549         }
550
551         /// Creates a new, empty, network graph.
552         pub fn new() -> NetworkGraph {
553                 Self {
554                         channels: BTreeMap::new(),
555                         nodes: BTreeMap::new(),
556                 }
557         }
558
559         /// For an already known node (from channel announcements), update its stored properties from a given node announcement
560         /// Announcement signatures are checked here only if Secp256k1 object is provided.
561         fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
562                 if let Some(sig_verifier) = secp_ctx {
563                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
564                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
565                 }
566
567                 match self.nodes.get_mut(&msg.contents.node_id) {
568                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
569                         Some(node) => {
570                                 if let Some(node_info) = node.announcement_info.as_ref() {
571                                         if node_info.last_update  >= msg.contents.timestamp {
572                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
573                                         }
574                                 }
575
576                                 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
577                                 node.announcement_info = Some(NodeAnnouncementInfo {
578                                         features: msg.contents.features.clone(),
579                                         last_update: msg.contents.timestamp,
580                                         rgb: msg.contents.rgb,
581                                         alias: msg.contents.alias,
582                                         addresses: msg.contents.addresses.clone(),
583                                         announcement_message: if should_relay { Some(msg.clone()) } else { None },
584                                 });
585
586                                 Ok(should_relay)
587                         }
588                 }
589         }
590
591         /// For a new or already known (from previous announcement) channel, store or update channel info.
592         /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
593         /// Checking utxo on-chain is useful if we receive an update for already known channel id,
594         /// which is probably result of a reorg. In that case, we update channel info only if the
595         /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
596         /// Announcement signatures are checked here only if Secp256k1 object is provided.
597         fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
598                 if let Some(sig_verifier) = secp_ctx {
599                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
600                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
601                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
602                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
603                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
604                 }
605
606                 let should_relay = msg.contents.excess_data.is_empty();
607
608                 let chan_info = ChannelInfo {
609                                 features: msg.contents.features.clone(),
610                                 node_one: msg.contents.node_id_1.clone(),
611                                 one_to_two: None,
612                                 node_two: msg.contents.node_id_2.clone(),
613                                 two_to_one: None,
614                                 capacity_sats: utxo_value,
615                                 announcement_message: if should_relay { Some(msg.clone()) } else { None },
616                         };
617
618                 match self.channels.entry(msg.contents.short_channel_id) {
619                         BtreeEntry::Occupied(mut entry) => {
620                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
621                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
622                                 //exactly how...
623                                 if utxo_value.is_some() {
624                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
625                                         // only sometimes returns results. In any case remove the previous entry. Note
626                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
627                                         // do that because
628                                         // a) we don't *require* a UTXO provider that always returns results.
629                                         // b) we don't track UTXOs of channels we know about and remove them if they
630                                         //    get reorg'd out.
631                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
632                                         Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
633                                         *entry.get_mut() = chan_info;
634                                 } else {
635                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
636                                 }
637                         },
638                         BtreeEntry::Vacant(entry) => {
639                                 entry.insert(chan_info);
640                         }
641                 };
642
643                 macro_rules! add_channel_to_node {
644                         ( $node_id: expr ) => {
645                                 match self.nodes.entry($node_id) {
646                                         BtreeEntry::Occupied(node_entry) => {
647                                                 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
648                                         },
649                                         BtreeEntry::Vacant(node_entry) => {
650                                                 node_entry.insert(NodeInfo {
651                                                         channels: vec!(msg.contents.short_channel_id),
652                                                         lowest_inbound_channel_fees: None,
653                                                         announcement_info: None,
654                                                 });
655                                         }
656                                 }
657                         };
658                 }
659
660                 add_channel_to_node!(msg.contents.node_id_1);
661                 add_channel_to_node!(msg.contents.node_id_2);
662
663                 Ok(should_relay)
664         }
665
666         /// Close a channel if a corresponding HTLC fail was sent.
667         /// If permanent, removes a channel from the local storage.
668         /// May cause the removal of nodes too, if this was their last channel.
669         /// If not permanent, makes channels unavailable for routing.
670         pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
671                 if is_permanent {
672                         if let Some(chan) = self.channels.remove(&short_channel_id) {
673                                 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
674                         }
675                 } else {
676                         if let Some(chan) = self.channels.get_mut(&short_channel_id) {
677                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
678                                         one_to_two.enabled = false;
679                                 }
680                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
681                                         two_to_one.enabled = false;
682                                 }
683                         }
684                 }
685         }
686
687         fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
688                 if is_permanent {
689                         // TODO: Wholly remove the node
690                 } else {
691                         // TODO: downgrade the node
692                 }
693         }
694
695         /// For an already known (from announcement) channel, update info about one of the directions of a channel.
696         /// Announcement signatures are checked here only if Secp256k1 object is provided.
697         fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
698                 let dest_node_id;
699                 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
700                 let chan_was_enabled;
701
702                 match self.channels.get_mut(&msg.contents.short_channel_id) {
703                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
704                         Some(channel) => {
705                                 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
706                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
707                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
708                                         }
709
710                                         if let Some(capacity_sats) = channel.capacity_sats {
711                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
712                                                 // Don't query UTXO set here to reduce DoS risks.
713                                                 if htlc_maximum_msat > capacity_sats * 1000 {
714                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
715                                                 }
716                                         }
717                                 }
718                                 macro_rules! maybe_update_channel_info {
719                                         ( $target: expr, $src_node: expr) => {
720                                                 if let Some(existing_chan_info) = $target.as_ref() {
721                                                         if existing_chan_info.last_update >= msg.contents.timestamp {
722                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
723                                                         }
724                                                         chan_was_enabled = existing_chan_info.enabled;
725                                                 } else {
726                                                         chan_was_enabled = false;
727                                                 }
728
729                                                 let last_update_message = if msg.contents.excess_data.is_empty() {
730                                                         Some(msg.clone())
731                                                 } else {
732                                                         None
733                                                 };
734
735                                                 let updated_channel_dir_info = DirectionalChannelInfo {
736                                                         enabled: chan_enabled,
737                                                         last_update: msg.contents.timestamp,
738                                                         cltv_expiry_delta: msg.contents.cltv_expiry_delta,
739                                                         htlc_minimum_msat: msg.contents.htlc_minimum_msat,
740                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
741                                                         fees: RoutingFees {
742                                                                 base_msat: msg.contents.fee_base_msat,
743                                                                 proportional_millionths: msg.contents.fee_proportional_millionths,
744                                                         },
745                                                         last_update_message
746                                                 };
747                                                 $target = Some(updated_channel_dir_info);
748                                         }
749                                 }
750
751                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
752                                 if msg.contents.flags & 1 == 1 {
753                                         dest_node_id = channel.node_one.clone();
754                                         if let Some(sig_verifier) = secp_ctx {
755                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
756                                         }
757                                         maybe_update_channel_info!(channel.two_to_one, channel.node_two);
758                                 } else {
759                                         dest_node_id = channel.node_two.clone();
760                                         if let Some(sig_verifier) = secp_ctx {
761                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
762                                         }
763                                         maybe_update_channel_info!(channel.one_to_two, channel.node_one);
764                                 }
765                         }
766                 }
767
768                 if chan_enabled {
769                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
770                         let mut base_msat = msg.contents.fee_base_msat;
771                         let mut proportional_millionths = msg.contents.fee_proportional_millionths;
772                         if let Some(fees) = node.lowest_inbound_channel_fees {
773                                 base_msat = cmp::min(base_msat, fees.base_msat);
774                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
775                         }
776                         node.lowest_inbound_channel_fees = Some(RoutingFees {
777                                 base_msat,
778                                 proportional_millionths
779                         });
780                 } else if chan_was_enabled {
781                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
782                         let mut lowest_inbound_channel_fees = None;
783
784                         for chan_id in node.channels.iter() {
785                                 let chan = self.channels.get(chan_id).unwrap();
786                                 let chan_info_opt;
787                                 if chan.node_one == dest_node_id {
788                                         chan_info_opt = chan.two_to_one.as_ref();
789                                 } else {
790                                         chan_info_opt = chan.one_to_two.as_ref();
791                                 }
792                                 if let Some(chan_info) = chan_info_opt {
793                                         if chan_info.enabled {
794                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
795                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
796                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
797                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
798                                         }
799                                 }
800                         }
801
802                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
803                 }
804
805                 Ok(msg.contents.excess_data.is_empty())
806         }
807
808         fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
809                 macro_rules! remove_from_node {
810                         ($node_id: expr) => {
811                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
812                                         entry.get_mut().channels.retain(|chan_id| {
813                                                 short_channel_id != *chan_id
814                                         });
815                                         if entry.get().channels.is_empty() {
816                                                 entry.remove_entry();
817                                         }
818                                 } else {
819                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
820                                 }
821                         }
822                 }
823
824                 remove_from_node!(chan.node_one);
825                 remove_from_node!(chan.node_two);
826         }
827 }
828
829 #[cfg(test)]
830 mod tests {
831         use chain::chaininterface;
832         use ln::features::{ChannelFeatures, NodeFeatures};
833         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
834         use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
835                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
836                 MAX_VALUE_MSAT};
837         use util::test_utils;
838         use util::logger::Logger;
839         use util::ser::{Readable, Writeable};
840
841         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
842         use bitcoin::hashes::Hash;
843         use bitcoin::network::constants::Network;
844         use bitcoin::blockdata::constants::genesis_block;
845         use bitcoin::blockdata::script::Builder;
846         use bitcoin::blockdata::opcodes;
847
848         use hex;
849
850         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
851         use bitcoin::secp256k1::{All, Secp256k1};
852
853         use std::sync::Arc;
854
855         fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
856                 let secp_ctx = Secp256k1::new();
857                 let logger = Arc::new(test_utils::TestLogger::new());
858                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
859                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
860                 (secp_ctx, net_graph_msg_handler)
861         }
862
863         #[test]
864         fn request_full_sync_finite_times() {
865                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
866                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
867
868                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
869                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
870                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
871                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
872                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
873                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
874         }
875
876         #[test]
877         fn handling_node_announcements() {
878                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
879
880                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
881                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
882                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
883                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
884                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
885                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
886                 let zero_hash = Sha256dHash::hash(&[0; 32]);
887                 let first_announcement_time = 500;
888
889                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
890                         features: NodeFeatures::known(),
891                         timestamp: first_announcement_time,
892                         node_id: node_id_1,
893                         rgb: [0; 3],
894                         alias: [0; 32],
895                         addresses: Vec::new(),
896                         excess_address_data: Vec::new(),
897                         excess_data: Vec::new(),
898                 };
899                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
900                 let valid_announcement = NodeAnnouncement {
901                         signature: secp_ctx.sign(&msghash, node_1_privkey),
902                         contents: unsigned_announcement.clone()
903                 };
904
905                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
906                         Ok(_) => panic!(),
907                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
908                 };
909
910                 {
911                         // Announce a channel to add a corresponding node.
912                         let unsigned_announcement = UnsignedChannelAnnouncement {
913                                 features: ChannelFeatures::known(),
914                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
915                                 short_channel_id: 0,
916                                 node_id_1,
917                                 node_id_2,
918                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
919                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
920                                 excess_data: Vec::new(),
921                         };
922
923                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
924                         let valid_announcement = ChannelAnnouncement {
925                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
926                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
927                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
928                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
929                                 contents: unsigned_announcement.clone(),
930                         };
931                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
932                                 Ok(res) => assert!(res),
933                                 _ => panic!()
934                         };
935                 }
936
937                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
938                         Ok(res) => assert!(res),
939                         Err(_) => panic!()
940                 };
941
942                 let fake_msghash = hash_to_message!(&zero_hash);
943                 match net_graph_msg_handler.handle_node_announcement(
944                         &NodeAnnouncement {
945                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
946                                 contents: unsigned_announcement.clone()
947                 }) {
948                         Ok(_) => panic!(),
949                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
950                 };
951
952                 unsigned_announcement.timestamp += 1000;
953                 unsigned_announcement.excess_data.push(1);
954                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
955                 let announcement_with_data = NodeAnnouncement {
956                         signature: secp_ctx.sign(&msghash, node_1_privkey),
957                         contents: unsigned_announcement.clone()
958                 };
959                 // Return false because contains excess data.
960                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
961                         Ok(res) => assert!(!res),
962                         Err(_) => panic!()
963                 };
964                 unsigned_announcement.excess_data = Vec::new();
965
966                 // Even though previous announcement was not relayed further, we still accepted it,
967                 // so we now won't accept announcements before the previous one.
968                 unsigned_announcement.timestamp -= 10;
969                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
970                 let outdated_announcement = NodeAnnouncement {
971                         signature: secp_ctx.sign(&msghash, node_1_privkey),
972                         contents: unsigned_announcement.clone()
973                 };
974                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
975                         Ok(_) => panic!(),
976                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
977                 };
978         }
979
980         #[test]
981         fn handling_channel_announcements() {
982                 let secp_ctx = Secp256k1::new();
983                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
984                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
985                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
986
987
988                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
989                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
990                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
991                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
992                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
993                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
994
995                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
996                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
997                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
998                    .push_opcode(opcodes::all::OP_PUSHNUM_2)
999                    .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1000
1001
1002                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1003                         features: ChannelFeatures::known(),
1004                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1005                         short_channel_id: 0,
1006                         node_id_1,
1007                         node_id_2,
1008                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1009                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1010                         excess_data: Vec::new(),
1011                 };
1012
1013                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1014                 let valid_announcement = ChannelAnnouncement {
1015                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1016                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1017                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1018                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1019                         contents: unsigned_announcement.clone(),
1020                 };
1021
1022                 // Test if the UTXO lookups were not supported
1023                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
1024
1025                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1026                         Ok(res) => assert!(res),
1027                         _ => panic!()
1028                 };
1029
1030                 {
1031                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1032                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1033                                 None => panic!(),
1034                                 Some(_) => ()
1035                         }
1036                 }
1037
1038
1039                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1040                 // drop new one on the floor, since we can't see any changes.
1041                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1042                         Ok(_) => panic!(),
1043                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1044                 };
1045
1046
1047                 // Test if an associated transaction were not on-chain (or not confirmed).
1048                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1049                 unsigned_announcement.short_channel_id += 1;
1050
1051                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1052                 let valid_announcement = ChannelAnnouncement {
1053                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1054                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1055                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1056                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1057                         contents: unsigned_announcement.clone(),
1058                 };
1059
1060                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1061                         Ok(_) => panic!(),
1062                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1063                 };
1064
1065
1066                 // Now test if the transaction is found in the UTXO set and the script is correct.
1067                 unsigned_announcement.short_channel_id += 1;
1068                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1069
1070                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1071                 let valid_announcement = ChannelAnnouncement {
1072                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1073                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1074                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1075                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1076                         contents: unsigned_announcement.clone(),
1077                 };
1078                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1079                         Ok(res) => assert!(res),
1080                         _ => panic!()
1081                 };
1082
1083                 {
1084                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1085                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1086                                 None => panic!(),
1087                                 Some(_) => ()
1088                         }
1089                 }
1090
1091                 // If we receive announcement for the same channel (but TX is not confirmed),
1092                 // drop new one on the floor, since we can't see any changes.
1093                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1094                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1095                         Ok(_) => panic!(),
1096                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1097                 };
1098
1099                 // But if it is confirmed, replace the channel
1100                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1101                 unsigned_announcement.features = ChannelFeatures::empty();
1102                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1103                 let valid_announcement = ChannelAnnouncement {
1104                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1105                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1106                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1107                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1108                         contents: unsigned_announcement.clone(),
1109                 };
1110                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1111                         Ok(res) => assert!(res),
1112                         _ => panic!()
1113                 };
1114                 {
1115                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1116                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1117                                 Some(channel_entry) => {
1118                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1119                                 },
1120                                 _ => panic!()
1121                         }
1122                 }
1123
1124                 // Don't relay valid channels with excess data
1125                 unsigned_announcement.short_channel_id += 1;
1126                 unsigned_announcement.excess_data.push(1);
1127                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1128                 let valid_announcement = ChannelAnnouncement {
1129                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1130                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1131                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1132                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1133                         contents: unsigned_announcement.clone(),
1134                 };
1135                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1136                         Ok(res) => assert!(!res),
1137                         _ => panic!()
1138                 };
1139
1140                 unsigned_announcement.excess_data = Vec::new();
1141                 let invalid_sig_announcement = ChannelAnnouncement {
1142                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1143                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1144                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1145                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1146                         contents: unsigned_announcement.clone(),
1147                 };
1148                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1149                         Ok(_) => panic!(),
1150                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1151                 };
1152
1153                 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1154                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1155                 let channel_to_itself_announcement = ChannelAnnouncement {
1156                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1157                         node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1158                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1159                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1160                         contents: unsigned_announcement.clone(),
1161                 };
1162                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1163                         Ok(_) => panic!(),
1164                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1165                 };
1166         }
1167
1168         #[test]
1169         fn handling_channel_update() {
1170                 let secp_ctx = Secp256k1::new();
1171                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1172                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1173                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1174
1175                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1176                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1177                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1178                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1179                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1180                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1181
1182                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1183                 let short_channel_id = 0;
1184                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1185                 let amount_sats = 1000_000;
1186
1187                 {
1188                         // Announce a channel we will update
1189                         let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1190                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1191                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1192                            .push_opcode(opcodes::all::OP_PUSHNUM_2)
1193                            .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1194                         *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1195                         let unsigned_announcement = UnsignedChannelAnnouncement {
1196                                 features: ChannelFeatures::empty(),
1197                                 chain_hash,
1198                                 short_channel_id,
1199                                 node_id_1,
1200                                 node_id_2,
1201                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1202                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1203                                 excess_data: Vec::new(),
1204                         };
1205
1206                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1207                         let valid_channel_announcement = ChannelAnnouncement {
1208                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1209                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1210                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1211                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1212                                 contents: unsigned_announcement.clone(),
1213                         };
1214                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1215                                 Ok(_) => (),
1216                                 Err(_) => panic!()
1217                         };
1218
1219                 }
1220
1221                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1222                         chain_hash,
1223                         short_channel_id,
1224                         timestamp: 100,
1225                         flags: 0,
1226                         cltv_expiry_delta: 144,
1227                         htlc_minimum_msat: 1000000,
1228                         htlc_maximum_msat: OptionalField::Absent,
1229                         fee_base_msat: 10000,
1230                         fee_proportional_millionths: 20,
1231                         excess_data: Vec::new()
1232                 };
1233                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1234                 let valid_channel_update = ChannelUpdate {
1235                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1236                         contents: unsigned_channel_update.clone()
1237                 };
1238
1239                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1240                         Ok(res) => assert!(res),
1241                         _ => panic!()
1242                 };
1243
1244                 {
1245                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1246                         match network.get_channels().get(&short_channel_id) {
1247                                 None => panic!(),
1248                                 Some(channel_info) => {
1249                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1250                                         assert!(channel_info.two_to_one.is_none());
1251                                 }
1252                         }
1253                 }
1254
1255                 unsigned_channel_update.timestamp += 100;
1256                 unsigned_channel_update.excess_data.push(1);
1257                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1258                 let valid_channel_update = ChannelUpdate {
1259                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1260                         contents: unsigned_channel_update.clone()
1261                 };
1262                 // Return false because contains excess data
1263                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1264                         Ok(res) => assert!(!res),
1265                         _ => panic!()
1266                 };
1267                 unsigned_channel_update.timestamp += 10;
1268
1269                 unsigned_channel_update.short_channel_id += 1;
1270                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1271                 let valid_channel_update = ChannelUpdate {
1272                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1273                         contents: unsigned_channel_update.clone()
1274                 };
1275
1276                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1277                         Ok(_) => panic!(),
1278                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1279                 };
1280                 unsigned_channel_update.short_channel_id = short_channel_id;
1281
1282                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1283                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1284                 let valid_channel_update = ChannelUpdate {
1285                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1286                         contents: unsigned_channel_update.clone()
1287                 };
1288
1289                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1290                         Ok(_) => panic!(),
1291                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1292                 };
1293                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1294
1295                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1296                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1297                 let valid_channel_update = ChannelUpdate {
1298                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1299                         contents: unsigned_channel_update.clone()
1300                 };
1301
1302                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1303                         Ok(_) => panic!(),
1304                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1305                 };
1306                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1307
1308                 // Even though previous update was not relayed further, we still accepted it,
1309                 // so we now won't accept update before the previous one.
1310                 unsigned_channel_update.timestamp -= 10;
1311                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1312                 let valid_channel_update = ChannelUpdate {
1313                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1314                         contents: unsigned_channel_update.clone()
1315                 };
1316
1317                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1318                         Ok(_) => panic!(),
1319                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1320                 };
1321                 unsigned_channel_update.timestamp += 500;
1322
1323                 let fake_msghash = hash_to_message!(&zero_hash);
1324                 let invalid_sig_channel_update = ChannelUpdate {
1325                         signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1326                         contents: unsigned_channel_update.clone()
1327                 };
1328
1329                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1330                         Ok(_) => panic!(),
1331                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1332                 };
1333
1334         }
1335
1336         #[test]
1337         fn handling_htlc_fail_channel_update() {
1338                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1339                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1340                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1341                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1342                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1343                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1344                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1345
1346                 let short_channel_id = 0;
1347                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1348
1349                 {
1350                         // There is no nodes in the table at the beginning.
1351                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1352                         assert_eq!(network.get_nodes().len(), 0);
1353                 }
1354
1355                 {
1356                         // Announce a channel we will update
1357                         let unsigned_announcement = UnsignedChannelAnnouncement {
1358                                 features: ChannelFeatures::empty(),
1359                                 chain_hash,
1360                                 short_channel_id,
1361                                 node_id_1,
1362                                 node_id_2,
1363                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1364                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1365                                 excess_data: Vec::new(),
1366                         };
1367
1368                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1369                         let valid_channel_announcement = ChannelAnnouncement {
1370                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1371                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1372                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1373                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1374                                 contents: unsigned_announcement.clone(),
1375                         };
1376                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1377                                 Ok(_) => (),
1378                                 Err(_) => panic!()
1379                         };
1380
1381                         let unsigned_channel_update = UnsignedChannelUpdate {
1382                                 chain_hash,
1383                                 short_channel_id,
1384                                 timestamp: 100,
1385                                 flags: 0,
1386                                 cltv_expiry_delta: 144,
1387                                 htlc_minimum_msat: 1000000,
1388                                 htlc_maximum_msat: OptionalField::Absent,
1389                                 fee_base_msat: 10000,
1390                                 fee_proportional_millionths: 20,
1391                                 excess_data: Vec::new()
1392                         };
1393                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1394                         let valid_channel_update = ChannelUpdate {
1395                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1396                                 contents: unsigned_channel_update.clone()
1397                         };
1398
1399                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1400                                 Ok(res) => assert!(res),
1401                                 _ => panic!()
1402                         };
1403                 }
1404
1405                 // Non-permanent closing just disables a channel
1406                 {
1407                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1408                         match network.get_channels().get(&short_channel_id) {
1409                                 None => panic!(),
1410                                 Some(channel_info) => {
1411                                         assert!(channel_info.one_to_two.is_some());
1412                                 }
1413                         }
1414                 }
1415
1416                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1417                         short_channel_id,
1418                         is_permanent: false
1419                 };
1420
1421                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1422
1423                 // Non-permanent closing just disables a channel
1424                 {
1425                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1426                         match network.get_channels().get(&short_channel_id) {
1427                                 None => panic!(),
1428                                 Some(channel_info) => {
1429                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1430                                 }
1431                         }
1432                 }
1433
1434                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1435                         short_channel_id,
1436                         is_permanent: true
1437                 };
1438
1439                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1440
1441                 // Permanent closing deletes a channel
1442                 {
1443                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1444                         assert_eq!(network.get_channels().len(), 0);
1445                         // Nodes are also deleted because there are no associated channels anymore
1446                         assert_eq!(network.get_nodes().len(), 0);
1447                 }
1448                 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1449         }
1450
1451         #[test]
1452         fn getting_next_channel_announcements() {
1453                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1454                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1455                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1456                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1457                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1458                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1459                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1460
1461                 let short_channel_id = 1;
1462                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1463
1464                 // Channels were not announced yet.
1465                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1466                 assert_eq!(channels_with_announcements.len(), 0);
1467
1468                 {
1469                         // Announce a channel we will update
1470                         let unsigned_announcement = UnsignedChannelAnnouncement {
1471                                 features: ChannelFeatures::empty(),
1472                                 chain_hash,
1473                                 short_channel_id,
1474                                 node_id_1,
1475                                 node_id_2,
1476                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1477                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1478                                 excess_data: Vec::new(),
1479                         };
1480
1481                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1482                         let valid_channel_announcement = ChannelAnnouncement {
1483                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1484                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1485                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1486                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1487                                 contents: unsigned_announcement.clone(),
1488                         };
1489                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1490                                 Ok(_) => (),
1491                                 Err(_) => panic!()
1492                         };
1493                 }
1494
1495                 // Contains initial channel announcement now.
1496                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1497                 assert_eq!(channels_with_announcements.len(), 1);
1498                 if let Some(channel_announcements) = channels_with_announcements.first() {
1499                         let &(_, ref update_1, ref update_2) = channel_announcements;
1500                         assert_eq!(update_1, &None);
1501                         assert_eq!(update_2, &None);
1502                 } else {
1503                         panic!();
1504                 }
1505
1506
1507                 {
1508                         // Valid channel update
1509                         let unsigned_channel_update = UnsignedChannelUpdate {
1510                                 chain_hash,
1511                                 short_channel_id,
1512                                 timestamp: 101,
1513                                 flags: 0,
1514                                 cltv_expiry_delta: 144,
1515                                 htlc_minimum_msat: 1000000,
1516                                 htlc_maximum_msat: OptionalField::Absent,
1517                                 fee_base_msat: 10000,
1518                                 fee_proportional_millionths: 20,
1519                                 excess_data: Vec::new()
1520                         };
1521                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1522                         let valid_channel_update = ChannelUpdate {
1523                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1524                                 contents: unsigned_channel_update.clone()
1525                         };
1526                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1527                                 Ok(_) => (),
1528                                 Err(_) => panic!()
1529                         };
1530                 }
1531
1532                 // Now contains an initial announcement and an update.
1533                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1534                 assert_eq!(channels_with_announcements.len(), 1);
1535                 if let Some(channel_announcements) = channels_with_announcements.first() {
1536                         let &(_, ref update_1, ref update_2) = channel_announcements;
1537                         assert_ne!(update_1, &None);
1538                         assert_eq!(update_2, &None);
1539                 } else {
1540                         panic!();
1541                 }
1542
1543
1544                 {
1545                         // Channel update with excess data.
1546                         let unsigned_channel_update = UnsignedChannelUpdate {
1547                                 chain_hash,
1548                                 short_channel_id,
1549                                 timestamp: 102,
1550                                 flags: 0,
1551                                 cltv_expiry_delta: 144,
1552                                 htlc_minimum_msat: 1000000,
1553                                 htlc_maximum_msat: OptionalField::Absent,
1554                                 fee_base_msat: 10000,
1555                                 fee_proportional_millionths: 20,
1556                                 excess_data: [1; 3].to_vec()
1557                         };
1558                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1559                         let valid_channel_update = ChannelUpdate {
1560                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1561                                 contents: unsigned_channel_update.clone()
1562                         };
1563                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1564                                 Ok(_) => (),
1565                                 Err(_) => panic!()
1566                         };
1567                 }
1568
1569                 // Test that announcements with excess data won't be returned
1570                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1571                 assert_eq!(channels_with_announcements.len(), 1);
1572                 if let Some(channel_announcements) = channels_with_announcements.first() {
1573                         let &(_, ref update_1, ref update_2) = channel_announcements;
1574                         assert_eq!(update_1, &None);
1575                         assert_eq!(update_2, &None);
1576                 } else {
1577                         panic!();
1578                 }
1579
1580                 // Further starting point have no channels after it
1581                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1582                 assert_eq!(channels_with_announcements.len(), 0);
1583         }
1584
1585         #[test]
1586         fn getting_next_node_announcements() {
1587                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1588                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1589                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1590                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1591                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1592                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1593                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1594
1595                 let short_channel_id = 1;
1596                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1597
1598                 // No nodes yet.
1599                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1600                 assert_eq!(next_announcements.len(), 0);
1601
1602                 {
1603                         // Announce a channel to add 2 nodes
1604                         let unsigned_announcement = UnsignedChannelAnnouncement {
1605                                 features: ChannelFeatures::empty(),
1606                                 chain_hash,
1607                                 short_channel_id,
1608                                 node_id_1,
1609                                 node_id_2,
1610                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1611                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1612                                 excess_data: Vec::new(),
1613                         };
1614
1615                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1616                         let valid_channel_announcement = ChannelAnnouncement {
1617                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1618                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1619                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1620                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1621                                 contents: unsigned_announcement.clone(),
1622                         };
1623                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1624                                 Ok(_) => (),
1625                                 Err(_) => panic!()
1626                         };
1627                 }
1628
1629
1630                 // Nodes were never announced
1631                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1632                 assert_eq!(next_announcements.len(), 0);
1633
1634                 {
1635                         let mut unsigned_announcement = UnsignedNodeAnnouncement {
1636                                 features: NodeFeatures::known(),
1637                                 timestamp: 1000,
1638                                 node_id: node_id_1,
1639                                 rgb: [0; 3],
1640                                 alias: [0; 32],
1641                                 addresses: Vec::new(),
1642                                 excess_address_data: Vec::new(),
1643                                 excess_data: Vec::new(),
1644                         };
1645                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1646                         let valid_announcement = NodeAnnouncement {
1647                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1648                                 contents: unsigned_announcement.clone()
1649                         };
1650                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1651                                 Ok(_) => (),
1652                                 Err(_) => panic!()
1653                         };
1654
1655                         unsigned_announcement.node_id = node_id_2;
1656                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1657                         let valid_announcement = NodeAnnouncement {
1658                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1659                                 contents: unsigned_announcement.clone()
1660                         };
1661
1662                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1663                                 Ok(_) => (),
1664                                 Err(_) => panic!()
1665                         };
1666                 }
1667
1668                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1669                 assert_eq!(next_announcements.len(), 2);
1670
1671                 // Skip the first node.
1672                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1673                 assert_eq!(next_announcements.len(), 1);
1674
1675                 {
1676                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1677                         let unsigned_announcement = UnsignedNodeAnnouncement {
1678                                 features: NodeFeatures::known(),
1679                                 timestamp: 1010,
1680                                 node_id: node_id_2,
1681                                 rgb: [0; 3],
1682                                 alias: [0; 32],
1683                                 addresses: Vec::new(),
1684                                 excess_address_data: Vec::new(),
1685                                 excess_data: [1; 3].to_vec(),
1686                         };
1687                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1688                         let valid_announcement = NodeAnnouncement {
1689                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1690                                 contents: unsigned_announcement.clone()
1691                         };
1692                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1693                                 Ok(res) => assert!(!res),
1694                                 Err(_) => panic!()
1695                         };
1696                 }
1697
1698                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1699                 assert_eq!(next_announcements.len(), 0);
1700         }
1701
1702         #[test]
1703         fn network_graph_serialization() {
1704                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1705
1706                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1707                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1708                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1709                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1710
1711                 // Announce a channel to add a corresponding node.
1712                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1713                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1714                 let unsigned_announcement = UnsignedChannelAnnouncement {
1715                         features: ChannelFeatures::known(),
1716                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1717                         short_channel_id: 0,
1718                         node_id_1,
1719                         node_id_2,
1720                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1721                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1722                         excess_data: Vec::new(),
1723                 };
1724
1725                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1726                 let valid_announcement = ChannelAnnouncement {
1727                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1728                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1729                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1730                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1731                         contents: unsigned_announcement.clone(),
1732                 };
1733                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1734                         Ok(res) => assert!(res),
1735                         _ => panic!()
1736                 };
1737
1738
1739                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1740                 let unsigned_announcement = UnsignedNodeAnnouncement {
1741                         features: NodeFeatures::known(),
1742                         timestamp: 100,
1743                         node_id,
1744                         rgb: [0; 3],
1745                         alias: [0; 32],
1746                         addresses: Vec::new(),
1747                         excess_address_data: Vec::new(),
1748                         excess_data: Vec::new(),
1749                 };
1750                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1751                 let valid_announcement = NodeAnnouncement {
1752                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1753                         contents: unsigned_announcement.clone()
1754                 };
1755
1756                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1757                         Ok(_) => (),
1758                         Err(_) => panic!()
1759                 };
1760
1761                 let network = net_graph_msg_handler.network_graph.write().unwrap();
1762                 let mut w = test_utils::TestVecWriter(Vec::new());
1763                 assert!(!network.get_nodes().is_empty());
1764                 assert!(!network.get_channels().is_empty());
1765                 network.write(&mut w).unwrap();
1766                 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1767         }
1768 }