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,Arc};
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
26 /// Receives and validates network updates from peers,
27 /// stores authentic and relevant data as a network graph.
28 /// This network graph is then used for routing payments.
29 /// Provides interface to help with initial routing sync by
30 /// serving historical announcements.
31 pub struct NetGraphMsgHandler {
32 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
33 /// Representation of the payment channel network
34 pub network_graph: RwLock<NetworkGraph>,
35 chain_monitor: Arc<ChainWatchInterface>,
36 full_syncs_requested: AtomicUsize,
40 impl NetGraphMsgHandler {
41 /// Creates a new tracker of the actual state of the network of channels and nodes,
42 /// assuming a fresh network graph.
43 /// Chain monitor is used to make sure announced channels exist on-chain,
44 /// channel data is correct, and that the announcement is signed with
45 /// channel owners' keys.
46 pub fn new(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Self {
48 secp_ctx: Secp256k1::verification_only(),
49 network_graph: RwLock::new(NetworkGraph {
50 channels: BTreeMap::new(),
51 nodes: BTreeMap::new(),
53 full_syncs_requested: AtomicUsize::new(0),
55 logger: logger.clone(),
59 /// Creates a new tracker of the actual state of the network of channels and nodes,
60 /// assuming an existing Network Graph.
61 pub fn from_net_graph(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>, network_graph: RwLock<NetworkGraph>) -> Self {
63 secp_ctx: Secp256k1::verification_only(),
64 network_graph: network_graph,
65 full_syncs_requested: AtomicUsize::new(0),
67 logger: logger.clone(),
71 /// Get network addresses by node id.
72 /// Returns None if the requested node is completely unknown,
73 /// or if node announcement for the node was never received.
74 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
75 let network = self.network_graph.read().unwrap();
76 if let Some(node) = network.get_nodes().get(pubkey) {
77 if let Some(node_info) = node.announcement_info.as_ref() {
78 return Some(node_info.addresses.clone())
84 /// Dumps the entire network view of this NetGraphMsgHandler to the logger provided in the constructor at
86 pub fn trace_state(&self) {
87 log_trace!(self, "{}", self.network_graph.read().unwrap());
92 macro_rules! secp_verify_sig {
93 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
94 match $secp_ctx.verify($msg, $sig, $pubkey) {
96 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
101 impl RoutingMessageHandler for NetGraphMsgHandler {
102 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
103 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
106 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
107 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
108 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
111 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
112 Ok((script_pubkey, _value)) => {
113 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
114 .push_slice(&msg.contents.bitcoin_key_1.serialize())
115 .push_slice(&msg.contents.bitcoin_key_2.serialize())
116 .push_opcode(opcodes::all::OP_PUSHNUM_2)
117 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
118 if script_pubkey != expected_script {
119 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
121 //TODO: Check if value is worth storing, use it to inform routing, and compare it
122 //to the new HTLC max field in channel_update
125 Err(ChainError::NotSupported) => {
126 // Tentatively accept, potentially exposing us to DoS attacks
129 Err(ChainError::NotWatched) => {
130 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
132 Err(ChainError::UnknownTx) => {
133 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
136 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
137 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
141 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
143 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
144 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
146 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
147 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
149 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
150 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
155 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
156 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
159 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
160 let network_graph = self.network_graph.read().unwrap();
161 let mut result = Vec::with_capacity(batch_amount as usize);
162 let mut iter = network_graph.get_channels().range(starting_point..);
163 while result.len() < batch_amount as usize {
164 if let Some((_, ref chan)) = iter.next() {
165 if chan.announcement_message.is_some() {
166 let chan_announcement = chan.announcement_message.clone().unwrap();
167 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
168 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
169 if let Some(one_to_two) = chan.one_to_two.as_ref() {
170 one_to_two_announcement = one_to_two.last_update_message.clone();
172 if let Some(two_to_one) = chan.two_to_one.as_ref() {
173 two_to_one_announcement = two_to_one.last_update_message.clone();
175 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
177 // TODO: We may end up sending un-announced channel_updates if we are sending
178 // initial sync data while receiving announce/updates for this channel.
187 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
188 let network_graph = self.network_graph.read().unwrap();
189 let mut result = Vec::with_capacity(batch_amount as usize);
190 let mut iter = if let Some(pubkey) = starting_point {
191 let mut iter = network_graph.get_nodes().range((*pubkey)..);
195 network_graph.get_nodes().range(..)
197 while result.len() < batch_amount as usize {
198 if let Some((_, ref node)) = iter.next() {
199 if let Some(node_info) = node.announcement_info.as_ref() {
200 if node_info.announcement_message.is_some() {
201 result.push(node_info.announcement_message.clone().unwrap());
211 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
212 //TODO: Determine whether to request a full sync based on the network map.
213 const FULL_SYNCS_TO_REQUEST: usize = 5;
214 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
215 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
223 #[derive(PartialEq, Debug)]
224 /// Details about one direction of a channel. Received
225 /// within a channel update.
226 pub struct DirectionalChannelInfo {
227 /// When the last update to the channel direction was issued.
228 /// Value is opaque, as set in the announcement.
229 pub last_update: u32,
230 /// Whether the channel can be currently used for payments (in this one direction).
232 /// The difference in CLTV values that you must have when routing through this channel.
233 pub cltv_expiry_delta: u16,
234 /// The minimum value, which must be relayed to the next hop via the channel
235 pub htlc_minimum_msat: u64,
236 /// Fees charged when the channel is used for routing
237 pub fees: RoutingFees,
238 /// Most recent update for the channel received from the network
239 pub last_update_message: Option<msgs::ChannelUpdate>,
242 impl std::fmt::Display for DirectionalChannelInfo {
243 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
244 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)?;
249 impl_writeable!(DirectionalChannelInfo, 0, {
259 /// Details about a channel (both directions).
260 /// Received within a channel announcement.
261 pub struct ChannelInfo {
262 /// Protocol features of a channel communicated during its announcement
263 pub features: ChannelFeatures,
264 /// Source node of the first direction of a channel
265 pub node_one: PublicKey,
266 /// Details about the first direction of a channel
267 pub one_to_two: Option<DirectionalChannelInfo>,
268 /// Source node of the second direction of a channel
269 pub node_two: PublicKey,
270 /// Details about the second direction of a channel
271 pub two_to_one: Option<DirectionalChannelInfo>,
272 /// An initial announcement of the channel
273 /// Mostly redundant with the data we store in fields explicitly.
274 /// Everything else is useful only for sending out for initial routing sync.
275 /// Not stored if contains excess data to prevent DoS.
276 pub announcement_message: Option<msgs::ChannelAnnouncement>,
279 impl std::fmt::Display for ChannelInfo {
280 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
281 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
282 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
287 impl_writeable!(ChannelInfo, 0, {
297 /// Fees for routing via a given channel or a node
298 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
299 pub struct RoutingFees {
300 /// Flat routing fee in satoshis
302 /// Liquidity-based routing fee in millionths of a routed amount.
303 /// In other words, 10000 is 1%.
304 pub proportional_millionths: u32,
307 impl Readable for RoutingFees{
308 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
309 let base_msat: u32 = Readable::read(reader)?;
310 let proportional_millionths: u32 = Readable::read(reader)?;
313 proportional_millionths,
318 impl Writeable for RoutingFees {
319 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
320 self.base_msat.write(writer)?;
321 self.proportional_millionths.write(writer)?;
326 #[derive(PartialEq, Debug)]
327 /// Information received in the latest node_announcement from this node.
328 pub struct NodeAnnouncementInfo {
329 /// Protocol features the node announced support for
330 pub features: NodeFeatures,
331 /// When the last known update to the node state was issued.
332 /// Value is opaque, as set in the announcement.
333 pub last_update: u32,
334 /// Color assigned to the node
336 /// Moniker assigned to the node.
337 /// May be invalid or malicious (eg control chars),
338 /// should not be exposed to the user.
340 /// Internet-level addresses via which one can connect to the node
341 pub addresses: Vec<NetAddress>,
342 /// An initial announcement of the node
343 /// Mostly redundant with the data we store in fields explicitly.
344 /// Everything else is useful only for sending out for initial routing sync.
345 /// Not stored if contains excess data to prevent DoS.
346 pub announcement_message: Option<msgs::NodeAnnouncement>
349 impl Writeable for NodeAnnouncementInfo {
350 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
351 self.features.write(writer)?;
352 self.last_update.write(writer)?;
353 self.rgb.write(writer)?;
354 self.alias.write(writer)?;
355 (self.addresses.len() as u64).write(writer)?;
356 for ref addr in &self.addresses {
359 self.announcement_message.write(writer)?;
364 impl Readable for NodeAnnouncementInfo {
365 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
366 let features = Readable::read(reader)?;
367 let last_update = Readable::read(reader)?;
368 let rgb = Readable::read(reader)?;
369 let alias = Readable::read(reader)?;
370 let addresses_count: u64 = Readable::read(reader)?;
371 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
372 for _ in 0..addresses_count {
373 match Readable::read(reader) {
374 Ok(Ok(addr)) => { addresses.push(addr); },
375 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
376 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
380 let announcement_message = Readable::read(reader)?;
381 Ok(NodeAnnouncementInfo {
393 /// Details about a node in the network, known from the network announcement.
394 pub struct NodeInfo {
395 /// All valid channels a node has announced
396 pub channels: Vec<u64>,
397 /// Lowest fees enabling routing via any of the known channels to a node.
398 /// The two fields (flat and proportional fee) are independent,
399 /// meaning they don't have to refer to the same channel.
400 pub lowest_inbound_channel_fees: Option<RoutingFees>,
401 /// More information about a node from node_announcement.
402 /// Optional because we store a Node entry after learning about it from
403 /// a channel announcement, but before receiving a node announcement.
404 pub announcement_info: Option<NodeAnnouncementInfo>
407 impl std::fmt::Display for NodeInfo {
408 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
409 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
410 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
415 impl Writeable for NodeInfo {
416 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
417 (self.channels.len() as u64).write(writer)?;
418 for ref chan in self.channels.iter() {
421 self.lowest_inbound_channel_fees.write(writer)?;
422 self.announcement_info.write(writer)?;
427 const MAX_ALLOC_SIZE: u64 = 64*1024;
429 impl Readable for NodeInfo {
430 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
431 let channels_count: u64 = Readable::read(reader)?;
432 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
433 for _ in 0..channels_count {
434 channels.push(Readable::read(reader)?);
436 let lowest_inbound_channel_fees = Readable::read(reader)?;
437 let announcement_info = Readable::read(reader)?;
440 lowest_inbound_channel_fees,
446 /// Represents the network as nodes and channels between them
448 pub struct NetworkGraph {
449 channels: BTreeMap<u64, ChannelInfo>,
450 nodes: BTreeMap<PublicKey, NodeInfo>,
453 impl Writeable for NetworkGraph {
454 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
455 (self.channels.len() as u64).write(writer)?;
456 for (ref chan_id, ref chan_info) in self.channels.iter() {
457 (*chan_id).write(writer)?;
458 chan_info.write(writer)?;
460 (self.nodes.len() as u64).write(writer)?;
461 for (ref node_id, ref node_info) in self.nodes.iter() {
462 node_id.write(writer)?;
463 node_info.write(writer)?;
469 impl Readable for NetworkGraph {
470 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
471 let channels_count: u64 = Readable::read(reader)?;
472 let mut channels = BTreeMap::new();
473 for _ in 0..channels_count {
474 let chan_id: u64 = Readable::read(reader)?;
475 let chan_info = Readable::read(reader)?;
476 channels.insert(chan_id, chan_info);
478 let nodes_count: u64 = Readable::read(reader)?;
479 let mut nodes = BTreeMap::new();
480 for _ in 0..nodes_count {
481 let node_id = Readable::read(reader)?;
482 let node_info = Readable::read(reader)?;
483 nodes.insert(node_id, node_info);
492 impl std::fmt::Display for NetworkGraph {
493 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
494 write!(f, "Network map\n[Channels]\n")?;
495 for (key, val) in self.channels.iter() {
496 write!(f, " {}: {}\n", key, val)?;
498 write!(f, "[Nodes]\n")?;
499 for (key, val) in self.nodes.iter() {
500 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
507 /// Returns all known valid channels' short ids along with announced channel info.
508 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
509 /// Returns all known nodes' public keys along with announced node info.
510 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
512 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
513 /// Announcement signatures are checked here only if Secp256k1 object is provided.
514 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
515 if let Some(sig_verifier) = secp_ctx {
516 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
517 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
520 match self.nodes.get_mut(&msg.contents.node_id) {
521 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
523 if let Some(node_info) = node.announcement_info.as_ref() {
524 if node_info.last_update >= msg.contents.timestamp {
525 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
529 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
530 node.announcement_info = Some(NodeAnnouncementInfo {
531 features: msg.contents.features.clone(),
532 last_update: msg.contents.timestamp,
533 rgb: msg.contents.rgb,
534 alias: msg.contents.alias,
535 addresses: msg.contents.addresses.clone(),
536 announcement_message: if should_relay { Some(msg.clone()) } else { None },
544 /// For a new or already known (from previous announcement) channel, store or update channel info.
545 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
546 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
547 /// which is probably result of a reorg. In that case, we update channel info only if the
548 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
549 /// Announcement signatures are checked here only if Secp256k1 object is provided.
550 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
551 if let Some(sig_verifier) = secp_ctx {
552 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
553 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
554 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
555 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
556 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
559 let should_relay = msg.contents.excess_data.is_empty();
561 let chan_info = ChannelInfo {
562 features: msg.contents.features.clone(),
563 node_one: msg.contents.node_id_1.clone(),
565 node_two: msg.contents.node_id_2.clone(),
567 announcement_message: if should_relay { Some(msg.clone()) } else { None },
570 match self.channels.entry(msg.contents.short_channel_id) {
571 BtreeEntry::Occupied(mut entry) => {
572 //TODO: because asking the blockchain if short_channel_id is valid is only optional
573 //in the blockchain API, we need to handle it smartly here, though it's unclear
576 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
577 // only sometimes returns results. In any case remove the previous entry. Note
578 // that the spec expects us to "blacklist" the node_ids involved, but we can't
580 // a) we don't *require* a UTXO provider that always returns results.
581 // b) we don't track UTXOs of channels we know about and remove them if they
583 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
584 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
585 *entry.get_mut() = chan_info;
587 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
590 BtreeEntry::Vacant(entry) => {
591 entry.insert(chan_info);
595 macro_rules! add_channel_to_node {
596 ( $node_id: expr ) => {
597 match self.nodes.entry($node_id) {
598 BtreeEntry::Occupied(node_entry) => {
599 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
601 BtreeEntry::Vacant(node_entry) => {
602 node_entry.insert(NodeInfo {
603 channels: vec!(msg.contents.short_channel_id),
604 lowest_inbound_channel_fees: None,
605 announcement_info: None,
612 add_channel_to_node!(msg.contents.node_id_1);
613 add_channel_to_node!(msg.contents.node_id_2);
618 /// Close a channel if a corresponding HTLC fail was sent.
619 /// If permanent, removes a channel from the local storage.
620 /// May cause the removal of nodes too, if this was their last channel.
621 /// If not permanent, makes channels unavailable for routing.
622 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
624 if let Some(chan) = self.channels.remove(short_channel_id) {
625 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
628 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
629 if let Some(one_to_two) = chan.one_to_two.as_mut() {
630 one_to_two.enabled = false;
632 if let Some(two_to_one) = chan.two_to_one.as_mut() {
633 two_to_one.enabled = false;
639 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
641 // TODO: Wholly remove the node
643 // TODO: downgrade the node
647 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
648 /// Announcement signatures are checked here only if Secp256k1 object is provided.
649 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
651 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
652 let chan_was_enabled;
654 match self.channels.get_mut(&msg.contents.short_channel_id) {
655 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
657 macro_rules! maybe_update_channel_info {
658 ( $target: expr, $src_node: expr) => {
659 if let Some(existing_chan_info) = $target.as_ref() {
660 if existing_chan_info.last_update >= msg.contents.timestamp {
661 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
663 chan_was_enabled = existing_chan_info.enabled;
665 chan_was_enabled = false;
668 let last_update_message = if msg.contents.excess_data.is_empty() {
674 let updated_channel_dir_info = DirectionalChannelInfo {
675 enabled: chan_enabled,
676 last_update: msg.contents.timestamp,
677 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
678 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
680 base_msat: msg.contents.fee_base_msat,
681 proportional_millionths: msg.contents.fee_proportional_millionths,
685 $target = Some(updated_channel_dir_info);
689 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
690 if msg.contents.flags & 1 == 1 {
691 dest_node_id = channel.node_one.clone();
692 if let Some(sig_verifier) = secp_ctx {
693 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
695 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
697 dest_node_id = channel.node_two.clone();
698 if let Some(sig_verifier) = secp_ctx {
699 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
701 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
707 let node = self.nodes.get_mut(&dest_node_id).unwrap();
708 let mut base_msat = msg.contents.fee_base_msat;
709 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
710 if let Some(fees) = node.lowest_inbound_channel_fees {
711 base_msat = cmp::min(base_msat, fees.base_msat);
712 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
714 node.lowest_inbound_channel_fees = Some(RoutingFees {
716 proportional_millionths
718 } else if chan_was_enabled {
719 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
720 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
723 let node = self.nodes.get(&dest_node_id).unwrap();
725 for chan_id in node.channels.iter() {
726 let chan = self.channels.get(chan_id).unwrap();
727 // Since direction was enabled, the channel indeed had directional info
729 if chan.node_one == dest_node_id {
730 chan_info = chan.two_to_one.as_ref().unwrap();
732 chan_info = chan.one_to_two.as_ref().unwrap();
734 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan_info.fees.base_msat);
735 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan_info.fees.proportional_millionths);
739 //TODO: satisfy the borrow-checker without a double-map-lookup :(
740 let mut_node = self.nodes.get_mut(&dest_node_id).unwrap();
741 if mut_node.channels.len() > 0 {
742 mut_node.lowest_inbound_channel_fees = Some(RoutingFees {
743 base_msat: lowest_inbound_channel_fee_base_msat,
744 proportional_millionths: lowest_inbound_channel_fee_proportional_millionths
749 Ok(msg.contents.excess_data.is_empty())
752 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
753 macro_rules! remove_from_node {
754 ($node_id: expr) => {
755 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
756 entry.get_mut().channels.retain(|chan_id| {
757 short_channel_id != *chan_id
759 if entry.get().channels.is_empty() {
760 entry.remove_entry();
763 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
768 remove_from_node!(chan.node_one);
769 remove_from_node!(chan.node_two);
775 use chain::chaininterface;
776 use ln::features::{ChannelFeatures, NodeFeatures};
777 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
778 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
779 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
780 use util::test_utils;
781 use util::logger::Logger;
782 use util::ser::{Readable, Writeable};
784 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
785 use bitcoin::hashes::Hash;
786 use bitcoin::network::constants::Network;
787 use bitcoin::blockdata::constants::genesis_block;
788 use bitcoin::blockdata::script::Builder;
789 use bitcoin::blockdata::opcodes;
790 use bitcoin::util::hash::BitcoinHash;
794 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
795 use bitcoin::secp256k1::{All, Secp256k1};
799 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
800 let secp_ctx = Secp256k1::new();
801 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
802 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
803 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
804 (secp_ctx, net_graph_msg_handler)
808 fn request_full_sync_finite_times() {
809 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
810 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
812 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
813 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
814 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
815 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
816 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
817 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
821 fn handling_node_announcements() {
822 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
824 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
825 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
826 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
827 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
828 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
829 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
830 let zero_hash = Sha256dHash::hash(&[0; 32]);
831 let first_announcement_time = 500;
833 let mut unsigned_announcement = UnsignedNodeAnnouncement {
834 features: NodeFeatures::known(),
835 timestamp: first_announcement_time,
839 addresses: Vec::new(),
840 excess_address_data: Vec::new(),
841 excess_data: Vec::new(),
843 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
844 let valid_announcement = NodeAnnouncement {
845 signature: secp_ctx.sign(&msghash, node_1_privkey),
846 contents: unsigned_announcement.clone()
849 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
851 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
855 // Announce a channel to add a corresponding node.
856 let unsigned_announcement = UnsignedChannelAnnouncement {
857 features: ChannelFeatures::known(),
858 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
862 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
863 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
864 excess_data: Vec::new(),
867 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
868 let valid_announcement = ChannelAnnouncement {
869 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
870 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
871 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
872 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
873 contents: unsigned_announcement.clone(),
875 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
876 Ok(res) => assert!(res),
881 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
882 Ok(res) => assert!(res),
886 let fake_msghash = hash_to_message!(&zero_hash);
887 match net_graph_msg_handler.handle_node_announcement(
889 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
890 contents: unsigned_announcement.clone()
893 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
896 unsigned_announcement.timestamp += 1000;
897 unsigned_announcement.excess_data.push(1);
898 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
899 let announcement_with_data = NodeAnnouncement {
900 signature: secp_ctx.sign(&msghash, node_1_privkey),
901 contents: unsigned_announcement.clone()
903 // Return false because contains excess data.
904 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
905 Ok(res) => assert!(!res),
908 unsigned_announcement.excess_data = Vec::new();
910 // Even though previous announcement was not relayed further, we still accepted it,
911 // so we now won't accept announcements before the previous one.
912 unsigned_announcement.timestamp -= 10;
913 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
914 let outdated_announcement = NodeAnnouncement {
915 signature: secp_ctx.sign(&msghash, node_1_privkey),
916 contents: unsigned_announcement.clone()
918 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
920 Err(e) => assert_eq!(e.err, "Update older than last processed update")
925 fn handling_channel_announcements() {
926 let secp_ctx = Secp256k1::new();
927 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
928 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
929 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
932 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
933 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
934 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
935 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
936 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
937 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
939 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
940 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
941 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
942 .push_opcode(opcodes::all::OP_PUSHNUM_2)
943 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
946 let mut unsigned_announcement = UnsignedChannelAnnouncement {
947 features: ChannelFeatures::known(),
948 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
952 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
953 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
954 excess_data: Vec::new(),
957 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
958 let valid_announcement = ChannelAnnouncement {
959 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
960 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
961 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
962 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
963 contents: unsigned_announcement.clone(),
966 // Test if the UTXO lookups were not supported
967 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
969 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
970 Ok(res) => assert!(res),
975 let network = net_graph_msg_handler.network_graph.read().unwrap();
976 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
983 // If we receive announcement for the same channel (with UTXO lookups disabled),
984 // drop new one on the floor, since we can't see any changes.
985 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
987 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
991 // Test if an associated transaction were not on-chain (or not confirmed).
992 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
993 unsigned_announcement.short_channel_id += 1;
995 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
996 let valid_announcement = ChannelAnnouncement {
997 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
998 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
999 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1000 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1001 contents: unsigned_announcement.clone(),
1004 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1006 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1010 // Now test if the transaction is found in the UTXO set and the script is correct.
1011 unsigned_announcement.short_channel_id += 1;
1012 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1014 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1015 let valid_announcement = ChannelAnnouncement {
1016 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1017 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1018 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1019 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1020 contents: unsigned_announcement.clone(),
1022 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1023 Ok(res) => assert!(res),
1028 let network = net_graph_msg_handler.network_graph.read().unwrap();
1029 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1035 // If we receive announcement for the same channel (but TX is not confirmed),
1036 // drop new one on the floor, since we can't see any changes.
1037 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1038 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1040 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1043 // But if it is confirmed, replace the channel
1044 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1045 unsigned_announcement.features = ChannelFeatures::empty();
1046 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1047 let valid_announcement = ChannelAnnouncement {
1048 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1049 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1050 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1051 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1052 contents: unsigned_announcement.clone(),
1054 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1055 Ok(res) => assert!(res),
1059 let network = net_graph_msg_handler.network_graph.read().unwrap();
1060 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1061 Some(channel_entry) => {
1062 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1068 // Don't relay valid channels with excess data
1069 unsigned_announcement.short_channel_id += 1;
1070 unsigned_announcement.excess_data.push(1);
1071 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1072 let valid_announcement = ChannelAnnouncement {
1073 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1074 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1075 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1076 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1077 contents: unsigned_announcement.clone(),
1079 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1080 Ok(res) => assert!(!res),
1084 unsigned_announcement.excess_data = Vec::new();
1085 let invalid_sig_announcement = ChannelAnnouncement {
1086 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1087 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1088 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1089 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1090 contents: unsigned_announcement.clone(),
1092 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1094 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1097 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1098 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1099 let channel_to_itself_announcement = ChannelAnnouncement {
1100 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1101 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1102 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1103 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1104 contents: unsigned_announcement.clone(),
1106 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1108 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1113 fn handling_channel_update() {
1114 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1115 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1116 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1117 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1118 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1119 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1120 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1122 let zero_hash = Sha256dHash::hash(&[0; 32]);
1123 let short_channel_id = 0;
1124 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1126 // Announce a channel we will update
1127 let unsigned_announcement = UnsignedChannelAnnouncement {
1128 features: ChannelFeatures::empty(),
1133 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1134 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1135 excess_data: Vec::new(),
1138 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1139 let valid_channel_announcement = ChannelAnnouncement {
1140 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1141 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1142 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1143 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1144 contents: unsigned_announcement.clone(),
1146 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1153 let mut unsigned_channel_update = UnsignedChannelUpdate {
1158 cltv_expiry_delta: 144,
1159 htlc_minimum_msat: 1000000,
1160 fee_base_msat: 10000,
1161 fee_proportional_millionths: 20,
1162 excess_data: Vec::new()
1164 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1165 let valid_channel_update = ChannelUpdate {
1166 signature: secp_ctx.sign(&msghash, node_1_privkey),
1167 contents: unsigned_channel_update.clone()
1170 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1171 Ok(res) => assert!(res),
1176 let network = net_graph_msg_handler.network_graph.read().unwrap();
1177 match network.get_channels().get(&short_channel_id) {
1179 Some(channel_info) => {
1180 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1181 assert!(channel_info.two_to_one.is_none());
1186 unsigned_channel_update.timestamp += 100;
1187 unsigned_channel_update.excess_data.push(1);
1188 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1189 let valid_channel_update = ChannelUpdate {
1190 signature: secp_ctx.sign(&msghash, node_1_privkey),
1191 contents: unsigned_channel_update.clone()
1193 // Return false because contains excess data
1194 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1195 Ok(res) => assert!(!res),
1199 unsigned_channel_update.short_channel_id += 1;
1200 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1201 let valid_channel_update = ChannelUpdate {
1202 signature: secp_ctx.sign(&msghash, node_1_privkey),
1203 contents: unsigned_channel_update.clone()
1206 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1208 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1210 unsigned_channel_update.short_channel_id = short_channel_id;
1213 // Even though previous update was not relayed further, we still accepted it,
1214 // so we now won't accept update before the previous one.
1215 unsigned_channel_update.timestamp -= 10;
1216 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1217 let valid_channel_update = ChannelUpdate {
1218 signature: secp_ctx.sign(&msghash, node_1_privkey),
1219 contents: unsigned_channel_update.clone()
1222 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1224 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1226 unsigned_channel_update.timestamp += 500;
1228 let fake_msghash = hash_to_message!(&zero_hash);
1229 let invalid_sig_channel_update = ChannelUpdate {
1230 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1231 contents: unsigned_channel_update.clone()
1234 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1236 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1242 fn handling_htlc_fail_channel_update() {
1243 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1244 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1245 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1246 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1247 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1248 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1249 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1251 let short_channel_id = 0;
1252 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1255 // There is no nodes in the table at the beginning.
1256 let network = net_graph_msg_handler.network_graph.read().unwrap();
1257 assert_eq!(network.get_nodes().len(), 0);
1261 // Announce a channel we will update
1262 let unsigned_announcement = UnsignedChannelAnnouncement {
1263 features: ChannelFeatures::empty(),
1268 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1269 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1270 excess_data: Vec::new(),
1273 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1274 let valid_channel_announcement = ChannelAnnouncement {
1275 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1276 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1277 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1278 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1279 contents: unsigned_announcement.clone(),
1281 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1286 let unsigned_channel_update = UnsignedChannelUpdate {
1291 cltv_expiry_delta: 144,
1292 htlc_minimum_msat: 1000000,
1293 fee_base_msat: 10000,
1294 fee_proportional_millionths: 20,
1295 excess_data: Vec::new()
1297 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1298 let valid_channel_update = ChannelUpdate {
1299 signature: secp_ctx.sign(&msghash, node_1_privkey),
1300 contents: unsigned_channel_update.clone()
1303 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1304 Ok(res) => assert!(res),
1309 // Non-permanent closing just disables a channel
1311 let network = net_graph_msg_handler.network_graph.read().unwrap();
1312 match network.get_channels().get(&short_channel_id) {
1314 Some(channel_info) => {
1315 assert!(channel_info.one_to_two.is_some());
1320 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1325 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1327 // Non-permanent closing just disables a channel
1329 let network = net_graph_msg_handler.network_graph.read().unwrap();
1330 match network.get_channels().get(&short_channel_id) {
1332 Some(channel_info) => {
1333 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1338 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1343 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1345 // Permanent closing deletes a channel
1347 let network = net_graph_msg_handler.network_graph.read().unwrap();
1348 assert_eq!(network.get_channels().len(), 0);
1349 // Nodes are also deleted because there are no associated channels anymore
1350 assert_eq!(network.get_nodes().len(), 0);
1352 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1356 fn getting_next_channel_announcements() {
1357 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1358 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1359 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1360 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1361 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1362 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1363 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1365 let short_channel_id = 1;
1366 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1368 // Channels were not announced yet.
1369 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1370 assert_eq!(channels_with_announcements.len(), 0);
1373 // Announce a channel we will update
1374 let unsigned_announcement = UnsignedChannelAnnouncement {
1375 features: ChannelFeatures::empty(),
1380 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1381 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1382 excess_data: Vec::new(),
1385 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1386 let valid_channel_announcement = ChannelAnnouncement {
1387 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1388 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1389 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1390 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1391 contents: unsigned_announcement.clone(),
1393 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1399 // Contains initial channel announcement now.
1400 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1401 assert_eq!(channels_with_announcements.len(), 1);
1402 if let Some(channel_announcements) = channels_with_announcements.first() {
1403 let &(_, ref update_1, ref update_2) = channel_announcements;
1404 assert_eq!(update_1, &None);
1405 assert_eq!(update_2, &None);
1412 // Valid channel update
1413 let unsigned_channel_update = UnsignedChannelUpdate {
1418 cltv_expiry_delta: 144,
1419 htlc_minimum_msat: 1000000,
1420 fee_base_msat: 10000,
1421 fee_proportional_millionths: 20,
1422 excess_data: Vec::new()
1424 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1425 let valid_channel_update = ChannelUpdate {
1426 signature: secp_ctx.sign(&msghash, node_1_privkey),
1427 contents: unsigned_channel_update.clone()
1429 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1435 // Now contains an initial announcement and an update.
1436 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1437 assert_eq!(channels_with_announcements.len(), 1);
1438 if let Some(channel_announcements) = channels_with_announcements.first() {
1439 let &(_, ref update_1, ref update_2) = channel_announcements;
1440 assert_ne!(update_1, &None);
1441 assert_eq!(update_2, &None);
1448 // Channel update with excess data.
1449 let unsigned_channel_update = UnsignedChannelUpdate {
1454 cltv_expiry_delta: 144,
1455 htlc_minimum_msat: 1000000,
1456 fee_base_msat: 10000,
1457 fee_proportional_millionths: 20,
1458 excess_data: [1; 3].to_vec()
1460 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1461 let valid_channel_update = ChannelUpdate {
1462 signature: secp_ctx.sign(&msghash, node_1_privkey),
1463 contents: unsigned_channel_update.clone()
1465 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1471 // Test that announcements with excess data won't be returned
1472 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1473 assert_eq!(channels_with_announcements.len(), 1);
1474 if let Some(channel_announcements) = channels_with_announcements.first() {
1475 let &(_, ref update_1, ref update_2) = channel_announcements;
1476 assert_eq!(update_1, &None);
1477 assert_eq!(update_2, &None);
1482 // Further starting point have no channels after it
1483 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1484 assert_eq!(channels_with_announcements.len(), 0);
1488 fn getting_next_node_announcements() {
1489 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1490 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1491 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1492 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1493 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1494 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1495 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1497 let short_channel_id = 1;
1498 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1501 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1502 assert_eq!(next_announcements.len(), 0);
1505 // Announce a channel to add 2 nodes
1506 let unsigned_announcement = UnsignedChannelAnnouncement {
1507 features: ChannelFeatures::empty(),
1512 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1513 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1514 excess_data: Vec::new(),
1517 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1518 let valid_channel_announcement = ChannelAnnouncement {
1519 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1520 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1521 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1522 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1523 contents: unsigned_announcement.clone(),
1525 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1532 // Nodes were never announced
1533 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1534 assert_eq!(next_announcements.len(), 0);
1537 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1538 features: NodeFeatures::known(),
1543 addresses: Vec::new(),
1544 excess_address_data: Vec::new(),
1545 excess_data: Vec::new(),
1547 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1548 let valid_announcement = NodeAnnouncement {
1549 signature: secp_ctx.sign(&msghash, node_1_privkey),
1550 contents: unsigned_announcement.clone()
1552 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1557 unsigned_announcement.node_id = node_id_2;
1558 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1559 let valid_announcement = NodeAnnouncement {
1560 signature: secp_ctx.sign(&msghash, node_2_privkey),
1561 contents: unsigned_announcement.clone()
1564 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1570 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1571 assert_eq!(next_announcements.len(), 2);
1573 // Skip the first node.
1574 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1575 assert_eq!(next_announcements.len(), 1);
1578 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1579 let unsigned_announcement = UnsignedNodeAnnouncement {
1580 features: NodeFeatures::known(),
1585 addresses: Vec::new(),
1586 excess_address_data: Vec::new(),
1587 excess_data: [1; 3].to_vec(),
1589 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1590 let valid_announcement = NodeAnnouncement {
1591 signature: secp_ctx.sign(&msghash, node_2_privkey),
1592 contents: unsigned_announcement.clone()
1594 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1595 Ok(res) => assert!(!res),
1600 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1601 assert_eq!(next_announcements.len(), 0);
1605 fn network_graph_serialization() {
1606 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1608 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1609 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1610 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1611 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1613 // Announce a channel to add a corresponding node.
1614 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1615 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1616 let unsigned_announcement = UnsignedChannelAnnouncement {
1617 features: ChannelFeatures::known(),
1618 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1619 short_channel_id: 0,
1622 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1623 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1624 excess_data: Vec::new(),
1627 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1628 let valid_announcement = ChannelAnnouncement {
1629 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1630 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1631 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1632 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1633 contents: unsigned_announcement.clone(),
1635 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1636 Ok(res) => assert!(res),
1641 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1642 let unsigned_announcement = UnsignedNodeAnnouncement {
1643 features: NodeFeatures::known(),
1648 addresses: Vec::new(),
1649 excess_address_data: Vec::new(),
1650 excess_data: Vec::new(),
1652 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1653 let valid_announcement = NodeAnnouncement {
1654 signature: secp_ctx.sign(&msghash, node_1_privkey),
1655 contents: unsigned_announcement.clone()
1658 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1663 let network = net_graph_msg_handler.network_graph.write().unwrap();
1664 let mut w = test_utils::TestVecWriter(Vec::new());
1665 assert!(!network.get_nodes().is_empty());
1666 assert!(!network.get_channels().is_empty());
1667 network.write(&mut w).unwrap();
1668 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);