Update to latest upstream rust-bitcoin
[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
842         use hex;
843
844         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
845         use bitcoin::secp256k1::{All, Secp256k1};
846
847         use std::sync::Arc;
848
849         fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
850                 let secp_ctx = Secp256k1::new();
851                 let logger = Arc::new(test_utils::TestLogger::new());
852                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
853                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
854                 (secp_ctx, net_graph_msg_handler)
855         }
856
857         #[test]
858         fn request_full_sync_finite_times() {
859                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
860                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
861
862                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
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         }
869
870         #[test]
871         fn handling_node_announcements() {
872                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
873
874                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
875                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
876                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
877                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
878                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
879                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
880                 let zero_hash = Sha256dHash::hash(&[0; 32]);
881                 let first_announcement_time = 500;
882
883                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
884                         features: NodeFeatures::known(),
885                         timestamp: first_announcement_time,
886                         node_id: node_id_1,
887                         rgb: [0; 3],
888                         alias: [0; 32],
889                         addresses: Vec::new(),
890                         excess_address_data: Vec::new(),
891                         excess_data: Vec::new(),
892                 };
893                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
894                 let valid_announcement = NodeAnnouncement {
895                         signature: secp_ctx.sign(&msghash, node_1_privkey),
896                         contents: unsigned_announcement.clone()
897                 };
898
899                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
900                         Ok(_) => panic!(),
901                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
902                 };
903
904                 {
905                         // Announce a channel to add a corresponding node.
906                         let unsigned_announcement = UnsignedChannelAnnouncement {
907                                 features: ChannelFeatures::known(),
908                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
909                                 short_channel_id: 0,
910                                 node_id_1,
911                                 node_id_2,
912                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
913                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
914                                 excess_data: Vec::new(),
915                         };
916
917                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
918                         let valid_announcement = ChannelAnnouncement {
919                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
920                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
921                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
922                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
923                                 contents: unsigned_announcement.clone(),
924                         };
925                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
926                                 Ok(res) => assert!(res),
927                                 _ => panic!()
928                         };
929                 }
930
931                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
932                         Ok(res) => assert!(res),
933                         Err(_) => panic!()
934                 };
935
936                 let fake_msghash = hash_to_message!(&zero_hash);
937                 match net_graph_msg_handler.handle_node_announcement(
938                         &NodeAnnouncement {
939                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
940                                 contents: unsigned_announcement.clone()
941                 }) {
942                         Ok(_) => panic!(),
943                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
944                 };
945
946                 unsigned_announcement.timestamp += 1000;
947                 unsigned_announcement.excess_data.push(1);
948                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
949                 let announcement_with_data = NodeAnnouncement {
950                         signature: secp_ctx.sign(&msghash, node_1_privkey),
951                         contents: unsigned_announcement.clone()
952                 };
953                 // Return false because contains excess data.
954                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
955                         Ok(res) => assert!(!res),
956                         Err(_) => panic!()
957                 };
958                 unsigned_announcement.excess_data = Vec::new();
959
960                 // Even though previous announcement was not relayed further, we still accepted it,
961                 // so we now won't accept announcements before the previous one.
962                 unsigned_announcement.timestamp -= 10;
963                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
964                 let outdated_announcement = NodeAnnouncement {
965                         signature: secp_ctx.sign(&msghash, node_1_privkey),
966                         contents: unsigned_announcement.clone()
967                 };
968                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
969                         Ok(_) => panic!(),
970                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
971                 };
972         }
973
974         #[test]
975         fn handling_channel_announcements() {
976                 let secp_ctx = Secp256k1::new();
977                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
978                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
979                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
980
981
982                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
983                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
984                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
985                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
986                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
987                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
988
989                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
990                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
991                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
992                    .push_opcode(opcodes::all::OP_PUSHNUM_2)
993                    .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
994
995
996                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
997                         features: ChannelFeatures::known(),
998                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
999                         short_channel_id: 0,
1000                         node_id_1,
1001                         node_id_2,
1002                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1003                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1004                         excess_data: Vec::new(),
1005                 };
1006
1007                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1008                 let valid_announcement = ChannelAnnouncement {
1009                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1010                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1011                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1012                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1013                         contents: unsigned_announcement.clone(),
1014                 };
1015
1016                 // Test if the UTXO lookups were not supported
1017                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
1018
1019                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1020                         Ok(res) => assert!(res),
1021                         _ => panic!()
1022                 };
1023
1024                 {
1025                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1026                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1027                                 None => panic!(),
1028                                 Some(_) => ()
1029                         }
1030                 }
1031
1032
1033                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1034                 // drop new one on the floor, since we can't see any changes.
1035                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1036                         Ok(_) => panic!(),
1037                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1038                 };
1039
1040
1041                 // Test if an associated transaction were not on-chain (or not confirmed).
1042                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1043                 unsigned_announcement.short_channel_id += 1;
1044
1045                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1046                 let valid_announcement = ChannelAnnouncement {
1047                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1048                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1049                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1050                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1051                         contents: unsigned_announcement.clone(),
1052                 };
1053
1054                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1055                         Ok(_) => panic!(),
1056                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1057                 };
1058
1059
1060                 // Now test if the transaction is found in the UTXO set and the script is correct.
1061                 unsigned_announcement.short_channel_id += 1;
1062                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1063
1064                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1065                 let valid_announcement = ChannelAnnouncement {
1066                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1067                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1068                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1069                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1070                         contents: unsigned_announcement.clone(),
1071                 };
1072                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1073                         Ok(res) => assert!(res),
1074                         _ => panic!()
1075                 };
1076
1077                 {
1078                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1079                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1080                                 None => panic!(),
1081                                 Some(_) => ()
1082                         }
1083                 }
1084
1085                 // If we receive announcement for the same channel (but TX is not confirmed),
1086                 // drop new one on the floor, since we can't see any changes.
1087                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1088                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1089                         Ok(_) => panic!(),
1090                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1091                 };
1092
1093                 // But if it is confirmed, replace the channel
1094                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1095                 unsigned_announcement.features = ChannelFeatures::empty();
1096                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1097                 let valid_announcement = ChannelAnnouncement {
1098                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1099                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1100                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1101                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1102                         contents: unsigned_announcement.clone(),
1103                 };
1104                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1105                         Ok(res) => assert!(res),
1106                         _ => panic!()
1107                 };
1108                 {
1109                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1110                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1111                                 Some(channel_entry) => {
1112                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1113                                 },
1114                                 _ => panic!()
1115                         }
1116                 }
1117
1118                 // Don't relay valid channels with excess data
1119                 unsigned_announcement.short_channel_id += 1;
1120                 unsigned_announcement.excess_data.push(1);
1121                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1122                 let valid_announcement = ChannelAnnouncement {
1123                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1124                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1125                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1126                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1127                         contents: unsigned_announcement.clone(),
1128                 };
1129                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1130                         Ok(res) => assert!(!res),
1131                         _ => panic!()
1132                 };
1133
1134                 unsigned_announcement.excess_data = Vec::new();
1135                 let invalid_sig_announcement = ChannelAnnouncement {
1136                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1137                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1138                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1139                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1140                         contents: unsigned_announcement.clone(),
1141                 };
1142                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1143                         Ok(_) => panic!(),
1144                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1145                 };
1146
1147                 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1148                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1149                 let channel_to_itself_announcement = ChannelAnnouncement {
1150                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1151                         node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1152                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1153                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1154                         contents: unsigned_announcement.clone(),
1155                 };
1156                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1157                         Ok(_) => panic!(),
1158                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1159                 };
1160         }
1161
1162         #[test]
1163         fn handling_channel_update() {
1164                 let secp_ctx = Secp256k1::new();
1165                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1166                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1167                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1168
1169                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1170                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1171                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1172                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1173                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1174                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1175
1176                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1177                 let short_channel_id = 0;
1178                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1179                 let amount_sats = 1000_000;
1180
1181                 {
1182                         // Announce a channel we will update
1183                         let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1184                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1185                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1186                            .push_opcode(opcodes::all::OP_PUSHNUM_2)
1187                            .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1188                         *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1189                         let unsigned_announcement = UnsignedChannelAnnouncement {
1190                                 features: ChannelFeatures::empty(),
1191                                 chain_hash,
1192                                 short_channel_id,
1193                                 node_id_1,
1194                                 node_id_2,
1195                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1196                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1197                                 excess_data: Vec::new(),
1198                         };
1199
1200                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1201                         let valid_channel_announcement = ChannelAnnouncement {
1202                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1203                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1204                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1205                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1206                                 contents: unsigned_announcement.clone(),
1207                         };
1208                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1209                                 Ok(_) => (),
1210                                 Err(_) => panic!()
1211                         };
1212
1213                 }
1214
1215                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1216                         chain_hash,
1217                         short_channel_id,
1218                         timestamp: 100,
1219                         flags: 0,
1220                         cltv_expiry_delta: 144,
1221                         htlc_minimum_msat: 1000000,
1222                         htlc_maximum_msat: OptionalField::Absent,
1223                         fee_base_msat: 10000,
1224                         fee_proportional_millionths: 20,
1225                         excess_data: Vec::new()
1226                 };
1227                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1228                 let valid_channel_update = ChannelUpdate {
1229                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1230                         contents: unsigned_channel_update.clone()
1231                 };
1232
1233                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1234                         Ok(res) => assert!(res),
1235                         _ => panic!()
1236                 };
1237
1238                 {
1239                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1240                         match network.get_channels().get(&short_channel_id) {
1241                                 None => panic!(),
1242                                 Some(channel_info) => {
1243                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1244                                         assert!(channel_info.two_to_one.is_none());
1245                                 }
1246                         }
1247                 }
1248
1249                 unsigned_channel_update.timestamp += 100;
1250                 unsigned_channel_update.excess_data.push(1);
1251                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1252                 let valid_channel_update = ChannelUpdate {
1253                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1254                         contents: unsigned_channel_update.clone()
1255                 };
1256                 // Return false because contains excess data
1257                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1258                         Ok(res) => assert!(!res),
1259                         _ => panic!()
1260                 };
1261                 unsigned_channel_update.timestamp += 10;
1262
1263                 unsigned_channel_update.short_channel_id += 1;
1264                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1265                 let valid_channel_update = ChannelUpdate {
1266                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1267                         contents: unsigned_channel_update.clone()
1268                 };
1269
1270                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1271                         Ok(_) => panic!(),
1272                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1273                 };
1274                 unsigned_channel_update.short_channel_id = short_channel_id;
1275
1276                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1277                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1278                 let valid_channel_update = ChannelUpdate {
1279                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1280                         contents: unsigned_channel_update.clone()
1281                 };
1282
1283                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1284                         Ok(_) => panic!(),
1285                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1286                 };
1287                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1288
1289                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1290                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1291                 let valid_channel_update = ChannelUpdate {
1292                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1293                         contents: unsigned_channel_update.clone()
1294                 };
1295
1296                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1297                         Ok(_) => panic!(),
1298                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1299                 };
1300                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1301
1302                 // Even though previous update was not relayed further, we still accepted it,
1303                 // so we now won't accept update before the previous one.
1304                 unsigned_channel_update.timestamp -= 10;
1305                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1306                 let valid_channel_update = ChannelUpdate {
1307                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1308                         contents: unsigned_channel_update.clone()
1309                 };
1310
1311                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1312                         Ok(_) => panic!(),
1313                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1314                 };
1315                 unsigned_channel_update.timestamp += 500;
1316
1317                 let fake_msghash = hash_to_message!(&zero_hash);
1318                 let invalid_sig_channel_update = ChannelUpdate {
1319                         signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1320                         contents: unsigned_channel_update.clone()
1321                 };
1322
1323                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1324                         Ok(_) => panic!(),
1325                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1326                 };
1327
1328         }
1329
1330         #[test]
1331         fn handling_htlc_fail_channel_update() {
1332                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1333                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1334                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1335                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1336                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1337                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1338                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1339
1340                 let short_channel_id = 0;
1341                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1342
1343                 {
1344                         // There is no nodes in the table at the beginning.
1345                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1346                         assert_eq!(network.get_nodes().len(), 0);
1347                 }
1348
1349                 {
1350                         // Announce a channel we will update
1351                         let unsigned_announcement = UnsignedChannelAnnouncement {
1352                                 features: ChannelFeatures::empty(),
1353                                 chain_hash,
1354                                 short_channel_id,
1355                                 node_id_1,
1356                                 node_id_2,
1357                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1358                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1359                                 excess_data: Vec::new(),
1360                         };
1361
1362                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1363                         let valid_channel_announcement = ChannelAnnouncement {
1364                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1365                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1366                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1367                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1368                                 contents: unsigned_announcement.clone(),
1369                         };
1370                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1371                                 Ok(_) => (),
1372                                 Err(_) => panic!()
1373                         };
1374
1375                         let unsigned_channel_update = UnsignedChannelUpdate {
1376                                 chain_hash,
1377                                 short_channel_id,
1378                                 timestamp: 100,
1379                                 flags: 0,
1380                                 cltv_expiry_delta: 144,
1381                                 htlc_minimum_msat: 1000000,
1382                                 htlc_maximum_msat: OptionalField::Absent,
1383                                 fee_base_msat: 10000,
1384                                 fee_proportional_millionths: 20,
1385                                 excess_data: Vec::new()
1386                         };
1387                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1388                         let valid_channel_update = ChannelUpdate {
1389                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1390                                 contents: unsigned_channel_update.clone()
1391                         };
1392
1393                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1394                                 Ok(res) => assert!(res),
1395                                 _ => panic!()
1396                         };
1397                 }
1398
1399                 // Non-permanent closing just disables a channel
1400                 {
1401                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1402                         match network.get_channels().get(&short_channel_id) {
1403                                 None => panic!(),
1404                                 Some(channel_info) => {
1405                                         assert!(channel_info.one_to_two.is_some());
1406                                 }
1407                         }
1408                 }
1409
1410                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1411                         short_channel_id,
1412                         is_permanent: false
1413                 };
1414
1415                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1416
1417                 // Non-permanent closing just disables a channel
1418                 {
1419                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1420                         match network.get_channels().get(&short_channel_id) {
1421                                 None => panic!(),
1422                                 Some(channel_info) => {
1423                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1424                                 }
1425                         }
1426                 }
1427
1428                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1429                         short_channel_id,
1430                         is_permanent: true
1431                 };
1432
1433                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1434
1435                 // Permanent closing deletes a channel
1436                 {
1437                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1438                         assert_eq!(network.get_channels().len(), 0);
1439                         // Nodes are also deleted because there are no associated channels anymore
1440                         assert_eq!(network.get_nodes().len(), 0);
1441                 }
1442                 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1443         }
1444
1445         #[test]
1446         fn getting_next_channel_announcements() {
1447                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1448                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1449                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1450                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1451                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1452                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1453                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1454
1455                 let short_channel_id = 1;
1456                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1457
1458                 // Channels were not announced yet.
1459                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1460                 assert_eq!(channels_with_announcements.len(), 0);
1461
1462                 {
1463                         // Announce a channel we will update
1464                         let unsigned_announcement = UnsignedChannelAnnouncement {
1465                                 features: ChannelFeatures::empty(),
1466                                 chain_hash,
1467                                 short_channel_id,
1468                                 node_id_1,
1469                                 node_id_2,
1470                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1471                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1472                                 excess_data: Vec::new(),
1473                         };
1474
1475                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1476                         let valid_channel_announcement = ChannelAnnouncement {
1477                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1478                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1479                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1480                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1481                                 contents: unsigned_announcement.clone(),
1482                         };
1483                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1484                                 Ok(_) => (),
1485                                 Err(_) => panic!()
1486                         };
1487                 }
1488
1489                 // Contains initial channel announcement now.
1490                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1491                 assert_eq!(channels_with_announcements.len(), 1);
1492                 if let Some(channel_announcements) = channels_with_announcements.first() {
1493                         let &(_, ref update_1, ref update_2) = channel_announcements;
1494                         assert_eq!(update_1, &None);
1495                         assert_eq!(update_2, &None);
1496                 } else {
1497                         panic!();
1498                 }
1499
1500
1501                 {
1502                         // Valid channel update
1503                         let unsigned_channel_update = UnsignedChannelUpdate {
1504                                 chain_hash,
1505                                 short_channel_id,
1506                                 timestamp: 101,
1507                                 flags: 0,
1508                                 cltv_expiry_delta: 144,
1509                                 htlc_minimum_msat: 1000000,
1510                                 htlc_maximum_msat: OptionalField::Absent,
1511                                 fee_base_msat: 10000,
1512                                 fee_proportional_millionths: 20,
1513                                 excess_data: Vec::new()
1514                         };
1515                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1516                         let valid_channel_update = ChannelUpdate {
1517                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1518                                 contents: unsigned_channel_update.clone()
1519                         };
1520                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1521                                 Ok(_) => (),
1522                                 Err(_) => panic!()
1523                         };
1524                 }
1525
1526                 // Now contains an initial announcement and an update.
1527                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1528                 assert_eq!(channels_with_announcements.len(), 1);
1529                 if let Some(channel_announcements) = channels_with_announcements.first() {
1530                         let &(_, ref update_1, ref update_2) = channel_announcements;
1531                         assert_ne!(update_1, &None);
1532                         assert_eq!(update_2, &None);
1533                 } else {
1534                         panic!();
1535                 }
1536
1537
1538                 {
1539                         // Channel update with excess data.
1540                         let unsigned_channel_update = UnsignedChannelUpdate {
1541                                 chain_hash,
1542                                 short_channel_id,
1543                                 timestamp: 102,
1544                                 flags: 0,
1545                                 cltv_expiry_delta: 144,
1546                                 htlc_minimum_msat: 1000000,
1547                                 htlc_maximum_msat: OptionalField::Absent,
1548                                 fee_base_msat: 10000,
1549                                 fee_proportional_millionths: 20,
1550                                 excess_data: [1; 3].to_vec()
1551                         };
1552                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1553                         let valid_channel_update = ChannelUpdate {
1554                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1555                                 contents: unsigned_channel_update.clone()
1556                         };
1557                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1558                                 Ok(_) => (),
1559                                 Err(_) => panic!()
1560                         };
1561                 }
1562
1563                 // Test that announcements with excess data won't be returned
1564                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1565                 assert_eq!(channels_with_announcements.len(), 1);
1566                 if let Some(channel_announcements) = channels_with_announcements.first() {
1567                         let &(_, ref update_1, ref update_2) = channel_announcements;
1568                         assert_eq!(update_1, &None);
1569                         assert_eq!(update_2, &None);
1570                 } else {
1571                         panic!();
1572                 }
1573
1574                 // Further starting point have no channels after it
1575                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1576                 assert_eq!(channels_with_announcements.len(), 0);
1577         }
1578
1579         #[test]
1580         fn getting_next_node_announcements() {
1581                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1582                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1583                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1584                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1585                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1586                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1587                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1588
1589                 let short_channel_id = 1;
1590                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1591
1592                 // No nodes yet.
1593                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1594                 assert_eq!(next_announcements.len(), 0);
1595
1596                 {
1597                         // Announce a channel to add 2 nodes
1598                         let unsigned_announcement = UnsignedChannelAnnouncement {
1599                                 features: ChannelFeatures::empty(),
1600                                 chain_hash,
1601                                 short_channel_id,
1602                                 node_id_1,
1603                                 node_id_2,
1604                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1605                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1606                                 excess_data: Vec::new(),
1607                         };
1608
1609                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1610                         let valid_channel_announcement = ChannelAnnouncement {
1611                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1612                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1613                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1614                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1615                                 contents: unsigned_announcement.clone(),
1616                         };
1617                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1618                                 Ok(_) => (),
1619                                 Err(_) => panic!()
1620                         };
1621                 }
1622
1623
1624                 // Nodes were never announced
1625                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1626                 assert_eq!(next_announcements.len(), 0);
1627
1628                 {
1629                         let mut unsigned_announcement = UnsignedNodeAnnouncement {
1630                                 features: NodeFeatures::known(),
1631                                 timestamp: 1000,
1632                                 node_id: node_id_1,
1633                                 rgb: [0; 3],
1634                                 alias: [0; 32],
1635                                 addresses: Vec::new(),
1636                                 excess_address_data: Vec::new(),
1637                                 excess_data: Vec::new(),
1638                         };
1639                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1640                         let valid_announcement = NodeAnnouncement {
1641                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1642                                 contents: unsigned_announcement.clone()
1643                         };
1644                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1645                                 Ok(_) => (),
1646                                 Err(_) => panic!()
1647                         };
1648
1649                         unsigned_announcement.node_id = node_id_2;
1650                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1651                         let valid_announcement = NodeAnnouncement {
1652                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1653                                 contents: unsigned_announcement.clone()
1654                         };
1655
1656                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1657                                 Ok(_) => (),
1658                                 Err(_) => panic!()
1659                         };
1660                 }
1661
1662                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1663                 assert_eq!(next_announcements.len(), 2);
1664
1665                 // Skip the first node.
1666                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1667                 assert_eq!(next_announcements.len(), 1);
1668
1669                 {
1670                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1671                         let unsigned_announcement = UnsignedNodeAnnouncement {
1672                                 features: NodeFeatures::known(),
1673                                 timestamp: 1010,
1674                                 node_id: node_id_2,
1675                                 rgb: [0; 3],
1676                                 alias: [0; 32],
1677                                 addresses: Vec::new(),
1678                                 excess_address_data: Vec::new(),
1679                                 excess_data: [1; 3].to_vec(),
1680                         };
1681                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1682                         let valid_announcement = NodeAnnouncement {
1683                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1684                                 contents: unsigned_announcement.clone()
1685                         };
1686                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1687                                 Ok(res) => assert!(!res),
1688                                 Err(_) => panic!()
1689                         };
1690                 }
1691
1692                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1693                 assert_eq!(next_announcements.len(), 0);
1694         }
1695
1696         #[test]
1697         fn network_graph_serialization() {
1698                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1699
1700                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1701                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1702                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1703                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1704
1705                 // Announce a channel to add a corresponding node.
1706                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1707                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1708                 let unsigned_announcement = UnsignedChannelAnnouncement {
1709                         features: ChannelFeatures::known(),
1710                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1711                         short_channel_id: 0,
1712                         node_id_1,
1713                         node_id_2,
1714                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1715                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1716                         excess_data: Vec::new(),
1717                 };
1718
1719                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1720                 let valid_announcement = ChannelAnnouncement {
1721                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1722                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1723                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1724                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1725                         contents: unsigned_announcement.clone(),
1726                 };
1727                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1728                         Ok(res) => assert!(res),
1729                         _ => panic!()
1730                 };
1731
1732
1733                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1734                 let unsigned_announcement = UnsignedNodeAnnouncement {
1735                         features: NodeFeatures::known(),
1736                         timestamp: 100,
1737                         node_id,
1738                         rgb: [0; 3],
1739                         alias: [0; 32],
1740                         addresses: Vec::new(),
1741                         excess_address_data: Vec::new(),
1742                         excess_data: Vec::new(),
1743                 };
1744                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1745                 let valid_announcement = NodeAnnouncement {
1746                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1747                         contents: unsigned_announcement.clone()
1748                 };
1749
1750                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1751                         Ok(_) => (),
1752                         Err(_) => panic!()
1753                 };
1754
1755                 let network = net_graph_msg_handler.network_graph.write().unwrap();
1756                 let mut w = test_utils::TestVecWriter(Vec::new());
1757                 assert!(!network.get_nodes().is_empty());
1758                 assert!(!network.get_channels().is_empty());
1759                 network.write(&mut w).unwrap();
1760                 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1761         }
1762 }