1 // This file is Copyright its original authors, visible in version control
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
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::opcodes;
21 use chain::chaininterface::{ChainError, ChainWatchInterface};
22 use ln::features::{ChannelFeatures, NodeFeatures};
23 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
24 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
26 use util::ser::{Writeable, Readable, Writer};
27 use util::logger::Logger;
30 use std::sync::RwLock;
31 use std::sync::atomic::{AtomicUsize, Ordering};
32 use std::collections::BTreeMap;
33 use std::collections::btree_map::Entry as BtreeEntry;
35 use bitcoin::hashes::hex::ToHex;
37 /// Represents the network as nodes and channels between them
39 pub struct NetworkGraph {
40 channels: BTreeMap<u64, ChannelInfo>,
41 nodes: BTreeMap<PublicKey, NodeInfo>,
44 /// Receives and validates network updates from peers,
45 /// stores authentic and relevant data as a network graph.
46 /// This network graph is then used for routing payments.
47 /// Provides interface to help with initial routing sync by
48 /// serving historical announcements.
49 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
50 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
51 /// Representation of the payment channel network
52 pub network_graph: RwLock<NetworkGraph>,
54 full_syncs_requested: AtomicUsize,
58 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
59 /// Creates a new tracker of the actual state of the network of channels and nodes,
60 /// assuming a fresh network graph.
61 /// Chain monitor is used to make sure announced channels exist on-chain,
62 /// channel data is correct, and that the announcement is signed with
63 /// channel owners' keys.
64 pub fn new(chain_monitor: C, logger: L) -> Self {
66 secp_ctx: Secp256k1::verification_only(),
67 network_graph: RwLock::new(NetworkGraph {
68 channels: BTreeMap::new(),
69 nodes: BTreeMap::new(),
71 full_syncs_requested: AtomicUsize::new(0),
77 /// Creates a new tracker of the actual state of the network of channels and nodes,
78 /// assuming an existing Network Graph.
79 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
81 secp_ctx: Secp256k1::verification_only(),
82 network_graph: RwLock::new(network_graph),
83 full_syncs_requested: AtomicUsize::new(0),
91 macro_rules! secp_verify_sig {
92 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
93 match $secp_ctx.verify($msg, $sig, $pubkey) {
95 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
100 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
101 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
102 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
105 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
106 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
107 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
110 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
111 Ok((script_pubkey, value)) => {
112 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
113 .push_slice(&msg.contents.bitcoin_key_1.serialize())
114 .push_slice(&msg.contents.bitcoin_key_2.serialize())
115 .push_opcode(opcodes::all::OP_PUSHNUM_2)
116 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
117 if script_pubkey != expected_script {
118 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});
120 //TODO: Check if value is worth storing, use it to inform routing, and compare it
121 //to the new HTLC max field in channel_update
124 Err(ChainError::NotSupported) => {
125 // Tentatively accept, potentially exposing us to DoS attacks
128 Err(ChainError::NotWatched) => {
129 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
131 Err(ChainError::UnknownTx) => {
132 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
135 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
136 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 { "" });
140 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
142 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
143 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
145 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
146 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
148 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
149 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
154 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
155 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
158 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
159 let network_graph = self.network_graph.read().unwrap();
160 let mut result = Vec::with_capacity(batch_amount as usize);
161 let mut iter = network_graph.get_channels().range(starting_point..);
162 while result.len() < batch_amount as usize {
163 if let Some((_, ref chan)) = iter.next() {
164 if chan.announcement_message.is_some() {
165 let chan_announcement = chan.announcement_message.clone().unwrap();
166 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
167 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
168 if let Some(one_to_two) = chan.one_to_two.as_ref() {
169 one_to_two_announcement = one_to_two.last_update_message.clone();
171 if let Some(two_to_one) = chan.two_to_one.as_ref() {
172 two_to_one_announcement = two_to_one.last_update_message.clone();
174 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
176 // TODO: We may end up sending un-announced channel_updates if we are sending
177 // initial sync data while receiving announce/updates for this channel.
186 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
187 let network_graph = self.network_graph.read().unwrap();
188 let mut result = Vec::with_capacity(batch_amount as usize);
189 let mut iter = if let Some(pubkey) = starting_point {
190 let mut iter = network_graph.get_nodes().range((*pubkey)..);
194 network_graph.get_nodes().range(..)
196 while result.len() < batch_amount as usize {
197 if let Some((_, ref node)) = iter.next() {
198 if let Some(node_info) = node.announcement_info.as_ref() {
199 if node_info.announcement_message.is_some() {
200 result.push(node_info.announcement_message.clone().unwrap());
210 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
211 //TODO: Determine whether to request a full sync based on the network map.
212 const FULL_SYNCS_TO_REQUEST: usize = 5;
213 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
214 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
222 #[derive(PartialEq, Debug)]
223 /// Details about one direction of a channel. Received
224 /// within a channel update.
225 pub struct DirectionalChannelInfo {
226 /// When the last update to the channel direction was issued.
227 /// Value is opaque, as set in the announcement.
228 pub last_update: u32,
229 /// Whether the channel can be currently used for payments (in this one direction).
231 /// The difference in CLTV values that you must have when routing through this channel.
232 pub cltv_expiry_delta: u16,
233 /// The minimum value, which must be relayed to the next hop via the channel
234 pub htlc_minimum_msat: u64,
235 /// The maximum value which may be relayed to the next hop via the channel.
236 pub htlc_maximum_msat: Option<u64>,
237 /// Fees charged when the channel is used for routing
238 pub fees: RoutingFees,
239 /// Most recent update for the channel received from the network
240 /// Mostly redundant with the data we store in fields explicitly.
241 /// Everything else is useful only for sending out for initial routing sync.
242 /// Not stored if contains excess data to prevent DoS.
243 pub last_update_message: Option<msgs::ChannelUpdate>,
246 impl fmt::Display for DirectionalChannelInfo {
247 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
248 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)?;
253 impl_writeable!(DirectionalChannelInfo, 0, {
264 /// Details about a channel (both directions).
265 /// Received within a channel announcement.
266 pub struct ChannelInfo {
267 /// Protocol features of a channel communicated during its announcement
268 pub features: ChannelFeatures,
269 /// Source node of the first direction of a channel
270 pub node_one: PublicKey,
271 /// Details about the first direction of a channel
272 pub one_to_two: Option<DirectionalChannelInfo>,
273 /// Source node of the second direction of a channel
274 pub node_two: PublicKey,
275 /// Details about the second direction of a channel
276 pub two_to_one: Option<DirectionalChannelInfo>,
277 /// The channel capacity as seen on-chain, if chain lookup is available.
278 pub capacity_sats: Option<u64>,
279 /// An initial announcement of the channel
280 /// Mostly redundant with the data we store in fields explicitly.
281 /// Everything else is useful only for sending out for initial routing sync.
282 /// Not stored if contains excess data to prevent DoS.
283 pub announcement_message: Option<msgs::ChannelAnnouncement>,
286 impl fmt::Display for ChannelInfo {
287 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
288 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
289 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
294 impl_writeable!(ChannelInfo, 0, {
305 /// Fees for routing via a given channel or a node
306 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
307 pub struct RoutingFees {
308 /// Flat routing fee in satoshis
310 /// Liquidity-based routing fee in millionths of a routed amount.
311 /// In other words, 10000 is 1%.
312 pub proportional_millionths: u32,
315 impl Readable for RoutingFees{
316 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
317 let base_msat: u32 = Readable::read(reader)?;
318 let proportional_millionths: u32 = Readable::read(reader)?;
321 proportional_millionths,
326 impl Writeable for RoutingFees {
327 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
328 self.base_msat.write(writer)?;
329 self.proportional_millionths.write(writer)?;
334 #[derive(PartialEq, Debug)]
335 /// Information received in the latest node_announcement from this node.
336 pub struct NodeAnnouncementInfo {
337 /// Protocol features the node announced support for
338 pub features: NodeFeatures,
339 /// When the last known update to the node state was issued.
340 /// Value is opaque, as set in the announcement.
341 pub last_update: u32,
342 /// Color assigned to the node
344 /// Moniker assigned to the node.
345 /// May be invalid or malicious (eg control chars),
346 /// should not be exposed to the user.
348 /// Internet-level addresses via which one can connect to the node
349 pub addresses: Vec<NetAddress>,
350 /// An initial announcement of the node
351 /// Mostly redundant with the data we store in fields explicitly.
352 /// Everything else is useful only for sending out for initial routing sync.
353 /// Not stored if contains excess data to prevent DoS.
354 pub announcement_message: Option<msgs::NodeAnnouncement>
357 impl Writeable for NodeAnnouncementInfo {
358 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
359 self.features.write(writer)?;
360 self.last_update.write(writer)?;
361 self.rgb.write(writer)?;
362 self.alias.write(writer)?;
363 (self.addresses.len() as u64).write(writer)?;
364 for ref addr in &self.addresses {
367 self.announcement_message.write(writer)?;
372 impl Readable for NodeAnnouncementInfo {
373 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
374 let features = Readable::read(reader)?;
375 let last_update = Readable::read(reader)?;
376 let rgb = Readable::read(reader)?;
377 let alias = Readable::read(reader)?;
378 let addresses_count: u64 = Readable::read(reader)?;
379 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
380 for _ in 0..addresses_count {
381 match Readable::read(reader) {
382 Ok(Ok(addr)) => { addresses.push(addr); },
383 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
384 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
388 let announcement_message = Readable::read(reader)?;
389 Ok(NodeAnnouncementInfo {
401 /// Details about a node in the network, known from the network announcement.
402 pub struct NodeInfo {
403 /// All valid channels a node has announced
404 pub channels: Vec<u64>,
405 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
406 /// The two fields (flat and proportional fee) are independent,
407 /// meaning they don't have to refer to the same channel.
408 pub lowest_inbound_channel_fees: Option<RoutingFees>,
409 /// More information about a node from node_announcement.
410 /// Optional because we store a Node entry after learning about it from
411 /// a channel announcement, but before receiving a node announcement.
412 pub announcement_info: Option<NodeAnnouncementInfo>
415 impl fmt::Display for NodeInfo {
416 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
417 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
418 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
423 impl Writeable for NodeInfo {
424 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
425 (self.channels.len() as u64).write(writer)?;
426 for ref chan in self.channels.iter() {
429 self.lowest_inbound_channel_fees.write(writer)?;
430 self.announcement_info.write(writer)?;
435 const MAX_ALLOC_SIZE: u64 = 64*1024;
437 impl Readable for NodeInfo {
438 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
439 let channels_count: u64 = Readable::read(reader)?;
440 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
441 for _ in 0..channels_count {
442 channels.push(Readable::read(reader)?);
444 let lowest_inbound_channel_fees = Readable::read(reader)?;
445 let announcement_info = Readable::read(reader)?;
448 lowest_inbound_channel_fees,
454 impl Writeable for NetworkGraph {
455 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
456 (self.channels.len() as u64).write(writer)?;
457 for (ref chan_id, ref chan_info) in self.channels.iter() {
458 (*chan_id).write(writer)?;
459 chan_info.write(writer)?;
461 (self.nodes.len() as u64).write(writer)?;
462 for (ref node_id, ref node_info) in self.nodes.iter() {
463 node_id.write(writer)?;
464 node_info.write(writer)?;
470 impl Readable for NetworkGraph {
471 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
472 let channels_count: u64 = Readable::read(reader)?;
473 let mut channels = BTreeMap::new();
474 for _ in 0..channels_count {
475 let chan_id: u64 = Readable::read(reader)?;
476 let chan_info = Readable::read(reader)?;
477 channels.insert(chan_id, chan_info);
479 let nodes_count: u64 = Readable::read(reader)?;
480 let mut nodes = BTreeMap::new();
481 for _ in 0..nodes_count {
482 let node_id = Readable::read(reader)?;
483 let node_info = Readable::read(reader)?;
484 nodes.insert(node_id, node_info);
493 impl fmt::Display for NetworkGraph {
494 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
495 write!(f, "Network map\n[Channels]\n")?;
496 for (key, val) in self.channels.iter() {
497 write!(f, " {}: {}\n", key, val)?;
499 write!(f, "[Nodes]\n")?;
500 for (key, val) in self.nodes.iter() {
501 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
508 /// Returns all known valid channels' short ids along with announced channel info.
509 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
510 /// Returns all known nodes' public keys along with announced node info.
511 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
513 /// Get network addresses by node id.
514 /// Returns None if the requested node is completely unknown,
515 /// or if node announcement for the node was never received.
516 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
517 if let Some(node) = self.nodes.get(pubkey) {
518 if let Some(node_info) = node.announcement_info.as_ref() {
519 return Some(&node_info.addresses)
525 /// Creates a new, empty, network graph.
526 pub fn new() -> NetworkGraph {
528 channels: BTreeMap::new(),
529 nodes: BTreeMap::new(),
533 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
534 /// Announcement signatures are checked here only if Secp256k1 object is provided.
535 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
536 if let Some(sig_verifier) = secp_ctx {
537 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
538 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
541 match self.nodes.get_mut(&msg.contents.node_id) {
542 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
544 if let Some(node_info) = node.announcement_info.as_ref() {
545 if node_info.last_update >= msg.contents.timestamp {
546 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
550 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
551 node.announcement_info = Some(NodeAnnouncementInfo {
552 features: msg.contents.features.clone(),
553 last_update: msg.contents.timestamp,
554 rgb: msg.contents.rgb,
555 alias: msg.contents.alias,
556 addresses: msg.contents.addresses.clone(),
557 announcement_message: if should_relay { Some(msg.clone()) } else { None },
565 /// For a new or already known (from previous announcement) channel, store or update channel info.
566 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
567 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
568 /// which is probably result of a reorg. In that case, we update channel info only if the
569 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
570 /// Announcement signatures are checked here only if Secp256k1 object is provided.
571 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
572 if let Some(sig_verifier) = secp_ctx {
573 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
574 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
575 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
576 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
577 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
580 let should_relay = msg.contents.excess_data.is_empty();
582 let chan_info = ChannelInfo {
583 features: msg.contents.features.clone(),
584 node_one: msg.contents.node_id_1.clone(),
586 node_two: msg.contents.node_id_2.clone(),
588 capacity_sats: utxo_value,
589 announcement_message: if should_relay { Some(msg.clone()) } else { None },
592 match self.channels.entry(msg.contents.short_channel_id) {
593 BtreeEntry::Occupied(mut entry) => {
594 //TODO: because asking the blockchain if short_channel_id is valid is only optional
595 //in the blockchain API, we need to handle it smartly here, though it's unclear
597 if utxo_value.is_some() {
598 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
599 // only sometimes returns results. In any case remove the previous entry. Note
600 // that the spec expects us to "blacklist" the node_ids involved, but we can't
602 // a) we don't *require* a UTXO provider that always returns results.
603 // b) we don't track UTXOs of channels we know about and remove them if they
605 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
606 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
607 *entry.get_mut() = chan_info;
609 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
612 BtreeEntry::Vacant(entry) => {
613 entry.insert(chan_info);
617 macro_rules! add_channel_to_node {
618 ( $node_id: expr ) => {
619 match self.nodes.entry($node_id) {
620 BtreeEntry::Occupied(node_entry) => {
621 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
623 BtreeEntry::Vacant(node_entry) => {
624 node_entry.insert(NodeInfo {
625 channels: vec!(msg.contents.short_channel_id),
626 lowest_inbound_channel_fees: None,
627 announcement_info: None,
634 add_channel_to_node!(msg.contents.node_id_1);
635 add_channel_to_node!(msg.contents.node_id_2);
640 /// Close a channel if a corresponding HTLC fail was sent.
641 /// If permanent, removes a channel from the local storage.
642 /// May cause the removal of nodes too, if this was their last channel.
643 /// If not permanent, makes channels unavailable for routing.
644 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
646 if let Some(chan) = self.channels.remove(&short_channel_id) {
647 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
650 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
651 if let Some(one_to_two) = chan.one_to_two.as_mut() {
652 one_to_two.enabled = false;
654 if let Some(two_to_one) = chan.two_to_one.as_mut() {
655 two_to_one.enabled = false;
661 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
663 // TODO: Wholly remove the node
665 // TODO: downgrade the node
669 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
670 /// Announcement signatures are checked here only if Secp256k1 object is provided.
671 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
673 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
674 let chan_was_enabled;
676 match self.channels.get_mut(&msg.contents.short_channel_id) {
677 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
679 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
680 if htlc_maximum_msat > MAX_VALUE_MSAT {
681 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
684 if let Some(capacity_sats) = channel.capacity_sats {
685 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
686 // Don't query UTXO set here to reduce DoS risks.
687 if htlc_maximum_msat > capacity_sats * 1000 {
688 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
692 macro_rules! maybe_update_channel_info {
693 ( $target: expr, $src_node: expr) => {
694 if let Some(existing_chan_info) = $target.as_ref() {
695 if existing_chan_info.last_update >= msg.contents.timestamp {
696 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
698 chan_was_enabled = existing_chan_info.enabled;
700 chan_was_enabled = false;
703 let last_update_message = if msg.contents.excess_data.is_empty() {
709 let updated_channel_dir_info = DirectionalChannelInfo {
710 enabled: chan_enabled,
711 last_update: msg.contents.timestamp,
712 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
713 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
714 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
716 base_msat: msg.contents.fee_base_msat,
717 proportional_millionths: msg.contents.fee_proportional_millionths,
721 $target = Some(updated_channel_dir_info);
725 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
726 if msg.contents.flags & 1 == 1 {
727 dest_node_id = channel.node_one.clone();
728 if let Some(sig_verifier) = secp_ctx {
729 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
731 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
733 dest_node_id = channel.node_two.clone();
734 if let Some(sig_verifier) = secp_ctx {
735 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
737 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
743 let node = self.nodes.get_mut(&dest_node_id).unwrap();
744 let mut base_msat = msg.contents.fee_base_msat;
745 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
746 if let Some(fees) = node.lowest_inbound_channel_fees {
747 base_msat = cmp::min(base_msat, fees.base_msat);
748 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
750 node.lowest_inbound_channel_fees = Some(RoutingFees {
752 proportional_millionths
754 } else if chan_was_enabled {
755 let node = self.nodes.get_mut(&dest_node_id).unwrap();
756 let mut lowest_inbound_channel_fees = None;
758 for chan_id in node.channels.iter() {
759 let chan = self.channels.get(chan_id).unwrap();
761 if chan.node_one == dest_node_id {
762 chan_info_opt = chan.two_to_one.as_ref();
764 chan_info_opt = chan.one_to_two.as_ref();
766 if let Some(chan_info) = chan_info_opt {
767 if chan_info.enabled {
768 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
769 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
770 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
771 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
776 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
779 Ok(msg.contents.excess_data.is_empty())
782 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
783 macro_rules! remove_from_node {
784 ($node_id: expr) => {
785 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
786 entry.get_mut().channels.retain(|chan_id| {
787 short_channel_id != *chan_id
789 if entry.get().channels.is_empty() {
790 entry.remove_entry();
793 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
798 remove_from_node!(chan.node_one);
799 remove_from_node!(chan.node_two);
805 use chain::chaininterface;
806 use ln::features::{ChannelFeatures, NodeFeatures};
807 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
808 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
809 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
811 use util::test_utils;
812 use util::logger::Logger;
813 use util::ser::{Readable, Writeable};
815 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
816 use bitcoin::hashes::Hash;
817 use bitcoin::network::constants::Network;
818 use bitcoin::blockdata::constants::genesis_block;
819 use bitcoin::blockdata::script::Builder;
820 use bitcoin::blockdata::opcodes;
821 use bitcoin::util::hash::BitcoinHash;
825 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
826 use bitcoin::secp256k1::{All, Secp256k1};
830 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
831 let secp_ctx = Secp256k1::new();
832 let logger = Arc::new(test_utils::TestLogger::new());
833 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
834 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
835 (secp_ctx, net_graph_msg_handler)
839 fn request_full_sync_finite_times() {
840 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
841 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
843 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
844 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
845 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
846 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
847 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
848 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
852 fn handling_node_announcements() {
853 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
855 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
856 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
857 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
858 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
859 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
860 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
861 let zero_hash = Sha256dHash::hash(&[0; 32]);
862 let first_announcement_time = 500;
864 let mut unsigned_announcement = UnsignedNodeAnnouncement {
865 features: NodeFeatures::known(),
866 timestamp: first_announcement_time,
870 addresses: Vec::new(),
871 excess_address_data: Vec::new(),
872 excess_data: Vec::new(),
874 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
875 let valid_announcement = NodeAnnouncement {
876 signature: secp_ctx.sign(&msghash, node_1_privkey),
877 contents: unsigned_announcement.clone()
880 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
882 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
886 // Announce a channel to add a corresponding node.
887 let unsigned_announcement = UnsignedChannelAnnouncement {
888 features: ChannelFeatures::known(),
889 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
893 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
894 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
895 excess_data: Vec::new(),
898 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
899 let valid_announcement = ChannelAnnouncement {
900 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
901 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
902 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
903 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
904 contents: unsigned_announcement.clone(),
906 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
907 Ok(res) => assert!(res),
912 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
913 Ok(res) => assert!(res),
917 let fake_msghash = hash_to_message!(&zero_hash);
918 match net_graph_msg_handler.handle_node_announcement(
920 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
921 contents: unsigned_announcement.clone()
924 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
927 unsigned_announcement.timestamp += 1000;
928 unsigned_announcement.excess_data.push(1);
929 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
930 let announcement_with_data = NodeAnnouncement {
931 signature: secp_ctx.sign(&msghash, node_1_privkey),
932 contents: unsigned_announcement.clone()
934 // Return false because contains excess data.
935 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
936 Ok(res) => assert!(!res),
939 unsigned_announcement.excess_data = Vec::new();
941 // Even though previous announcement was not relayed further, we still accepted it,
942 // so we now won't accept announcements before the previous one.
943 unsigned_announcement.timestamp -= 10;
944 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
945 let outdated_announcement = NodeAnnouncement {
946 signature: secp_ctx.sign(&msghash, node_1_privkey),
947 contents: unsigned_announcement.clone()
949 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
951 Err(e) => assert_eq!(e.err, "Update older than last processed update")
956 fn handling_channel_announcements() {
957 let secp_ctx = Secp256k1::new();
958 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
959 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
960 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
963 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
964 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
965 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
966 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
967 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
968 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
970 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
971 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
972 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
973 .push_opcode(opcodes::all::OP_PUSHNUM_2)
974 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
977 let mut unsigned_announcement = UnsignedChannelAnnouncement {
978 features: ChannelFeatures::known(),
979 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
983 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
984 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
985 excess_data: Vec::new(),
988 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
989 let valid_announcement = ChannelAnnouncement {
990 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
991 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
992 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
993 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
994 contents: unsigned_announcement.clone(),
997 // Test if the UTXO lookups were not supported
998 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
1000 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1001 Ok(res) => assert!(res),
1006 let network = net_graph_msg_handler.network_graph.read().unwrap();
1007 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1014 // If we receive announcement for the same channel (with UTXO lookups disabled),
1015 // drop new one on the floor, since we can't see any changes.
1016 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1018 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1022 // Test if an associated transaction were not on-chain (or not confirmed).
1023 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1024 unsigned_announcement.short_channel_id += 1;
1026 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1027 let valid_announcement = ChannelAnnouncement {
1028 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1029 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1030 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1031 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1032 contents: unsigned_announcement.clone(),
1035 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1037 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1041 // Now test if the transaction is found in the UTXO set and the script is correct.
1042 unsigned_announcement.short_channel_id += 1;
1043 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1045 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1046 let valid_announcement = ChannelAnnouncement {
1047 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1048 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1049 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1050 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1051 contents: unsigned_announcement.clone(),
1053 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1054 Ok(res) => assert!(res),
1059 let network = net_graph_msg_handler.network_graph.read().unwrap();
1060 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1066 // If we receive announcement for the same channel (but TX is not confirmed),
1067 // drop new one on the floor, since we can't see any changes.
1068 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1069 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1071 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1074 // But if it is confirmed, replace the channel
1075 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1076 unsigned_announcement.features = ChannelFeatures::empty();
1077 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1078 let valid_announcement = ChannelAnnouncement {
1079 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1080 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1081 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1082 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1083 contents: unsigned_announcement.clone(),
1085 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1086 Ok(res) => assert!(res),
1090 let network = net_graph_msg_handler.network_graph.read().unwrap();
1091 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1092 Some(channel_entry) => {
1093 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1099 // Don't relay valid channels with excess data
1100 unsigned_announcement.short_channel_id += 1;
1101 unsigned_announcement.excess_data.push(1);
1102 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1103 let valid_announcement = ChannelAnnouncement {
1104 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1105 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1106 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1107 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1108 contents: unsigned_announcement.clone(),
1110 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1111 Ok(res) => assert!(!res),
1115 unsigned_announcement.excess_data = Vec::new();
1116 let invalid_sig_announcement = ChannelAnnouncement {
1117 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1118 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1119 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1120 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1121 contents: unsigned_announcement.clone(),
1123 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1125 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1128 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1129 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1130 let channel_to_itself_announcement = ChannelAnnouncement {
1131 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1132 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1133 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1134 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1135 contents: unsigned_announcement.clone(),
1137 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1139 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1144 fn handling_channel_update() {
1145 let secp_ctx = Secp256k1::new();
1146 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1147 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1148 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1150 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1151 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1152 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1153 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1154 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1155 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1157 let zero_hash = Sha256dHash::hash(&[0; 32]);
1158 let short_channel_id = 0;
1159 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1160 let amount_sats = 1000_000;
1163 // Announce a channel we will update
1164 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1165 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1166 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1167 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1168 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1169 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1170 let unsigned_announcement = UnsignedChannelAnnouncement {
1171 features: ChannelFeatures::empty(),
1176 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1177 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1178 excess_data: Vec::new(),
1181 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1182 let valid_channel_announcement = ChannelAnnouncement {
1183 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1184 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1185 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1186 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1187 contents: unsigned_announcement.clone(),
1189 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1196 let mut unsigned_channel_update = UnsignedChannelUpdate {
1201 cltv_expiry_delta: 144,
1202 htlc_minimum_msat: 1000000,
1203 htlc_maximum_msat: OptionalField::Absent,
1204 fee_base_msat: 10000,
1205 fee_proportional_millionths: 20,
1206 excess_data: Vec::new()
1208 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1209 let valid_channel_update = ChannelUpdate {
1210 signature: secp_ctx.sign(&msghash, node_1_privkey),
1211 contents: unsigned_channel_update.clone()
1214 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1215 Ok(res) => assert!(res),
1220 let network = net_graph_msg_handler.network_graph.read().unwrap();
1221 match network.get_channels().get(&short_channel_id) {
1223 Some(channel_info) => {
1224 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1225 assert!(channel_info.two_to_one.is_none());
1230 unsigned_channel_update.timestamp += 100;
1231 unsigned_channel_update.excess_data.push(1);
1232 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1233 let valid_channel_update = ChannelUpdate {
1234 signature: secp_ctx.sign(&msghash, node_1_privkey),
1235 contents: unsigned_channel_update.clone()
1237 // Return false because contains excess data
1238 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1239 Ok(res) => assert!(!res),
1242 unsigned_channel_update.timestamp += 10;
1244 unsigned_channel_update.short_channel_id += 1;
1245 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1246 let valid_channel_update = ChannelUpdate {
1247 signature: secp_ctx.sign(&msghash, node_1_privkey),
1248 contents: unsigned_channel_update.clone()
1251 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1253 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1255 unsigned_channel_update.short_channel_id = short_channel_id;
1257 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 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()
1264 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1266 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1268 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1270 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 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()
1277 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1279 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1281 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1283 // Even though previous update was not relayed further, we still accepted it,
1284 // so we now won't accept update before the previous one.
1285 unsigned_channel_update.timestamp -= 10;
1286 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1287 let valid_channel_update = ChannelUpdate {
1288 signature: secp_ctx.sign(&msghash, node_1_privkey),
1289 contents: unsigned_channel_update.clone()
1292 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1294 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1296 unsigned_channel_update.timestamp += 500;
1298 let fake_msghash = hash_to_message!(&zero_hash);
1299 let invalid_sig_channel_update = ChannelUpdate {
1300 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1301 contents: unsigned_channel_update.clone()
1304 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1306 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1312 fn handling_htlc_fail_channel_update() {
1313 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1314 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1315 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1316 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1317 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1318 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1319 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1321 let short_channel_id = 0;
1322 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1325 // There is no nodes in the table at the beginning.
1326 let network = net_graph_msg_handler.network_graph.read().unwrap();
1327 assert_eq!(network.get_nodes().len(), 0);
1331 // Announce a channel we will update
1332 let unsigned_announcement = UnsignedChannelAnnouncement {
1333 features: ChannelFeatures::empty(),
1338 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1339 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1340 excess_data: Vec::new(),
1343 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1344 let valid_channel_announcement = ChannelAnnouncement {
1345 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1346 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1347 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1348 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1349 contents: unsigned_announcement.clone(),
1351 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1356 let unsigned_channel_update = UnsignedChannelUpdate {
1361 cltv_expiry_delta: 144,
1362 htlc_minimum_msat: 1000000,
1363 htlc_maximum_msat: OptionalField::Absent,
1364 fee_base_msat: 10000,
1365 fee_proportional_millionths: 20,
1366 excess_data: Vec::new()
1368 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1369 let valid_channel_update = ChannelUpdate {
1370 signature: secp_ctx.sign(&msghash, node_1_privkey),
1371 contents: unsigned_channel_update.clone()
1374 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1375 Ok(res) => assert!(res),
1380 // Non-permanent closing just disables a channel
1382 let network = net_graph_msg_handler.network_graph.read().unwrap();
1383 match network.get_channels().get(&short_channel_id) {
1385 Some(channel_info) => {
1386 assert!(channel_info.one_to_two.is_some());
1391 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1396 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1398 // Non-permanent closing just disables a channel
1400 let network = net_graph_msg_handler.network_graph.read().unwrap();
1401 match network.get_channels().get(&short_channel_id) {
1403 Some(channel_info) => {
1404 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1409 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1414 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1416 // Permanent closing deletes a channel
1418 let network = net_graph_msg_handler.network_graph.read().unwrap();
1419 assert_eq!(network.get_channels().len(), 0);
1420 // Nodes are also deleted because there are no associated channels anymore
1421 assert_eq!(network.get_nodes().len(), 0);
1423 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1427 fn getting_next_channel_announcements() {
1428 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1429 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1430 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1431 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1432 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1433 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1434 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1436 let short_channel_id = 1;
1437 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1439 // Channels were not announced yet.
1440 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1441 assert_eq!(channels_with_announcements.len(), 0);
1444 // Announce a channel we will update
1445 let unsigned_announcement = UnsignedChannelAnnouncement {
1446 features: ChannelFeatures::empty(),
1451 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1452 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1453 excess_data: Vec::new(),
1456 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1457 let valid_channel_announcement = ChannelAnnouncement {
1458 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1459 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1460 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1461 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1462 contents: unsigned_announcement.clone(),
1464 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1470 // Contains initial channel announcement now.
1471 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1472 assert_eq!(channels_with_announcements.len(), 1);
1473 if let Some(channel_announcements) = channels_with_announcements.first() {
1474 let &(_, ref update_1, ref update_2) = channel_announcements;
1475 assert_eq!(update_1, &None);
1476 assert_eq!(update_2, &None);
1483 // Valid channel update
1484 let unsigned_channel_update = UnsignedChannelUpdate {
1489 cltv_expiry_delta: 144,
1490 htlc_minimum_msat: 1000000,
1491 htlc_maximum_msat: OptionalField::Absent,
1492 fee_base_msat: 10000,
1493 fee_proportional_millionths: 20,
1494 excess_data: Vec::new()
1496 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1497 let valid_channel_update = ChannelUpdate {
1498 signature: secp_ctx.sign(&msghash, node_1_privkey),
1499 contents: unsigned_channel_update.clone()
1501 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1507 // Now contains an initial announcement and an update.
1508 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1509 assert_eq!(channels_with_announcements.len(), 1);
1510 if let Some(channel_announcements) = channels_with_announcements.first() {
1511 let &(_, ref update_1, ref update_2) = channel_announcements;
1512 assert_ne!(update_1, &None);
1513 assert_eq!(update_2, &None);
1520 // Channel update with excess data.
1521 let unsigned_channel_update = UnsignedChannelUpdate {
1526 cltv_expiry_delta: 144,
1527 htlc_minimum_msat: 1000000,
1528 htlc_maximum_msat: OptionalField::Absent,
1529 fee_base_msat: 10000,
1530 fee_proportional_millionths: 20,
1531 excess_data: [1; 3].to_vec()
1533 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1534 let valid_channel_update = ChannelUpdate {
1535 signature: secp_ctx.sign(&msghash, node_1_privkey),
1536 contents: unsigned_channel_update.clone()
1538 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1544 // Test that announcements with excess data won't be returned
1545 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1546 assert_eq!(channels_with_announcements.len(), 1);
1547 if let Some(channel_announcements) = channels_with_announcements.first() {
1548 let &(_, ref update_1, ref update_2) = channel_announcements;
1549 assert_eq!(update_1, &None);
1550 assert_eq!(update_2, &None);
1555 // Further starting point have no channels after it
1556 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1557 assert_eq!(channels_with_announcements.len(), 0);
1561 fn getting_next_node_announcements() {
1562 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1563 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1564 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1565 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1566 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1567 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1568 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1570 let short_channel_id = 1;
1571 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1574 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1575 assert_eq!(next_announcements.len(), 0);
1578 // Announce a channel to add 2 nodes
1579 let unsigned_announcement = UnsignedChannelAnnouncement {
1580 features: ChannelFeatures::empty(),
1585 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1586 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1587 excess_data: Vec::new(),
1590 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1591 let valid_channel_announcement = ChannelAnnouncement {
1592 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1593 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1594 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1595 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1596 contents: unsigned_announcement.clone(),
1598 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1605 // Nodes were never announced
1606 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1607 assert_eq!(next_announcements.len(), 0);
1610 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1611 features: NodeFeatures::known(),
1616 addresses: Vec::new(),
1617 excess_address_data: Vec::new(),
1618 excess_data: Vec::new(),
1620 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1621 let valid_announcement = NodeAnnouncement {
1622 signature: secp_ctx.sign(&msghash, node_1_privkey),
1623 contents: unsigned_announcement.clone()
1625 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1630 unsigned_announcement.node_id = node_id_2;
1631 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1632 let valid_announcement = NodeAnnouncement {
1633 signature: secp_ctx.sign(&msghash, node_2_privkey),
1634 contents: unsigned_announcement.clone()
1637 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1643 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1644 assert_eq!(next_announcements.len(), 2);
1646 // Skip the first node.
1647 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1648 assert_eq!(next_announcements.len(), 1);
1651 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1652 let unsigned_announcement = UnsignedNodeAnnouncement {
1653 features: NodeFeatures::known(),
1658 addresses: Vec::new(),
1659 excess_address_data: Vec::new(),
1660 excess_data: [1; 3].to_vec(),
1662 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1663 let valid_announcement = NodeAnnouncement {
1664 signature: secp_ctx.sign(&msghash, node_2_privkey),
1665 contents: unsigned_announcement.clone()
1667 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1668 Ok(res) => assert!(!res),
1673 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1674 assert_eq!(next_announcements.len(), 0);
1678 fn network_graph_serialization() {
1679 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1681 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1682 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1683 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1684 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1686 // Announce a channel to add a corresponding node.
1687 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1688 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1689 let unsigned_announcement = UnsignedChannelAnnouncement {
1690 features: ChannelFeatures::known(),
1691 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1692 short_channel_id: 0,
1695 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1696 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1697 excess_data: Vec::new(),
1700 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1701 let valid_announcement = ChannelAnnouncement {
1702 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1703 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1704 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1705 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1706 contents: unsigned_announcement.clone(),
1708 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1709 Ok(res) => assert!(res),
1714 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1715 let unsigned_announcement = UnsignedNodeAnnouncement {
1716 features: NodeFeatures::known(),
1721 addresses: Vec::new(),
1722 excess_address_data: Vec::new(),
1723 excess_data: Vec::new(),
1725 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1726 let valid_announcement = NodeAnnouncement {
1727 signature: secp_ctx.sign(&msghash, node_1_privkey),
1728 contents: unsigned_announcement.clone()
1731 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1736 let network = net_graph_msg_handler.network_graph.write().unwrap();
1737 let mut w = test_utils::TestVecWriter(Vec::new());
1738 assert!(!network.get_nodes().is_empty());
1739 assert!(!network.get_channels().is_empty());
1740 network.write(&mut w).unwrap();
1741 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);