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