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