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, RwLockReadGuard};
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 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
45 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
46 /// the C bindings, as it can be done directly in Rust code.
47 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
49 /// Receives and validates network updates from peers,
50 /// stores authentic and relevant data as a network graph.
51 /// This network graph is then used for routing payments.
52 /// Provides interface to help with initial routing sync by
53 /// serving historical announcements.
54 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
55 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
56 /// Representation of the payment channel network
57 pub network_graph: RwLock<NetworkGraph>,
59 full_syncs_requested: AtomicUsize,
63 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
64 /// Creates a new tracker of the actual state of the network of channels and nodes,
65 /// assuming a fresh network graph.
66 /// Chain monitor is used to make sure announced channels exist on-chain,
67 /// channel data is correct, and that the announcement is signed with
68 /// channel owners' keys.
69 pub fn new(chain_monitor: C, logger: L) -> Self {
71 secp_ctx: Secp256k1::verification_only(),
72 network_graph: RwLock::new(NetworkGraph {
73 channels: BTreeMap::new(),
74 nodes: BTreeMap::new(),
76 full_syncs_requested: AtomicUsize::new(0),
82 /// Creates a new tracker of the actual state of the network of channels and nodes,
83 /// assuming an existing Network Graph.
84 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
86 secp_ctx: Secp256k1::verification_only(),
87 network_graph: RwLock::new(network_graph),
88 full_syncs_requested: AtomicUsize::new(0),
94 /// Take a read lock on the network_graph and return it in the C-bindings
95 /// newtype helper. This is likely only useful when called via the C
96 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
98 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
99 LockedNetworkGraph(self.network_graph.read().unwrap())
103 impl<'a> LockedNetworkGraph<'a> {
104 /// Get a reference to the NetworkGraph which this read-lock contains.
105 pub fn graph(&self) -> &NetworkGraph {
111 macro_rules! secp_verify_sig {
112 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
113 match $secp_ctx.verify($msg, $sig, $pubkey) {
115 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
120 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
121 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
122 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
125 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
126 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
127 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
130 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
131 Ok((script_pubkey, value)) => {
132 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
133 .push_slice(&msg.contents.bitcoin_key_1.serialize())
134 .push_slice(&msg.contents.bitcoin_key_2.serialize())
135 .push_opcode(opcodes::all::OP_PUSHNUM_2)
136 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
137 if script_pubkey != expected_script {
138 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});
140 //TODO: Check if value is worth storing, use it to inform routing, and compare it
141 //to the new HTLC max field in channel_update
144 Err(ChainError::NotSupported) => {
145 // Tentatively accept, potentially exposing us to DoS attacks
148 Err(ChainError::NotWatched) => {
149 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
151 Err(ChainError::UnknownTx) => {
152 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
155 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
156 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 { "" });
160 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
162 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
163 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
165 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
166 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
168 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
169 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
174 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
175 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
178 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
179 let network_graph = self.network_graph.read().unwrap();
180 let mut result = Vec::with_capacity(batch_amount as usize);
181 let mut iter = network_graph.get_channels().range(starting_point..);
182 while result.len() < batch_amount as usize {
183 if let Some((_, ref chan)) = iter.next() {
184 if chan.announcement_message.is_some() {
185 let chan_announcement = chan.announcement_message.clone().unwrap();
186 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
187 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
188 if let Some(one_to_two) = chan.one_to_two.as_ref() {
189 one_to_two_announcement = one_to_two.last_update_message.clone();
191 if let Some(two_to_one) = chan.two_to_one.as_ref() {
192 two_to_one_announcement = two_to_one.last_update_message.clone();
194 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
196 // TODO: We may end up sending un-announced channel_updates if we are sending
197 // initial sync data while receiving announce/updates for this channel.
206 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
207 let network_graph = self.network_graph.read().unwrap();
208 let mut result = Vec::with_capacity(batch_amount as usize);
209 let mut iter = if let Some(pubkey) = starting_point {
210 let mut iter = network_graph.get_nodes().range((*pubkey)..);
214 network_graph.get_nodes().range(..)
216 while result.len() < batch_amount as usize {
217 if let Some((_, ref node)) = iter.next() {
218 if let Some(node_info) = node.announcement_info.as_ref() {
219 if node_info.announcement_message.is_some() {
220 result.push(node_info.announcement_message.clone().unwrap());
230 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
231 //TODO: Determine whether to request a full sync based on the network map.
232 const FULL_SYNCS_TO_REQUEST: usize = 5;
233 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
234 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
242 #[derive(PartialEq, Debug)]
243 /// Details about one direction of a channel. Received
244 /// within a channel update.
245 pub struct DirectionalChannelInfo {
246 /// When the last update to the channel direction was issued.
247 /// Value is opaque, as set in the announcement.
248 pub last_update: u32,
249 /// Whether the channel can be currently used for payments (in this one direction).
251 /// The difference in CLTV values that you must have when routing through this channel.
252 pub cltv_expiry_delta: u16,
253 /// The minimum value, which must be relayed to the next hop via the channel
254 pub htlc_minimum_msat: u64,
255 /// The maximum value which may be relayed to the next hop via the channel.
256 pub htlc_maximum_msat: Option<u64>,
257 /// Fees charged when the channel is used for routing
258 pub fees: RoutingFees,
259 /// Most recent update for the channel received from the network
260 /// Mostly redundant with the data we store in fields explicitly.
261 /// Everything else is useful only for sending out for initial routing sync.
262 /// Not stored if contains excess data to prevent DoS.
263 pub last_update_message: Option<ChannelUpdate>,
266 impl fmt::Display for DirectionalChannelInfo {
267 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
268 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)?;
273 impl_writeable!(DirectionalChannelInfo, 0, {
284 /// Details about a channel (both directions).
285 /// Received within a channel announcement.
286 pub struct ChannelInfo {
287 /// Protocol features of a channel communicated during its announcement
288 pub features: ChannelFeatures,
289 /// Source node of the first direction of a channel
290 pub node_one: PublicKey,
291 /// Details about the first direction of a channel
292 pub one_to_two: Option<DirectionalChannelInfo>,
293 /// Source node of the second direction of a channel
294 pub node_two: PublicKey,
295 /// Details about the second direction of a channel
296 pub two_to_one: Option<DirectionalChannelInfo>,
297 /// The channel capacity as seen on-chain, if chain lookup is available.
298 pub capacity_sats: Option<u64>,
299 /// An initial announcement of the channel
300 /// Mostly redundant with the data we store in fields explicitly.
301 /// Everything else is useful only for sending out for initial routing sync.
302 /// Not stored if contains excess data to prevent DoS.
303 pub announcement_message: Option<ChannelAnnouncement>,
306 impl fmt::Display for ChannelInfo {
307 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
308 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
309 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
314 impl_writeable!(ChannelInfo, 0, {
325 /// Fees for routing via a given channel or a node
326 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
327 pub struct RoutingFees {
328 /// Flat routing fee in satoshis
330 /// Liquidity-based routing fee in millionths of a routed amount.
331 /// In other words, 10000 is 1%.
332 pub proportional_millionths: u32,
335 impl Readable for RoutingFees{
336 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
337 let base_msat: u32 = Readable::read(reader)?;
338 let proportional_millionths: u32 = Readable::read(reader)?;
341 proportional_millionths,
346 impl Writeable for RoutingFees {
347 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
348 self.base_msat.write(writer)?;
349 self.proportional_millionths.write(writer)?;
354 #[derive(PartialEq, Debug)]
355 /// Information received in the latest node_announcement from this node.
356 pub struct NodeAnnouncementInfo {
357 /// Protocol features the node announced support for
358 pub features: NodeFeatures,
359 /// When the last known update to the node state was issued.
360 /// Value is opaque, as set in the announcement.
361 pub last_update: u32,
362 /// Color assigned to the node
364 /// Moniker assigned to the node.
365 /// May be invalid or malicious (eg control chars),
366 /// should not be exposed to the user.
368 /// Internet-level addresses via which one can connect to the node
369 pub addresses: Vec<NetAddress>,
370 /// An initial announcement of the node
371 /// Mostly redundant with the data we store in fields explicitly.
372 /// Everything else is useful only for sending out for initial routing sync.
373 /// Not stored if contains excess data to prevent DoS.
374 pub announcement_message: Option<NodeAnnouncement>
377 impl Writeable for NodeAnnouncementInfo {
378 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
379 self.features.write(writer)?;
380 self.last_update.write(writer)?;
381 self.rgb.write(writer)?;
382 self.alias.write(writer)?;
383 (self.addresses.len() as u64).write(writer)?;
384 for ref addr in &self.addresses {
387 self.announcement_message.write(writer)?;
392 impl Readable for NodeAnnouncementInfo {
393 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
394 let features = Readable::read(reader)?;
395 let last_update = Readable::read(reader)?;
396 let rgb = Readable::read(reader)?;
397 let alias = Readable::read(reader)?;
398 let addresses_count: u64 = Readable::read(reader)?;
399 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
400 for _ in 0..addresses_count {
401 match Readable::read(reader) {
402 Ok(Ok(addr)) => { addresses.push(addr); },
403 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
404 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
408 let announcement_message = Readable::read(reader)?;
409 Ok(NodeAnnouncementInfo {
421 /// Details about a node in the network, known from the network announcement.
422 pub struct NodeInfo {
423 /// All valid channels a node has announced
424 pub channels: Vec<u64>,
425 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
426 /// The two fields (flat and proportional fee) are independent,
427 /// meaning they don't have to refer to the same channel.
428 pub lowest_inbound_channel_fees: Option<RoutingFees>,
429 /// More information about a node from node_announcement.
430 /// Optional because we store a Node entry after learning about it from
431 /// a channel announcement, but before receiving a node announcement.
432 pub announcement_info: Option<NodeAnnouncementInfo>
435 impl fmt::Display for NodeInfo {
436 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
437 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
438 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
443 impl Writeable for NodeInfo {
444 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
445 (self.channels.len() as u64).write(writer)?;
446 for ref chan in self.channels.iter() {
449 self.lowest_inbound_channel_fees.write(writer)?;
450 self.announcement_info.write(writer)?;
455 const MAX_ALLOC_SIZE: u64 = 64*1024;
457 impl Readable for NodeInfo {
458 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
459 let channels_count: u64 = Readable::read(reader)?;
460 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
461 for _ in 0..channels_count {
462 channels.push(Readable::read(reader)?);
464 let lowest_inbound_channel_fees = Readable::read(reader)?;
465 let announcement_info = Readable::read(reader)?;
468 lowest_inbound_channel_fees,
474 impl Writeable for NetworkGraph {
475 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
476 (self.channels.len() as u64).write(writer)?;
477 for (ref chan_id, ref chan_info) in self.channels.iter() {
478 (*chan_id).write(writer)?;
479 chan_info.write(writer)?;
481 (self.nodes.len() as u64).write(writer)?;
482 for (ref node_id, ref node_info) in self.nodes.iter() {
483 node_id.write(writer)?;
484 node_info.write(writer)?;
490 impl Readable for NetworkGraph {
491 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
492 let channels_count: u64 = Readable::read(reader)?;
493 let mut channels = BTreeMap::new();
494 for _ in 0..channels_count {
495 let chan_id: u64 = Readable::read(reader)?;
496 let chan_info = Readable::read(reader)?;
497 channels.insert(chan_id, chan_info);
499 let nodes_count: u64 = Readable::read(reader)?;
500 let mut nodes = BTreeMap::new();
501 for _ in 0..nodes_count {
502 let node_id = Readable::read(reader)?;
503 let node_info = Readable::read(reader)?;
504 nodes.insert(node_id, node_info);
513 impl fmt::Display for NetworkGraph {
514 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
515 write!(f, "Network map\n[Channels]\n")?;
516 for (key, val) in self.channels.iter() {
517 write!(f, " {}: {}\n", key, val)?;
519 write!(f, "[Nodes]\n")?;
520 for (key, val) in self.nodes.iter() {
521 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
528 /// Returns all known valid channels' short ids along with announced channel info.
530 /// (C-not exported) because we have no mapping for `BTreeMap`s
531 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
532 /// Returns all known nodes' public keys along with announced node info.
534 /// (C-not exported) because we have no mapping for `BTreeMap`s
535 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
537 /// Get network addresses by node id.
538 /// Returns None if the requested node is completely unknown,
539 /// or if node announcement for the node was never received.
541 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
542 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
543 if let Some(node) = self.nodes.get(pubkey) {
544 if let Some(node_info) = node.announcement_info.as_ref() {
545 return Some(&node_info.addresses)
551 /// Creates a new, empty, network graph.
552 pub fn new() -> NetworkGraph {
554 channels: BTreeMap::new(),
555 nodes: BTreeMap::new(),
559 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
560 /// Announcement signatures are checked here only if Secp256k1 object is provided.
561 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
562 if let Some(sig_verifier) = secp_ctx {
563 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
564 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
567 match self.nodes.get_mut(&msg.contents.node_id) {
568 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
570 if let Some(node_info) = node.announcement_info.as_ref() {
571 if node_info.last_update >= msg.contents.timestamp {
572 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
576 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
577 node.announcement_info = Some(NodeAnnouncementInfo {
578 features: msg.contents.features.clone(),
579 last_update: msg.contents.timestamp,
580 rgb: msg.contents.rgb,
581 alias: msg.contents.alias,
582 addresses: msg.contents.addresses.clone(),
583 announcement_message: if should_relay { Some(msg.clone()) } else { None },
591 /// For a new or already known (from previous announcement) channel, store or update channel info.
592 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
593 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
594 /// which is probably result of a reorg. In that case, we update channel info only if the
595 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
596 /// Announcement signatures are checked here only if Secp256k1 object is provided.
597 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
598 if let Some(sig_verifier) = secp_ctx {
599 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
600 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
601 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
602 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
603 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
606 let should_relay = msg.contents.excess_data.is_empty();
608 let chan_info = ChannelInfo {
609 features: msg.contents.features.clone(),
610 node_one: msg.contents.node_id_1.clone(),
612 node_two: msg.contents.node_id_2.clone(),
614 capacity_sats: utxo_value,
615 announcement_message: if should_relay { Some(msg.clone()) } else { None },
618 match self.channels.entry(msg.contents.short_channel_id) {
619 BtreeEntry::Occupied(mut entry) => {
620 //TODO: because asking the blockchain if short_channel_id is valid is only optional
621 //in the blockchain API, we need to handle it smartly here, though it's unclear
623 if utxo_value.is_some() {
624 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
625 // only sometimes returns results. In any case remove the previous entry. Note
626 // that the spec expects us to "blacklist" the node_ids involved, but we can't
628 // a) we don't *require* a UTXO provider that always returns results.
629 // b) we don't track UTXOs of channels we know about and remove them if they
631 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
632 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
633 *entry.get_mut() = chan_info;
635 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
638 BtreeEntry::Vacant(entry) => {
639 entry.insert(chan_info);
643 macro_rules! add_channel_to_node {
644 ( $node_id: expr ) => {
645 match self.nodes.entry($node_id) {
646 BtreeEntry::Occupied(node_entry) => {
647 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
649 BtreeEntry::Vacant(node_entry) => {
650 node_entry.insert(NodeInfo {
651 channels: vec!(msg.contents.short_channel_id),
652 lowest_inbound_channel_fees: None,
653 announcement_info: None,
660 add_channel_to_node!(msg.contents.node_id_1);
661 add_channel_to_node!(msg.contents.node_id_2);
666 /// Close a channel if a corresponding HTLC fail was sent.
667 /// If permanent, removes a channel from the local storage.
668 /// May cause the removal of nodes too, if this was their last channel.
669 /// If not permanent, makes channels unavailable for routing.
670 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
672 if let Some(chan) = self.channels.remove(&short_channel_id) {
673 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
676 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
677 if let Some(one_to_two) = chan.one_to_two.as_mut() {
678 one_to_two.enabled = false;
680 if let Some(two_to_one) = chan.two_to_one.as_mut() {
681 two_to_one.enabled = false;
687 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
689 // TODO: Wholly remove the node
691 // TODO: downgrade the node
695 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
696 /// Announcement signatures are checked here only if Secp256k1 object is provided.
697 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
699 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
700 let chan_was_enabled;
702 match self.channels.get_mut(&msg.contents.short_channel_id) {
703 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
705 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
706 if htlc_maximum_msat > MAX_VALUE_MSAT {
707 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
710 if let Some(capacity_sats) = channel.capacity_sats {
711 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
712 // Don't query UTXO set here to reduce DoS risks.
713 if htlc_maximum_msat > capacity_sats * 1000 {
714 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
718 macro_rules! maybe_update_channel_info {
719 ( $target: expr, $src_node: expr) => {
720 if let Some(existing_chan_info) = $target.as_ref() {
721 if existing_chan_info.last_update >= msg.contents.timestamp {
722 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
724 chan_was_enabled = existing_chan_info.enabled;
726 chan_was_enabled = false;
729 let last_update_message = if msg.contents.excess_data.is_empty() {
735 let updated_channel_dir_info = DirectionalChannelInfo {
736 enabled: chan_enabled,
737 last_update: msg.contents.timestamp,
738 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
739 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
740 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
742 base_msat: msg.contents.fee_base_msat,
743 proportional_millionths: msg.contents.fee_proportional_millionths,
747 $target = Some(updated_channel_dir_info);
751 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
752 if msg.contents.flags & 1 == 1 {
753 dest_node_id = channel.node_one.clone();
754 if let Some(sig_verifier) = secp_ctx {
755 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
757 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
759 dest_node_id = channel.node_two.clone();
760 if let Some(sig_verifier) = secp_ctx {
761 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
763 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
769 let node = self.nodes.get_mut(&dest_node_id).unwrap();
770 let mut base_msat = msg.contents.fee_base_msat;
771 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
772 if let Some(fees) = node.lowest_inbound_channel_fees {
773 base_msat = cmp::min(base_msat, fees.base_msat);
774 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
776 node.lowest_inbound_channel_fees = Some(RoutingFees {
778 proportional_millionths
780 } else if chan_was_enabled {
781 let node = self.nodes.get_mut(&dest_node_id).unwrap();
782 let mut lowest_inbound_channel_fees = None;
784 for chan_id in node.channels.iter() {
785 let chan = self.channels.get(chan_id).unwrap();
787 if chan.node_one == dest_node_id {
788 chan_info_opt = chan.two_to_one.as_ref();
790 chan_info_opt = chan.one_to_two.as_ref();
792 if let Some(chan_info) = chan_info_opt {
793 if chan_info.enabled {
794 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
795 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
796 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
797 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
802 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
805 Ok(msg.contents.excess_data.is_empty())
808 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
809 macro_rules! remove_from_node {
810 ($node_id: expr) => {
811 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
812 entry.get_mut().channels.retain(|chan_id| {
813 short_channel_id != *chan_id
815 if entry.get().channels.is_empty() {
816 entry.remove_entry();
819 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
824 remove_from_node!(chan.node_one);
825 remove_from_node!(chan.node_two);
831 use chain::chaininterface;
832 use ln::features::{ChannelFeatures, NodeFeatures};
833 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
834 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
835 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
837 use util::test_utils;
838 use util::logger::Logger;
839 use util::ser::{Readable, Writeable};
841 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
842 use bitcoin::hashes::Hash;
843 use bitcoin::network::constants::Network;
844 use bitcoin::blockdata::constants::genesis_block;
845 use bitcoin::blockdata::script::Builder;
846 use bitcoin::blockdata::opcodes;
850 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
851 use bitcoin::secp256k1::{All, Secp256k1};
855 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
856 let secp_ctx = Secp256k1::new();
857 let logger = Arc::new(test_utils::TestLogger::new());
858 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
859 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
860 (secp_ctx, net_graph_msg_handler)
864 fn request_full_sync_finite_times() {
865 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
866 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
868 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
869 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
870 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
871 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
872 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
873 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
877 fn handling_node_announcements() {
878 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
880 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
881 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
882 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
883 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
884 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
885 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
886 let zero_hash = Sha256dHash::hash(&[0; 32]);
887 let first_announcement_time = 500;
889 let mut unsigned_announcement = UnsignedNodeAnnouncement {
890 features: NodeFeatures::known(),
891 timestamp: first_announcement_time,
895 addresses: Vec::new(),
896 excess_address_data: Vec::new(),
897 excess_data: Vec::new(),
899 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
900 let valid_announcement = NodeAnnouncement {
901 signature: secp_ctx.sign(&msghash, node_1_privkey),
902 contents: unsigned_announcement.clone()
905 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
907 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
911 // Announce a channel to add a corresponding node.
912 let unsigned_announcement = UnsignedChannelAnnouncement {
913 features: ChannelFeatures::known(),
914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
918 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
919 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
920 excess_data: Vec::new(),
923 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
924 let valid_announcement = ChannelAnnouncement {
925 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
926 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
927 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
928 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
929 contents: unsigned_announcement.clone(),
931 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
932 Ok(res) => assert!(res),
937 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
938 Ok(res) => assert!(res),
942 let fake_msghash = hash_to_message!(&zero_hash);
943 match net_graph_msg_handler.handle_node_announcement(
945 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
946 contents: unsigned_announcement.clone()
949 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
952 unsigned_announcement.timestamp += 1000;
953 unsigned_announcement.excess_data.push(1);
954 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
955 let announcement_with_data = NodeAnnouncement {
956 signature: secp_ctx.sign(&msghash, node_1_privkey),
957 contents: unsigned_announcement.clone()
959 // Return false because contains excess data.
960 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
961 Ok(res) => assert!(!res),
964 unsigned_announcement.excess_data = Vec::new();
966 // Even though previous announcement was not relayed further, we still accepted it,
967 // so we now won't accept announcements before the previous one.
968 unsigned_announcement.timestamp -= 10;
969 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
970 let outdated_announcement = NodeAnnouncement {
971 signature: secp_ctx.sign(&msghash, node_1_privkey),
972 contents: unsigned_announcement.clone()
974 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
976 Err(e) => assert_eq!(e.err, "Update older than last processed update")
981 fn handling_channel_announcements() {
982 let secp_ctx = Secp256k1::new();
983 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
984 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
985 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
988 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
989 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
990 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
991 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
992 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
993 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
995 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
996 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
997 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
998 .push_opcode(opcodes::all::OP_PUSHNUM_2)
999 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1002 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1003 features: ChannelFeatures::known(),
1004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1005 short_channel_id: 0,
1008 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1009 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1010 excess_data: Vec::new(),
1013 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1014 let valid_announcement = ChannelAnnouncement {
1015 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1016 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1017 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1018 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1019 contents: unsigned_announcement.clone(),
1022 // Test if the UTXO lookups were not supported
1023 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
1025 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1026 Ok(res) => assert!(res),
1031 let network = net_graph_msg_handler.network_graph.read().unwrap();
1032 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1039 // If we receive announcement for the same channel (with UTXO lookups disabled),
1040 // drop new one on the floor, since we can't see any changes.
1041 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1043 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1047 // Test if an associated transaction were not on-chain (or not confirmed).
1048 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1049 unsigned_announcement.short_channel_id += 1;
1051 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1052 let valid_announcement = ChannelAnnouncement {
1053 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1054 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1055 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1056 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1057 contents: unsigned_announcement.clone(),
1060 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1062 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1066 // Now test if the transaction is found in the UTXO set and the script is correct.
1067 unsigned_announcement.short_channel_id += 1;
1068 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1070 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1071 let valid_announcement = ChannelAnnouncement {
1072 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1073 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1074 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1075 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1076 contents: unsigned_announcement.clone(),
1078 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1079 Ok(res) => assert!(res),
1084 let network = net_graph_msg_handler.network_graph.read().unwrap();
1085 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1091 // If we receive announcement for the same channel (but TX is not confirmed),
1092 // drop new one on the floor, since we can't see any changes.
1093 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1094 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1096 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1099 // But if it is confirmed, replace the channel
1100 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1101 unsigned_announcement.features = ChannelFeatures::empty();
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 let network = net_graph_msg_handler.network_graph.read().unwrap();
1116 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1117 Some(channel_entry) => {
1118 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1124 // Don't relay valid channels with excess data
1125 unsigned_announcement.short_channel_id += 1;
1126 unsigned_announcement.excess_data.push(1);
1127 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1128 let valid_announcement = ChannelAnnouncement {
1129 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1130 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1131 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1132 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1133 contents: unsigned_announcement.clone(),
1135 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1136 Ok(res) => assert!(!res),
1140 unsigned_announcement.excess_data = Vec::new();
1141 let invalid_sig_announcement = ChannelAnnouncement {
1142 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1143 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1144 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1145 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1146 contents: unsigned_announcement.clone(),
1148 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1150 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1153 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1154 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1155 let channel_to_itself_announcement = ChannelAnnouncement {
1156 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1157 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1158 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1159 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1160 contents: unsigned_announcement.clone(),
1162 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1164 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1169 fn handling_channel_update() {
1170 let secp_ctx = Secp256k1::new();
1171 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1172 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1173 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1175 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1176 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1177 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1178 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1179 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1180 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1182 let zero_hash = Sha256dHash::hash(&[0; 32]);
1183 let short_channel_id = 0;
1184 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1185 let amount_sats = 1000_000;
1188 // Announce a channel we will update
1189 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1190 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1191 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1192 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1193 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1194 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1195 let unsigned_announcement = UnsignedChannelAnnouncement {
1196 features: ChannelFeatures::empty(),
1201 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1202 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1203 excess_data: Vec::new(),
1206 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1207 let valid_channel_announcement = ChannelAnnouncement {
1208 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1209 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1210 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1211 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1212 contents: unsigned_announcement.clone(),
1214 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1221 let mut unsigned_channel_update = UnsignedChannelUpdate {
1226 cltv_expiry_delta: 144,
1227 htlc_minimum_msat: 1000000,
1228 htlc_maximum_msat: OptionalField::Absent,
1229 fee_base_msat: 10000,
1230 fee_proportional_millionths: 20,
1231 excess_data: Vec::new()
1233 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1234 let valid_channel_update = ChannelUpdate {
1235 signature: secp_ctx.sign(&msghash, node_1_privkey),
1236 contents: unsigned_channel_update.clone()
1239 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1240 Ok(res) => assert!(res),
1245 let network = net_graph_msg_handler.network_graph.read().unwrap();
1246 match network.get_channels().get(&short_channel_id) {
1248 Some(channel_info) => {
1249 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1250 assert!(channel_info.two_to_one.is_none());
1255 unsigned_channel_update.timestamp += 100;
1256 unsigned_channel_update.excess_data.push(1);
1257 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1258 let valid_channel_update = ChannelUpdate {
1259 signature: secp_ctx.sign(&msghash, node_1_privkey),
1260 contents: unsigned_channel_update.clone()
1262 // Return false because contains excess data
1263 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1264 Ok(res) => assert!(!res),
1267 unsigned_channel_update.timestamp += 10;
1269 unsigned_channel_update.short_channel_id += 1;
1270 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1271 let valid_channel_update = ChannelUpdate {
1272 signature: secp_ctx.sign(&msghash, node_1_privkey),
1273 contents: unsigned_channel_update.clone()
1276 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1278 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1280 unsigned_channel_update.short_channel_id = short_channel_id;
1282 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1283 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1284 let valid_channel_update = ChannelUpdate {
1285 signature: secp_ctx.sign(&msghash, node_1_privkey),
1286 contents: unsigned_channel_update.clone()
1289 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1291 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1293 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1295 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1296 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1297 let valid_channel_update = ChannelUpdate {
1298 signature: secp_ctx.sign(&msghash, node_1_privkey),
1299 contents: unsigned_channel_update.clone()
1302 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1304 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1306 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1308 // Even though previous update was not relayed further, we still accepted it,
1309 // so we now won't accept update before the previous one.
1310 unsigned_channel_update.timestamp -= 10;
1311 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1312 let valid_channel_update = ChannelUpdate {
1313 signature: secp_ctx.sign(&msghash, node_1_privkey),
1314 contents: unsigned_channel_update.clone()
1317 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1319 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1321 unsigned_channel_update.timestamp += 500;
1323 let fake_msghash = hash_to_message!(&zero_hash);
1324 let invalid_sig_channel_update = ChannelUpdate {
1325 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1326 contents: unsigned_channel_update.clone()
1329 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1331 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1337 fn handling_htlc_fail_channel_update() {
1338 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1339 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1340 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1341 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1342 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1343 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1344 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1346 let short_channel_id = 0;
1347 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1350 // There is no nodes in the table at the beginning.
1351 let network = net_graph_msg_handler.network_graph.read().unwrap();
1352 assert_eq!(network.get_nodes().len(), 0);
1356 // Announce a channel we will update
1357 let unsigned_announcement = UnsignedChannelAnnouncement {
1358 features: ChannelFeatures::empty(),
1363 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1364 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1365 excess_data: Vec::new(),
1368 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1369 let valid_channel_announcement = ChannelAnnouncement {
1370 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1371 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1372 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1373 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1374 contents: unsigned_announcement.clone(),
1376 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1381 let unsigned_channel_update = UnsignedChannelUpdate {
1386 cltv_expiry_delta: 144,
1387 htlc_minimum_msat: 1000000,
1388 htlc_maximum_msat: OptionalField::Absent,
1389 fee_base_msat: 10000,
1390 fee_proportional_millionths: 20,
1391 excess_data: Vec::new()
1393 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1394 let valid_channel_update = ChannelUpdate {
1395 signature: secp_ctx.sign(&msghash, node_1_privkey),
1396 contents: unsigned_channel_update.clone()
1399 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1400 Ok(res) => assert!(res),
1405 // Non-permanent closing just disables a channel
1407 let network = net_graph_msg_handler.network_graph.read().unwrap();
1408 match network.get_channels().get(&short_channel_id) {
1410 Some(channel_info) => {
1411 assert!(channel_info.one_to_two.is_some());
1416 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1421 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1423 // Non-permanent closing just disables a channel
1425 let network = net_graph_msg_handler.network_graph.read().unwrap();
1426 match network.get_channels().get(&short_channel_id) {
1428 Some(channel_info) => {
1429 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1434 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1439 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1441 // Permanent closing deletes a channel
1443 let network = net_graph_msg_handler.network_graph.read().unwrap();
1444 assert_eq!(network.get_channels().len(), 0);
1445 // Nodes are also deleted because there are no associated channels anymore
1446 assert_eq!(network.get_nodes().len(), 0);
1448 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1452 fn getting_next_channel_announcements() {
1453 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1454 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1455 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1456 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1457 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1458 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1459 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1461 let short_channel_id = 1;
1462 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1464 // Channels were not announced yet.
1465 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1466 assert_eq!(channels_with_announcements.len(), 0);
1469 // Announce a channel we will update
1470 let unsigned_announcement = UnsignedChannelAnnouncement {
1471 features: ChannelFeatures::empty(),
1476 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1477 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1478 excess_data: Vec::new(),
1481 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1482 let valid_channel_announcement = ChannelAnnouncement {
1483 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1484 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1485 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1486 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1487 contents: unsigned_announcement.clone(),
1489 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1495 // Contains initial channel announcement now.
1496 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1497 assert_eq!(channels_with_announcements.len(), 1);
1498 if let Some(channel_announcements) = channels_with_announcements.first() {
1499 let &(_, ref update_1, ref update_2) = channel_announcements;
1500 assert_eq!(update_1, &None);
1501 assert_eq!(update_2, &None);
1508 // Valid channel update
1509 let unsigned_channel_update = UnsignedChannelUpdate {
1514 cltv_expiry_delta: 144,
1515 htlc_minimum_msat: 1000000,
1516 htlc_maximum_msat: OptionalField::Absent,
1517 fee_base_msat: 10000,
1518 fee_proportional_millionths: 20,
1519 excess_data: Vec::new()
1521 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1522 let valid_channel_update = ChannelUpdate {
1523 signature: secp_ctx.sign(&msghash, node_1_privkey),
1524 contents: unsigned_channel_update.clone()
1526 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1532 // Now contains an initial announcement and an update.
1533 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1534 assert_eq!(channels_with_announcements.len(), 1);
1535 if let Some(channel_announcements) = channels_with_announcements.first() {
1536 let &(_, ref update_1, ref update_2) = channel_announcements;
1537 assert_ne!(update_1, &None);
1538 assert_eq!(update_2, &None);
1545 // Channel update with excess data.
1546 let unsigned_channel_update = UnsignedChannelUpdate {
1551 cltv_expiry_delta: 144,
1552 htlc_minimum_msat: 1000000,
1553 htlc_maximum_msat: OptionalField::Absent,
1554 fee_base_msat: 10000,
1555 fee_proportional_millionths: 20,
1556 excess_data: [1; 3].to_vec()
1558 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1559 let valid_channel_update = ChannelUpdate {
1560 signature: secp_ctx.sign(&msghash, node_1_privkey),
1561 contents: unsigned_channel_update.clone()
1563 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1569 // Test that announcements with excess data won't be returned
1570 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1571 assert_eq!(channels_with_announcements.len(), 1);
1572 if let Some(channel_announcements) = channels_with_announcements.first() {
1573 let &(_, ref update_1, ref update_2) = channel_announcements;
1574 assert_eq!(update_1, &None);
1575 assert_eq!(update_2, &None);
1580 // Further starting point have no channels after it
1581 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1582 assert_eq!(channels_with_announcements.len(), 0);
1586 fn getting_next_node_announcements() {
1587 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1588 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1589 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1590 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1591 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1592 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1593 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1595 let short_channel_id = 1;
1596 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1599 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1600 assert_eq!(next_announcements.len(), 0);
1603 // Announce a channel to add 2 nodes
1604 let unsigned_announcement = UnsignedChannelAnnouncement {
1605 features: ChannelFeatures::empty(),
1610 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1611 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1612 excess_data: Vec::new(),
1615 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1616 let valid_channel_announcement = ChannelAnnouncement {
1617 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1618 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1619 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1620 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1621 contents: unsigned_announcement.clone(),
1623 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1630 // Nodes were never announced
1631 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1632 assert_eq!(next_announcements.len(), 0);
1635 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1636 features: NodeFeatures::known(),
1641 addresses: Vec::new(),
1642 excess_address_data: Vec::new(),
1643 excess_data: Vec::new(),
1645 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1646 let valid_announcement = NodeAnnouncement {
1647 signature: secp_ctx.sign(&msghash, node_1_privkey),
1648 contents: unsigned_announcement.clone()
1650 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1655 unsigned_announcement.node_id = node_id_2;
1656 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1657 let valid_announcement = NodeAnnouncement {
1658 signature: secp_ctx.sign(&msghash, node_2_privkey),
1659 contents: unsigned_announcement.clone()
1662 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1668 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1669 assert_eq!(next_announcements.len(), 2);
1671 // Skip the first node.
1672 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1673 assert_eq!(next_announcements.len(), 1);
1676 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1677 let unsigned_announcement = UnsignedNodeAnnouncement {
1678 features: NodeFeatures::known(),
1683 addresses: Vec::new(),
1684 excess_address_data: Vec::new(),
1685 excess_data: [1; 3].to_vec(),
1687 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1688 let valid_announcement = NodeAnnouncement {
1689 signature: secp_ctx.sign(&msghash, node_2_privkey),
1690 contents: unsigned_announcement.clone()
1692 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1693 Ok(res) => assert!(!res),
1698 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1699 assert_eq!(next_announcements.len(), 0);
1703 fn network_graph_serialization() {
1704 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1706 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1707 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1708 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1709 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1711 // Announce a channel to add a corresponding node.
1712 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1713 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1714 let unsigned_announcement = UnsignedChannelAnnouncement {
1715 features: ChannelFeatures::known(),
1716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1717 short_channel_id: 0,
1720 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1721 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1722 excess_data: Vec::new(),
1725 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1726 let valid_announcement = ChannelAnnouncement {
1727 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1728 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1729 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1730 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1731 contents: unsigned_announcement.clone(),
1733 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1734 Ok(res) => assert!(res),
1739 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1740 let unsigned_announcement = UnsignedNodeAnnouncement {
1741 features: NodeFeatures::known(),
1746 addresses: Vec::new(),
1747 excess_address_data: Vec::new(),
1748 excess_data: Vec::new(),
1750 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1751 let valid_announcement = NodeAnnouncement {
1752 signature: secp_ctx.sign(&msghash, node_1_privkey),
1753 contents: unsigned_announcement.clone()
1756 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1761 let network = net_graph_msg_handler.network_graph.write().unwrap();
1762 let mut w = test_utils::TestVecWriter(Vec::new());
1763 assert!(!network.get_nodes().is_empty());
1764 assert!(!network.get_channels().is_empty());
1765 network.write(&mut w).unwrap();
1766 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);