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