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