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, OptionalField};
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 /// The maximum value which may be relayed to the next hop via the channel.
219 pub htlc_maximum_msat: Option<u64>,
220 /// Fees charged when the channel is used for routing
221 pub fees: RoutingFees,
222 /// Most recent update for the channel received from the network
223 /// Mostly redundant with the data we store in fields explicitly.
224 /// Everything else is useful only for sending out for initial routing sync.
225 /// Not stored if contains excess data to prevent DoS.
226 pub last_update_message: Option<msgs::ChannelUpdate>,
229 impl fmt::Display for DirectionalChannelInfo {
230 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
231 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)?;
236 impl_writeable!(DirectionalChannelInfo, 0, {
247 /// Details about a channel (both directions).
248 /// Received within a channel announcement.
249 pub struct ChannelInfo {
250 /// Protocol features of a channel communicated during its announcement
251 pub features: ChannelFeatures,
252 /// Source node of the first direction of a channel
253 pub node_one: PublicKey,
254 /// Details about the first direction of a channel
255 pub one_to_two: Option<DirectionalChannelInfo>,
256 /// Source node of the second direction of a channel
257 pub node_two: PublicKey,
258 /// Details about the second direction of a channel
259 pub two_to_one: Option<DirectionalChannelInfo>,
260 /// An initial announcement of the channel
261 /// Mostly redundant with the data we store in fields explicitly.
262 /// Everything else is useful only for sending out for initial routing sync.
263 /// Not stored if contains excess data to prevent DoS.
264 pub announcement_message: Option<msgs::ChannelAnnouncement>,
267 impl fmt::Display for ChannelInfo {
268 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
269 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
270 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
275 impl_writeable!(ChannelInfo, 0, {
285 /// Fees for routing via a given channel or a node
286 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
287 pub struct RoutingFees {
288 /// Flat routing fee in satoshis
290 /// Liquidity-based routing fee in millionths of a routed amount.
291 /// In other words, 10000 is 1%.
292 pub proportional_millionths: u32,
295 impl Readable for RoutingFees{
296 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
297 let base_msat: u32 = Readable::read(reader)?;
298 let proportional_millionths: u32 = Readable::read(reader)?;
301 proportional_millionths,
306 impl Writeable for RoutingFees {
307 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
308 self.base_msat.write(writer)?;
309 self.proportional_millionths.write(writer)?;
314 #[derive(PartialEq, Debug)]
315 /// Information received in the latest node_announcement from this node.
316 pub struct NodeAnnouncementInfo {
317 /// Protocol features the node announced support for
318 pub features: NodeFeatures,
319 /// When the last known update to the node state was issued.
320 /// Value is opaque, as set in the announcement.
321 pub last_update: u32,
322 /// Color assigned to the node
324 /// Moniker assigned to the node.
325 /// May be invalid or malicious (eg control chars),
326 /// should not be exposed to the user.
328 /// Internet-level addresses via which one can connect to the node
329 pub addresses: Vec<NetAddress>,
330 /// An initial announcement of the node
331 /// Mostly redundant with the data we store in fields explicitly.
332 /// Everything else is useful only for sending out for initial routing sync.
333 /// Not stored if contains excess data to prevent DoS.
334 pub announcement_message: Option<msgs::NodeAnnouncement>
337 impl Writeable for NodeAnnouncementInfo {
338 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
339 self.features.write(writer)?;
340 self.last_update.write(writer)?;
341 self.rgb.write(writer)?;
342 self.alias.write(writer)?;
343 (self.addresses.len() as u64).write(writer)?;
344 for ref addr in &self.addresses {
347 self.announcement_message.write(writer)?;
352 impl Readable for NodeAnnouncementInfo {
353 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
354 let features = Readable::read(reader)?;
355 let last_update = Readable::read(reader)?;
356 let rgb = Readable::read(reader)?;
357 let alias = Readable::read(reader)?;
358 let addresses_count: u64 = Readable::read(reader)?;
359 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
360 for _ in 0..addresses_count {
361 match Readable::read(reader) {
362 Ok(Ok(addr)) => { addresses.push(addr); },
363 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
364 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
368 let announcement_message = Readable::read(reader)?;
369 Ok(NodeAnnouncementInfo {
381 /// Details about a node in the network, known from the network announcement.
382 pub struct NodeInfo {
383 /// All valid channels a node has announced
384 pub channels: Vec<u64>,
385 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
386 /// The two fields (flat and proportional fee) are independent,
387 /// meaning they don't have to refer to the same channel.
388 pub lowest_inbound_channel_fees: Option<RoutingFees>,
389 /// More information about a node from node_announcement.
390 /// Optional because we store a Node entry after learning about it from
391 /// a channel announcement, but before receiving a node announcement.
392 pub announcement_info: Option<NodeAnnouncementInfo>
395 impl fmt::Display for NodeInfo {
396 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
397 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
398 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
403 impl Writeable for NodeInfo {
404 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
405 (self.channels.len() as u64).write(writer)?;
406 for ref chan in self.channels.iter() {
409 self.lowest_inbound_channel_fees.write(writer)?;
410 self.announcement_info.write(writer)?;
415 const MAX_ALLOC_SIZE: u64 = 64*1024;
417 impl Readable for NodeInfo {
418 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
419 let channels_count: u64 = Readable::read(reader)?;
420 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
421 for _ in 0..channels_count {
422 channels.push(Readable::read(reader)?);
424 let lowest_inbound_channel_fees = Readable::read(reader)?;
425 let announcement_info = Readable::read(reader)?;
428 lowest_inbound_channel_fees,
434 /// Represents the network as nodes and channels between them
436 pub struct NetworkGraph {
437 channels: BTreeMap<u64, ChannelInfo>,
438 nodes: BTreeMap<PublicKey, NodeInfo>,
441 impl Writeable for NetworkGraph {
442 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
443 (self.channels.len() as u64).write(writer)?;
444 for (ref chan_id, ref chan_info) in self.channels.iter() {
445 (*chan_id).write(writer)?;
446 chan_info.write(writer)?;
448 (self.nodes.len() as u64).write(writer)?;
449 for (ref node_id, ref node_info) in self.nodes.iter() {
450 node_id.write(writer)?;
451 node_info.write(writer)?;
457 impl Readable for NetworkGraph {
458 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
459 let channels_count: u64 = Readable::read(reader)?;
460 let mut channels = BTreeMap::new();
461 for _ in 0..channels_count {
462 let chan_id: u64 = Readable::read(reader)?;
463 let chan_info = Readable::read(reader)?;
464 channels.insert(chan_id, chan_info);
466 let nodes_count: u64 = Readable::read(reader)?;
467 let mut nodes = BTreeMap::new();
468 for _ in 0..nodes_count {
469 let node_id = Readable::read(reader)?;
470 let node_info = Readable::read(reader)?;
471 nodes.insert(node_id, node_info);
480 impl fmt::Display for NetworkGraph {
481 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
482 write!(f, "Network map\n[Channels]\n")?;
483 for (key, val) in self.channels.iter() {
484 write!(f, " {}: {}\n", key, val)?;
486 write!(f, "[Nodes]\n")?;
487 for (key, val) in self.nodes.iter() {
488 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
495 /// Returns all known valid channels' short ids along with announced channel info.
496 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
497 /// Returns all known nodes' public keys along with announced node info.
498 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
500 /// Get network addresses by node id.
501 /// Returns None if the requested node is completely unknown,
502 /// or if node announcement for the node was never received.
503 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
504 if let Some(node) = self.nodes.get(pubkey) {
505 if let Some(node_info) = node.announcement_info.as_ref() {
506 return Some(&node_info.addresses)
512 /// Creates a new, empty, network graph.
513 pub fn new() -> NetworkGraph {
515 channels: BTreeMap::new(),
516 nodes: BTreeMap::new(),
520 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
521 /// Announcement signatures are checked here only if Secp256k1 object is provided.
522 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
523 if let Some(sig_verifier) = secp_ctx {
524 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
525 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
528 match self.nodes.get_mut(&msg.contents.node_id) {
529 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
531 if let Some(node_info) = node.announcement_info.as_ref() {
532 if node_info.last_update >= msg.contents.timestamp {
533 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
537 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
538 node.announcement_info = Some(NodeAnnouncementInfo {
539 features: msg.contents.features.clone(),
540 last_update: msg.contents.timestamp,
541 rgb: msg.contents.rgb,
542 alias: msg.contents.alias,
543 addresses: msg.contents.addresses.clone(),
544 announcement_message: if should_relay { Some(msg.clone()) } else { None },
552 /// For a new or already known (from previous announcement) channel, store or update channel info.
553 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
554 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
555 /// which is probably result of a reorg. In that case, we update channel info only if the
556 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
557 /// Announcement signatures are checked here only if Secp256k1 object is provided.
558 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
559 if let Some(sig_verifier) = secp_ctx {
560 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
561 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
562 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
563 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
564 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
567 let should_relay = msg.contents.excess_data.is_empty();
569 let chan_info = ChannelInfo {
570 features: msg.contents.features.clone(),
571 node_one: msg.contents.node_id_1.clone(),
573 node_two: msg.contents.node_id_2.clone(),
575 announcement_message: if should_relay { Some(msg.clone()) } else { None },
578 match self.channels.entry(msg.contents.short_channel_id) {
579 BtreeEntry::Occupied(mut entry) => {
580 //TODO: because asking the blockchain if short_channel_id is valid is only optional
581 //in the blockchain API, we need to handle it smartly here, though it's unclear
584 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
585 // only sometimes returns results. In any case remove the previous entry. Note
586 // that the spec expects us to "blacklist" the node_ids involved, but we can't
588 // a) we don't *require* a UTXO provider that always returns results.
589 // b) we don't track UTXOs of channels we know about and remove them if they
591 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
592 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
593 *entry.get_mut() = chan_info;
595 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
598 BtreeEntry::Vacant(entry) => {
599 entry.insert(chan_info);
603 macro_rules! add_channel_to_node {
604 ( $node_id: expr ) => {
605 match self.nodes.entry($node_id) {
606 BtreeEntry::Occupied(node_entry) => {
607 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
609 BtreeEntry::Vacant(node_entry) => {
610 node_entry.insert(NodeInfo {
611 channels: vec!(msg.contents.short_channel_id),
612 lowest_inbound_channel_fees: None,
613 announcement_info: None,
620 add_channel_to_node!(msg.contents.node_id_1);
621 add_channel_to_node!(msg.contents.node_id_2);
626 /// Close a channel if a corresponding HTLC fail was sent.
627 /// If permanent, removes a channel from the local storage.
628 /// May cause the removal of nodes too, if this was their last channel.
629 /// If not permanent, makes channels unavailable for routing.
630 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
632 if let Some(chan) = self.channels.remove(&short_channel_id) {
633 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
636 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
637 if let Some(one_to_two) = chan.one_to_two.as_mut() {
638 one_to_two.enabled = false;
640 if let Some(two_to_one) = chan.two_to_one.as_mut() {
641 two_to_one.enabled = false;
647 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
649 // TODO: Wholly remove the node
651 // TODO: downgrade the node
655 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
656 /// Announcement signatures are checked here only if Secp256k1 object is provided.
657 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
659 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
660 let chan_was_enabled;
662 match self.channels.get_mut(&msg.contents.short_channel_id) {
663 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
665 macro_rules! maybe_update_channel_info {
666 ( $target: expr, $src_node: expr) => {
667 if let Some(existing_chan_info) = $target.as_ref() {
668 if existing_chan_info.last_update >= msg.contents.timestamp {
669 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
671 chan_was_enabled = existing_chan_info.enabled;
673 chan_was_enabled = false;
676 let last_update_message = if msg.contents.excess_data.is_empty() {
682 let updated_channel_dir_info = DirectionalChannelInfo {
683 enabled: chan_enabled,
684 last_update: msg.contents.timestamp,
685 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
686 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
687 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
689 base_msat: msg.contents.fee_base_msat,
690 proportional_millionths: msg.contents.fee_proportional_millionths,
694 $target = Some(updated_channel_dir_info);
698 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
699 if msg.contents.flags & 1 == 1 {
700 dest_node_id = channel.node_one.clone();
701 if let Some(sig_verifier) = secp_ctx {
702 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
704 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
706 dest_node_id = channel.node_two.clone();
707 if let Some(sig_verifier) = secp_ctx {
708 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
710 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
716 let node = self.nodes.get_mut(&dest_node_id).unwrap();
717 let mut base_msat = msg.contents.fee_base_msat;
718 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
719 if let Some(fees) = node.lowest_inbound_channel_fees {
720 base_msat = cmp::min(base_msat, fees.base_msat);
721 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
723 node.lowest_inbound_channel_fees = Some(RoutingFees {
725 proportional_millionths
727 } else if chan_was_enabled {
728 let node = self.nodes.get_mut(&dest_node_id).unwrap();
729 let mut lowest_inbound_channel_fees = None;
731 for chan_id in node.channels.iter() {
732 let chan = self.channels.get(chan_id).unwrap();
734 if chan.node_one == dest_node_id {
735 chan_info_opt = chan.two_to_one.as_ref();
737 chan_info_opt = chan.one_to_two.as_ref();
739 if let Some(chan_info) = chan_info_opt {
740 if chan_info.enabled {
741 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
742 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
743 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
744 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
749 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
752 Ok(msg.contents.excess_data.is_empty())
755 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
756 macro_rules! remove_from_node {
757 ($node_id: expr) => {
758 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
759 entry.get_mut().channels.retain(|chan_id| {
760 short_channel_id != *chan_id
762 if entry.get().channels.is_empty() {
763 entry.remove_entry();
766 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
771 remove_from_node!(chan.node_one);
772 remove_from_node!(chan.node_two);
778 use chain::chaininterface;
779 use ln::features::{ChannelFeatures, NodeFeatures};
780 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
781 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
782 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
783 use util::test_utils;
784 use util::logger::Logger;
785 use util::ser::{Readable, Writeable};
787 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
788 use bitcoin::hashes::Hash;
789 use bitcoin::network::constants::Network;
790 use bitcoin::blockdata::constants::genesis_block;
791 use bitcoin::blockdata::script::Builder;
792 use bitcoin::blockdata::opcodes;
793 use bitcoin::util::hash::BitcoinHash;
797 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
798 use bitcoin::secp256k1::{All, Secp256k1};
802 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
803 let secp_ctx = Secp256k1::new();
804 let logger = Arc::new(test_utils::TestLogger::new());
805 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
806 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
807 (secp_ctx, net_graph_msg_handler)
811 fn request_full_sync_finite_times() {
812 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
813 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
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));
818 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
819 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
820 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
824 fn handling_node_announcements() {
825 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
827 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
828 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
829 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
830 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
831 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
832 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
833 let zero_hash = Sha256dHash::hash(&[0; 32]);
834 let first_announcement_time = 500;
836 let mut unsigned_announcement = UnsignedNodeAnnouncement {
837 features: NodeFeatures::known(),
838 timestamp: first_announcement_time,
842 addresses: Vec::new(),
843 excess_address_data: Vec::new(),
844 excess_data: Vec::new(),
846 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
847 let valid_announcement = NodeAnnouncement {
848 signature: secp_ctx.sign(&msghash, node_1_privkey),
849 contents: unsigned_announcement.clone()
852 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
854 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
858 // Announce a channel to add a corresponding node.
859 let unsigned_announcement = UnsignedChannelAnnouncement {
860 features: ChannelFeatures::known(),
861 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
865 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
866 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
867 excess_data: Vec::new(),
870 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
871 let valid_announcement = ChannelAnnouncement {
872 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
873 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
874 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
875 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
876 contents: unsigned_announcement.clone(),
878 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
879 Ok(res) => assert!(res),
884 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
885 Ok(res) => assert!(res),
889 let fake_msghash = hash_to_message!(&zero_hash);
890 match net_graph_msg_handler.handle_node_announcement(
892 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
893 contents: unsigned_announcement.clone()
896 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
899 unsigned_announcement.timestamp += 1000;
900 unsigned_announcement.excess_data.push(1);
901 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
902 let announcement_with_data = NodeAnnouncement {
903 signature: secp_ctx.sign(&msghash, node_1_privkey),
904 contents: unsigned_announcement.clone()
906 // Return false because contains excess data.
907 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
908 Ok(res) => assert!(!res),
911 unsigned_announcement.excess_data = Vec::new();
913 // Even though previous announcement was not relayed further, we still accepted it,
914 // so we now won't accept announcements before the previous one.
915 unsigned_announcement.timestamp -= 10;
916 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
917 let outdated_announcement = NodeAnnouncement {
918 signature: secp_ctx.sign(&msghash, node_1_privkey),
919 contents: unsigned_announcement.clone()
921 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
923 Err(e) => assert_eq!(e.err, "Update older than last processed update")
928 fn handling_channel_announcements() {
929 let secp_ctx = Secp256k1::new();
930 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
931 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
932 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
935 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
936 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
937 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
938 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
939 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
940 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
942 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
943 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
944 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
945 .push_opcode(opcodes::all::OP_PUSHNUM_2)
946 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
949 let mut unsigned_announcement = UnsignedChannelAnnouncement {
950 features: ChannelFeatures::known(),
951 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
955 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
956 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
957 excess_data: Vec::new(),
960 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
961 let valid_announcement = ChannelAnnouncement {
962 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
963 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
964 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
965 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
966 contents: unsigned_announcement.clone(),
969 // Test if the UTXO lookups were not supported
970 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
972 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
973 Ok(res) => assert!(res),
978 let network = net_graph_msg_handler.network_graph.read().unwrap();
979 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
986 // If we receive announcement for the same channel (with UTXO lookups disabled),
987 // drop new one on the floor, since we can't see any changes.
988 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
990 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
994 // Test if an associated transaction were not on-chain (or not confirmed).
995 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
996 unsigned_announcement.short_channel_id += 1;
998 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
999 let valid_announcement = ChannelAnnouncement {
1000 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1001 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1002 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1003 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1004 contents: unsigned_announcement.clone(),
1007 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1009 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1013 // Now test if the transaction is found in the UTXO set and the script is correct.
1014 unsigned_announcement.short_channel_id += 1;
1015 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1017 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1018 let valid_announcement = ChannelAnnouncement {
1019 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1020 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1021 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1022 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1023 contents: unsigned_announcement.clone(),
1025 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1026 Ok(res) => assert!(res),
1031 let network = net_graph_msg_handler.network_graph.read().unwrap();
1032 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1038 // If we receive announcement for the same channel (but TX is not confirmed),
1039 // drop new one on the floor, since we can't see any changes.
1040 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1041 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1043 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1046 // But if it is confirmed, replace the channel
1047 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1048 unsigned_announcement.features = ChannelFeatures::empty();
1049 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1050 let valid_announcement = ChannelAnnouncement {
1051 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1052 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1053 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1054 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1055 contents: unsigned_announcement.clone(),
1057 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1058 Ok(res) => assert!(res),
1062 let network = net_graph_msg_handler.network_graph.read().unwrap();
1063 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1064 Some(channel_entry) => {
1065 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1071 // Don't relay valid channels with excess data
1072 unsigned_announcement.short_channel_id += 1;
1073 unsigned_announcement.excess_data.push(1);
1074 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1075 let valid_announcement = ChannelAnnouncement {
1076 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1077 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1078 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1079 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1080 contents: unsigned_announcement.clone(),
1082 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1083 Ok(res) => assert!(!res),
1087 unsigned_announcement.excess_data = Vec::new();
1088 let invalid_sig_announcement = ChannelAnnouncement {
1089 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1090 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1091 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1092 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1093 contents: unsigned_announcement.clone(),
1095 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1097 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1100 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1101 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1102 let channel_to_itself_announcement = ChannelAnnouncement {
1103 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1104 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1105 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1106 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1107 contents: unsigned_announcement.clone(),
1109 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1111 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1116 fn handling_channel_update() {
1117 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1118 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1119 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1120 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1121 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1122 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1123 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1125 let zero_hash = Sha256dHash::hash(&[0; 32]);
1126 let short_channel_id = 0;
1127 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1129 // Announce a channel we will update
1130 let unsigned_announcement = UnsignedChannelAnnouncement {
1131 features: ChannelFeatures::empty(),
1136 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1137 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1138 excess_data: Vec::new(),
1141 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1142 let valid_channel_announcement = ChannelAnnouncement {
1143 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1144 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1145 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1146 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1147 contents: unsigned_announcement.clone(),
1149 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1156 let mut unsigned_channel_update = UnsignedChannelUpdate {
1161 cltv_expiry_delta: 144,
1162 htlc_minimum_msat: 1000000,
1163 htlc_maximum_msat: OptionalField::Absent,
1164 fee_base_msat: 10000,
1165 fee_proportional_millionths: 20,
1166 excess_data: Vec::new()
1168 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1169 let valid_channel_update = ChannelUpdate {
1170 signature: secp_ctx.sign(&msghash, node_1_privkey),
1171 contents: unsigned_channel_update.clone()
1174 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1175 Ok(res) => assert!(res),
1180 let network = net_graph_msg_handler.network_graph.read().unwrap();
1181 match network.get_channels().get(&short_channel_id) {
1183 Some(channel_info) => {
1184 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1185 assert!(channel_info.two_to_one.is_none());
1190 unsigned_channel_update.timestamp += 100;
1191 unsigned_channel_update.excess_data.push(1);
1192 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1193 let valid_channel_update = ChannelUpdate {
1194 signature: secp_ctx.sign(&msghash, node_1_privkey),
1195 contents: unsigned_channel_update.clone()
1197 // Return false because contains excess data
1198 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1199 Ok(res) => assert!(!res),
1202 unsigned_channel_update.timestamp += 10;
1204 unsigned_channel_update.short_channel_id += 1;
1205 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1206 let valid_channel_update = ChannelUpdate {
1207 signature: secp_ctx.sign(&msghash, node_1_privkey),
1208 contents: unsigned_channel_update.clone()
1211 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1213 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1215 unsigned_channel_update.short_channel_id = short_channel_id;
1218 // Even though previous update was not relayed further, we still accepted it,
1219 // so we now won't accept update before the previous one.
1220 unsigned_channel_update.timestamp -= 10;
1221 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1222 let valid_channel_update = ChannelUpdate {
1223 signature: secp_ctx.sign(&msghash, node_1_privkey),
1224 contents: unsigned_channel_update.clone()
1227 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1229 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1231 unsigned_channel_update.timestamp += 500;
1233 let fake_msghash = hash_to_message!(&zero_hash);
1234 let invalid_sig_channel_update = ChannelUpdate {
1235 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1236 contents: unsigned_channel_update.clone()
1239 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1241 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1247 fn handling_htlc_fail_channel_update() {
1248 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1249 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1250 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1251 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1252 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1253 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1254 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1256 let short_channel_id = 0;
1257 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1260 // There is no nodes in the table at the beginning.
1261 let network = net_graph_msg_handler.network_graph.read().unwrap();
1262 assert_eq!(network.get_nodes().len(), 0);
1266 // Announce a channel we will update
1267 let unsigned_announcement = UnsignedChannelAnnouncement {
1268 features: ChannelFeatures::empty(),
1273 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1274 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1275 excess_data: Vec::new(),
1278 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1279 let valid_channel_announcement = ChannelAnnouncement {
1280 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1281 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1282 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1283 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1284 contents: unsigned_announcement.clone(),
1286 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1291 let unsigned_channel_update = UnsignedChannelUpdate {
1296 cltv_expiry_delta: 144,
1297 htlc_minimum_msat: 1000000,
1298 htlc_maximum_msat: OptionalField::Absent,
1299 fee_base_msat: 10000,
1300 fee_proportional_millionths: 20,
1301 excess_data: Vec::new()
1303 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1304 let valid_channel_update = ChannelUpdate {
1305 signature: secp_ctx.sign(&msghash, node_1_privkey),
1306 contents: unsigned_channel_update.clone()
1309 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1310 Ok(res) => assert!(res),
1315 // Non-permanent closing just disables a channel
1317 let network = net_graph_msg_handler.network_graph.read().unwrap();
1318 match network.get_channels().get(&short_channel_id) {
1320 Some(channel_info) => {
1321 assert!(channel_info.one_to_two.is_some());
1326 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1331 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1333 // Non-permanent closing just disables a channel
1335 let network = net_graph_msg_handler.network_graph.read().unwrap();
1336 match network.get_channels().get(&short_channel_id) {
1338 Some(channel_info) => {
1339 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1344 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1349 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1351 // Permanent closing deletes a channel
1353 let network = net_graph_msg_handler.network_graph.read().unwrap();
1354 assert_eq!(network.get_channels().len(), 0);
1355 // Nodes are also deleted because there are no associated channels anymore
1356 assert_eq!(network.get_nodes().len(), 0);
1358 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1362 fn getting_next_channel_announcements() {
1363 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1364 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1365 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1366 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1367 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1368 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1369 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1371 let short_channel_id = 1;
1372 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1374 // Channels were not announced yet.
1375 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1376 assert_eq!(channels_with_announcements.len(), 0);
1379 // Announce a channel we will update
1380 let unsigned_announcement = UnsignedChannelAnnouncement {
1381 features: ChannelFeatures::empty(),
1386 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1387 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1388 excess_data: Vec::new(),
1391 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1392 let valid_channel_announcement = ChannelAnnouncement {
1393 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1394 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1395 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1396 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1397 contents: unsigned_announcement.clone(),
1399 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1405 // Contains initial channel announcement now.
1406 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1407 assert_eq!(channels_with_announcements.len(), 1);
1408 if let Some(channel_announcements) = channels_with_announcements.first() {
1409 let &(_, ref update_1, ref update_2) = channel_announcements;
1410 assert_eq!(update_1, &None);
1411 assert_eq!(update_2, &None);
1418 // Valid channel update
1419 let unsigned_channel_update = UnsignedChannelUpdate {
1424 cltv_expiry_delta: 144,
1425 htlc_minimum_msat: 1000000,
1426 htlc_maximum_msat: OptionalField::Absent,
1427 fee_base_msat: 10000,
1428 fee_proportional_millionths: 20,
1429 excess_data: Vec::new()
1431 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1432 let valid_channel_update = ChannelUpdate {
1433 signature: secp_ctx.sign(&msghash, node_1_privkey),
1434 contents: unsigned_channel_update.clone()
1436 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1442 // Now contains an initial announcement and an update.
1443 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1444 assert_eq!(channels_with_announcements.len(), 1);
1445 if let Some(channel_announcements) = channels_with_announcements.first() {
1446 let &(_, ref update_1, ref update_2) = channel_announcements;
1447 assert_ne!(update_1, &None);
1448 assert_eq!(update_2, &None);
1455 // Channel update with excess data.
1456 let unsigned_channel_update = UnsignedChannelUpdate {
1461 cltv_expiry_delta: 144,
1462 htlc_minimum_msat: 1000000,
1463 htlc_maximum_msat: OptionalField::Absent,
1464 fee_base_msat: 10000,
1465 fee_proportional_millionths: 20,
1466 excess_data: [1; 3].to_vec()
1468 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1469 let valid_channel_update = ChannelUpdate {
1470 signature: secp_ctx.sign(&msghash, node_1_privkey),
1471 contents: unsigned_channel_update.clone()
1473 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1479 // Test that announcements with excess data won't be returned
1480 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1481 assert_eq!(channels_with_announcements.len(), 1);
1482 if let Some(channel_announcements) = channels_with_announcements.first() {
1483 let &(_, ref update_1, ref update_2) = channel_announcements;
1484 assert_eq!(update_1, &None);
1485 assert_eq!(update_2, &None);
1490 // Further starting point have no channels after it
1491 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1492 assert_eq!(channels_with_announcements.len(), 0);
1496 fn getting_next_node_announcements() {
1497 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1498 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1499 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1500 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1501 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1502 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1503 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1505 let short_channel_id = 1;
1506 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1509 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1510 assert_eq!(next_announcements.len(), 0);
1513 // Announce a channel to add 2 nodes
1514 let unsigned_announcement = UnsignedChannelAnnouncement {
1515 features: ChannelFeatures::empty(),
1520 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1521 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1522 excess_data: Vec::new(),
1525 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1526 let valid_channel_announcement = ChannelAnnouncement {
1527 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1528 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1529 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1530 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1531 contents: unsigned_announcement.clone(),
1533 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1540 // Nodes were never announced
1541 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1542 assert_eq!(next_announcements.len(), 0);
1545 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1546 features: NodeFeatures::known(),
1551 addresses: Vec::new(),
1552 excess_address_data: Vec::new(),
1553 excess_data: Vec::new(),
1555 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1556 let valid_announcement = NodeAnnouncement {
1557 signature: secp_ctx.sign(&msghash, node_1_privkey),
1558 contents: unsigned_announcement.clone()
1560 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1565 unsigned_announcement.node_id = node_id_2;
1566 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1567 let valid_announcement = NodeAnnouncement {
1568 signature: secp_ctx.sign(&msghash, node_2_privkey),
1569 contents: unsigned_announcement.clone()
1572 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1578 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1579 assert_eq!(next_announcements.len(), 2);
1581 // Skip the first node.
1582 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1583 assert_eq!(next_announcements.len(), 1);
1586 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1587 let unsigned_announcement = UnsignedNodeAnnouncement {
1588 features: NodeFeatures::known(),
1593 addresses: Vec::new(),
1594 excess_address_data: Vec::new(),
1595 excess_data: [1; 3].to_vec(),
1597 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1598 let valid_announcement = NodeAnnouncement {
1599 signature: secp_ctx.sign(&msghash, node_2_privkey),
1600 contents: unsigned_announcement.clone()
1602 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1603 Ok(res) => assert!(!res),
1608 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1609 assert_eq!(next_announcements.len(), 0);
1613 fn network_graph_serialization() {
1614 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1616 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1617 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1618 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1619 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1621 // Announce a channel to add a corresponding node.
1622 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1623 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1624 let unsigned_announcement = UnsignedChannelAnnouncement {
1625 features: ChannelFeatures::known(),
1626 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1627 short_channel_id: 0,
1630 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1631 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1632 excess_data: Vec::new(),
1635 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1636 let valid_announcement = ChannelAnnouncement {
1637 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1638 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1639 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1640 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1641 contents: unsigned_announcement.clone(),
1643 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1644 Ok(res) => assert!(res),
1649 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1650 let unsigned_announcement = UnsignedNodeAnnouncement {
1651 features: NodeFeatures::known(),
1656 addresses: Vec::new(),
1657 excess_address_data: Vec::new(),
1658 excess_data: Vec::new(),
1660 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1661 let valid_announcement = NodeAnnouncement {
1662 signature: secp_ctx.sign(&msghash, node_1_privkey),
1663 contents: unsigned_announcement.clone()
1666 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1671 let network = net_graph_msg_handler.network_graph.write().unwrap();
1672 let mut w = test_utils::TestVecWriter(Vec::new());
1673 assert!(!network.get_nodes().is_empty());
1674 assert!(!network.get_channels().is_empty());
1675 network.write(&mut w).unwrap();
1676 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);