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