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};
17 use util::logger::Logger;
20 use std::sync::RwLock;
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
25 use bitcoin::hashes::hex::ToHex;
27 /// Receives and validates network updates from peers,
28 /// stores authentic and relevant data as a network graph.
29 /// This network graph is then used for routing payments.
30 /// Provides interface to help with initial routing sync by
31 /// serving historical announcements.
32 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
33 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
34 /// Representation of the payment channel network
35 pub network_graph: RwLock<NetworkGraph>,
37 full_syncs_requested: AtomicUsize,
41 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
42 /// Creates a new tracker of the actual state of the network of channels and nodes,
43 /// assuming a fresh network graph.
44 /// Chain monitor is used to make sure announced channels exist on-chain,
45 /// channel data is correct, and that the announcement is signed with
46 /// channel owners' keys.
47 pub fn new(chain_monitor: C, logger: L) -> Self {
49 secp_ctx: Secp256k1::verification_only(),
50 network_graph: RwLock::new(NetworkGraph {
51 channels: BTreeMap::new(),
52 nodes: BTreeMap::new(),
54 full_syncs_requested: AtomicUsize::new(0),
60 /// Creates a new tracker of the actual state of the network of channels and nodes,
61 /// assuming an existing Network Graph.
62 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
64 secp_ctx: Secp256k1::verification_only(),
65 network_graph: RwLock::new(network_graph),
66 full_syncs_requested: AtomicUsize::new(0),
74 macro_rules! secp_verify_sig {
75 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
76 match $secp_ctx.verify($msg, $sig, $pubkey) {
78 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
83 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
84 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
85 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
88 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
89 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
90 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
93 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
94 Ok((script_pubkey, _value)) => {
95 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
96 .push_slice(&msg.contents.bitcoin_key_1.serialize())
97 .push_slice(&msg.contents.bitcoin_key_2.serialize())
98 .push_opcode(opcodes::all::OP_PUSHNUM_2)
99 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
100 if script_pubkey != expected_script {
101 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});
103 //TODO: Check if value is worth storing, use it to inform routing, and compare it
104 //to the new HTLC max field in channel_update
107 Err(ChainError::NotSupported) => {
108 // Tentatively accept, potentially exposing us to DoS attacks
111 Err(ChainError::NotWatched) => {
112 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
114 Err(ChainError::UnknownTx) => {
115 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
118 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
119 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 { "" });
123 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
125 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
126 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
128 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
129 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
131 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
132 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
137 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
138 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
141 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
142 let network_graph = self.network_graph.read().unwrap();
143 let mut result = Vec::with_capacity(batch_amount as usize);
144 let mut iter = network_graph.get_channels().range(starting_point..);
145 while result.len() < batch_amount as usize {
146 if let Some((_, ref chan)) = iter.next() {
147 if chan.announcement_message.is_some() {
148 let chan_announcement = chan.announcement_message.clone().unwrap();
149 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
150 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
151 if let Some(one_to_two) = chan.one_to_two.as_ref() {
152 one_to_two_announcement = one_to_two.last_update_message.clone();
154 if let Some(two_to_one) = chan.two_to_one.as_ref() {
155 two_to_one_announcement = two_to_one.last_update_message.clone();
157 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
159 // TODO: We may end up sending un-announced channel_updates if we are sending
160 // initial sync data while receiving announce/updates for this channel.
169 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
170 let network_graph = self.network_graph.read().unwrap();
171 let mut result = Vec::with_capacity(batch_amount as usize);
172 let mut iter = if let Some(pubkey) = starting_point {
173 let mut iter = network_graph.get_nodes().range((*pubkey)..);
177 network_graph.get_nodes().range(..)
179 while result.len() < batch_amount as usize {
180 if let Some((_, ref node)) = iter.next() {
181 if let Some(node_info) = node.announcement_info.as_ref() {
182 if node_info.announcement_message.is_some() {
183 result.push(node_info.announcement_message.clone().unwrap());
193 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
194 //TODO: Determine whether to request a full sync based on the network map.
195 const FULL_SYNCS_TO_REQUEST: usize = 5;
196 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
197 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
205 #[derive(PartialEq, Debug)]
206 /// Details about one direction of a channel. Received
207 /// within a channel update.
208 pub struct DirectionalChannelInfo {
209 /// When the last update to the channel direction was issued.
210 /// Value is opaque, as set in the announcement.
211 pub last_update: u32,
212 /// Whether the channel can be currently used for payments (in this one direction).
214 /// The difference in CLTV values that you must have when routing through this channel.
215 pub cltv_expiry_delta: u16,
216 /// The minimum value, which must be relayed to the next hop via the channel
217 pub htlc_minimum_msat: u64,
218 /// Fees charged when the channel is used for routing
219 pub fees: RoutingFees,
220 /// Most recent update for the channel received from the network
221 /// Mostly redundant with the data we store in fields explicitly.
222 /// Everything else is useful only for sending out for initial routing sync.
223 /// Not stored if contains excess data to prevent DoS.
224 pub last_update_message: Option<msgs::ChannelUpdate>,
227 impl fmt::Display for DirectionalChannelInfo {
228 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
229 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)?;
234 impl_writeable!(DirectionalChannelInfo, 0, {
244 /// Details about a channel (both directions).
245 /// Received within a channel announcement.
246 pub struct ChannelInfo {
247 /// Protocol features of a channel communicated during its announcement
248 pub features: ChannelFeatures,
249 /// Source node of the first direction of a channel
250 pub node_one: PublicKey,
251 /// Details about the first direction of a channel
252 pub one_to_two: Option<DirectionalChannelInfo>,
253 /// Source node of the second direction of a channel
254 pub node_two: PublicKey,
255 /// Details about the second direction of a channel
256 pub two_to_one: Option<DirectionalChannelInfo>,
257 /// An initial announcement of the channel
258 /// Mostly redundant with the data we store in fields explicitly.
259 /// Everything else is useful only for sending out for initial routing sync.
260 /// Not stored if contains excess data to prevent DoS.
261 pub announcement_message: Option<msgs::ChannelAnnouncement>,
264 impl fmt::Display for ChannelInfo {
265 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
266 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
267 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
272 impl_writeable!(ChannelInfo, 0, {
282 /// Fees for routing via a given channel or a node
283 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
284 pub struct RoutingFees {
285 /// Flat routing fee in satoshis
287 /// Liquidity-based routing fee in millionths of a routed amount.
288 /// In other words, 10000 is 1%.
289 pub proportional_millionths: u32,
292 impl Readable for RoutingFees{
293 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
294 let base_msat: u32 = Readable::read(reader)?;
295 let proportional_millionths: u32 = Readable::read(reader)?;
298 proportional_millionths,
303 impl Writeable for RoutingFees {
304 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
305 self.base_msat.write(writer)?;
306 self.proportional_millionths.write(writer)?;
311 #[derive(PartialEq, Debug)]
312 /// Information received in the latest node_announcement from this node.
313 pub struct NodeAnnouncementInfo {
314 /// Protocol features the node announced support for
315 pub features: NodeFeatures,
316 /// When the last known update to the node state was issued.
317 /// Value is opaque, as set in the announcement.
318 pub last_update: u32,
319 /// Color assigned to the node
321 /// Moniker assigned to the node.
322 /// May be invalid or malicious (eg control chars),
323 /// should not be exposed to the user.
325 /// Internet-level addresses via which one can connect to the node
326 pub addresses: Vec<NetAddress>,
327 /// An initial announcement of the node
328 /// Mostly redundant with the data we store in fields explicitly.
329 /// Everything else is useful only for sending out for initial routing sync.
330 /// Not stored if contains excess data to prevent DoS.
331 pub announcement_message: Option<msgs::NodeAnnouncement>
334 impl Writeable for NodeAnnouncementInfo {
335 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
336 self.features.write(writer)?;
337 self.last_update.write(writer)?;
338 self.rgb.write(writer)?;
339 self.alias.write(writer)?;
340 (self.addresses.len() as u64).write(writer)?;
341 for ref addr in &self.addresses {
344 self.announcement_message.write(writer)?;
349 impl Readable for NodeAnnouncementInfo {
350 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
351 let features = Readable::read(reader)?;
352 let last_update = Readable::read(reader)?;
353 let rgb = Readable::read(reader)?;
354 let alias = Readable::read(reader)?;
355 let addresses_count: u64 = Readable::read(reader)?;
356 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
357 for _ in 0..addresses_count {
358 match Readable::read(reader) {
359 Ok(Ok(addr)) => { addresses.push(addr); },
360 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
361 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
365 let announcement_message = Readable::read(reader)?;
366 Ok(NodeAnnouncementInfo {
378 /// Details about a node in the network, known from the network announcement.
379 pub struct NodeInfo {
380 /// All valid channels a node has announced
381 pub channels: Vec<u64>,
382 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
383 /// The two fields (flat and proportional fee) are independent,
384 /// meaning they don't have to refer to the same channel.
385 pub lowest_inbound_channel_fees: Option<RoutingFees>,
386 /// More information about a node from node_announcement.
387 /// Optional because we store a Node entry after learning about it from
388 /// a channel announcement, but before receiving a node announcement.
389 pub announcement_info: Option<NodeAnnouncementInfo>
392 impl fmt::Display for NodeInfo {
393 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
394 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
395 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
400 impl Writeable for NodeInfo {
401 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
402 (self.channels.len() as u64).write(writer)?;
403 for ref chan in self.channels.iter() {
406 self.lowest_inbound_channel_fees.write(writer)?;
407 self.announcement_info.write(writer)?;
412 const MAX_ALLOC_SIZE: u64 = 64*1024;
414 impl Readable for NodeInfo {
415 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
416 let channels_count: u64 = Readable::read(reader)?;
417 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
418 for _ in 0..channels_count {
419 channels.push(Readable::read(reader)?);
421 let lowest_inbound_channel_fees = Readable::read(reader)?;
422 let announcement_info = Readable::read(reader)?;
425 lowest_inbound_channel_fees,
431 /// Represents the network as nodes and channels between them
433 pub struct NetworkGraph {
434 channels: BTreeMap<u64, ChannelInfo>,
435 nodes: BTreeMap<PublicKey, NodeInfo>,
438 impl Writeable for NetworkGraph {
439 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
440 (self.channels.len() as u64).write(writer)?;
441 for (ref chan_id, ref chan_info) in self.channels.iter() {
442 (*chan_id).write(writer)?;
443 chan_info.write(writer)?;
445 (self.nodes.len() as u64).write(writer)?;
446 for (ref node_id, ref node_info) in self.nodes.iter() {
447 node_id.write(writer)?;
448 node_info.write(writer)?;
454 impl Readable for NetworkGraph {
455 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
456 let channels_count: u64 = Readable::read(reader)?;
457 let mut channels = BTreeMap::new();
458 for _ in 0..channels_count {
459 let chan_id: u64 = Readable::read(reader)?;
460 let chan_info = Readable::read(reader)?;
461 channels.insert(chan_id, chan_info);
463 let nodes_count: u64 = Readable::read(reader)?;
464 let mut nodes = BTreeMap::new();
465 for _ in 0..nodes_count {
466 let node_id = Readable::read(reader)?;
467 let node_info = Readable::read(reader)?;
468 nodes.insert(node_id, node_info);
477 impl fmt::Display for NetworkGraph {
478 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
479 write!(f, "Network map\n[Channels]\n")?;
480 for (key, val) in self.channels.iter() {
481 write!(f, " {}: {}\n", key, val)?;
483 write!(f, "[Nodes]\n")?;
484 for (key, val) in self.nodes.iter() {
485 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
492 /// Returns all known valid channels' short ids along with announced channel info.
493 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
494 /// Returns all known nodes' public keys along with announced node info.
495 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
497 /// Get network addresses by node id.
498 /// Returns None if the requested node is completely unknown,
499 /// or if node announcement for the node was never received.
500 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
501 if let Some(node) = self.nodes.get(pubkey) {
502 if let Some(node_info) = node.announcement_info.as_ref() {
503 return Some(&node_info.addresses)
509 /// Creates a new, empty, network graph.
510 pub fn new() -> NetworkGraph {
512 channels: BTreeMap::new(),
513 nodes: BTreeMap::new(),
517 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
518 /// Announcement signatures are checked here only if Secp256k1 object is provided.
519 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
520 if let Some(sig_verifier) = secp_ctx {
521 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
522 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
525 match self.nodes.get_mut(&msg.contents.node_id) {
526 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
528 if let Some(node_info) = node.announcement_info.as_ref() {
529 if node_info.last_update >= msg.contents.timestamp {
530 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
534 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
535 node.announcement_info = Some(NodeAnnouncementInfo {
536 features: msg.contents.features.clone(),
537 last_update: msg.contents.timestamp,
538 rgb: msg.contents.rgb,
539 alias: msg.contents.alias,
540 addresses: msg.contents.addresses.clone(),
541 announcement_message: if should_relay { Some(msg.clone()) } else { None },
549 /// For a new or already known (from previous announcement) channel, store or update channel info.
550 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
551 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
552 /// which is probably result of a reorg. In that case, we update channel info only if the
553 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
554 /// Announcement signatures are checked here only if Secp256k1 object is provided.
555 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
556 if let Some(sig_verifier) = secp_ctx {
557 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
558 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
559 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
560 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
561 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
564 let should_relay = msg.contents.excess_data.is_empty();
566 let chan_info = ChannelInfo {
567 features: msg.contents.features.clone(),
568 node_one: msg.contents.node_id_1.clone(),
570 node_two: msg.contents.node_id_2.clone(),
572 announcement_message: if should_relay { Some(msg.clone()) } else { None },
575 match self.channels.entry(msg.contents.short_channel_id) {
576 BtreeEntry::Occupied(mut entry) => {
577 //TODO: because asking the blockchain if short_channel_id is valid is only optional
578 //in the blockchain API, we need to handle it smartly here, though it's unclear
581 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
582 // only sometimes returns results. In any case remove the previous entry. Note
583 // that the spec expects us to "blacklist" the node_ids involved, but we can't
585 // a) we don't *require* a UTXO provider that always returns results.
586 // b) we don't track UTXOs of channels we know about and remove them if they
588 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
589 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
590 *entry.get_mut() = chan_info;
592 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
595 BtreeEntry::Vacant(entry) => {
596 entry.insert(chan_info);
600 macro_rules! add_channel_to_node {
601 ( $node_id: expr ) => {
602 match self.nodes.entry($node_id) {
603 BtreeEntry::Occupied(node_entry) => {
604 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
606 BtreeEntry::Vacant(node_entry) => {
607 node_entry.insert(NodeInfo {
608 channels: vec!(msg.contents.short_channel_id),
609 lowest_inbound_channel_fees: None,
610 announcement_info: None,
617 add_channel_to_node!(msg.contents.node_id_1);
618 add_channel_to_node!(msg.contents.node_id_2);
623 /// Close a channel if a corresponding HTLC fail was sent.
624 /// If permanent, removes a channel from the local storage.
625 /// May cause the removal of nodes too, if this was their last channel.
626 /// If not permanent, makes channels unavailable for routing.
627 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
629 if let Some(chan) = self.channels.remove(&short_channel_id) {
630 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
633 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
634 if let Some(one_to_two) = chan.one_to_two.as_mut() {
635 one_to_two.enabled = false;
637 if let Some(two_to_one) = chan.two_to_one.as_mut() {
638 two_to_one.enabled = false;
644 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
646 // TODO: Wholly remove the node
648 // TODO: downgrade the node
652 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
653 /// Announcement signatures are checked here only if Secp256k1 object is provided.
654 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
656 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
657 let chan_was_enabled;
659 match self.channels.get_mut(&msg.contents.short_channel_id) {
660 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
662 macro_rules! maybe_update_channel_info {
663 ( $target: expr, $src_node: expr) => {
664 if let Some(existing_chan_info) = $target.as_ref() {
665 if existing_chan_info.last_update >= msg.contents.timestamp {
666 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
668 chan_was_enabled = existing_chan_info.enabled;
670 chan_was_enabled = false;
673 let last_update_message = if msg.contents.excess_data.is_empty() {
679 let updated_channel_dir_info = DirectionalChannelInfo {
680 enabled: chan_enabled,
681 last_update: msg.contents.timestamp,
682 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
683 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
685 base_msat: msg.contents.fee_base_msat,
686 proportional_millionths: msg.contents.fee_proportional_millionths,
690 $target = Some(updated_channel_dir_info);
694 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
695 if msg.contents.flags & 1 == 1 {
696 dest_node_id = channel.node_one.clone();
697 if let Some(sig_verifier) = secp_ctx {
698 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
700 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
702 dest_node_id = channel.node_two.clone();
703 if let Some(sig_verifier) = secp_ctx {
704 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
706 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
712 let node = self.nodes.get_mut(&dest_node_id).unwrap();
713 let mut base_msat = msg.contents.fee_base_msat;
714 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
715 if let Some(fees) = node.lowest_inbound_channel_fees {
716 base_msat = cmp::min(base_msat, fees.base_msat);
717 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
719 node.lowest_inbound_channel_fees = Some(RoutingFees {
721 proportional_millionths
723 } else if chan_was_enabled {
724 let node = self.nodes.get_mut(&dest_node_id).unwrap();
725 let mut lowest_inbound_channel_fees = None;
727 for chan_id in node.channels.iter() {
728 let chan = self.channels.get(chan_id).unwrap();
730 if chan.node_one == dest_node_id {
731 chan_info_opt = chan.two_to_one.as_ref();
733 chan_info_opt = chan.one_to_two.as_ref();
735 if let Some(chan_info) = chan_info_opt {
736 if chan_info.enabled {
737 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
738 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
739 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
740 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
745 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
748 Ok(msg.contents.excess_data.is_empty())
751 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
752 macro_rules! remove_from_node {
753 ($node_id: expr) => {
754 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
755 entry.get_mut().channels.retain(|chan_id| {
756 short_channel_id != *chan_id
758 if entry.get().channels.is_empty() {
759 entry.remove_entry();
762 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
767 remove_from_node!(chan.node_one);
768 remove_from_node!(chan.node_two);
774 use chain::chaininterface;
775 use ln::features::{ChannelFeatures, NodeFeatures};
776 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
777 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
778 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
779 use util::test_utils;
780 use util::logger::Logger;
781 use util::ser::{Readable, Writeable};
783 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
784 use bitcoin::hashes::Hash;
785 use bitcoin::network::constants::Network;
786 use bitcoin::blockdata::constants::genesis_block;
787 use bitcoin::blockdata::script::Builder;
788 use bitcoin::blockdata::opcodes;
789 use bitcoin::util::hash::BitcoinHash;
793 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
794 use bitcoin::secp256k1::{All, Secp256k1};
798 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
799 let secp_ctx = Secp256k1::new();
800 let logger = Arc::new(test_utils::TestLogger::new());
801 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
802 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
803 (secp_ctx, net_graph_msg_handler)
807 fn request_full_sync_finite_times() {
808 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
809 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
811 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
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));
820 fn handling_node_announcements() {
821 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
823 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
824 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
825 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
826 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
827 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
828 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
829 let zero_hash = Sha256dHash::hash(&[0; 32]);
830 let first_announcement_time = 500;
832 let mut unsigned_announcement = UnsignedNodeAnnouncement {
833 features: NodeFeatures::known(),
834 timestamp: first_announcement_time,
838 addresses: Vec::new(),
839 excess_address_data: Vec::new(),
840 excess_data: Vec::new(),
842 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
843 let valid_announcement = NodeAnnouncement {
844 signature: secp_ctx.sign(&msghash, node_1_privkey),
845 contents: unsigned_announcement.clone()
848 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
850 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
854 // Announce a channel to add a corresponding node.
855 let unsigned_announcement = UnsignedChannelAnnouncement {
856 features: ChannelFeatures::known(),
857 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
861 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
862 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
863 excess_data: Vec::new(),
866 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
867 let valid_announcement = ChannelAnnouncement {
868 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
869 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
870 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
871 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
872 contents: unsigned_announcement.clone(),
874 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
875 Ok(res) => assert!(res),
880 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
881 Ok(res) => assert!(res),
885 let fake_msghash = hash_to_message!(&zero_hash);
886 match net_graph_msg_handler.handle_node_announcement(
888 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
889 contents: unsigned_announcement.clone()
892 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
895 unsigned_announcement.timestamp += 1000;
896 unsigned_announcement.excess_data.push(1);
897 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
898 let announcement_with_data = NodeAnnouncement {
899 signature: secp_ctx.sign(&msghash, node_1_privkey),
900 contents: unsigned_announcement.clone()
902 // Return false because contains excess data.
903 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
904 Ok(res) => assert!(!res),
907 unsigned_announcement.excess_data = Vec::new();
909 // Even though previous announcement was not relayed further, we still accepted it,
910 // so we now won't accept announcements before the previous one.
911 unsigned_announcement.timestamp -= 10;
912 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
913 let outdated_announcement = NodeAnnouncement {
914 signature: secp_ctx.sign(&msghash, node_1_privkey),
915 contents: unsigned_announcement.clone()
917 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
919 Err(e) => assert_eq!(e.err, "Update older than last processed update")
924 fn handling_channel_announcements() {
925 let secp_ctx = Secp256k1::new();
926 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
927 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
928 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
931 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
932 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
933 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
934 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
935 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
936 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
938 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
939 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
940 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
941 .push_opcode(opcodes::all::OP_PUSHNUM_2)
942 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
945 let mut unsigned_announcement = UnsignedChannelAnnouncement {
946 features: ChannelFeatures::known(),
947 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
951 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
952 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
953 excess_data: Vec::new(),
956 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
957 let valid_announcement = ChannelAnnouncement {
958 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
959 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
960 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
961 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
962 contents: unsigned_announcement.clone(),
965 // Test if the UTXO lookups were not supported
966 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
968 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
969 Ok(res) => assert!(res),
974 let network = net_graph_msg_handler.network_graph.read().unwrap();
975 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
982 // If we receive announcement for the same channel (with UTXO lookups disabled),
983 // drop new one on the floor, since we can't see any changes.
984 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
986 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
990 // Test if an associated transaction were not on-chain (or not confirmed).
991 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
992 unsigned_announcement.short_channel_id += 1;
994 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
995 let valid_announcement = ChannelAnnouncement {
996 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
997 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
998 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
999 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1000 contents: unsigned_announcement.clone(),
1003 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1005 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1009 // Now test if the transaction is found in the UTXO set and the script is correct.
1010 unsigned_announcement.short_channel_id += 1;
1011 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1013 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1014 let valid_announcement = ChannelAnnouncement {
1015 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1016 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1017 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1018 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1019 contents: unsigned_announcement.clone(),
1021 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1022 Ok(res) => assert!(res),
1027 let network = net_graph_msg_handler.network_graph.read().unwrap();
1028 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1034 // If we receive announcement for the same channel (but TX is not confirmed),
1035 // drop new one on the floor, since we can't see any changes.
1036 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1037 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1039 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1042 // But if it is confirmed, replace the channel
1043 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1044 unsigned_announcement.features = ChannelFeatures::empty();
1045 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1046 let valid_announcement = ChannelAnnouncement {
1047 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1048 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1049 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1050 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1051 contents: unsigned_announcement.clone(),
1053 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1054 Ok(res) => assert!(res),
1058 let network = net_graph_msg_handler.network_graph.read().unwrap();
1059 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1060 Some(channel_entry) => {
1061 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1067 // Don't relay valid channels with excess data
1068 unsigned_announcement.short_channel_id += 1;
1069 unsigned_announcement.excess_data.push(1);
1070 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1071 let valid_announcement = ChannelAnnouncement {
1072 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1073 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1074 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1075 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1076 contents: unsigned_announcement.clone(),
1078 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1079 Ok(res) => assert!(!res),
1083 unsigned_announcement.excess_data = Vec::new();
1084 let invalid_sig_announcement = ChannelAnnouncement {
1085 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1086 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1087 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1088 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1089 contents: unsigned_announcement.clone(),
1091 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1093 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1096 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1097 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1098 let channel_to_itself_announcement = ChannelAnnouncement {
1099 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1100 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1101 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1102 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1103 contents: unsigned_announcement.clone(),
1105 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1107 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1112 fn handling_channel_update() {
1113 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1114 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1115 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1116 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1117 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1118 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1119 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1121 let zero_hash = Sha256dHash::hash(&[0; 32]);
1122 let short_channel_id = 0;
1123 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1125 // Announce a channel we will update
1126 let unsigned_announcement = UnsignedChannelAnnouncement {
1127 features: ChannelFeatures::empty(),
1132 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1133 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1134 excess_data: Vec::new(),
1137 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1138 let valid_channel_announcement = ChannelAnnouncement {
1139 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1140 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1141 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1142 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1143 contents: unsigned_announcement.clone(),
1145 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1152 let mut unsigned_channel_update = UnsignedChannelUpdate {
1157 cltv_expiry_delta: 144,
1158 htlc_minimum_msat: 1000000,
1159 fee_base_msat: 10000,
1160 fee_proportional_millionths: 20,
1161 excess_data: Vec::new()
1163 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1164 let valid_channel_update = ChannelUpdate {
1165 signature: secp_ctx.sign(&msghash, node_1_privkey),
1166 contents: unsigned_channel_update.clone()
1169 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1170 Ok(res) => assert!(res),
1175 let network = net_graph_msg_handler.network_graph.read().unwrap();
1176 match network.get_channels().get(&short_channel_id) {
1178 Some(channel_info) => {
1179 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1180 assert!(channel_info.two_to_one.is_none());
1185 unsigned_channel_update.timestamp += 100;
1186 unsigned_channel_update.excess_data.push(1);
1187 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1188 let valid_channel_update = ChannelUpdate {
1189 signature: secp_ctx.sign(&msghash, node_1_privkey),
1190 contents: unsigned_channel_update.clone()
1192 // Return false because contains excess data
1193 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1194 Ok(res) => assert!(!res),
1198 unsigned_channel_update.short_channel_id += 1;
1199 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1200 let valid_channel_update = ChannelUpdate {
1201 signature: secp_ctx.sign(&msghash, node_1_privkey),
1202 contents: unsigned_channel_update.clone()
1205 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1207 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1209 unsigned_channel_update.short_channel_id = short_channel_id;
1212 // Even though previous update was not relayed further, we still accepted it,
1213 // so we now won't accept update before the previous one.
1214 unsigned_channel_update.timestamp -= 10;
1215 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1216 let valid_channel_update = ChannelUpdate {
1217 signature: secp_ctx.sign(&msghash, node_1_privkey),
1218 contents: unsigned_channel_update.clone()
1221 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1223 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1225 unsigned_channel_update.timestamp += 500;
1227 let fake_msghash = hash_to_message!(&zero_hash);
1228 let invalid_sig_channel_update = ChannelUpdate {
1229 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1230 contents: unsigned_channel_update.clone()
1233 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1235 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1241 fn handling_htlc_fail_channel_update() {
1242 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1243 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1244 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1245 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1246 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1247 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1248 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1250 let short_channel_id = 0;
1251 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1254 // There is no nodes in the table at the beginning.
1255 let network = net_graph_msg_handler.network_graph.read().unwrap();
1256 assert_eq!(network.get_nodes().len(), 0);
1260 // Announce a channel we will update
1261 let unsigned_announcement = UnsignedChannelAnnouncement {
1262 features: ChannelFeatures::empty(),
1267 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1268 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1269 excess_data: Vec::new(),
1272 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1273 let valid_channel_announcement = ChannelAnnouncement {
1274 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1275 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1276 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1277 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1278 contents: unsigned_announcement.clone(),
1280 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1285 let unsigned_channel_update = UnsignedChannelUpdate {
1290 cltv_expiry_delta: 144,
1291 htlc_minimum_msat: 1000000,
1292 fee_base_msat: 10000,
1293 fee_proportional_millionths: 20,
1294 excess_data: Vec::new()
1296 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1297 let valid_channel_update = ChannelUpdate {
1298 signature: secp_ctx.sign(&msghash, node_1_privkey),
1299 contents: unsigned_channel_update.clone()
1302 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1303 Ok(res) => assert!(res),
1308 // Non-permanent closing just disables a channel
1310 let network = net_graph_msg_handler.network_graph.read().unwrap();
1311 match network.get_channels().get(&short_channel_id) {
1313 Some(channel_info) => {
1314 assert!(channel_info.one_to_two.is_some());
1319 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1324 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1326 // Non-permanent closing just disables a channel
1328 let network = net_graph_msg_handler.network_graph.read().unwrap();
1329 match network.get_channels().get(&short_channel_id) {
1331 Some(channel_info) => {
1332 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1337 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1342 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1344 // Permanent closing deletes a channel
1346 let network = net_graph_msg_handler.network_graph.read().unwrap();
1347 assert_eq!(network.get_channels().len(), 0);
1348 // Nodes are also deleted because there are no associated channels anymore
1349 assert_eq!(network.get_nodes().len(), 0);
1351 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1355 fn getting_next_channel_announcements() {
1356 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1357 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1358 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1359 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1360 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1361 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1362 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1364 let short_channel_id = 1;
1365 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1367 // Channels were not announced yet.
1368 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1369 assert_eq!(channels_with_announcements.len(), 0);
1372 // Announce a channel we will update
1373 let unsigned_announcement = UnsignedChannelAnnouncement {
1374 features: ChannelFeatures::empty(),
1379 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1380 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1381 excess_data: Vec::new(),
1384 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1385 let valid_channel_announcement = ChannelAnnouncement {
1386 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1387 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1388 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1389 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1390 contents: unsigned_announcement.clone(),
1392 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1398 // Contains initial channel announcement now.
1399 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1400 assert_eq!(channels_with_announcements.len(), 1);
1401 if let Some(channel_announcements) = channels_with_announcements.first() {
1402 let &(_, ref update_1, ref update_2) = channel_announcements;
1403 assert_eq!(update_1, &None);
1404 assert_eq!(update_2, &None);
1411 // Valid channel update
1412 let unsigned_channel_update = UnsignedChannelUpdate {
1417 cltv_expiry_delta: 144,
1418 htlc_minimum_msat: 1000000,
1419 fee_base_msat: 10000,
1420 fee_proportional_millionths: 20,
1421 excess_data: Vec::new()
1423 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1424 let valid_channel_update = ChannelUpdate {
1425 signature: secp_ctx.sign(&msghash, node_1_privkey),
1426 contents: unsigned_channel_update.clone()
1428 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1434 // Now contains an initial announcement and an update.
1435 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1436 assert_eq!(channels_with_announcements.len(), 1);
1437 if let Some(channel_announcements) = channels_with_announcements.first() {
1438 let &(_, ref update_1, ref update_2) = channel_announcements;
1439 assert_ne!(update_1, &None);
1440 assert_eq!(update_2, &None);
1447 // Channel update with excess data.
1448 let unsigned_channel_update = UnsignedChannelUpdate {
1453 cltv_expiry_delta: 144,
1454 htlc_minimum_msat: 1000000,
1455 fee_base_msat: 10000,
1456 fee_proportional_millionths: 20,
1457 excess_data: [1; 3].to_vec()
1459 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1460 let valid_channel_update = ChannelUpdate {
1461 signature: secp_ctx.sign(&msghash, node_1_privkey),
1462 contents: unsigned_channel_update.clone()
1464 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1470 // Test that announcements with excess data won't be returned
1471 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1472 assert_eq!(channels_with_announcements.len(), 1);
1473 if let Some(channel_announcements) = channels_with_announcements.first() {
1474 let &(_, ref update_1, ref update_2) = channel_announcements;
1475 assert_eq!(update_1, &None);
1476 assert_eq!(update_2, &None);
1481 // Further starting point have no channels after it
1482 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1483 assert_eq!(channels_with_announcements.len(), 0);
1487 fn getting_next_node_announcements() {
1488 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1489 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1490 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1491 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1492 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1493 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1494 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1496 let short_channel_id = 1;
1497 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1500 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1501 assert_eq!(next_announcements.len(), 0);
1504 // Announce a channel to add 2 nodes
1505 let unsigned_announcement = UnsignedChannelAnnouncement {
1506 features: ChannelFeatures::empty(),
1511 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1512 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1513 excess_data: Vec::new(),
1516 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1517 let valid_channel_announcement = ChannelAnnouncement {
1518 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1519 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1520 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1521 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1522 contents: unsigned_announcement.clone(),
1524 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1531 // Nodes were never announced
1532 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1533 assert_eq!(next_announcements.len(), 0);
1536 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1537 features: NodeFeatures::known(),
1542 addresses: Vec::new(),
1543 excess_address_data: Vec::new(),
1544 excess_data: Vec::new(),
1546 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1547 let valid_announcement = NodeAnnouncement {
1548 signature: secp_ctx.sign(&msghash, node_1_privkey),
1549 contents: unsigned_announcement.clone()
1551 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1556 unsigned_announcement.node_id = node_id_2;
1557 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1558 let valid_announcement = NodeAnnouncement {
1559 signature: secp_ctx.sign(&msghash, node_2_privkey),
1560 contents: unsigned_announcement.clone()
1563 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1569 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1570 assert_eq!(next_announcements.len(), 2);
1572 // Skip the first node.
1573 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1574 assert_eq!(next_announcements.len(), 1);
1577 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1578 let unsigned_announcement = UnsignedNodeAnnouncement {
1579 features: NodeFeatures::known(),
1584 addresses: Vec::new(),
1585 excess_address_data: Vec::new(),
1586 excess_data: [1; 3].to_vec(),
1588 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1589 let valid_announcement = NodeAnnouncement {
1590 signature: secp_ctx.sign(&msghash, node_2_privkey),
1591 contents: unsigned_announcement.clone()
1593 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1594 Ok(res) => assert!(!res),
1599 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1600 assert_eq!(next_announcements.len(), 0);
1604 fn network_graph_serialization() {
1605 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1607 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1608 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1609 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1610 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1612 // Announce a channel to add a corresponding node.
1613 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1614 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1615 let unsigned_announcement = UnsignedChannelAnnouncement {
1616 features: ChannelFeatures::known(),
1617 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1618 short_channel_id: 0,
1621 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1622 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1623 excess_data: Vec::new(),
1626 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1627 let valid_announcement = ChannelAnnouncement {
1628 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1629 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1630 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1631 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1632 contents: unsigned_announcement.clone(),
1634 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1635 Ok(res) => assert!(res),
1640 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1641 let unsigned_announcement = UnsignedNodeAnnouncement {
1642 features: NodeFeatures::known(),
1647 addresses: Vec::new(),
1648 excess_address_data: Vec::new(),
1649 excess_data: Vec::new(),
1651 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1652 let valid_announcement = NodeAnnouncement {
1653 signature: secp_ctx.sign(&msghash, node_1_privkey),
1654 contents: unsigned_announcement.clone()
1657 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1662 let network = net_graph_msg_handler.network_graph.write().unwrap();
1663 let mut w = test_utils::TestVecWriter(Vec::new());
1664 assert!(!network.get_nodes().is_empty());
1665 assert!(!network.get_channels().is_empty());
1666 network.write(&mut w).unwrap();
1667 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);