c46781d11b5888b8e0f55114a525db4ea0908a75
[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<msgs::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<msgs::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<msgs::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         pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
530         /// Returns all known nodes' public keys along with announced node info.
531         pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
532
533         /// Get network addresses by node id.
534         /// Returns None if the requested node is completely unknown,
535         /// or if node announcement for the node was never received.
536         pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
537                 if let Some(node) = self.nodes.get(pubkey) {
538                         if let Some(node_info) = node.announcement_info.as_ref() {
539                                 return Some(&node_info.addresses)
540                         }
541                 }
542                 None
543         }
544
545         /// Creates a new, empty, network graph.
546         pub fn new() -> NetworkGraph {
547                 Self {
548                         channels: BTreeMap::new(),
549                         nodes: BTreeMap::new(),
550                 }
551         }
552
553         /// For an already known node (from channel announcements), update its stored properties from a given node announcement
554         /// Announcement signatures are checked here only if Secp256k1 object is provided.
555         fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
556                 if let Some(sig_verifier) = secp_ctx {
557                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
558                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
559                 }
560
561                 match self.nodes.get_mut(&msg.contents.node_id) {
562                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
563                         Some(node) => {
564                                 if let Some(node_info) = node.announcement_info.as_ref() {
565                                         if node_info.last_update  >= msg.contents.timestamp {
566                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
567                                         }
568                                 }
569
570                                 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
571                                 node.announcement_info = Some(NodeAnnouncementInfo {
572                                         features: msg.contents.features.clone(),
573                                         last_update: msg.contents.timestamp,
574                                         rgb: msg.contents.rgb,
575                                         alias: msg.contents.alias,
576                                         addresses: msg.contents.addresses.clone(),
577                                         announcement_message: if should_relay { Some(msg.clone()) } else { None },
578                                 });
579
580                                 Ok(should_relay)
581                         }
582                 }
583         }
584
585         /// For a new or already known (from previous announcement) channel, store or update channel info.
586         /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
587         /// Checking utxo on-chain is useful if we receive an update for already known channel id,
588         /// which is probably result of a reorg. In that case, we update channel info only if the
589         /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
590         /// Announcement signatures are checked here only if Secp256k1 object is provided.
591         fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
592                 if let Some(sig_verifier) = secp_ctx {
593                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
594                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
595                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
596                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
597                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
598                 }
599
600                 let should_relay = msg.contents.excess_data.is_empty();
601
602                 let chan_info = ChannelInfo {
603                                 features: msg.contents.features.clone(),
604                                 node_one: msg.contents.node_id_1.clone(),
605                                 one_to_two: None,
606                                 node_two: msg.contents.node_id_2.clone(),
607                                 two_to_one: None,
608                                 capacity_sats: utxo_value,
609                                 announcement_message: if should_relay { Some(msg.clone()) } else { None },
610                         };
611
612                 match self.channels.entry(msg.contents.short_channel_id) {
613                         BtreeEntry::Occupied(mut entry) => {
614                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
615                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
616                                 //exactly how...
617                                 if utxo_value.is_some() {
618                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
619                                         // only sometimes returns results. In any case remove the previous entry. Note
620                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
621                                         // do that because
622                                         // a) we don't *require* a UTXO provider that always returns results.
623                                         // b) we don't track UTXOs of channels we know about and remove them if they
624                                         //    get reorg'd out.
625                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
626                                         Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
627                                         *entry.get_mut() = chan_info;
628                                 } else {
629                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
630                                 }
631                         },
632                         BtreeEntry::Vacant(entry) => {
633                                 entry.insert(chan_info);
634                         }
635                 };
636
637                 macro_rules! add_channel_to_node {
638                         ( $node_id: expr ) => {
639                                 match self.nodes.entry($node_id) {
640                                         BtreeEntry::Occupied(node_entry) => {
641                                                 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
642                                         },
643                                         BtreeEntry::Vacant(node_entry) => {
644                                                 node_entry.insert(NodeInfo {
645                                                         channels: vec!(msg.contents.short_channel_id),
646                                                         lowest_inbound_channel_fees: None,
647                                                         announcement_info: None,
648                                                 });
649                                         }
650                                 }
651                         };
652                 }
653
654                 add_channel_to_node!(msg.contents.node_id_1);
655                 add_channel_to_node!(msg.contents.node_id_2);
656
657                 Ok(should_relay)
658         }
659
660         /// Close a channel if a corresponding HTLC fail was sent.
661         /// If permanent, removes a channel from the local storage.
662         /// May cause the removal of nodes too, if this was their last channel.
663         /// If not permanent, makes channels unavailable for routing.
664         pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
665                 if is_permanent {
666                         if let Some(chan) = self.channels.remove(&short_channel_id) {
667                                 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
668                         }
669                 } else {
670                         if let Some(chan) = self.channels.get_mut(&short_channel_id) {
671                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
672                                         one_to_two.enabled = false;
673                                 }
674                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
675                                         two_to_one.enabled = false;
676                                 }
677                         }
678                 }
679         }
680
681         fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
682                 if is_permanent {
683                         // TODO: Wholly remove the node
684                 } else {
685                         // TODO: downgrade the node
686                 }
687         }
688
689         /// For an already known (from announcement) channel, update info about one of the directions of a channel.
690         /// Announcement signatures are checked here only if Secp256k1 object is provided.
691         fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
692                 let dest_node_id;
693                 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
694                 let chan_was_enabled;
695
696                 match self.channels.get_mut(&msg.contents.short_channel_id) {
697                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
698                         Some(channel) => {
699                                 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
700                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
701                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
702                                         }
703
704                                         if let Some(capacity_sats) = channel.capacity_sats {
705                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
706                                                 // Don't query UTXO set here to reduce DoS risks.
707                                                 if htlc_maximum_msat > capacity_sats * 1000 {
708                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
709                                                 }
710                                         }
711                                 }
712                                 macro_rules! maybe_update_channel_info {
713                                         ( $target: expr, $src_node: expr) => {
714                                                 if let Some(existing_chan_info) = $target.as_ref() {
715                                                         if existing_chan_info.last_update >= msg.contents.timestamp {
716                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
717                                                         }
718                                                         chan_was_enabled = existing_chan_info.enabled;
719                                                 } else {
720                                                         chan_was_enabled = false;
721                                                 }
722
723                                                 let last_update_message = if msg.contents.excess_data.is_empty() {
724                                                         Some(msg.clone())
725                                                 } else {
726                                                         None
727                                                 };
728
729                                                 let updated_channel_dir_info = DirectionalChannelInfo {
730                                                         enabled: chan_enabled,
731                                                         last_update: msg.contents.timestamp,
732                                                         cltv_expiry_delta: msg.contents.cltv_expiry_delta,
733                                                         htlc_minimum_msat: msg.contents.htlc_minimum_msat,
734                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
735                                                         fees: RoutingFees {
736                                                                 base_msat: msg.contents.fee_base_msat,
737                                                                 proportional_millionths: msg.contents.fee_proportional_millionths,
738                                                         },
739                                                         last_update_message
740                                                 };
741                                                 $target = Some(updated_channel_dir_info);
742                                         }
743                                 }
744
745                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
746                                 if msg.contents.flags & 1 == 1 {
747                                         dest_node_id = channel.node_one.clone();
748                                         if let Some(sig_verifier) = secp_ctx {
749                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
750                                         }
751                                         maybe_update_channel_info!(channel.two_to_one, channel.node_two);
752                                 } else {
753                                         dest_node_id = channel.node_two.clone();
754                                         if let Some(sig_verifier) = secp_ctx {
755                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
756                                         }
757                                         maybe_update_channel_info!(channel.one_to_two, channel.node_one);
758                                 }
759                         }
760                 }
761
762                 if chan_enabled {
763                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
764                         let mut base_msat = msg.contents.fee_base_msat;
765                         let mut proportional_millionths = msg.contents.fee_proportional_millionths;
766                         if let Some(fees) = node.lowest_inbound_channel_fees {
767                                 base_msat = cmp::min(base_msat, fees.base_msat);
768                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
769                         }
770                         node.lowest_inbound_channel_fees = Some(RoutingFees {
771                                 base_msat,
772                                 proportional_millionths
773                         });
774                 } else if chan_was_enabled {
775                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
776                         let mut lowest_inbound_channel_fees = None;
777
778                         for chan_id in node.channels.iter() {
779                                 let chan = self.channels.get(chan_id).unwrap();
780                                 let chan_info_opt;
781                                 if chan.node_one == dest_node_id {
782                                         chan_info_opt = chan.two_to_one.as_ref();
783                                 } else {
784                                         chan_info_opt = chan.one_to_two.as_ref();
785                                 }
786                                 if let Some(chan_info) = chan_info_opt {
787                                         if chan_info.enabled {
788                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
789                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
790                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
791                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
792                                         }
793                                 }
794                         }
795
796                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
797                 }
798
799                 Ok(msg.contents.excess_data.is_empty())
800         }
801
802         fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
803                 macro_rules! remove_from_node {
804                         ($node_id: expr) => {
805                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
806                                         entry.get_mut().channels.retain(|chan_id| {
807                                                 short_channel_id != *chan_id
808                                         });
809                                         if entry.get().channels.is_empty() {
810                                                 entry.remove_entry();
811                                         }
812                                 } else {
813                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
814                                 }
815                         }
816                 }
817
818                 remove_from_node!(chan.node_one);
819                 remove_from_node!(chan.node_two);
820         }
821 }
822
823 #[cfg(test)]
824 mod tests {
825         use chain::chaininterface;
826         use ln::features::{ChannelFeatures, NodeFeatures};
827         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
828         use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
829                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
830                 MAX_VALUE_MSAT};
831         use util::test_utils;
832         use util::logger::Logger;
833         use util::ser::{Readable, Writeable};
834
835         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
836         use bitcoin::hashes::Hash;
837         use bitcoin::network::constants::Network;
838         use bitcoin::blockdata::constants::genesis_block;
839         use bitcoin::blockdata::script::Builder;
840         use bitcoin::blockdata::opcodes;
841         use bitcoin::util::hash::BitcoinHash;
842
843         use hex;
844
845         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
846         use bitcoin::secp256k1::{All, Secp256k1};
847
848         use std::sync::Arc;
849
850         fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
851                 let secp_ctx = Secp256k1::new();
852                 let logger = Arc::new(test_utils::TestLogger::new());
853                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
854                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
855                 (secp_ctx, net_graph_msg_handler)
856         }
857
858         #[test]
859         fn request_full_sync_finite_times() {
860                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
861                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
862
863                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
864                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
865                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
866                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
867                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
868                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
869         }
870
871         #[test]
872         fn handling_node_announcements() {
873                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
874
875                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
876                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
877                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
878                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
879                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
880                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
881                 let zero_hash = Sha256dHash::hash(&[0; 32]);
882                 let first_announcement_time = 500;
883
884                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
885                         features: NodeFeatures::known(),
886                         timestamp: first_announcement_time,
887                         node_id: node_id_1,
888                         rgb: [0; 3],
889                         alias: [0; 32],
890                         addresses: Vec::new(),
891                         excess_address_data: Vec::new(),
892                         excess_data: Vec::new(),
893                 };
894                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
895                 let valid_announcement = NodeAnnouncement {
896                         signature: secp_ctx.sign(&msghash, node_1_privkey),
897                         contents: unsigned_announcement.clone()
898                 };
899
900                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
901                         Ok(_) => panic!(),
902                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
903                 };
904
905                 {
906                         // Announce a channel to add a corresponding node.
907                         let unsigned_announcement = UnsignedChannelAnnouncement {
908                                 features: ChannelFeatures::known(),
909                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
910                                 short_channel_id: 0,
911                                 node_id_1,
912                                 node_id_2,
913                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
914                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
915                                 excess_data: Vec::new(),
916                         };
917
918                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
919                         let valid_announcement = ChannelAnnouncement {
920                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
921                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
922                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
923                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
924                                 contents: unsigned_announcement.clone(),
925                         };
926                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
927                                 Ok(res) => assert!(res),
928                                 _ => panic!()
929                         };
930                 }
931
932                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
933                         Ok(res) => assert!(res),
934                         Err(_) => panic!()
935                 };
936
937                 let fake_msghash = hash_to_message!(&zero_hash);
938                 match net_graph_msg_handler.handle_node_announcement(
939                         &NodeAnnouncement {
940                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
941                                 contents: unsigned_announcement.clone()
942                 }) {
943                         Ok(_) => panic!(),
944                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
945                 };
946
947                 unsigned_announcement.timestamp += 1000;
948                 unsigned_announcement.excess_data.push(1);
949                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
950                 let announcement_with_data = NodeAnnouncement {
951                         signature: secp_ctx.sign(&msghash, node_1_privkey),
952                         contents: unsigned_announcement.clone()
953                 };
954                 // Return false because contains excess data.
955                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
956                         Ok(res) => assert!(!res),
957                         Err(_) => panic!()
958                 };
959                 unsigned_announcement.excess_data = Vec::new();
960
961                 // Even though previous announcement was not relayed further, we still accepted it,
962                 // so we now won't accept announcements before the previous one.
963                 unsigned_announcement.timestamp -= 10;
964                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
965                 let outdated_announcement = NodeAnnouncement {
966                         signature: secp_ctx.sign(&msghash, node_1_privkey),
967                         contents: unsigned_announcement.clone()
968                 };
969                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
970                         Ok(_) => panic!(),
971                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
972                 };
973         }
974
975         #[test]
976         fn handling_channel_announcements() {
977                 let secp_ctx = Secp256k1::new();
978                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
979                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
980                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
981
982
983                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
984                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
985                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
986                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
987                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
988                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
989
990                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
991                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
992                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
993                    .push_opcode(opcodes::all::OP_PUSHNUM_2)
994                    .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
995
996
997                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
998                         features: ChannelFeatures::known(),
999                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1000                         short_channel_id: 0,
1001                         node_id_1,
1002                         node_id_2,
1003                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1004                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1005                         excess_data: Vec::new(),
1006                 };
1007
1008                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1009                 let valid_announcement = ChannelAnnouncement {
1010                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1011                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1012                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1013                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1014                         contents: unsigned_announcement.clone(),
1015                 };
1016
1017                 // Test if the UTXO lookups were not supported
1018                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
1019
1020                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1021                         Ok(res) => assert!(res),
1022                         _ => panic!()
1023                 };
1024
1025                 {
1026                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1027                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1028                                 None => panic!(),
1029                                 Some(_) => ()
1030                         }
1031                 }
1032
1033
1034                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1035                 // drop new one on the floor, since we can't see any changes.
1036                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1037                         Ok(_) => panic!(),
1038                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1039                 };
1040
1041
1042                 // Test if an associated transaction were not on-chain (or not confirmed).
1043                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1044                 unsigned_announcement.short_channel_id += 1;
1045
1046                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1047                 let valid_announcement = ChannelAnnouncement {
1048                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1049                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1050                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1051                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1052                         contents: unsigned_announcement.clone(),
1053                 };
1054
1055                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1056                         Ok(_) => panic!(),
1057                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1058                 };
1059
1060
1061                 // Now test if the transaction is found in the UTXO set and the script is correct.
1062                 unsigned_announcement.short_channel_id += 1;
1063                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1064
1065                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1066                 let valid_announcement = ChannelAnnouncement {
1067                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1068                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1069                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1070                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1071                         contents: unsigned_announcement.clone(),
1072                 };
1073                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1074                         Ok(res) => assert!(res),
1075                         _ => panic!()
1076                 };
1077
1078                 {
1079                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1080                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1081                                 None => panic!(),
1082                                 Some(_) => ()
1083                         }
1084                 }
1085
1086                 // If we receive announcement for the same channel (but TX is not confirmed),
1087                 // drop new one on the floor, since we can't see any changes.
1088                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1089                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1090                         Ok(_) => panic!(),
1091                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1092                 };
1093
1094                 // But if it is confirmed, replace the channel
1095                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1096                 unsigned_announcement.features = ChannelFeatures::empty();
1097                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1098                 let valid_announcement = ChannelAnnouncement {
1099                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1100                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1101                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1102                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1103                         contents: unsigned_announcement.clone(),
1104                 };
1105                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1106                         Ok(res) => assert!(res),
1107                         _ => panic!()
1108                 };
1109                 {
1110                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1111                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1112                                 Some(channel_entry) => {
1113                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1114                                 },
1115                                 _ => panic!()
1116                         }
1117                 }
1118
1119                 // Don't relay valid channels with excess data
1120                 unsigned_announcement.short_channel_id += 1;
1121                 unsigned_announcement.excess_data.push(1);
1122                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1123                 let valid_announcement = ChannelAnnouncement {
1124                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1125                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1126                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1127                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1128                         contents: unsigned_announcement.clone(),
1129                 };
1130                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1131                         Ok(res) => assert!(!res),
1132                         _ => panic!()
1133                 };
1134
1135                 unsigned_announcement.excess_data = Vec::new();
1136                 let invalid_sig_announcement = ChannelAnnouncement {
1137                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1138                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1139                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1140                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1141                         contents: unsigned_announcement.clone(),
1142                 };
1143                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1144                         Ok(_) => panic!(),
1145                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1146                 };
1147
1148                 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1149                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1150                 let channel_to_itself_announcement = ChannelAnnouncement {
1151                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1152                         node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1153                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1154                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1155                         contents: unsigned_announcement.clone(),
1156                 };
1157                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1158                         Ok(_) => panic!(),
1159                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1160                 };
1161         }
1162
1163         #[test]
1164         fn handling_channel_update() {
1165                 let secp_ctx = Secp256k1::new();
1166                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1167                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1168                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1169
1170                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1171                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1172                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1173                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1174                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1175                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1176
1177                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1178                 let short_channel_id = 0;
1179                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1180                 let amount_sats = 1000_000;
1181
1182                 {
1183                         // Announce a channel we will update
1184                         let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1185                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1186                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1187                            .push_opcode(opcodes::all::OP_PUSHNUM_2)
1188                            .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1189                         *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1190                         let unsigned_announcement = UnsignedChannelAnnouncement {
1191                                 features: ChannelFeatures::empty(),
1192                                 chain_hash,
1193                                 short_channel_id,
1194                                 node_id_1,
1195                                 node_id_2,
1196                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1197                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1198                                 excess_data: Vec::new(),
1199                         };
1200
1201                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1202                         let valid_channel_announcement = ChannelAnnouncement {
1203                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1204                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1205                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1206                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1207                                 contents: unsigned_announcement.clone(),
1208                         };
1209                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1210                                 Ok(_) => (),
1211                                 Err(_) => panic!()
1212                         };
1213
1214                 }
1215
1216                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1217                         chain_hash,
1218                         short_channel_id,
1219                         timestamp: 100,
1220                         flags: 0,
1221                         cltv_expiry_delta: 144,
1222                         htlc_minimum_msat: 1000000,
1223                         htlc_maximum_msat: OptionalField::Absent,
1224                         fee_base_msat: 10000,
1225                         fee_proportional_millionths: 20,
1226                         excess_data: Vec::new()
1227                 };
1228                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1229                 let valid_channel_update = ChannelUpdate {
1230                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1231                         contents: unsigned_channel_update.clone()
1232                 };
1233
1234                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1235                         Ok(res) => assert!(res),
1236                         _ => panic!()
1237                 };
1238
1239                 {
1240                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1241                         match network.get_channels().get(&short_channel_id) {
1242                                 None => panic!(),
1243                                 Some(channel_info) => {
1244                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1245                                         assert!(channel_info.two_to_one.is_none());
1246                                 }
1247                         }
1248                 }
1249
1250                 unsigned_channel_update.timestamp += 100;
1251                 unsigned_channel_update.excess_data.push(1);
1252                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1253                 let valid_channel_update = ChannelUpdate {
1254                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1255                         contents: unsigned_channel_update.clone()
1256                 };
1257                 // Return false because contains excess data
1258                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1259                         Ok(res) => assert!(!res),
1260                         _ => panic!()
1261                 };
1262                 unsigned_channel_update.timestamp += 10;
1263
1264                 unsigned_channel_update.short_channel_id += 1;
1265                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1266                 let valid_channel_update = ChannelUpdate {
1267                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1268                         contents: unsigned_channel_update.clone()
1269                 };
1270
1271                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1272                         Ok(_) => panic!(),
1273                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1274                 };
1275                 unsigned_channel_update.short_channel_id = short_channel_id;
1276
1277                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1278                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1279                 let valid_channel_update = ChannelUpdate {
1280                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1281                         contents: unsigned_channel_update.clone()
1282                 };
1283
1284                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1285                         Ok(_) => panic!(),
1286                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1287                 };
1288                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1289
1290                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1291                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1292                 let valid_channel_update = ChannelUpdate {
1293                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1294                         contents: unsigned_channel_update.clone()
1295                 };
1296
1297                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1298                         Ok(_) => panic!(),
1299                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1300                 };
1301                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1302
1303                 // Even though previous update was not relayed further, we still accepted it,
1304                 // so we now won't accept update before the previous one.
1305                 unsigned_channel_update.timestamp -= 10;
1306                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1307                 let valid_channel_update = ChannelUpdate {
1308                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1309                         contents: unsigned_channel_update.clone()
1310                 };
1311
1312                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1313                         Ok(_) => panic!(),
1314                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1315                 };
1316                 unsigned_channel_update.timestamp += 500;
1317
1318                 let fake_msghash = hash_to_message!(&zero_hash);
1319                 let invalid_sig_channel_update = ChannelUpdate {
1320                         signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1321                         contents: unsigned_channel_update.clone()
1322                 };
1323
1324                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1325                         Ok(_) => panic!(),
1326                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1327                 };
1328
1329         }
1330
1331         #[test]
1332         fn handling_htlc_fail_channel_update() {
1333                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1334                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1335                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1336                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1337                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1338                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1339                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1340
1341                 let short_channel_id = 0;
1342                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1343
1344                 {
1345                         // There is no nodes in the table at the beginning.
1346                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1347                         assert_eq!(network.get_nodes().len(), 0);
1348                 }
1349
1350                 {
1351                         // Announce a channel we will update
1352                         let unsigned_announcement = UnsignedChannelAnnouncement {
1353                                 features: ChannelFeatures::empty(),
1354                                 chain_hash,
1355                                 short_channel_id,
1356                                 node_id_1,
1357                                 node_id_2,
1358                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1359                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1360                                 excess_data: Vec::new(),
1361                         };
1362
1363                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1364                         let valid_channel_announcement = ChannelAnnouncement {
1365                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1366                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1367                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1368                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1369                                 contents: unsigned_announcement.clone(),
1370                         };
1371                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1372                                 Ok(_) => (),
1373                                 Err(_) => panic!()
1374                         };
1375
1376                         let unsigned_channel_update = UnsignedChannelUpdate {
1377                                 chain_hash,
1378                                 short_channel_id,
1379                                 timestamp: 100,
1380                                 flags: 0,
1381                                 cltv_expiry_delta: 144,
1382                                 htlc_minimum_msat: 1000000,
1383                                 htlc_maximum_msat: OptionalField::Absent,
1384                                 fee_base_msat: 10000,
1385                                 fee_proportional_millionths: 20,
1386                                 excess_data: Vec::new()
1387                         };
1388                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1389                         let valid_channel_update = ChannelUpdate {
1390                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1391                                 contents: unsigned_channel_update.clone()
1392                         };
1393
1394                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1395                                 Ok(res) => assert!(res),
1396                                 _ => panic!()
1397                         };
1398                 }
1399
1400                 // Non-permanent closing just disables a channel
1401                 {
1402                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1403                         match network.get_channels().get(&short_channel_id) {
1404                                 None => panic!(),
1405                                 Some(channel_info) => {
1406                                         assert!(channel_info.one_to_two.is_some());
1407                                 }
1408                         }
1409                 }
1410
1411                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1412                         short_channel_id,
1413                         is_permanent: false
1414                 };
1415
1416                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1417
1418                 // Non-permanent closing just disables a channel
1419                 {
1420                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1421                         match network.get_channels().get(&short_channel_id) {
1422                                 None => panic!(),
1423                                 Some(channel_info) => {
1424                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1425                                 }
1426                         }
1427                 }
1428
1429                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1430                         short_channel_id,
1431                         is_permanent: true
1432                 };
1433
1434                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1435
1436                 // Permanent closing deletes a channel
1437                 {
1438                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1439                         assert_eq!(network.get_channels().len(), 0);
1440                         // Nodes are also deleted because there are no associated channels anymore
1441                         assert_eq!(network.get_nodes().len(), 0);
1442                 }
1443                 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1444         }
1445
1446         #[test]
1447         fn getting_next_channel_announcements() {
1448                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1449                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1450                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1451                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1452                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1453                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1454                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1455
1456                 let short_channel_id = 1;
1457                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1458
1459                 // Channels were not announced yet.
1460                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1461                 assert_eq!(channels_with_announcements.len(), 0);
1462
1463                 {
1464                         // Announce a channel we will update
1465                         let unsigned_announcement = UnsignedChannelAnnouncement {
1466                                 features: ChannelFeatures::empty(),
1467                                 chain_hash,
1468                                 short_channel_id,
1469                                 node_id_1,
1470                                 node_id_2,
1471                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1472                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1473                                 excess_data: Vec::new(),
1474                         };
1475
1476                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1477                         let valid_channel_announcement = ChannelAnnouncement {
1478                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1479                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1480                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1481                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1482                                 contents: unsigned_announcement.clone(),
1483                         };
1484                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1485                                 Ok(_) => (),
1486                                 Err(_) => panic!()
1487                         };
1488                 }
1489
1490                 // Contains initial channel announcement now.
1491                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1492                 assert_eq!(channels_with_announcements.len(), 1);
1493                 if let Some(channel_announcements) = channels_with_announcements.first() {
1494                         let &(_, ref update_1, ref update_2) = channel_announcements;
1495                         assert_eq!(update_1, &None);
1496                         assert_eq!(update_2, &None);
1497                 } else {
1498                         panic!();
1499                 }
1500
1501
1502                 {
1503                         // Valid channel update
1504                         let unsigned_channel_update = UnsignedChannelUpdate {
1505                                 chain_hash,
1506                                 short_channel_id,
1507                                 timestamp: 101,
1508                                 flags: 0,
1509                                 cltv_expiry_delta: 144,
1510                                 htlc_minimum_msat: 1000000,
1511                                 htlc_maximum_msat: OptionalField::Absent,
1512                                 fee_base_msat: 10000,
1513                                 fee_proportional_millionths: 20,
1514                                 excess_data: Vec::new()
1515                         };
1516                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1517                         let valid_channel_update = ChannelUpdate {
1518                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1519                                 contents: unsigned_channel_update.clone()
1520                         };
1521                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1522                                 Ok(_) => (),
1523                                 Err(_) => panic!()
1524                         };
1525                 }
1526
1527                 // Now contains an initial announcement and an update.
1528                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1529                 assert_eq!(channels_with_announcements.len(), 1);
1530                 if let Some(channel_announcements) = channels_with_announcements.first() {
1531                         let &(_, ref update_1, ref update_2) = channel_announcements;
1532                         assert_ne!(update_1, &None);
1533                         assert_eq!(update_2, &None);
1534                 } else {
1535                         panic!();
1536                 }
1537
1538
1539                 {
1540                         // Channel update with excess data.
1541                         let unsigned_channel_update = UnsignedChannelUpdate {
1542                                 chain_hash,
1543                                 short_channel_id,
1544                                 timestamp: 102,
1545                                 flags: 0,
1546                                 cltv_expiry_delta: 144,
1547                                 htlc_minimum_msat: 1000000,
1548                                 htlc_maximum_msat: OptionalField::Absent,
1549                                 fee_base_msat: 10000,
1550                                 fee_proportional_millionths: 20,
1551                                 excess_data: [1; 3].to_vec()
1552                         };
1553                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1554                         let valid_channel_update = ChannelUpdate {
1555                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1556                                 contents: unsigned_channel_update.clone()
1557                         };
1558                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1559                                 Ok(_) => (),
1560                                 Err(_) => panic!()
1561                         };
1562                 }
1563
1564                 // Test that announcements with excess data won't be returned
1565                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1566                 assert_eq!(channels_with_announcements.len(), 1);
1567                 if let Some(channel_announcements) = channels_with_announcements.first() {
1568                         let &(_, ref update_1, ref update_2) = channel_announcements;
1569                         assert_eq!(update_1, &None);
1570                         assert_eq!(update_2, &None);
1571                 } else {
1572                         panic!();
1573                 }
1574
1575                 // Further starting point have no channels after it
1576                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1577                 assert_eq!(channels_with_announcements.len(), 0);
1578         }
1579
1580         #[test]
1581         fn getting_next_node_announcements() {
1582                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1583                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1584                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1585                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1586                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1587                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1588                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1589
1590                 let short_channel_id = 1;
1591                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1592
1593                 // No nodes yet.
1594                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1595                 assert_eq!(next_announcements.len(), 0);
1596
1597                 {
1598                         // Announce a channel to add 2 nodes
1599                         let unsigned_announcement = UnsignedChannelAnnouncement {
1600                                 features: ChannelFeatures::empty(),
1601                                 chain_hash,
1602                                 short_channel_id,
1603                                 node_id_1,
1604                                 node_id_2,
1605                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1606                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1607                                 excess_data: Vec::new(),
1608                         };
1609
1610                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1611                         let valid_channel_announcement = ChannelAnnouncement {
1612                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1613                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1614                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1615                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1616                                 contents: unsigned_announcement.clone(),
1617                         };
1618                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1619                                 Ok(_) => (),
1620                                 Err(_) => panic!()
1621                         };
1622                 }
1623
1624
1625                 // Nodes were never announced
1626                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1627                 assert_eq!(next_announcements.len(), 0);
1628
1629                 {
1630                         let mut unsigned_announcement = UnsignedNodeAnnouncement {
1631                                 features: NodeFeatures::known(),
1632                                 timestamp: 1000,
1633                                 node_id: node_id_1,
1634                                 rgb: [0; 3],
1635                                 alias: [0; 32],
1636                                 addresses: Vec::new(),
1637                                 excess_address_data: Vec::new(),
1638                                 excess_data: Vec::new(),
1639                         };
1640                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1641                         let valid_announcement = NodeAnnouncement {
1642                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1643                                 contents: unsigned_announcement.clone()
1644                         };
1645                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1646                                 Ok(_) => (),
1647                                 Err(_) => panic!()
1648                         };
1649
1650                         unsigned_announcement.node_id = node_id_2;
1651                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1652                         let valid_announcement = NodeAnnouncement {
1653                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1654                                 contents: unsigned_announcement.clone()
1655                         };
1656
1657                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1658                                 Ok(_) => (),
1659                                 Err(_) => panic!()
1660                         };
1661                 }
1662
1663                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1664                 assert_eq!(next_announcements.len(), 2);
1665
1666                 // Skip the first node.
1667                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1668                 assert_eq!(next_announcements.len(), 1);
1669
1670                 {
1671                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1672                         let unsigned_announcement = UnsignedNodeAnnouncement {
1673                                 features: NodeFeatures::known(),
1674                                 timestamp: 1010,
1675                                 node_id: node_id_2,
1676                                 rgb: [0; 3],
1677                                 alias: [0; 32],
1678                                 addresses: Vec::new(),
1679                                 excess_address_data: Vec::new(),
1680                                 excess_data: [1; 3].to_vec(),
1681                         };
1682                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1683                         let valid_announcement = NodeAnnouncement {
1684                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1685                                 contents: unsigned_announcement.clone()
1686                         };
1687                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1688                                 Ok(res) => assert!(!res),
1689                                 Err(_) => panic!()
1690                         };
1691                 }
1692
1693                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1694                 assert_eq!(next_announcements.len(), 0);
1695         }
1696
1697         #[test]
1698         fn network_graph_serialization() {
1699                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1700
1701                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1702                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1703                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1704                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1705
1706                 // Announce a channel to add a corresponding node.
1707                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1708                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1709                 let unsigned_announcement = UnsignedChannelAnnouncement {
1710                         features: ChannelFeatures::known(),
1711                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1712                         short_channel_id: 0,
1713                         node_id_1,
1714                         node_id_2,
1715                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1716                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1717                         excess_data: Vec::new(),
1718                 };
1719
1720                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1721                 let valid_announcement = ChannelAnnouncement {
1722                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1723                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1724                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1725                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1726                         contents: unsigned_announcement.clone(),
1727                 };
1728                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1729                         Ok(res) => assert!(res),
1730                         _ => panic!()
1731                 };
1732
1733
1734                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1735                 let unsigned_announcement = UnsignedNodeAnnouncement {
1736                         features: NodeFeatures::known(),
1737                         timestamp: 100,
1738                         node_id,
1739                         rgb: [0; 3],
1740                         alias: [0; 32],
1741                         addresses: Vec::new(),
1742                         excess_address_data: Vec::new(),
1743                         excess_data: Vec::new(),
1744                 };
1745                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1746                 let valid_announcement = NodeAnnouncement {
1747                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1748                         contents: unsigned_announcement.clone()
1749                 };
1750
1751                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1752                         Ok(_) => (),
1753                         Err(_) => panic!()
1754                 };
1755
1756                 let network = net_graph_msg_handler.network_graph.write().unwrap();
1757                 let mut w = test_utils::TestVecWriter(Vec::new());
1758                 assert!(!network.get_nodes().is_empty());
1759                 assert!(!network.get_channels().is_empty());
1760                 network.write(&mut w).unwrap();
1761                 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1762         }
1763 }