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