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;
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: RwLock<NetworkGraph>) -> Self {
64 secp_ctx: Secp256k1::verification_only(),
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", 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", 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: "Channel announcement keys didn't match on-chain script", 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: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
114 Err(ChainError::UnknownTx) => {
115 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", 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 { ref short_channel_id, ref is_permanent } => {
129 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
131 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref 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 std::fmt::Display for DirectionalChannelInfo {
228 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::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 std::fmt::Display for ChannelInfo {
265 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::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 std::fmt::Display for NodeInfo {
393 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::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 std::fmt::Display for NetworkGraph {
478 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::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 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
510 /// Announcement signatures are checked here only if Secp256k1 object is provided.
511 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
512 if let Some(sig_verifier) = secp_ctx {
513 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
514 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
517 match self.nodes.get_mut(&msg.contents.node_id) {
518 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
520 if let Some(node_info) = node.announcement_info.as_ref() {
521 if node_info.last_update >= msg.contents.timestamp {
522 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
526 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
527 node.announcement_info = Some(NodeAnnouncementInfo {
528 features: msg.contents.features.clone(),
529 last_update: msg.contents.timestamp,
530 rgb: msg.contents.rgb,
531 alias: msg.contents.alias,
532 addresses: msg.contents.addresses.clone(),
533 announcement_message: if should_relay { Some(msg.clone()) } else { None },
541 /// For a new or already known (from previous announcement) channel, store or update channel info.
542 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
543 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
544 /// which is probably result of a reorg. In that case, we update channel info only if the
545 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
546 /// Announcement signatures are checked here only if Secp256k1 object is provided.
547 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
548 if let Some(sig_verifier) = secp_ctx {
549 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
550 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
551 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
552 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
553 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
556 let should_relay = msg.contents.excess_data.is_empty();
558 let chan_info = ChannelInfo {
559 features: msg.contents.features.clone(),
560 node_one: msg.contents.node_id_1.clone(),
562 node_two: msg.contents.node_id_2.clone(),
564 announcement_message: if should_relay { Some(msg.clone()) } else { None },
567 match self.channels.entry(msg.contents.short_channel_id) {
568 BtreeEntry::Occupied(mut entry) => {
569 //TODO: because asking the blockchain if short_channel_id is valid is only optional
570 //in the blockchain API, we need to handle it smartly here, though it's unclear
573 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
574 // only sometimes returns results. In any case remove the previous entry. Note
575 // that the spec expects us to "blacklist" the node_ids involved, but we can't
577 // a) we don't *require* a UTXO provider that always returns results.
578 // b) we don't track UTXOs of channels we know about and remove them if they
580 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
581 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
582 *entry.get_mut() = chan_info;
584 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
587 BtreeEntry::Vacant(entry) => {
588 entry.insert(chan_info);
592 macro_rules! add_channel_to_node {
593 ( $node_id: expr ) => {
594 match self.nodes.entry($node_id) {
595 BtreeEntry::Occupied(node_entry) => {
596 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
598 BtreeEntry::Vacant(node_entry) => {
599 node_entry.insert(NodeInfo {
600 channels: vec!(msg.contents.short_channel_id),
601 lowest_inbound_channel_fees: None,
602 announcement_info: None,
609 add_channel_to_node!(msg.contents.node_id_1);
610 add_channel_to_node!(msg.contents.node_id_2);
615 /// Close a channel if a corresponding HTLC fail was sent.
616 /// If permanent, removes a channel from the local storage.
617 /// May cause the removal of nodes too, if this was their last channel.
618 /// If not permanent, makes channels unavailable for routing.
619 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
621 if let Some(chan) = self.channels.remove(short_channel_id) {
622 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
625 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
626 if let Some(one_to_two) = chan.one_to_two.as_mut() {
627 one_to_two.enabled = false;
629 if let Some(two_to_one) = chan.two_to_one.as_mut() {
630 two_to_one.enabled = false;
636 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
638 // TODO: Wholly remove the node
640 // TODO: downgrade the node
644 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
645 /// Announcement signatures are checked here only if Secp256k1 object is provided.
646 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
648 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
649 let chan_was_enabled;
651 match self.channels.get_mut(&msg.contents.short_channel_id) {
652 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
654 macro_rules! maybe_update_channel_info {
655 ( $target: expr, $src_node: expr) => {
656 if let Some(existing_chan_info) = $target.as_ref() {
657 if existing_chan_info.last_update >= msg.contents.timestamp {
658 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
660 chan_was_enabled = existing_chan_info.enabled;
662 chan_was_enabled = false;
665 let last_update_message = if msg.contents.excess_data.is_empty() {
671 let updated_channel_dir_info = DirectionalChannelInfo {
672 enabled: chan_enabled,
673 last_update: msg.contents.timestamp,
674 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
675 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
677 base_msat: msg.contents.fee_base_msat,
678 proportional_millionths: msg.contents.fee_proportional_millionths,
682 $target = Some(updated_channel_dir_info);
686 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
687 if msg.contents.flags & 1 == 1 {
688 dest_node_id = channel.node_one.clone();
689 if let Some(sig_verifier) = secp_ctx {
690 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
692 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
694 dest_node_id = channel.node_two.clone();
695 if let Some(sig_verifier) = secp_ctx {
696 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
698 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
704 let node = self.nodes.get_mut(&dest_node_id).unwrap();
705 let mut base_msat = msg.contents.fee_base_msat;
706 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
707 if let Some(fees) = node.lowest_inbound_channel_fees {
708 base_msat = cmp::min(base_msat, fees.base_msat);
709 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
711 node.lowest_inbound_channel_fees = Some(RoutingFees {
713 proportional_millionths
715 } else if chan_was_enabled {
716 let node = self.nodes.get_mut(&dest_node_id).unwrap();
717 let mut lowest_inbound_channel_fees = None;
719 for chan_id in node.channels.iter() {
720 let chan = self.channels.get(chan_id).unwrap();
722 if chan.node_one == dest_node_id {
723 chan_info_opt = chan.two_to_one.as_ref();
725 chan_info_opt = chan.one_to_two.as_ref();
727 if let Some(chan_info) = chan_info_opt {
728 if chan_info.enabled {
729 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
730 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
731 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
732 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
737 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
740 Ok(msg.contents.excess_data.is_empty())
743 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
744 macro_rules! remove_from_node {
745 ($node_id: expr) => {
746 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
747 entry.get_mut().channels.retain(|chan_id| {
748 short_channel_id != *chan_id
750 if entry.get().channels.is_empty() {
751 entry.remove_entry();
754 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
759 remove_from_node!(chan.node_one);
760 remove_from_node!(chan.node_two);
766 use chain::chaininterface;
767 use ln::features::{ChannelFeatures, NodeFeatures};
768 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
769 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
770 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
771 use util::test_utils;
772 use util::logger::Logger;
773 use util::ser::{Readable, Writeable};
775 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
776 use bitcoin::hashes::Hash;
777 use bitcoin::network::constants::Network;
778 use bitcoin::blockdata::constants::genesis_block;
779 use bitcoin::blockdata::script::Builder;
780 use bitcoin::blockdata::opcodes;
781 use bitcoin::util::hash::BitcoinHash;
785 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
786 use bitcoin::secp256k1::{All, Secp256k1};
790 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
791 let secp_ctx = Secp256k1::new();
792 let logger = Arc::new(test_utils::TestLogger::new());
793 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
794 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
795 (secp_ctx, net_graph_msg_handler)
799 fn request_full_sync_finite_times() {
800 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
801 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
803 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
804 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
805 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
806 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
807 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
808 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
812 fn handling_node_announcements() {
813 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
815 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
816 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
817 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
818 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
819 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
820 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
821 let zero_hash = Sha256dHash::hash(&[0; 32]);
822 let first_announcement_time = 500;
824 let mut unsigned_announcement = UnsignedNodeAnnouncement {
825 features: NodeFeatures::known(),
826 timestamp: first_announcement_time,
830 addresses: Vec::new(),
831 excess_address_data: Vec::new(),
832 excess_data: Vec::new(),
834 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
835 let valid_announcement = NodeAnnouncement {
836 signature: secp_ctx.sign(&msghash, node_1_privkey),
837 contents: unsigned_announcement.clone()
840 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
842 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
846 // Announce a channel to add a corresponding node.
847 let unsigned_announcement = UnsignedChannelAnnouncement {
848 features: ChannelFeatures::known(),
849 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
853 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
854 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
855 excess_data: Vec::new(),
858 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
859 let valid_announcement = ChannelAnnouncement {
860 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
861 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
862 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
863 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
864 contents: unsigned_announcement.clone(),
866 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
867 Ok(res) => assert!(res),
872 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
873 Ok(res) => assert!(res),
877 let fake_msghash = hash_to_message!(&zero_hash);
878 match net_graph_msg_handler.handle_node_announcement(
880 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
881 contents: unsigned_announcement.clone()
884 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
887 unsigned_announcement.timestamp += 1000;
888 unsigned_announcement.excess_data.push(1);
889 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
890 let announcement_with_data = NodeAnnouncement {
891 signature: secp_ctx.sign(&msghash, node_1_privkey),
892 contents: unsigned_announcement.clone()
894 // Return false because contains excess data.
895 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
896 Ok(res) => assert!(!res),
899 unsigned_announcement.excess_data = Vec::new();
901 // Even though previous announcement was not relayed further, we still accepted it,
902 // so we now won't accept announcements before the previous one.
903 unsigned_announcement.timestamp -= 10;
904 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
905 let outdated_announcement = NodeAnnouncement {
906 signature: secp_ctx.sign(&msghash, node_1_privkey),
907 contents: unsigned_announcement.clone()
909 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
911 Err(e) => assert_eq!(e.err, "Update older than last processed update")
916 fn handling_channel_announcements() {
917 let secp_ctx = Secp256k1::new();
918 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
919 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
920 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
923 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
924 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
925 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
926 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
927 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
928 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
930 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
931 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
932 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
933 .push_opcode(opcodes::all::OP_PUSHNUM_2)
934 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
937 let mut unsigned_announcement = UnsignedChannelAnnouncement {
938 features: ChannelFeatures::known(),
939 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
943 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
944 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
945 excess_data: Vec::new(),
948 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
949 let valid_announcement = ChannelAnnouncement {
950 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
951 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
952 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
953 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
954 contents: unsigned_announcement.clone(),
957 // Test if the UTXO lookups were not supported
958 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
960 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
961 Ok(res) => assert!(res),
966 let network = net_graph_msg_handler.network_graph.read().unwrap();
967 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
974 // If we receive announcement for the same channel (with UTXO lookups disabled),
975 // drop new one on the floor, since we can't see any changes.
976 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
978 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
982 // Test if an associated transaction were not on-chain (or not confirmed).
983 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
984 unsigned_announcement.short_channel_id += 1;
986 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
987 let valid_announcement = ChannelAnnouncement {
988 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
989 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
990 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
991 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
992 contents: unsigned_announcement.clone(),
995 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
997 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1001 // Now test if the transaction is found in the UTXO set and the script is correct.
1002 unsigned_announcement.short_channel_id += 1;
1003 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1005 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1006 let valid_announcement = ChannelAnnouncement {
1007 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1008 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1009 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1010 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1011 contents: unsigned_announcement.clone(),
1013 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1014 Ok(res) => assert!(res),
1019 let network = net_graph_msg_handler.network_graph.read().unwrap();
1020 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1026 // If we receive announcement for the same channel (but TX is not confirmed),
1027 // drop new one on the floor, since we can't see any changes.
1028 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1029 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1031 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1034 // But if it is confirmed, replace the channel
1035 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1036 unsigned_announcement.features = ChannelFeatures::empty();
1037 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1038 let valid_announcement = ChannelAnnouncement {
1039 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1040 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1041 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1042 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1043 contents: unsigned_announcement.clone(),
1045 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1046 Ok(res) => assert!(res),
1050 let network = net_graph_msg_handler.network_graph.read().unwrap();
1051 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1052 Some(channel_entry) => {
1053 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1059 // Don't relay valid channels with excess data
1060 unsigned_announcement.short_channel_id += 1;
1061 unsigned_announcement.excess_data.push(1);
1062 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1063 let valid_announcement = ChannelAnnouncement {
1064 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1065 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1066 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1067 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1068 contents: unsigned_announcement.clone(),
1070 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1071 Ok(res) => assert!(!res),
1075 unsigned_announcement.excess_data = Vec::new();
1076 let invalid_sig_announcement = ChannelAnnouncement {
1077 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1078 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1079 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1080 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1081 contents: unsigned_announcement.clone(),
1083 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1085 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1088 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1089 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1090 let channel_to_itself_announcement = ChannelAnnouncement {
1091 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1092 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1093 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1094 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1095 contents: unsigned_announcement.clone(),
1097 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1099 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1104 fn handling_channel_update() {
1105 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1106 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1107 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1108 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1109 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1110 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1111 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1113 let zero_hash = Sha256dHash::hash(&[0; 32]);
1114 let short_channel_id = 0;
1115 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1117 // Announce a channel we will update
1118 let unsigned_announcement = UnsignedChannelAnnouncement {
1119 features: ChannelFeatures::empty(),
1124 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1125 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1126 excess_data: Vec::new(),
1129 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1130 let valid_channel_announcement = ChannelAnnouncement {
1131 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1132 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1133 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1134 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1135 contents: unsigned_announcement.clone(),
1137 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1144 let mut unsigned_channel_update = UnsignedChannelUpdate {
1149 cltv_expiry_delta: 144,
1150 htlc_minimum_msat: 1000000,
1151 fee_base_msat: 10000,
1152 fee_proportional_millionths: 20,
1153 excess_data: Vec::new()
1155 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1156 let valid_channel_update = ChannelUpdate {
1157 signature: secp_ctx.sign(&msghash, node_1_privkey),
1158 contents: unsigned_channel_update.clone()
1161 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1162 Ok(res) => assert!(res),
1167 let network = net_graph_msg_handler.network_graph.read().unwrap();
1168 match network.get_channels().get(&short_channel_id) {
1170 Some(channel_info) => {
1171 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1172 assert!(channel_info.two_to_one.is_none());
1177 unsigned_channel_update.timestamp += 100;
1178 unsigned_channel_update.excess_data.push(1);
1179 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1180 let valid_channel_update = ChannelUpdate {
1181 signature: secp_ctx.sign(&msghash, node_1_privkey),
1182 contents: unsigned_channel_update.clone()
1184 // Return false because contains excess data
1185 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1186 Ok(res) => assert!(!res),
1190 unsigned_channel_update.short_channel_id += 1;
1191 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1192 let valid_channel_update = ChannelUpdate {
1193 signature: secp_ctx.sign(&msghash, node_1_privkey),
1194 contents: unsigned_channel_update.clone()
1197 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1199 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1201 unsigned_channel_update.short_channel_id = short_channel_id;
1204 // Even though previous update was not relayed further, we still accepted it,
1205 // so we now won't accept update before the previous one.
1206 unsigned_channel_update.timestamp -= 10;
1207 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1208 let valid_channel_update = ChannelUpdate {
1209 signature: secp_ctx.sign(&msghash, node_1_privkey),
1210 contents: unsigned_channel_update.clone()
1213 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1215 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1217 unsigned_channel_update.timestamp += 500;
1219 let fake_msghash = hash_to_message!(&zero_hash);
1220 let invalid_sig_channel_update = ChannelUpdate {
1221 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1222 contents: unsigned_channel_update.clone()
1225 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1227 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1233 fn handling_htlc_fail_channel_update() {
1234 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1235 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1236 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1237 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1238 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1239 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1240 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1242 let short_channel_id = 0;
1243 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1246 // There is no nodes in the table at the beginning.
1247 let network = net_graph_msg_handler.network_graph.read().unwrap();
1248 assert_eq!(network.get_nodes().len(), 0);
1252 // Announce a channel we will update
1253 let unsigned_announcement = UnsignedChannelAnnouncement {
1254 features: ChannelFeatures::empty(),
1259 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1260 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1261 excess_data: Vec::new(),
1264 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1265 let valid_channel_announcement = ChannelAnnouncement {
1266 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1267 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1268 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1269 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1270 contents: unsigned_announcement.clone(),
1272 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1277 let unsigned_channel_update = UnsignedChannelUpdate {
1282 cltv_expiry_delta: 144,
1283 htlc_minimum_msat: 1000000,
1284 fee_base_msat: 10000,
1285 fee_proportional_millionths: 20,
1286 excess_data: Vec::new()
1288 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1289 let valid_channel_update = ChannelUpdate {
1290 signature: secp_ctx.sign(&msghash, node_1_privkey),
1291 contents: unsigned_channel_update.clone()
1294 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1295 Ok(res) => assert!(res),
1300 // Non-permanent closing just disables a channel
1302 let network = net_graph_msg_handler.network_graph.read().unwrap();
1303 match network.get_channels().get(&short_channel_id) {
1305 Some(channel_info) => {
1306 assert!(channel_info.one_to_two.is_some());
1311 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1316 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1318 // Non-permanent closing just disables a channel
1320 let network = net_graph_msg_handler.network_graph.read().unwrap();
1321 match network.get_channels().get(&short_channel_id) {
1323 Some(channel_info) => {
1324 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1329 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1334 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1336 // Permanent closing deletes a channel
1338 let network = net_graph_msg_handler.network_graph.read().unwrap();
1339 assert_eq!(network.get_channels().len(), 0);
1340 // Nodes are also deleted because there are no associated channels anymore
1341 assert_eq!(network.get_nodes().len(), 0);
1343 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1347 fn getting_next_channel_announcements() {
1348 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1349 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1350 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1351 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1352 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1353 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1354 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1356 let short_channel_id = 1;
1357 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1359 // Channels were not announced yet.
1360 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1361 assert_eq!(channels_with_announcements.len(), 0);
1364 // Announce a channel we will update
1365 let unsigned_announcement = UnsignedChannelAnnouncement {
1366 features: ChannelFeatures::empty(),
1371 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1372 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1373 excess_data: Vec::new(),
1376 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1377 let valid_channel_announcement = ChannelAnnouncement {
1378 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1379 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1380 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1381 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1382 contents: unsigned_announcement.clone(),
1384 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1390 // Contains initial channel announcement now.
1391 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1392 assert_eq!(channels_with_announcements.len(), 1);
1393 if let Some(channel_announcements) = channels_with_announcements.first() {
1394 let &(_, ref update_1, ref update_2) = channel_announcements;
1395 assert_eq!(update_1, &None);
1396 assert_eq!(update_2, &None);
1403 // Valid channel update
1404 let unsigned_channel_update = UnsignedChannelUpdate {
1409 cltv_expiry_delta: 144,
1410 htlc_minimum_msat: 1000000,
1411 fee_base_msat: 10000,
1412 fee_proportional_millionths: 20,
1413 excess_data: Vec::new()
1415 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1416 let valid_channel_update = ChannelUpdate {
1417 signature: secp_ctx.sign(&msghash, node_1_privkey),
1418 contents: unsigned_channel_update.clone()
1420 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1426 // Now contains an initial announcement and an update.
1427 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1428 assert_eq!(channels_with_announcements.len(), 1);
1429 if let Some(channel_announcements) = channels_with_announcements.first() {
1430 let &(_, ref update_1, ref update_2) = channel_announcements;
1431 assert_ne!(update_1, &None);
1432 assert_eq!(update_2, &None);
1439 // Channel update with excess data.
1440 let unsigned_channel_update = UnsignedChannelUpdate {
1445 cltv_expiry_delta: 144,
1446 htlc_minimum_msat: 1000000,
1447 fee_base_msat: 10000,
1448 fee_proportional_millionths: 20,
1449 excess_data: [1; 3].to_vec()
1451 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1452 let valid_channel_update = ChannelUpdate {
1453 signature: secp_ctx.sign(&msghash, node_1_privkey),
1454 contents: unsigned_channel_update.clone()
1456 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1462 // Test that announcements with excess data won't be returned
1463 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1464 assert_eq!(channels_with_announcements.len(), 1);
1465 if let Some(channel_announcements) = channels_with_announcements.first() {
1466 let &(_, ref update_1, ref update_2) = channel_announcements;
1467 assert_eq!(update_1, &None);
1468 assert_eq!(update_2, &None);
1473 // Further starting point have no channels after it
1474 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1475 assert_eq!(channels_with_announcements.len(), 0);
1479 fn getting_next_node_announcements() {
1480 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1481 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1482 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1483 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1484 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1485 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1486 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1488 let short_channel_id = 1;
1489 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1492 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1493 assert_eq!(next_announcements.len(), 0);
1496 // Announce a channel to add 2 nodes
1497 let unsigned_announcement = UnsignedChannelAnnouncement {
1498 features: ChannelFeatures::empty(),
1503 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1504 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1505 excess_data: Vec::new(),
1508 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1509 let valid_channel_announcement = ChannelAnnouncement {
1510 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1511 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1512 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1513 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1514 contents: unsigned_announcement.clone(),
1516 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1523 // Nodes were never announced
1524 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1525 assert_eq!(next_announcements.len(), 0);
1528 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1529 features: NodeFeatures::known(),
1534 addresses: Vec::new(),
1535 excess_address_data: Vec::new(),
1536 excess_data: Vec::new(),
1538 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1539 let valid_announcement = NodeAnnouncement {
1540 signature: secp_ctx.sign(&msghash, node_1_privkey),
1541 contents: unsigned_announcement.clone()
1543 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1548 unsigned_announcement.node_id = node_id_2;
1549 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1550 let valid_announcement = NodeAnnouncement {
1551 signature: secp_ctx.sign(&msghash, node_2_privkey),
1552 contents: unsigned_announcement.clone()
1555 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1561 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1562 assert_eq!(next_announcements.len(), 2);
1564 // Skip the first node.
1565 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1566 assert_eq!(next_announcements.len(), 1);
1569 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1570 let unsigned_announcement = UnsignedNodeAnnouncement {
1571 features: NodeFeatures::known(),
1576 addresses: Vec::new(),
1577 excess_address_data: Vec::new(),
1578 excess_data: [1; 3].to_vec(),
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1581 let valid_announcement = NodeAnnouncement {
1582 signature: secp_ctx.sign(&msghash, node_2_privkey),
1583 contents: unsigned_announcement.clone()
1585 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1586 Ok(res) => assert!(!res),
1591 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1592 assert_eq!(next_announcements.len(), 0);
1596 fn network_graph_serialization() {
1597 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1599 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1600 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1601 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1602 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1604 // Announce a channel to add a corresponding node.
1605 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1606 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1607 let unsigned_announcement = UnsignedChannelAnnouncement {
1608 features: ChannelFeatures::known(),
1609 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1610 short_channel_id: 0,
1613 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1614 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1615 excess_data: Vec::new(),
1618 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1619 let valid_announcement = ChannelAnnouncement {
1620 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1621 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1622 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1623 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1624 contents: unsigned_announcement.clone(),
1626 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1627 Ok(res) => assert!(res),
1632 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1633 let unsigned_announcement = UnsignedNodeAnnouncement {
1634 features: NodeFeatures::known(),
1639 addresses: Vec::new(),
1640 excess_address_data: Vec::new(),
1641 excess_data: Vec::new(),
1643 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1644 let valid_announcement = NodeAnnouncement {
1645 signature: secp_ctx.sign(&msghash, node_1_privkey),
1646 contents: unsigned_announcement.clone()
1649 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1654 let network = net_graph_msg_handler.network_graph.write().unwrap();
1655 let mut w = test_utils::TestVecWriter(Vec::new());
1656 assert!(!network.get_nodes().is_empty());
1657 assert!(!network.get_channels().is_empty());
1658 network.write(&mut w).unwrap();
1659 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);