1 //! The top-level network map tracking logic lives here.
3 use bitcoin::secp256k1::key::PublicKey;
4 use bitcoin::secp256k1::Secp256k1;
5 use bitcoin::secp256k1;
7 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
8 use bitcoin::hashes::Hash;
9 use bitcoin::blockdata::script::Builder;
10 use bitcoin::blockdata::opcodes;
12 use chain::chaininterface::{ChainError, ChainWatchInterface};
13 use ln::features::{ChannelFeatures, NodeFeatures};
14 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress};
16 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
17 use util::logger::Logger;
20 use std::sync::{RwLock,Arc};
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
26 /// Receives network updates from peers to track view of the network.
27 pub struct NetGraphMsgHandler {
28 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
29 /// Representation of the payment channel network
30 pub network_graph: RwLock<NetworkGraph>,
31 chain_monitor: Arc<ChainWatchInterface>,
32 full_syncs_requested: AtomicUsize,
36 impl NetGraphMsgHandler {
37 /// Creates a new tracker of the actual state of the network of channels and nodes.
38 pub fn new(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Self {
40 secp_ctx: Secp256k1::verification_only(),
41 network_graph: RwLock::new(NetworkGraph {
42 channels: BTreeMap::new(),
43 nodes: BTreeMap::new(),
45 full_syncs_requested: AtomicUsize::new(0),
47 logger: logger.clone(),
51 /// Get network addresses by node id
52 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
53 let network = self.network_graph.read().unwrap();
54 if let Some(node) = network.get_nodes().get(pubkey) {
55 if let Some(node_info) = node.announcement_info.as_ref() {
56 return Some(node_info.addresses.clone())
62 /// Dumps the entire network view of this NetGraphMsgHandler to the logger provided in the constructor at
64 pub fn trace_state(&self) {
65 log_trace!(self, "{}", self.network_graph.read().unwrap());
70 macro_rules! secp_verify_sig {
71 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
72 match $secp_ctx.verify($msg, $sig, $pubkey) {
74 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
79 impl RoutingMessageHandler for NetGraphMsgHandler {
80 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
81 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
84 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
85 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
86 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
89 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
90 Ok((script_pubkey, _value)) => {
91 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
92 .push_slice(&msg.contents.bitcoin_key_1.serialize())
93 .push_slice(&msg.contents.bitcoin_key_2.serialize())
94 .push_opcode(opcodes::all::OP_PUSHNUM_2)
95 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
96 if script_pubkey != expected_script {
97 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
99 //TODO: Check if value is worth storing, use it to inform routing, and compare it
100 //to the new HTLC max field in channel_update
103 Err(ChainError::NotSupported) => {
104 // Tentatively accept, potentially exposing us to DoS attacks
107 Err(ChainError::NotWatched) => {
108 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
110 Err(ChainError::UnknownTx) => {
111 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
114 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
115 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
119 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
121 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
122 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
124 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
125 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
127 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
128 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
133 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
134 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
137 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
138 let network_graph = self.network_graph.read().unwrap();
139 let mut result = Vec::with_capacity(batch_amount as usize);
140 let mut iter = network_graph.get_channels().range(starting_point..);
141 while result.len() < batch_amount as usize {
142 if let Some((_, ref chan)) = iter.next() {
143 if chan.announcement_message.is_some() {
144 result.push((chan.announcement_message.clone().unwrap(),
145 chan.one_to_two.last_update_message.clone(),
146 chan.two_to_one.last_update_message.clone()));
148 // TODO: We may end up sending un-announced channel_updates if we are sending
149 // initial sync data while receiving announce/updates for this channel.
158 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
159 let network_graph = self.network_graph.read().unwrap();
160 let mut result = Vec::with_capacity(batch_amount as usize);
161 let mut iter = if let Some(pubkey) = starting_point {
162 let mut iter = network_graph.get_nodes().range((*pubkey)..);
166 network_graph.get_nodes().range(..)
168 while result.len() < batch_amount as usize {
169 if let Some((_, ref node)) = iter.next() {
170 if let Some(node_info) = node.announcement_info.as_ref() {
171 if node_info.announcement_message.is_some() {
172 result.push(node_info.announcement_message.clone().unwrap());
182 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
183 //TODO: Determine whether to request a full sync based on the network map.
184 const FULL_SYNCS_TO_REQUEST: usize = 5;
185 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
186 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
195 const SERIALIZATION_VERSION: u8 = 1;
196 const MIN_SERIALIZATION_VERSION: u8 = 1;
198 impl Writeable for NetGraphMsgHandler {
199 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
200 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
201 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
203 let network = self.network_graph.read().unwrap();
204 network.write(writer)?;
209 /// Arguments for the creation of a NetGraphMsgHandler that are not deserialized.
210 /// At a high-level, the process for deserializing a NetGraphMsgHandler and resuming normal operation is:
211 /// 1) Deserialize the NetGraphMsgHandler by filling in this struct and calling <NetGraphMsgHandler>::read(reaser, args).
212 /// 2) Register the new NetGraphMsgHandler with your ChainWatchInterface
213 pub struct NetGraphMsgHandlerReadArgs {
214 /// The ChainWatchInterface for use in the NetGraphMsgHandler in the future.
216 /// No calls to the ChainWatchInterface will be made during deserialization.
217 pub chain_monitor: Arc<ChainWatchInterface>,
218 /// The Logger for use in the ChannelManager and which may be used to log information during
220 pub logger: Arc<Logger>,
223 impl ReadableArgs<NetGraphMsgHandlerReadArgs> for NetGraphMsgHandler {
224 fn read<R: ::std::io::Read>(reader: &mut R, args: NetGraphMsgHandlerReadArgs) -> Result<NetGraphMsgHandler, DecodeError> {
225 let _ver: u8 = Readable::read(reader)?;
226 let min_ver: u8 = Readable::read(reader)?;
227 if min_ver > SERIALIZATION_VERSION {
228 return Err(DecodeError::UnknownVersion);
230 let network_graph = Readable::read(reader)?;
231 Ok(NetGraphMsgHandler {
232 secp_ctx: Secp256k1::verification_only(),
233 network_graph: RwLock::new(network_graph),
234 chain_monitor: args.chain_monitor,
235 full_syncs_requested: AtomicUsize::new(0),
236 logger: args.logger.clone(),
242 /// Details regarding one direction of a channel
243 pub struct DirectionalChannelInfo {
244 /// A node from which the channel direction starts
245 pub src_node_id: PublicKey,
246 /// When the last update to the channel direction was issued
247 pub last_update: u32,
248 /// Whether the channel can be currently used for payments
250 /// The difference in CLTV values between the source and the destination node of the channel
251 pub cltv_expiry_delta: u16,
252 /// The minimum value, which must be relayed to the next hop via the channel
253 pub htlc_minimum_msat: u64,
254 /// Fees charged when the channel is used for routing
255 pub fees: RoutingFees,
256 /// Most recent update for the channel received from the network
257 pub last_update_message: Option<msgs::ChannelUpdate>,
260 impl std::fmt::Display for DirectionalChannelInfo {
261 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
262 write!(f, "src_node_id {}, last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", log_pubkey!(self.src_node_id), self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
267 impl_writeable!(DirectionalChannelInfo, 0, {
278 /// Details regarding a channel (both directions)
279 pub struct ChannelInfo {
280 /// Protocol features of a channel communicated during its announcement
281 pub features: ChannelFeatures,
282 /// Details regarding one of the directions of a channel
283 pub one_to_two: DirectionalChannelInfo,
284 /// Details regarding another direction of a channel
285 pub two_to_one: DirectionalChannelInfo,
286 /// An initial announcement of the channel
287 //this is cached here so we can send out it later if required by initial routing sync
288 //keep an eye on this to see if the extra memory is a problem
289 pub announcement_message: Option<msgs::ChannelAnnouncement>,
292 impl std::fmt::Display for ChannelInfo {
293 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
294 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
299 impl_writeable!(ChannelInfo, 0, {
307 /// Fees for routing via a given channel or a node
308 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
309 pub struct RoutingFees {
312 /// Liquidity-based routing fee
313 pub proportional_millionths: u32,
316 impl Readable for RoutingFees{
317 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
318 let base_msat: u32 = Readable::read(reader)?;
319 let proportional_millionths: u32 = Readable::read(reader)?;
322 proportional_millionths,
327 impl Writeable for RoutingFees {
328 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
329 self.base_msat.write(writer)?;
330 self.proportional_millionths.write(writer)?;
335 #[derive(PartialEq, Debug)]
336 /// Information received in the latest node_announcement from this node.
337 pub struct NodeAnnouncementInfo {
338 /// Protocol features the node announced support for
339 pub features: NodeFeatures,
340 /// When the last known update to the node state was issued
341 pub last_update: u32,
342 /// Color assigned to the node
344 /// Moniker assigned to the node
346 /// Internet-level addresses via which one can connect to the node
347 pub addresses: Vec<NetAddress>,
348 /// An initial announcement of the node
349 // this is cached here so we can send out it later if required by initial routing sync
350 // keep an eye on this to see if the extra memory is a problem
351 pub announcement_message: Option<msgs::NodeAnnouncement>
354 impl Writeable for NodeAnnouncementInfo {
355 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
356 self.features.write(writer)?;
357 self.last_update.write(writer)?;
358 self.rgb.write(writer)?;
359 self.alias.write(writer)?;
360 (self.addresses.len() as u64).write(writer)?;
361 for ref addr in &self.addresses {
364 self.announcement_message.write(writer)?;
369 impl Readable for NodeAnnouncementInfo {
370 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
371 let features = Readable::read(reader)?;
372 let last_update = Readable::read(reader)?;
373 let rgb = Readable::read(reader)?;
374 let alias = Readable::read(reader)?;
375 let addresses_count: u64 = Readable::read(reader)?;
376 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
377 for _ in 0..addresses_count {
378 match Readable::read(reader) {
379 Ok(Ok(addr)) => { addresses.push(addr); },
380 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
381 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
385 let announcement_message = Readable::read(reader)?;
386 Ok(NodeAnnouncementInfo {
398 /// Details regarding a node in the network
399 pub struct NodeInfo {
400 /// All valid channels a node has announced
401 pub channels: Vec<u64>,
402 /// Lowest fees enabling routing via any of the known channels to a node
403 pub lowest_inbound_channel_fees: Option<RoutingFees>,
404 /// More information about a node from node_announcement
405 /// Optional because we may have a NodeInfo entry before having received the announcement
406 pub announcement_info: Option<NodeAnnouncementInfo>
409 impl std::fmt::Display for NodeInfo {
410 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
411 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
412 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
417 impl Writeable for NodeInfo {
418 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
419 (self.channels.len() as u64).write(writer)?;
420 for ref chan in self.channels.iter() {
423 self.lowest_inbound_channel_fees.write(writer)?;
424 self.announcement_info.write(writer)?;
429 const MAX_ALLOC_SIZE: u64 = 64*1024;
431 impl Readable for NodeInfo {
432 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
433 let channels_count: u64 = Readable::read(reader)?;
434 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
435 for _ in 0..channels_count {
436 channels.push(Readable::read(reader)?);
438 let lowest_inbound_channel_fees = Readable::read(reader)?;
439 let announcement_info = Readable::read(reader)?;
442 lowest_inbound_channel_fees,
448 /// Represents the network as nodes and channels between them
450 pub struct NetworkGraph {
451 channels: BTreeMap<u64, ChannelInfo>,
452 nodes: BTreeMap<PublicKey, NodeInfo>,
455 impl Writeable for NetworkGraph {
456 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
457 (self.channels.len() as u64).write(writer)?;
458 for (ref chan_id, ref chan_info) in self.channels.iter() {
459 (*chan_id).write(writer)?;
460 chan_info.write(writer)?;
462 (self.nodes.len() as u64).write(writer)?;
463 for (ref node_id, ref node_info) in self.nodes.iter() {
464 node_id.write(writer)?;
465 node_info.write(writer)?;
471 impl Readable for NetworkGraph {
472 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
473 let channels_count: u64 = Readable::read(reader)?;
474 let mut channels = BTreeMap::new();
475 for _ in 0..channels_count {
476 let chan_id: u64 = Readable::read(reader)?;
477 let chan_info = Readable::read(reader)?;
478 channels.insert(chan_id, chan_info);
480 let nodes_count: u64 = Readable::read(reader)?;
481 let mut nodes = BTreeMap::new();
482 for _ in 0..nodes_count {
483 let node_id = Readable::read(reader)?;
484 let node_info = Readable::read(reader)?;
485 nodes.insert(node_id, node_info);
494 impl std::fmt::Display for NetworkGraph {
495 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
496 write!(f, "Network map\n[Channels]\n")?;
497 for (key, val) in self.channels.iter() {
498 write!(f, " {}: {}\n", key, val)?;
500 write!(f, "[Nodes]\n")?;
501 for (key, val) in self.nodes.iter() {
502 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
509 /// Returns all known valid channels
510 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
511 /// Returns all known nodes
512 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
514 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
515 /// Announcement signatures are checked here only if Secp256k1 object is provided.
516 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
517 if let Some(sig_verifier) = secp_ctx {
518 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
519 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
522 match self.nodes.get_mut(&msg.contents.node_id) {
523 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
525 if let Some(node_info) = node.announcement_info.as_ref() {
526 if node_info.last_update >= msg.contents.timestamp {
527 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
531 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
532 node.announcement_info = Some(NodeAnnouncementInfo {
533 features: msg.contents.features.clone(),
534 last_update: msg.contents.timestamp,
535 rgb: msg.contents.rgb,
536 alias: msg.contents.alias,
537 addresses: msg.contents.addresses.clone(),
538 announcement_message: if should_relay { Some(msg.clone()) } else { None },
546 /// For a new or already known (from previous announcement) channel, store or update channel info,
547 /// after making sure it corresponds to a real transaction on-chain.
548 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
549 /// Announcement signatures are checked here only if Secp256k1 object is provided.
550 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
551 if let Some(sig_verifier) = secp_ctx {
552 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
553 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
554 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
555 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
556 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
559 let should_relay = msg.contents.excess_data.is_empty();
561 let chan_info = ChannelInfo {
562 features: msg.contents.features.clone(),
563 one_to_two: DirectionalChannelInfo {
564 src_node_id: msg.contents.node_id_1.clone(),
567 cltv_expiry_delta: u16::max_value(),
568 htlc_minimum_msat: u64::max_value(),
570 base_msat: u32::max_value(),
571 proportional_millionths: u32::max_value(),
573 last_update_message: None,
575 two_to_one: DirectionalChannelInfo {
576 src_node_id: msg.contents.node_id_2.clone(),
579 cltv_expiry_delta: u16::max_value(),
580 htlc_minimum_msat: u64::max_value(),
582 base_msat: u32::max_value(),
583 proportional_millionths: u32::max_value(),
585 last_update_message: None,
587 announcement_message: if should_relay { Some(msg.clone()) } else { None },
590 match self.channels.entry(msg.contents.short_channel_id) {
591 BtreeEntry::Occupied(mut entry) => {
592 //TODO: because asking the blockchain if short_channel_id is valid is only optional
593 //in the blockchain API, we need to handle it smartly here, though it's unclear
596 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
597 // only sometimes returns results. In any case remove the previous entry. Note
598 // that the spec expects us to "blacklist" the node_ids involved, but we can't
600 // a) we don't *require* a UTXO provider that always returns results.
601 // b) we don't track UTXOs of channels we know about and remove them if they
603 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
604 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
605 *entry.get_mut() = chan_info;
607 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
610 BtreeEntry::Vacant(entry) => {
611 entry.insert(chan_info);
615 macro_rules! add_channel_to_node {
616 ( $node_id: expr ) => {
617 match self.nodes.entry($node_id) {
618 BtreeEntry::Occupied(node_entry) => {
619 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
621 BtreeEntry::Vacant(node_entry) => {
622 node_entry.insert(NodeInfo {
623 channels: vec!(msg.contents.short_channel_id),
624 lowest_inbound_channel_fees: None,
625 announcement_info: None,
632 add_channel_to_node!(msg.contents.node_id_1);
633 add_channel_to_node!(msg.contents.node_id_2);
638 /// Close a channel if a corresponding HTLC fail was sent.
639 /// If permanent, removes a channel from the local storage.
640 /// May cause the removal of nodes too, if this was their last channel.
641 /// If not permanent, makes channels unavailable for routing.
642 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
644 if let Some(chan) = self.channels.remove(short_channel_id) {
645 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
648 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
649 chan.one_to_two.enabled = false;
650 chan.two_to_one.enabled = false;
655 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
657 // TODO: Wholly remove the node
659 // TODO: downgrade the node
663 /// For an already known (from announcement) channel, update info regarding one of the directions of a channel.
664 /// Announcement signatures are checked here only if Secp256k1 object is provided.
665 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
667 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
668 let chan_was_enabled;
670 match self.channels.get_mut(&msg.contents.short_channel_id) {
671 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
673 macro_rules! maybe_update_channel_info {
674 ( $target: expr) => {
675 if $target.last_update >= msg.contents.timestamp {
676 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
678 chan_was_enabled = $target.enabled;
679 $target.last_update = msg.contents.timestamp;
680 $target.enabled = chan_enabled;
681 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
682 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
683 $target.fees.base_msat = msg.contents.fee_base_msat;
684 $target.fees.proportional_millionths = msg.contents.fee_proportional_millionths;
685 $target.last_update_message = if msg.contents.excess_data.is_empty() {
692 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
693 if msg.contents.flags & 1 == 1 {
694 dest_node_id = channel.one_to_two.src_node_id.clone();
695 if let Some(sig_verifier) = secp_ctx {
696 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
698 maybe_update_channel_info!(channel.two_to_one);
700 dest_node_id = channel.two_to_one.src_node_id.clone();
701 if let Some(sig_verifier) = secp_ctx {
702 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
704 maybe_update_channel_info!(channel.one_to_two);
710 let node = self.nodes.get_mut(&dest_node_id).unwrap();
711 let mut base_msat = msg.contents.fee_base_msat;
712 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
713 if let Some(fees) = node.lowest_inbound_channel_fees {
714 base_msat = cmp::min(base_msat, fees.base_msat);
715 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
717 node.lowest_inbound_channel_fees = Some(RoutingFees {
719 proportional_millionths
721 } else if chan_was_enabled {
722 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
723 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
726 let node = self.nodes.get(&dest_node_id).unwrap();
728 for chan_id in node.channels.iter() {
729 let chan = self.channels.get(chan_id).unwrap();
730 if chan.one_to_two.src_node_id == dest_node_id {
731 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fees.base_msat);
732 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fees.proportional_millionths);
734 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fees.base_msat);
735 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fees.proportional_millionths);
740 //TODO: satisfy the borrow-checker without a double-map-lookup :(
741 let mut_node = self.nodes.get_mut(&dest_node_id).unwrap();
742 if mut_node.channels.len() > 0 {
743 mut_node.lowest_inbound_channel_fees = Some(RoutingFees {
744 base_msat: lowest_inbound_channel_fee_base_msat,
745 proportional_millionths: lowest_inbound_channel_fee_proportional_millionths
750 Ok(msg.contents.excess_data.is_empty())
753 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
754 macro_rules! remove_from_node {
755 ($node_id: expr) => {
756 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
757 entry.get_mut().channels.retain(|chan_id| {
758 short_channel_id != *chan_id
760 if entry.get().channels.is_empty() {
761 entry.remove_entry();
764 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
768 remove_from_node!(chan.one_to_two.src_node_id);
769 remove_from_node!(chan.two_to_one.src_node_id);
775 use chain::chaininterface;
776 use ln::features::{ChannelFeatures, NodeFeatures};
777 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
778 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
779 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
780 use util::test_utils;
781 use util::logger::Logger;
782 use util::ser::{Readable, Writeable};
784 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
785 use bitcoin::hashes::Hash;
786 use bitcoin::network::constants::Network;
787 use bitcoin::blockdata::constants::genesis_block;
788 use bitcoin::blockdata::script::Builder;
789 use bitcoin::blockdata::opcodes;
790 use bitcoin::util::hash::BitcoinHash;
794 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
795 use bitcoin::secp256k1::{All, Secp256k1};
799 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
800 let secp_ctx = Secp256k1::new();
801 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
802 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
803 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
804 (secp_ctx, net_graph_msg_handler)
808 fn request_full_sync_finite_times() {
809 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
810 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
812 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
813 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
814 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
815 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
816 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
817 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
821 fn handling_node_announcements() {
822 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
824 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
825 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
826 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
827 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
828 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
829 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
830 let zero_hash = Sha256dHash::hash(&[0; 32]);
831 let first_announcement_time = 500;
833 let mut unsigned_announcement = UnsignedNodeAnnouncement {
834 features: NodeFeatures::known(),
835 timestamp: first_announcement_time,
839 addresses: Vec::new(),
840 excess_address_data: Vec::new(),
841 excess_data: Vec::new(),
843 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
844 let valid_announcement = NodeAnnouncement {
845 signature: secp_ctx.sign(&msghash, node_1_privkey),
846 contents: unsigned_announcement.clone()
849 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
851 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
855 // Announce a channel to add a corresponding node.
856 let unsigned_announcement = UnsignedChannelAnnouncement {
857 features: ChannelFeatures::known(),
858 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
862 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
863 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
864 excess_data: Vec::new(),
867 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
868 let valid_announcement = ChannelAnnouncement {
869 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
870 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
871 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
872 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
873 contents: unsigned_announcement.clone(),
875 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
876 Ok(res) => assert!(res),
881 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
882 Ok(res) => assert!(res),
886 let fake_msghash = hash_to_message!(&zero_hash);
887 match net_graph_msg_handler.handle_node_announcement(
889 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
890 contents: unsigned_announcement.clone()
893 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
896 unsigned_announcement.timestamp += 1000;
897 unsigned_announcement.excess_data.push(1);
898 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
899 let announcement_with_data = NodeAnnouncement {
900 signature: secp_ctx.sign(&msghash, node_1_privkey),
901 contents: unsigned_announcement.clone()
903 // Return false because contains excess data.
904 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
905 Ok(res) => assert!(!res),
908 unsigned_announcement.excess_data = Vec::new();
910 // Even though previous announcement was not relayed further, we still accepted it,
911 // so we now won't accept announcements before the previous one.
912 unsigned_announcement.timestamp -= 10;
913 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
914 let outdated_announcement = NodeAnnouncement {
915 signature: secp_ctx.sign(&msghash, node_1_privkey),
916 contents: unsigned_announcement.clone()
918 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
920 Err(e) => assert_eq!(e.err, "Update older than last processed update")
925 fn handling_channel_announcements() {
926 let secp_ctx = Secp256k1::new();
927 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
928 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
929 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
932 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
933 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
934 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
935 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
936 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
937 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
939 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
940 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
941 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
942 .push_opcode(opcodes::all::OP_PUSHNUM_2)
943 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
946 let mut unsigned_announcement = UnsignedChannelAnnouncement {
947 features: ChannelFeatures::known(),
948 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
952 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
953 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
954 excess_data: Vec::new(),
957 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
958 let valid_announcement = ChannelAnnouncement {
959 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
960 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
961 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
962 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
963 contents: unsigned_announcement.clone(),
966 // Test if the UTXO lookups were not supported
967 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
969 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
970 Ok(res) => assert!(res),
975 let network = net_graph_msg_handler.network_graph.read().unwrap();
976 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
983 // If we receive announcement for the same channel (with UTXO lookups disabled),
984 // drop new one on the floor, since we can't see any changes.
985 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
987 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
991 // Test if an associated transaction were not on-chain (or not confirmed).
992 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
993 unsigned_announcement.short_channel_id += 1;
995 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
996 let valid_announcement = ChannelAnnouncement {
997 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
998 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
999 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1000 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1001 contents: unsigned_announcement.clone(),
1004 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1006 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1010 // Now test if the transaction is found in the UTXO set and the script is correct.
1011 unsigned_announcement.short_channel_id += 1;
1012 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1014 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1015 let valid_announcement = ChannelAnnouncement {
1016 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1017 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1018 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1019 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1020 contents: unsigned_announcement.clone(),
1022 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1023 Ok(res) => assert!(res),
1028 let network = net_graph_msg_handler.network_graph.read().unwrap();
1029 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1035 // If we receive announcement for the same channel (but TX is not confirmed),
1036 // drop new one on the floor, since we can't see any changes.
1037 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1038 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1040 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1043 // But if it is confirmed, replace the channel
1044 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1045 unsigned_announcement.features = ChannelFeatures::empty();
1046 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1047 let valid_announcement = ChannelAnnouncement {
1048 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1049 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1050 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1051 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1052 contents: unsigned_announcement.clone(),
1054 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1055 Ok(res) => assert!(res),
1059 let network = net_graph_msg_handler.network_graph.read().unwrap();
1060 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1061 Some(channel_entry) => {
1062 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1068 // Don't relay valid channels with excess data
1069 unsigned_announcement.short_channel_id += 1;
1070 unsigned_announcement.excess_data.push(1);
1071 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1072 let valid_announcement = ChannelAnnouncement {
1073 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1074 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1075 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1076 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1077 contents: unsigned_announcement.clone(),
1079 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1080 Ok(res) => assert!(!res),
1084 unsigned_announcement.excess_data = Vec::new();
1085 let invalid_sig_announcement = ChannelAnnouncement {
1086 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1087 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1088 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1089 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1090 contents: unsigned_announcement.clone(),
1092 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1094 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1097 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1098 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1099 let channel_to_itself_announcement = ChannelAnnouncement {
1100 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1101 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1102 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1103 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1104 contents: unsigned_announcement.clone(),
1106 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1108 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1113 fn handling_channel_update() {
1114 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1115 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1116 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1117 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1118 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1119 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1120 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1122 let zero_hash = Sha256dHash::hash(&[0; 32]);
1123 let short_channel_id = 0;
1124 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1126 // Announce a channel we will update
1127 let unsigned_announcement = UnsignedChannelAnnouncement {
1128 features: ChannelFeatures::empty(),
1133 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1134 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1135 excess_data: Vec::new(),
1138 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1139 let valid_channel_announcement = ChannelAnnouncement {
1140 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1141 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1142 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1143 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1144 contents: unsigned_announcement.clone(),
1146 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1153 let mut unsigned_channel_update = UnsignedChannelUpdate {
1158 cltv_expiry_delta: 144,
1159 htlc_minimum_msat: 1000000,
1160 fee_base_msat: 10000,
1161 fee_proportional_millionths: 20,
1162 excess_data: Vec::new()
1164 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1165 let valid_channel_update = ChannelUpdate {
1166 signature: secp_ctx.sign(&msghash, node_1_privkey),
1167 contents: unsigned_channel_update.clone()
1170 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1171 Ok(res) => assert!(res),
1176 let network = net_graph_msg_handler.network_graph.read().unwrap();
1177 match network.get_channels().get(&short_channel_id) {
1179 Some(channel_info) => {
1180 assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
1181 assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
1186 unsigned_channel_update.timestamp += 100;
1187 unsigned_channel_update.excess_data.push(1);
1188 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1189 let valid_channel_update = ChannelUpdate {
1190 signature: secp_ctx.sign(&msghash, node_1_privkey),
1191 contents: unsigned_channel_update.clone()
1193 // Return false because contains excess data
1194 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1195 Ok(res) => assert!(!res),
1199 unsigned_channel_update.short_channel_id += 1;
1200 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1201 let valid_channel_update = ChannelUpdate {
1202 signature: secp_ctx.sign(&msghash, node_1_privkey),
1203 contents: unsigned_channel_update.clone()
1206 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1208 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1210 unsigned_channel_update.short_channel_id = short_channel_id;
1213 // Even though previous update was not relayed further, we still accepted it,
1214 // so we now won't accept update before the previous one.
1215 unsigned_channel_update.timestamp -= 10;
1216 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1217 let valid_channel_update = ChannelUpdate {
1218 signature: secp_ctx.sign(&msghash, node_1_privkey),
1219 contents: unsigned_channel_update.clone()
1222 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1224 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1226 unsigned_channel_update.timestamp += 500;
1228 let fake_msghash = hash_to_message!(&zero_hash);
1229 let invalid_sig_channel_update = ChannelUpdate {
1230 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1231 contents: unsigned_channel_update.clone()
1234 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1236 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1242 fn handling_htlc_fail_channel_update() {
1243 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1244 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1245 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1246 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1247 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1248 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1249 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1251 let short_channel_id = 0;
1252 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1255 // There is no nodes in the table at the beginning.
1256 let network = net_graph_msg_handler.network_graph.read().unwrap();
1257 assert_eq!(network.get_nodes().len(), 0);
1261 // Announce a channel we will update
1262 let unsigned_announcement = UnsignedChannelAnnouncement {
1263 features: ChannelFeatures::empty(),
1268 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1269 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1270 excess_data: Vec::new(),
1273 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1274 let valid_channel_announcement = ChannelAnnouncement {
1275 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1276 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1277 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1278 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1279 contents: unsigned_announcement.clone(),
1281 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1288 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1293 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1295 // Non-permanent closing just disables a channel
1297 let network = net_graph_msg_handler.network_graph.read().unwrap();
1298 match network.get_channels().get(&short_channel_id) {
1300 Some(channel_info) => {
1301 assert!(!channel_info.one_to_two.enabled);
1302 assert!(!channel_info.two_to_one.enabled);
1307 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1312 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1314 // Permanent closing deletes a channel
1316 let network = net_graph_msg_handler.network_graph.read().unwrap();
1317 assert_eq!(network.get_channels().len(), 0);
1318 // Nodes are also deleted because there are no associated channels anymore
1319 assert_eq!(network.get_nodes().len(), 0);
1321 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1325 fn getting_next_channel_announcements() {
1326 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1327 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1328 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1329 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1330 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1331 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1332 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1334 let short_channel_id = 1;
1335 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1337 // Channels were not announced yet.
1338 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1339 assert_eq!(channels_with_announcements.len(), 0);
1342 // Announce a channel we will update
1343 let unsigned_announcement = UnsignedChannelAnnouncement {
1344 features: ChannelFeatures::empty(),
1349 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1350 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1351 excess_data: Vec::new(),
1354 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1355 let valid_channel_announcement = ChannelAnnouncement {
1356 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1357 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1358 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1359 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1360 contents: unsigned_announcement.clone(),
1362 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1368 // Contains initial channel announcement now.
1369 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1370 assert_eq!(channels_with_announcements.len(), 1);
1371 if let Some(channel_announcements) = channels_with_announcements.first() {
1372 let &(_, ref update_1, ref update_2) = channel_announcements;
1373 assert_eq!(update_1, &None);
1374 assert_eq!(update_2, &None);
1381 // Valid channel update
1382 let unsigned_channel_update = UnsignedChannelUpdate {
1387 cltv_expiry_delta: 144,
1388 htlc_minimum_msat: 1000000,
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()
1398 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1404 // Now contains an initial announcement and an update.
1405 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1406 assert_eq!(channels_with_announcements.len(), 1);
1407 if let Some(channel_announcements) = channels_with_announcements.first() {
1408 let &(_, ref update_1, ref update_2) = channel_announcements;
1409 assert_ne!(update_1, &None);
1410 assert_eq!(update_2, &None);
1417 // Channel update with excess data.
1418 let unsigned_channel_update = UnsignedChannelUpdate {
1423 cltv_expiry_delta: 144,
1424 htlc_minimum_msat: 1000000,
1425 fee_base_msat: 10000,
1426 fee_proportional_millionths: 20,
1427 excess_data: [1; 3].to_vec()
1429 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1430 let valid_channel_update = ChannelUpdate {
1431 signature: secp_ctx.sign(&msghash, node_1_privkey),
1432 contents: unsigned_channel_update.clone()
1434 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1440 // Test that announcements with excess data won't be returned
1441 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1442 assert_eq!(channels_with_announcements.len(), 1);
1443 if let Some(channel_announcements) = channels_with_announcements.first() {
1444 let &(_, ref update_1, ref update_2) = channel_announcements;
1445 assert_eq!(update_1, &None);
1446 assert_eq!(update_2, &None);
1451 // Further starting point have no channels after it
1452 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1453 assert_eq!(channels_with_announcements.len(), 0);
1457 fn getting_next_node_announcements() {
1458 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1459 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1460 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1461 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1462 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1463 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1464 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1466 let short_channel_id = 1;
1467 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1470 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1471 assert_eq!(next_announcements.len(), 0);
1474 // Announce a channel to add 2 nodes
1475 let unsigned_announcement = UnsignedChannelAnnouncement {
1476 features: ChannelFeatures::empty(),
1481 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1482 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1483 excess_data: Vec::new(),
1486 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1487 let valid_channel_announcement = ChannelAnnouncement {
1488 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1489 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1490 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1491 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1492 contents: unsigned_announcement.clone(),
1494 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1501 // Nodes were never announced
1502 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1503 assert_eq!(next_announcements.len(), 0);
1506 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1507 features: NodeFeatures::known(),
1512 addresses: Vec::new(),
1513 excess_address_data: Vec::new(),
1514 excess_data: Vec::new(),
1516 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1517 let valid_announcement = NodeAnnouncement {
1518 signature: secp_ctx.sign(&msghash, node_1_privkey),
1519 contents: unsigned_announcement.clone()
1521 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1526 unsigned_announcement.node_id = node_id_2;
1527 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1528 let valid_announcement = NodeAnnouncement {
1529 signature: secp_ctx.sign(&msghash, node_2_privkey),
1530 contents: unsigned_announcement.clone()
1533 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1539 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1540 assert_eq!(next_announcements.len(), 2);
1542 // Skip the first node.
1543 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1544 assert_eq!(next_announcements.len(), 1);
1547 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1548 let unsigned_announcement = UnsignedNodeAnnouncement {
1549 features: NodeFeatures::known(),
1554 addresses: Vec::new(),
1555 excess_address_data: Vec::new(),
1556 excess_data: [1; 3].to_vec(),
1558 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1559 let valid_announcement = NodeAnnouncement {
1560 signature: secp_ctx.sign(&msghash, node_2_privkey),
1561 contents: unsigned_announcement.clone()
1563 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1564 Ok(res) => assert!(!res),
1569 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1570 assert_eq!(next_announcements.len(), 0);
1574 fn network_graph_serialization() {
1575 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1577 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1578 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1579 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1580 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1582 // Announce a channel to add a corresponding node.
1583 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1584 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1585 let unsigned_announcement = UnsignedChannelAnnouncement {
1586 features: ChannelFeatures::known(),
1587 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1588 short_channel_id: 0,
1591 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1592 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1593 excess_data: Vec::new(),
1596 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1597 let valid_announcement = ChannelAnnouncement {
1598 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1599 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1600 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1601 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1602 contents: unsigned_announcement.clone(),
1604 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1605 Ok(res) => assert!(res),
1610 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1611 let unsigned_announcement = UnsignedNodeAnnouncement {
1612 features: NodeFeatures::known(),
1617 addresses: Vec::new(),
1618 excess_address_data: Vec::new(),
1619 excess_data: Vec::new(),
1621 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1622 let valid_announcement = NodeAnnouncement {
1623 signature: secp_ctx.sign(&msghash, node_1_privkey),
1624 contents: unsigned_announcement.clone()
1627 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1632 let network = net_graph_msg_handler.network_graph.write().unwrap();
1633 let mut w = test_utils::TestVecWriter(Vec::new());
1634 assert!(!network.get_nodes().is_empty());
1635 assert!(!network.get_channels().is_empty());
1636 network.write(&mut w).unwrap();
1637 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);