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, OptionalField, MAX_VALUE_MSAT};
25 use util::ser::{Writeable, Readable, Writer};
26 use util::logger::Logger;
29 use std::sync::RwLock;
30 use std::sync::atomic::{AtomicUsize, Ordering};
31 use std::collections::BTreeMap;
32 use std::collections::btree_map::Entry as BtreeEntry;
34 use bitcoin::hashes::hex::ToHex;
36 /// Represents the network as nodes and channels between them
38 pub struct NetworkGraph {
39 channels: BTreeMap<u64, ChannelInfo>,
40 nodes: BTreeMap<PublicKey, NodeInfo>,
43 /// Receives and validates network updates from peers,
44 /// stores authentic and relevant data as a network graph.
45 /// This network graph is then used for routing payments.
46 /// Provides interface to help with initial routing sync by
47 /// serving historical announcements.
48 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
49 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
50 /// Representation of the payment channel network
51 pub network_graph: RwLock<NetworkGraph>,
53 full_syncs_requested: AtomicUsize,
57 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
58 /// Creates a new tracker of the actual state of the network of channels and nodes,
59 /// assuming a fresh network graph.
60 /// Chain monitor is used to make sure announced channels exist on-chain,
61 /// channel data is correct, and that the announcement is signed with
62 /// channel owners' keys.
63 pub fn new(chain_monitor: C, logger: L) -> Self {
65 secp_ctx: Secp256k1::verification_only(),
66 network_graph: RwLock::new(NetworkGraph {
67 channels: BTreeMap::new(),
68 nodes: BTreeMap::new(),
70 full_syncs_requested: AtomicUsize::new(0),
76 /// Creates a new tracker of the actual state of the network of channels and nodes,
77 /// assuming an existing Network Graph.
78 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
80 secp_ctx: Secp256k1::verification_only(),
81 network_graph: RwLock::new(network_graph),
82 full_syncs_requested: AtomicUsize::new(0),
90 macro_rules! secp_verify_sig {
91 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
92 match $secp_ctx.verify($msg, $sig, $pubkey) {
94 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
99 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
100 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
101 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
104 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
105 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
106 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
109 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
110 Ok((script_pubkey, value)) => {
111 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
112 .push_slice(&msg.contents.bitcoin_key_1.serialize())
113 .push_slice(&msg.contents.bitcoin_key_2.serialize())
114 .push_opcode(opcodes::all::OP_PUSHNUM_2)
115 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
116 if script_pubkey != expected_script {
117 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});
119 //TODO: Check if value is worth storing, use it to inform routing, and compare it
120 //to the new HTLC max field in channel_update
123 Err(ChainError::NotSupported) => {
124 // Tentatively accept, potentially exposing us to DoS attacks
127 Err(ChainError::NotWatched) => {
128 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
130 Err(ChainError::UnknownTx) => {
131 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
134 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
135 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 { "" });
139 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
141 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
142 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
144 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
145 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
147 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
148 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
153 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
154 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
157 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
158 let network_graph = self.network_graph.read().unwrap();
159 let mut result = Vec::with_capacity(batch_amount as usize);
160 let mut iter = network_graph.get_channels().range(starting_point..);
161 while result.len() < batch_amount as usize {
162 if let Some((_, ref chan)) = iter.next() {
163 if chan.announcement_message.is_some() {
164 let chan_announcement = chan.announcement_message.clone().unwrap();
165 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
166 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
167 if let Some(one_to_two) = chan.one_to_two.as_ref() {
168 one_to_two_announcement = one_to_two.last_update_message.clone();
170 if let Some(two_to_one) = chan.two_to_one.as_ref() {
171 two_to_one_announcement = two_to_one.last_update_message.clone();
173 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
175 // TODO: We may end up sending un-announced channel_updates if we are sending
176 // initial sync data while receiving announce/updates for this channel.
185 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
186 let network_graph = self.network_graph.read().unwrap();
187 let mut result = Vec::with_capacity(batch_amount as usize);
188 let mut iter = if let Some(pubkey) = starting_point {
189 let mut iter = network_graph.get_nodes().range((*pubkey)..);
193 network_graph.get_nodes().range(..)
195 while result.len() < batch_amount as usize {
196 if let Some((_, ref node)) = iter.next() {
197 if let Some(node_info) = node.announcement_info.as_ref() {
198 if node_info.announcement_message.is_some() {
199 result.push(node_info.announcement_message.clone().unwrap());
209 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
210 //TODO: Determine whether to request a full sync based on the network map.
211 const FULL_SYNCS_TO_REQUEST: usize = 5;
212 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
213 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
221 #[derive(PartialEq, Debug)]
222 /// Details about one direction of a channel. Received
223 /// within a channel update.
224 pub struct DirectionalChannelInfo {
225 /// When the last update to the channel direction was issued.
226 /// Value is opaque, as set in the announcement.
227 pub last_update: u32,
228 /// Whether the channel can be currently used for payments (in this one direction).
230 /// The difference in CLTV values that you must have when routing through this channel.
231 pub cltv_expiry_delta: u16,
232 /// The minimum value, which must be relayed to the next hop via the channel
233 pub htlc_minimum_msat: u64,
234 /// The maximum value which may be relayed to the next hop via the channel.
235 pub htlc_maximum_msat: Option<u64>,
236 /// Fees charged when the channel is used for routing
237 pub fees: RoutingFees,
238 /// Most recent update for the channel received from the network
239 /// Mostly redundant with the data we store in fields explicitly.
240 /// Everything else is useful only for sending out for initial routing sync.
241 /// Not stored if contains excess data to prevent DoS.
242 pub last_update_message: Option<msgs::ChannelUpdate>,
245 impl fmt::Display for DirectionalChannelInfo {
246 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
247 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)?;
252 impl_writeable!(DirectionalChannelInfo, 0, {
263 /// Details about a channel (both directions).
264 /// Received within a channel announcement.
265 pub struct ChannelInfo {
266 /// Protocol features of a channel communicated during its announcement
267 pub features: ChannelFeatures,
268 /// Source node of the first direction of a channel
269 pub node_one: PublicKey,
270 /// Details about the first direction of a channel
271 pub one_to_two: Option<DirectionalChannelInfo>,
272 /// Source node of the second direction of a channel
273 pub node_two: PublicKey,
274 /// Details about the second direction of a channel
275 pub two_to_one: Option<DirectionalChannelInfo>,
276 /// The channel capacity as seen on-chain, if chain lookup is available.
277 pub capacity_sats: Option<u64>,
278 /// An initial announcement of the channel
279 /// Mostly redundant with the data we store in fields explicitly.
280 /// Everything else is useful only for sending out for initial routing sync.
281 /// Not stored if contains excess data to prevent DoS.
282 pub announcement_message: Option<msgs::ChannelAnnouncement>,
285 impl fmt::Display for ChannelInfo {
286 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
287 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
288 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
293 impl_writeable!(ChannelInfo, 0, {
304 /// Fees for routing via a given channel or a node
305 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
306 pub struct RoutingFees {
307 /// Flat routing fee in satoshis
309 /// Liquidity-based routing fee in millionths of a routed amount.
310 /// In other words, 10000 is 1%.
311 pub proportional_millionths: u32,
314 impl Readable for RoutingFees{
315 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
316 let base_msat: u32 = Readable::read(reader)?;
317 let proportional_millionths: u32 = Readable::read(reader)?;
320 proportional_millionths,
325 impl Writeable for RoutingFees {
326 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
327 self.base_msat.write(writer)?;
328 self.proportional_millionths.write(writer)?;
333 #[derive(PartialEq, Debug)]
334 /// Information received in the latest node_announcement from this node.
335 pub struct NodeAnnouncementInfo {
336 /// Protocol features the node announced support for
337 pub features: NodeFeatures,
338 /// When the last known update to the node state was issued.
339 /// Value is opaque, as set in the announcement.
340 pub last_update: u32,
341 /// Color assigned to the node
343 /// Moniker assigned to the node.
344 /// May be invalid or malicious (eg control chars),
345 /// should not be exposed to the user.
347 /// Internet-level addresses via which one can connect to the node
348 pub addresses: Vec<NetAddress>,
349 /// An initial announcement of the node
350 /// Mostly redundant with the data we store in fields explicitly.
351 /// Everything else is useful only for sending out for initial routing sync.
352 /// Not stored if contains excess data to prevent DoS.
353 pub announcement_message: Option<msgs::NodeAnnouncement>
356 impl Writeable for NodeAnnouncementInfo {
357 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
358 self.features.write(writer)?;
359 self.last_update.write(writer)?;
360 self.rgb.write(writer)?;
361 self.alias.write(writer)?;
362 (self.addresses.len() as u64).write(writer)?;
363 for ref addr in &self.addresses {
366 self.announcement_message.write(writer)?;
371 impl Readable for NodeAnnouncementInfo {
372 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
373 let features = Readable::read(reader)?;
374 let last_update = Readable::read(reader)?;
375 let rgb = Readable::read(reader)?;
376 let alias = Readable::read(reader)?;
377 let addresses_count: u64 = Readable::read(reader)?;
378 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
379 for _ in 0..addresses_count {
380 match Readable::read(reader) {
381 Ok(Ok(addr)) => { addresses.push(addr); },
382 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
383 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
387 let announcement_message = Readable::read(reader)?;
388 Ok(NodeAnnouncementInfo {
400 /// Details about a node in the network, known from the network announcement.
401 pub struct NodeInfo {
402 /// All valid channels a node has announced
403 pub channels: Vec<u64>,
404 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
405 /// The two fields (flat and proportional fee) are independent,
406 /// meaning they don't have to refer to the same channel.
407 pub lowest_inbound_channel_fees: Option<RoutingFees>,
408 /// More information about a node from node_announcement.
409 /// Optional because we store a Node entry after learning about it from
410 /// a channel announcement, but before receiving a node announcement.
411 pub announcement_info: Option<NodeAnnouncementInfo>
414 impl fmt::Display for NodeInfo {
415 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
416 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
417 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
422 impl Writeable for NodeInfo {
423 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
424 (self.channels.len() as u64).write(writer)?;
425 for ref chan in self.channels.iter() {
428 self.lowest_inbound_channel_fees.write(writer)?;
429 self.announcement_info.write(writer)?;
434 const MAX_ALLOC_SIZE: u64 = 64*1024;
436 impl Readable for NodeInfo {
437 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
438 let channels_count: u64 = Readable::read(reader)?;
439 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
440 for _ in 0..channels_count {
441 channels.push(Readable::read(reader)?);
443 let lowest_inbound_channel_fees = Readable::read(reader)?;
444 let announcement_info = Readable::read(reader)?;
447 lowest_inbound_channel_fees,
453 impl Writeable for NetworkGraph {
454 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
455 (self.channels.len() as u64).write(writer)?;
456 for (ref chan_id, ref chan_info) in self.channels.iter() {
457 (*chan_id).write(writer)?;
458 chan_info.write(writer)?;
460 (self.nodes.len() as u64).write(writer)?;
461 for (ref node_id, ref node_info) in self.nodes.iter() {
462 node_id.write(writer)?;
463 node_info.write(writer)?;
469 impl Readable for NetworkGraph {
470 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
471 let channels_count: u64 = Readable::read(reader)?;
472 let mut channels = BTreeMap::new();
473 for _ in 0..channels_count {
474 let chan_id: u64 = Readable::read(reader)?;
475 let chan_info = Readable::read(reader)?;
476 channels.insert(chan_id, chan_info);
478 let nodes_count: u64 = Readable::read(reader)?;
479 let mut nodes = BTreeMap::new();
480 for _ in 0..nodes_count {
481 let node_id = Readable::read(reader)?;
482 let node_info = Readable::read(reader)?;
483 nodes.insert(node_id, node_info);
492 impl fmt::Display for NetworkGraph {
493 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
494 write!(f, "Network map\n[Channels]\n")?;
495 for (key, val) in self.channels.iter() {
496 write!(f, " {}: {}\n", key, val)?;
498 write!(f, "[Nodes]\n")?;
499 for (key, val) in self.nodes.iter() {
500 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
507 /// Returns all known valid channels' short ids along with announced channel info.
508 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
509 /// Returns all known nodes' public keys along with announced node info.
510 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
512 /// Get network addresses by node id.
513 /// Returns None if the requested node is completely unknown,
514 /// or if node announcement for the node was never received.
515 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
516 if let Some(node) = self.nodes.get(pubkey) {
517 if let Some(node_info) = node.announcement_info.as_ref() {
518 return Some(&node_info.addresses)
524 /// Creates a new, empty, network graph.
525 pub fn new() -> NetworkGraph {
527 channels: BTreeMap::new(),
528 nodes: BTreeMap::new(),
532 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
533 /// Announcement signatures are checked here only if Secp256k1 object is provided.
534 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
535 if let Some(sig_verifier) = secp_ctx {
536 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
537 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
540 match self.nodes.get_mut(&msg.contents.node_id) {
541 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
543 if let Some(node_info) = node.announcement_info.as_ref() {
544 if node_info.last_update >= msg.contents.timestamp {
545 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
549 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
550 node.announcement_info = Some(NodeAnnouncementInfo {
551 features: msg.contents.features.clone(),
552 last_update: msg.contents.timestamp,
553 rgb: msg.contents.rgb,
554 alias: msg.contents.alias,
555 addresses: msg.contents.addresses.clone(),
556 announcement_message: if should_relay { Some(msg.clone()) } else { None },
564 /// For a new or already known (from previous announcement) channel, store or update channel info.
565 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
566 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
567 /// which is probably result of a reorg. In that case, we update channel info only if the
568 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
569 /// Announcement signatures are checked here only if Secp256k1 object is provided.
570 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
571 if let Some(sig_verifier) = secp_ctx {
572 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
573 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
574 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
575 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
576 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
579 let should_relay = msg.contents.excess_data.is_empty();
581 let chan_info = ChannelInfo {
582 features: msg.contents.features.clone(),
583 node_one: msg.contents.node_id_1.clone(),
585 node_two: msg.contents.node_id_2.clone(),
587 capacity_sats: utxo_value,
588 announcement_message: if should_relay { Some(msg.clone()) } else { None },
591 match self.channels.entry(msg.contents.short_channel_id) {
592 BtreeEntry::Occupied(mut entry) => {
593 //TODO: because asking the blockchain if short_channel_id is valid is only optional
594 //in the blockchain API, we need to handle it smartly here, though it's unclear
596 if utxo_value.is_some() {
597 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
598 // only sometimes returns results. In any case remove the previous entry. Note
599 // that the spec expects us to "blacklist" the node_ids involved, but we can't
601 // a) we don't *require* a UTXO provider that always returns results.
602 // b) we don't track UTXOs of channels we know about and remove them if they
604 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
605 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
606 *entry.get_mut() = chan_info;
608 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
611 BtreeEntry::Vacant(entry) => {
612 entry.insert(chan_info);
616 macro_rules! add_channel_to_node {
617 ( $node_id: expr ) => {
618 match self.nodes.entry($node_id) {
619 BtreeEntry::Occupied(node_entry) => {
620 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
622 BtreeEntry::Vacant(node_entry) => {
623 node_entry.insert(NodeInfo {
624 channels: vec!(msg.contents.short_channel_id),
625 lowest_inbound_channel_fees: None,
626 announcement_info: None,
633 add_channel_to_node!(msg.contents.node_id_1);
634 add_channel_to_node!(msg.contents.node_id_2);
639 /// Close a channel if a corresponding HTLC fail was sent.
640 /// If permanent, removes a channel from the local storage.
641 /// May cause the removal of nodes too, if this was their last channel.
642 /// If not permanent, makes channels unavailable for routing.
643 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
645 if let Some(chan) = self.channels.remove(&short_channel_id) {
646 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
649 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
650 if let Some(one_to_two) = chan.one_to_two.as_mut() {
651 one_to_two.enabled = false;
653 if let Some(two_to_one) = chan.two_to_one.as_mut() {
654 two_to_one.enabled = false;
660 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
662 // TODO: Wholly remove the node
664 // TODO: downgrade the node
668 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
669 /// Announcement signatures are checked here only if Secp256k1 object is provided.
670 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
672 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
673 let chan_was_enabled;
675 match self.channels.get_mut(&msg.contents.short_channel_id) {
676 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
678 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
679 if htlc_maximum_msat > MAX_VALUE_MSAT {
680 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
683 if let Some(capacity_sats) = channel.capacity_sats {
684 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
685 // Don't query UTXO set here to reduce DoS risks.
686 if htlc_maximum_msat > capacity_sats * 1000 {
687 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
691 macro_rules! maybe_update_channel_info {
692 ( $target: expr, $src_node: expr) => {
693 if let Some(existing_chan_info) = $target.as_ref() {
694 if existing_chan_info.last_update >= msg.contents.timestamp {
695 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
697 chan_was_enabled = existing_chan_info.enabled;
699 chan_was_enabled = false;
702 let last_update_message = if msg.contents.excess_data.is_empty() {
708 let updated_channel_dir_info = DirectionalChannelInfo {
709 enabled: chan_enabled,
710 last_update: msg.contents.timestamp,
711 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
712 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
713 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
715 base_msat: msg.contents.fee_base_msat,
716 proportional_millionths: msg.contents.fee_proportional_millionths,
720 $target = Some(updated_channel_dir_info);
724 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
725 if msg.contents.flags & 1 == 1 {
726 dest_node_id = channel.node_one.clone();
727 if let Some(sig_verifier) = secp_ctx {
728 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
730 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
732 dest_node_id = channel.node_two.clone();
733 if let Some(sig_verifier) = secp_ctx {
734 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
736 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
742 let node = self.nodes.get_mut(&dest_node_id).unwrap();
743 let mut base_msat = msg.contents.fee_base_msat;
744 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
745 if let Some(fees) = node.lowest_inbound_channel_fees {
746 base_msat = cmp::min(base_msat, fees.base_msat);
747 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
749 node.lowest_inbound_channel_fees = Some(RoutingFees {
751 proportional_millionths
753 } else if chan_was_enabled {
754 let node = self.nodes.get_mut(&dest_node_id).unwrap();
755 let mut lowest_inbound_channel_fees = None;
757 for chan_id in node.channels.iter() {
758 let chan = self.channels.get(chan_id).unwrap();
760 if chan.node_one == dest_node_id {
761 chan_info_opt = chan.two_to_one.as_ref();
763 chan_info_opt = chan.one_to_two.as_ref();
765 if let Some(chan_info) = chan_info_opt {
766 if chan_info.enabled {
767 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
768 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
769 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
770 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
775 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
778 Ok(msg.contents.excess_data.is_empty())
781 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
782 macro_rules! remove_from_node {
783 ($node_id: expr) => {
784 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
785 entry.get_mut().channels.retain(|chan_id| {
786 short_channel_id != *chan_id
788 if entry.get().channels.is_empty() {
789 entry.remove_entry();
792 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
797 remove_from_node!(chan.node_one);
798 remove_from_node!(chan.node_two);
804 use chain::chaininterface;
805 use ln::features::{ChannelFeatures, NodeFeatures};
806 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
807 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
808 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
810 use util::test_utils;
811 use util::logger::Logger;
812 use util::ser::{Readable, Writeable};
814 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
815 use bitcoin::hashes::Hash;
816 use bitcoin::network::constants::Network;
817 use bitcoin::blockdata::constants::genesis_block;
818 use bitcoin::blockdata::script::Builder;
819 use bitcoin::blockdata::opcodes;
820 use bitcoin::util::hash::BitcoinHash;
824 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
825 use bitcoin::secp256k1::{All, Secp256k1};
829 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
830 let secp_ctx = Secp256k1::new();
831 let logger = Arc::new(test_utils::TestLogger::new());
832 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
833 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
834 (secp_ctx, net_graph_msg_handler)
838 fn request_full_sync_finite_times() {
839 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
840 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
842 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
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));
851 fn handling_node_announcements() {
852 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
854 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
855 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
856 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
857 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
858 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
859 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
860 let zero_hash = Sha256dHash::hash(&[0; 32]);
861 let first_announcement_time = 500;
863 let mut unsigned_announcement = UnsignedNodeAnnouncement {
864 features: NodeFeatures::known(),
865 timestamp: first_announcement_time,
869 addresses: Vec::new(),
870 excess_address_data: Vec::new(),
871 excess_data: Vec::new(),
873 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
874 let valid_announcement = NodeAnnouncement {
875 signature: secp_ctx.sign(&msghash, node_1_privkey),
876 contents: unsigned_announcement.clone()
879 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
881 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
885 // Announce a channel to add a corresponding node.
886 let unsigned_announcement = UnsignedChannelAnnouncement {
887 features: ChannelFeatures::known(),
888 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
892 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
893 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
894 excess_data: Vec::new(),
897 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
898 let valid_announcement = ChannelAnnouncement {
899 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
900 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
901 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
902 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
903 contents: unsigned_announcement.clone(),
905 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
906 Ok(res) => assert!(res),
911 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
912 Ok(res) => assert!(res),
916 let fake_msghash = hash_to_message!(&zero_hash);
917 match net_graph_msg_handler.handle_node_announcement(
919 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
920 contents: unsigned_announcement.clone()
923 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
926 unsigned_announcement.timestamp += 1000;
927 unsigned_announcement.excess_data.push(1);
928 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
929 let announcement_with_data = NodeAnnouncement {
930 signature: secp_ctx.sign(&msghash, node_1_privkey),
931 contents: unsigned_announcement.clone()
933 // Return false because contains excess data.
934 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
935 Ok(res) => assert!(!res),
938 unsigned_announcement.excess_data = Vec::new();
940 // Even though previous announcement was not relayed further, we still accepted it,
941 // so we now won't accept announcements before the previous one.
942 unsigned_announcement.timestamp -= 10;
943 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
944 let outdated_announcement = NodeAnnouncement {
945 signature: secp_ctx.sign(&msghash, node_1_privkey),
946 contents: unsigned_announcement.clone()
948 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
950 Err(e) => assert_eq!(e.err, "Update older than last processed update")
955 fn handling_channel_announcements() {
956 let secp_ctx = Secp256k1::new();
957 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
958 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
959 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
962 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
963 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
964 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
965 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
966 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
967 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
969 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
970 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
971 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
972 .push_opcode(opcodes::all::OP_PUSHNUM_2)
973 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
976 let mut unsigned_announcement = UnsignedChannelAnnouncement {
977 features: ChannelFeatures::known(),
978 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
982 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
983 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
984 excess_data: Vec::new(),
987 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
988 let valid_announcement = ChannelAnnouncement {
989 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
990 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
991 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
992 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
993 contents: unsigned_announcement.clone(),
996 // Test if the UTXO lookups were not supported
997 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
999 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1000 Ok(res) => assert!(res),
1005 let network = net_graph_msg_handler.network_graph.read().unwrap();
1006 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1013 // If we receive announcement for the same channel (with UTXO lookups disabled),
1014 // drop new one on the floor, since we can't see any changes.
1015 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1017 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1021 // Test if an associated transaction were not on-chain (or not confirmed).
1022 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1023 unsigned_announcement.short_channel_id += 1;
1025 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1026 let valid_announcement = ChannelAnnouncement {
1027 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1028 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1029 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1030 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1031 contents: unsigned_announcement.clone(),
1034 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1036 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1040 // Now test if the transaction is found in the UTXO set and the script is correct.
1041 unsigned_announcement.short_channel_id += 1;
1042 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1044 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1045 let valid_announcement = ChannelAnnouncement {
1046 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1047 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1048 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1049 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1050 contents: unsigned_announcement.clone(),
1052 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1053 Ok(res) => assert!(res),
1058 let network = net_graph_msg_handler.network_graph.read().unwrap();
1059 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1065 // If we receive announcement for the same channel (but TX is not confirmed),
1066 // drop new one on the floor, since we can't see any changes.
1067 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1068 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1070 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1073 // But if it is confirmed, replace the channel
1074 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1075 unsigned_announcement.features = ChannelFeatures::empty();
1076 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1077 let valid_announcement = ChannelAnnouncement {
1078 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1079 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1080 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1081 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1082 contents: unsigned_announcement.clone(),
1084 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1085 Ok(res) => assert!(res),
1089 let network = net_graph_msg_handler.network_graph.read().unwrap();
1090 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1091 Some(channel_entry) => {
1092 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1098 // Don't relay valid channels with excess data
1099 unsigned_announcement.short_channel_id += 1;
1100 unsigned_announcement.excess_data.push(1);
1101 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1102 let valid_announcement = ChannelAnnouncement {
1103 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1104 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1105 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1106 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1107 contents: unsigned_announcement.clone(),
1109 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1110 Ok(res) => assert!(!res),
1114 unsigned_announcement.excess_data = Vec::new();
1115 let invalid_sig_announcement = ChannelAnnouncement {
1116 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1117 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1118 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1119 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1120 contents: unsigned_announcement.clone(),
1122 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1124 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1127 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1128 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1129 let channel_to_itself_announcement = ChannelAnnouncement {
1130 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1131 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1132 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1133 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1134 contents: unsigned_announcement.clone(),
1136 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1138 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1143 fn handling_channel_update() {
1144 let secp_ctx = Secp256k1::new();
1145 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1146 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1147 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1149 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1150 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1151 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1152 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1153 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1154 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1156 let zero_hash = Sha256dHash::hash(&[0; 32]);
1157 let short_channel_id = 0;
1158 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1159 let amount_sats = 1000_000;
1162 // Announce a channel we will update
1163 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1164 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1165 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1166 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1167 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1168 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1169 let unsigned_announcement = UnsignedChannelAnnouncement {
1170 features: ChannelFeatures::empty(),
1175 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1176 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1177 excess_data: Vec::new(),
1180 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1181 let valid_channel_announcement = ChannelAnnouncement {
1182 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1183 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1184 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1185 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1186 contents: unsigned_announcement.clone(),
1188 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1195 let mut unsigned_channel_update = UnsignedChannelUpdate {
1200 cltv_expiry_delta: 144,
1201 htlc_minimum_msat: 1000000,
1202 htlc_maximum_msat: OptionalField::Absent,
1203 fee_base_msat: 10000,
1204 fee_proportional_millionths: 20,
1205 excess_data: Vec::new()
1207 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1208 let valid_channel_update = ChannelUpdate {
1209 signature: secp_ctx.sign(&msghash, node_1_privkey),
1210 contents: unsigned_channel_update.clone()
1213 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1214 Ok(res) => assert!(res),
1219 let network = net_graph_msg_handler.network_graph.read().unwrap();
1220 match network.get_channels().get(&short_channel_id) {
1222 Some(channel_info) => {
1223 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1224 assert!(channel_info.two_to_one.is_none());
1229 unsigned_channel_update.timestamp += 100;
1230 unsigned_channel_update.excess_data.push(1);
1231 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1232 let valid_channel_update = ChannelUpdate {
1233 signature: secp_ctx.sign(&msghash, node_1_privkey),
1234 contents: unsigned_channel_update.clone()
1236 // Return false because contains excess data
1237 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1238 Ok(res) => assert!(!res),
1241 unsigned_channel_update.timestamp += 10;
1243 unsigned_channel_update.short_channel_id += 1;
1244 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1245 let valid_channel_update = ChannelUpdate {
1246 signature: secp_ctx.sign(&msghash, node_1_privkey),
1247 contents: unsigned_channel_update.clone()
1250 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1252 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1254 unsigned_channel_update.short_channel_id = short_channel_id;
1256 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 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()
1263 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1265 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1267 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1269 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 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, "htlc_maximum_msat is larger than channel capacity")
1280 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1282 // Even though previous update was not relayed further, we still accepted it,
1283 // so we now won't accept update before the previous one.
1284 unsigned_channel_update.timestamp -= 10;
1285 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1286 let valid_channel_update = ChannelUpdate {
1287 signature: secp_ctx.sign(&msghash, node_1_privkey),
1288 contents: unsigned_channel_update.clone()
1291 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1293 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1295 unsigned_channel_update.timestamp += 500;
1297 let fake_msghash = hash_to_message!(&zero_hash);
1298 let invalid_sig_channel_update = ChannelUpdate {
1299 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1300 contents: unsigned_channel_update.clone()
1303 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1305 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1311 fn handling_htlc_fail_channel_update() {
1312 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1313 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1314 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1315 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1316 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1317 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1318 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1320 let short_channel_id = 0;
1321 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1324 // There is no nodes in the table at the beginning.
1325 let network = net_graph_msg_handler.network_graph.read().unwrap();
1326 assert_eq!(network.get_nodes().len(), 0);
1330 // Announce a channel we will update
1331 let unsigned_announcement = UnsignedChannelAnnouncement {
1332 features: ChannelFeatures::empty(),
1337 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1338 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1339 excess_data: Vec::new(),
1342 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1343 let valid_channel_announcement = ChannelAnnouncement {
1344 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1345 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1346 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1347 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1348 contents: unsigned_announcement.clone(),
1350 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1355 let unsigned_channel_update = UnsignedChannelUpdate {
1360 cltv_expiry_delta: 144,
1361 htlc_minimum_msat: 1000000,
1362 htlc_maximum_msat: OptionalField::Absent,
1363 fee_base_msat: 10000,
1364 fee_proportional_millionths: 20,
1365 excess_data: Vec::new()
1367 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1368 let valid_channel_update = ChannelUpdate {
1369 signature: secp_ctx.sign(&msghash, node_1_privkey),
1370 contents: unsigned_channel_update.clone()
1373 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1374 Ok(res) => assert!(res),
1379 // Non-permanent closing just disables a channel
1381 let network = net_graph_msg_handler.network_graph.read().unwrap();
1382 match network.get_channels().get(&short_channel_id) {
1384 Some(channel_info) => {
1385 assert!(channel_info.one_to_two.is_some());
1390 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1395 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1397 // Non-permanent closing just disables a channel
1399 let network = net_graph_msg_handler.network_graph.read().unwrap();
1400 match network.get_channels().get(&short_channel_id) {
1402 Some(channel_info) => {
1403 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1408 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1413 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1415 // Permanent closing deletes a channel
1417 let network = net_graph_msg_handler.network_graph.read().unwrap();
1418 assert_eq!(network.get_channels().len(), 0);
1419 // Nodes are also deleted because there are no associated channels anymore
1420 assert_eq!(network.get_nodes().len(), 0);
1422 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1426 fn getting_next_channel_announcements() {
1427 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1428 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1429 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1430 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1431 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1432 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1433 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1435 let short_channel_id = 1;
1436 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1438 // Channels were not announced yet.
1439 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1440 assert_eq!(channels_with_announcements.len(), 0);
1443 // Announce a channel we will update
1444 let unsigned_announcement = UnsignedChannelAnnouncement {
1445 features: ChannelFeatures::empty(),
1450 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1451 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1452 excess_data: Vec::new(),
1455 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1456 let valid_channel_announcement = ChannelAnnouncement {
1457 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1458 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1459 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1460 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1461 contents: unsigned_announcement.clone(),
1463 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1469 // Contains initial channel announcement now.
1470 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1471 assert_eq!(channels_with_announcements.len(), 1);
1472 if let Some(channel_announcements) = channels_with_announcements.first() {
1473 let &(_, ref update_1, ref update_2) = channel_announcements;
1474 assert_eq!(update_1, &None);
1475 assert_eq!(update_2, &None);
1482 // Valid channel update
1483 let unsigned_channel_update = UnsignedChannelUpdate {
1488 cltv_expiry_delta: 144,
1489 htlc_minimum_msat: 1000000,
1490 htlc_maximum_msat: OptionalField::Absent,
1491 fee_base_msat: 10000,
1492 fee_proportional_millionths: 20,
1493 excess_data: Vec::new()
1495 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1496 let valid_channel_update = ChannelUpdate {
1497 signature: secp_ctx.sign(&msghash, node_1_privkey),
1498 contents: unsigned_channel_update.clone()
1500 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1506 // Now contains an initial announcement and an update.
1507 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1508 assert_eq!(channels_with_announcements.len(), 1);
1509 if let Some(channel_announcements) = channels_with_announcements.first() {
1510 let &(_, ref update_1, ref update_2) = channel_announcements;
1511 assert_ne!(update_1, &None);
1512 assert_eq!(update_2, &None);
1519 // Channel update with excess data.
1520 let unsigned_channel_update = UnsignedChannelUpdate {
1525 cltv_expiry_delta: 144,
1526 htlc_minimum_msat: 1000000,
1527 htlc_maximum_msat: OptionalField::Absent,
1528 fee_base_msat: 10000,
1529 fee_proportional_millionths: 20,
1530 excess_data: [1; 3].to_vec()
1532 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1533 let valid_channel_update = ChannelUpdate {
1534 signature: secp_ctx.sign(&msghash, node_1_privkey),
1535 contents: unsigned_channel_update.clone()
1537 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1543 // Test that announcements with excess data won't be returned
1544 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1545 assert_eq!(channels_with_announcements.len(), 1);
1546 if let Some(channel_announcements) = channels_with_announcements.first() {
1547 let &(_, ref update_1, ref update_2) = channel_announcements;
1548 assert_eq!(update_1, &None);
1549 assert_eq!(update_2, &None);
1554 // Further starting point have no channels after it
1555 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1556 assert_eq!(channels_with_announcements.len(), 0);
1560 fn getting_next_node_announcements() {
1561 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1562 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1563 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1564 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1565 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1566 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1567 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1569 let short_channel_id = 1;
1570 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1573 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1574 assert_eq!(next_announcements.len(), 0);
1577 // Announce a channel to add 2 nodes
1578 let unsigned_announcement = UnsignedChannelAnnouncement {
1579 features: ChannelFeatures::empty(),
1584 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1585 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1586 excess_data: Vec::new(),
1589 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1590 let valid_channel_announcement = ChannelAnnouncement {
1591 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1592 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1593 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1594 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1595 contents: unsigned_announcement.clone(),
1597 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1604 // Nodes were never announced
1605 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1606 assert_eq!(next_announcements.len(), 0);
1609 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1610 features: NodeFeatures::known(),
1615 addresses: Vec::new(),
1616 excess_address_data: Vec::new(),
1617 excess_data: Vec::new(),
1619 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1620 let valid_announcement = NodeAnnouncement {
1621 signature: secp_ctx.sign(&msghash, node_1_privkey),
1622 contents: unsigned_announcement.clone()
1624 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1629 unsigned_announcement.node_id = node_id_2;
1630 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1631 let valid_announcement = NodeAnnouncement {
1632 signature: secp_ctx.sign(&msghash, node_2_privkey),
1633 contents: unsigned_announcement.clone()
1636 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1642 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1643 assert_eq!(next_announcements.len(), 2);
1645 // Skip the first node.
1646 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1647 assert_eq!(next_announcements.len(), 1);
1650 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1651 let unsigned_announcement = UnsignedNodeAnnouncement {
1652 features: NodeFeatures::known(),
1657 addresses: Vec::new(),
1658 excess_address_data: Vec::new(),
1659 excess_data: [1; 3].to_vec(),
1661 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1662 let valid_announcement = NodeAnnouncement {
1663 signature: secp_ctx.sign(&msghash, node_2_privkey),
1664 contents: unsigned_announcement.clone()
1666 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1667 Ok(res) => assert!(!res),
1672 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1673 assert_eq!(next_announcements.len(), 0);
1677 fn network_graph_serialization() {
1678 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1680 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1681 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1682 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1683 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1685 // Announce a channel to add a corresponding node.
1686 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1687 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1688 let unsigned_announcement = UnsignedChannelAnnouncement {
1689 features: ChannelFeatures::known(),
1690 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1691 short_channel_id: 0,
1694 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1695 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1696 excess_data: Vec::new(),
1699 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1700 let valid_announcement = ChannelAnnouncement {
1701 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1702 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1703 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1704 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1705 contents: unsigned_announcement.clone(),
1707 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1708 Ok(res) => assert!(res),
1713 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1714 let unsigned_announcement = UnsignedNodeAnnouncement {
1715 features: NodeFeatures::known(),
1720 addresses: Vec::new(),
1721 excess_address_data: Vec::new(),
1722 excess_data: Vec::new(),
1724 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1725 let valid_announcement = NodeAnnouncement {
1726 signature: secp_ctx.sign(&msghash, node_1_privkey),
1727 contents: unsigned_announcement.clone()
1730 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1735 let network = net_graph_msg_handler.network_graph.write().unwrap();
1736 let mut w = test_utils::TestVecWriter(Vec::new());
1737 assert!(!network.get_nodes().is_empty());
1738 assert!(!network.get_channels().is_empty());
1739 network.write(&mut w).unwrap();
1740 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);