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