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