1 //! The top-level network map tracking logic lives here.
3 use bitcoin::secp256k1::key::PublicKey;
4 use bitcoin::secp256k1::Secp256k1;
5 use bitcoin::secp256k1;
7 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
8 use bitcoin::hashes::Hash;
9 use bitcoin::blockdata::script::Builder;
10 use bitcoin::blockdata::opcodes;
12 use chain::chaininterface::{ChainError, ChainWatchInterface};
13 use ln::features::{ChannelFeatures, NodeFeatures};
14 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress};
16 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
17 use util::logger::Logger;
20 use std::sync::{RwLock,Arc};
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
26 /// Receives network updates from peers to track view of the network.
27 pub struct NetGraphMsgHandler {
28 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
29 /// Representation of the payment channel network
30 pub network_graph: RwLock<NetworkGraph>,
31 chain_monitor: Arc<ChainWatchInterface>,
32 full_syncs_requested: AtomicUsize,
36 impl NetGraphMsgHandler {
37 /// Creates a new tracker of the actual state of the network of channels and nodes.
38 pub fn new(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Self {
40 secp_ctx: Secp256k1::verification_only(),
41 network_graph: RwLock::new(NetworkGraph {
42 channels: BTreeMap::new(),
43 nodes: BTreeMap::new(),
45 full_syncs_requested: AtomicUsize::new(0),
47 logger: logger.clone(),
51 /// Get network addresses by node id
52 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
53 let network = self.network_graph.read().unwrap();
54 if let Some(node) = network.get_nodes().get(pubkey) {
55 if let Some(node_info) = node.announcement_info.as_ref() {
56 return Some(node_info.addresses.clone())
62 /// Dumps the entire network view of this NetGraphMsgHandler to the logger provided in the constructor at
64 pub fn trace_state(&self) {
65 log_trace!(self, "{}", self.network_graph.read().unwrap());
70 macro_rules! secp_verify_sig {
71 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
72 match $secp_ctx.verify($msg, $sig, $pubkey) {
74 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
79 impl RoutingMessageHandler for NetGraphMsgHandler {
80 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
81 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
84 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
85 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
86 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
89 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
90 Ok((script_pubkey, _value)) => {
91 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
92 .push_slice(&msg.contents.bitcoin_key_1.serialize())
93 .push_slice(&msg.contents.bitcoin_key_2.serialize())
94 .push_opcode(opcodes::all::OP_PUSHNUM_2)
95 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
96 if script_pubkey != expected_script {
97 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
99 //TODO: Check if value is worth storing, use it to inform routing, and compare it
100 //to the new HTLC max field in channel_update
103 Err(ChainError::NotSupported) => {
104 // Tentatively accept, potentially exposing us to DoS attacks
107 Err(ChainError::NotWatched) => {
108 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
110 Err(ChainError::UnknownTx) => {
111 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
114 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
115 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
119 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
121 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
122 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
124 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
125 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
127 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
128 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
133 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
134 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
137 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
138 let network_graph = self.network_graph.read().unwrap();
139 let mut result = Vec::with_capacity(batch_amount as usize);
140 let mut iter = network_graph.get_channels().range(starting_point..);
141 while result.len() < batch_amount as usize {
142 if let Some((_, ref chan)) = iter.next() {
143 if chan.announcement_message.is_some() {
144 let chan_announcement = chan.announcement_message.clone().unwrap();
145 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
146 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
147 if let Some(one_to_two) = chan.one_to_two.as_ref() {
148 one_to_two_announcement = one_to_two.last_update_message.clone();
150 if let Some(two_to_one) = chan.two_to_one.as_ref() {
151 two_to_one_announcement = two_to_one.last_update_message.clone();
153 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
155 // TODO: We may end up sending un-announced channel_updates if we are sending
156 // initial sync data while receiving announce/updates for this channel.
165 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
166 let network_graph = self.network_graph.read().unwrap();
167 let mut result = Vec::with_capacity(batch_amount as usize);
168 let mut iter = if let Some(pubkey) = starting_point {
169 let mut iter = network_graph.get_nodes().range((*pubkey)..);
173 network_graph.get_nodes().range(..)
175 while result.len() < batch_amount as usize {
176 if let Some((_, ref node)) = iter.next() {
177 if let Some(node_info) = node.announcement_info.as_ref() {
178 if node_info.announcement_message.is_some() {
179 result.push(node_info.announcement_message.clone().unwrap());
189 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
190 //TODO: Determine whether to request a full sync based on the network map.
191 const FULL_SYNCS_TO_REQUEST: usize = 5;
192 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
193 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
202 const SERIALIZATION_VERSION: u8 = 1;
203 const MIN_SERIALIZATION_VERSION: u8 = 1;
205 impl Writeable for NetGraphMsgHandler {
206 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
207 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
208 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
210 let network = self.network_graph.read().unwrap();
211 network.write(writer)?;
216 /// Arguments for the creation of a NetGraphMsgHandler that are not deserialized.
217 /// At a high-level, the process for deserializing a NetGraphMsgHandler and resuming normal operation is:
218 /// 1) Deserialize the NetGraphMsgHandler by filling in this struct and calling <NetGraphMsgHandler>::read(reaser, args).
219 /// 2) Register the new NetGraphMsgHandler with your ChainWatchInterface
220 pub struct NetGraphMsgHandlerReadArgs {
221 /// The ChainWatchInterface for use in the NetGraphMsgHandler in the future.
223 /// No calls to the ChainWatchInterface will be made during deserialization.
224 pub chain_monitor: Arc<ChainWatchInterface>,
225 /// The Logger for use in the ChannelManager and which may be used to log information during
227 pub logger: Arc<Logger>,
230 impl ReadableArgs<NetGraphMsgHandlerReadArgs> for NetGraphMsgHandler {
231 fn read<R: ::std::io::Read>(reader: &mut R, args: NetGraphMsgHandlerReadArgs) -> Result<NetGraphMsgHandler, DecodeError> {
232 let _ver: u8 = Readable::read(reader)?;
233 let min_ver: u8 = Readable::read(reader)?;
234 if min_ver > SERIALIZATION_VERSION {
235 return Err(DecodeError::UnknownVersion);
237 let network_graph = Readable::read(reader)?;
238 Ok(NetGraphMsgHandler {
239 secp_ctx: Secp256k1::verification_only(),
240 network_graph: RwLock::new(network_graph),
241 chain_monitor: args.chain_monitor,
242 full_syncs_requested: AtomicUsize::new(0),
243 logger: args.logger.clone(),
248 #[derive(PartialEq, Debug)]
249 /// Details regarding one direction of a channel
250 pub struct DirectionalChannelInfo {
251 /// When the last update to the channel direction was issued
252 pub last_update: u32,
253 /// Whether the channel can be currently used for payments
255 /// The difference in CLTV values between the source and the destination node of the channel
256 pub cltv_expiry_delta: u16,
257 /// The minimum value, which must be relayed to the next hop via the channel
258 pub htlc_minimum_msat: u64,
259 /// Fees charged when the channel is used for routing
260 pub fees: RoutingFees,
261 /// Most recent update for the channel received from the network
262 pub last_update_message: Option<msgs::ChannelUpdate>,
265 impl std::fmt::Display for DirectionalChannelInfo {
266 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
267 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)?;
272 impl_writeable!(DirectionalChannelInfo, 0, {
282 /// Details regarding a channel (both directions)
283 pub struct ChannelInfo {
284 /// Protocol features of a channel communicated during its announcement
285 pub features: ChannelFeatures,
286 /// Source node of the first direction of a channel
287 pub node_one: PublicKey,
288 /// Details about the first direction of a channel
289 pub one_to_two: Option<DirectionalChannelInfo>,
290 /// Source node of the second direction of a channel
291 pub node_two: PublicKey,
292 /// Details about the second direction of a channel
293 pub two_to_one: Option<DirectionalChannelInfo>,
294 /// An initial announcement of the channel
295 //this is cached here so we can send out it later if required by initial routing sync
296 //keep an eye on this to see if the extra memory is a problem
297 pub announcement_message: Option<msgs::ChannelAnnouncement>,
300 impl std::fmt::Display for ChannelInfo {
301 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
302 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
303 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
308 impl_writeable!(ChannelInfo, 0, {
318 /// Fees for routing via a given channel or a node
319 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
320 pub struct RoutingFees {
323 /// Liquidity-based routing fee
324 pub proportional_millionths: u32,
327 impl Readable for RoutingFees{
328 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
329 let base_msat: u32 = Readable::read(reader)?;
330 let proportional_millionths: u32 = Readable::read(reader)?;
333 proportional_millionths,
338 impl Writeable for RoutingFees {
339 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
340 self.base_msat.write(writer)?;
341 self.proportional_millionths.write(writer)?;
346 #[derive(PartialEq, Debug)]
347 /// Information received in the latest node_announcement from this node.
348 pub struct NodeAnnouncementInfo {
349 /// Protocol features the node announced support for
350 pub features: NodeFeatures,
351 /// When the last known update to the node state was issued
352 pub last_update: u32,
353 /// Color assigned to the node
355 /// Moniker assigned to the node
357 /// Internet-level addresses via which one can connect to the node
358 pub addresses: Vec<NetAddress>,
359 /// An initial announcement of the node
360 // this is cached here so we can send out it later if required by initial routing sync
361 // keep an eye on this to see if the extra memory is a problem
362 pub announcement_message: Option<msgs::NodeAnnouncement>
365 impl Writeable for NodeAnnouncementInfo {
366 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
367 self.features.write(writer)?;
368 self.last_update.write(writer)?;
369 self.rgb.write(writer)?;
370 self.alias.write(writer)?;
371 (self.addresses.len() as u64).write(writer)?;
372 for ref addr in &self.addresses {
375 self.announcement_message.write(writer)?;
380 impl Readable for NodeAnnouncementInfo {
381 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
382 let features = Readable::read(reader)?;
383 let last_update = Readable::read(reader)?;
384 let rgb = Readable::read(reader)?;
385 let alias = Readable::read(reader)?;
386 let addresses_count: u64 = Readable::read(reader)?;
387 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
388 for _ in 0..addresses_count {
389 match Readable::read(reader) {
390 Ok(Ok(addr)) => { addresses.push(addr); },
391 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
392 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
396 let announcement_message = Readable::read(reader)?;
397 Ok(NodeAnnouncementInfo {
409 /// Details regarding a node in the network
410 pub struct NodeInfo {
411 /// All valid channels a node has announced
412 pub channels: Vec<u64>,
413 /// Lowest fees enabling routing via any of the known channels to a node
414 pub lowest_inbound_channel_fees: Option<RoutingFees>,
415 /// More information about a node from node_announcement
416 /// Optional because we may have a NodeInfo entry before having received the announcement
417 pub announcement_info: Option<NodeAnnouncementInfo>
420 impl std::fmt::Display for NodeInfo {
421 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
422 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
423 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
428 impl Writeable for NodeInfo {
429 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
430 (self.channels.len() as u64).write(writer)?;
431 for ref chan in self.channels.iter() {
434 self.lowest_inbound_channel_fees.write(writer)?;
435 self.announcement_info.write(writer)?;
440 const MAX_ALLOC_SIZE: u64 = 64*1024;
442 impl Readable for NodeInfo {
443 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
444 let channels_count: u64 = Readable::read(reader)?;
445 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
446 for _ in 0..channels_count {
447 channels.push(Readable::read(reader)?);
449 let lowest_inbound_channel_fees = Readable::read(reader)?;
450 let announcement_info = Readable::read(reader)?;
453 lowest_inbound_channel_fees,
459 /// Represents the network as nodes and channels between them
461 pub struct NetworkGraph {
462 channels: BTreeMap<u64, ChannelInfo>,
463 nodes: BTreeMap<PublicKey, NodeInfo>,
466 impl Writeable for NetworkGraph {
467 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
468 (self.channels.len() as u64).write(writer)?;
469 for (ref chan_id, ref chan_info) in self.channels.iter() {
470 (*chan_id).write(writer)?;
471 chan_info.write(writer)?;
473 (self.nodes.len() as u64).write(writer)?;
474 for (ref node_id, ref node_info) in self.nodes.iter() {
475 node_id.write(writer)?;
476 node_info.write(writer)?;
482 impl Readable for NetworkGraph {
483 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
484 let channels_count: u64 = Readable::read(reader)?;
485 let mut channels = BTreeMap::new();
486 for _ in 0..channels_count {
487 let chan_id: u64 = Readable::read(reader)?;
488 let chan_info = Readable::read(reader)?;
489 channels.insert(chan_id, chan_info);
491 let nodes_count: u64 = Readable::read(reader)?;
492 let mut nodes = BTreeMap::new();
493 for _ in 0..nodes_count {
494 let node_id = Readable::read(reader)?;
495 let node_info = Readable::read(reader)?;
496 nodes.insert(node_id, node_info);
505 impl std::fmt::Display for NetworkGraph {
506 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
507 write!(f, "Network map\n[Channels]\n")?;
508 for (key, val) in self.channels.iter() {
509 write!(f, " {}: {}\n", key, val)?;
511 write!(f, "[Nodes]\n")?;
512 for (key, val) in self.nodes.iter() {
513 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
520 /// Returns all known valid channels
521 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
522 /// Returns all known nodes
523 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
525 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
526 /// Announcement signatures are checked here only if Secp256k1 object is provided.
527 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
528 if let Some(sig_verifier) = secp_ctx {
529 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
530 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
533 match self.nodes.get_mut(&msg.contents.node_id) {
534 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
536 if let Some(node_info) = node.announcement_info.as_ref() {
537 if node_info.last_update >= msg.contents.timestamp {
538 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
542 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
543 node.announcement_info = Some(NodeAnnouncementInfo {
544 features: msg.contents.features.clone(),
545 last_update: msg.contents.timestamp,
546 rgb: msg.contents.rgb,
547 alias: msg.contents.alias,
548 addresses: msg.contents.addresses.clone(),
549 announcement_message: if should_relay { Some(msg.clone()) } else { None },
557 /// For a new or already known (from previous announcement) channel, store or update channel info,
558 /// after making sure it corresponds to a real transaction on-chain.
559 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
560 /// Announcement signatures are checked here only if Secp256k1 object is provided.
561 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
562 if let Some(sig_verifier) = secp_ctx {
563 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
564 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
565 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
566 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
567 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
570 let should_relay = msg.contents.excess_data.is_empty();
572 let chan_info = ChannelInfo {
573 features: msg.contents.features.clone(),
574 node_one: msg.contents.node_id_1.clone(),
576 node_two: msg.contents.node_id_2.clone(),
578 announcement_message: if should_relay { Some(msg.clone()) } else { None },
581 match self.channels.entry(msg.contents.short_channel_id) {
582 BtreeEntry::Occupied(mut entry) => {
583 //TODO: because asking the blockchain if short_channel_id is valid is only optional
584 //in the blockchain API, we need to handle it smartly here, though it's unclear
587 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
588 // only sometimes returns results. In any case remove the previous entry. Note
589 // that the spec expects us to "blacklist" the node_ids involved, but we can't
591 // a) we don't *require* a UTXO provider that always returns results.
592 // b) we don't track UTXOs of channels we know about and remove them if they
594 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
595 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
596 *entry.get_mut() = chan_info;
598 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
601 BtreeEntry::Vacant(entry) => {
602 entry.insert(chan_info);
606 macro_rules! add_channel_to_node {
607 ( $node_id: expr ) => {
608 match self.nodes.entry($node_id) {
609 BtreeEntry::Occupied(node_entry) => {
610 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
612 BtreeEntry::Vacant(node_entry) => {
613 node_entry.insert(NodeInfo {
614 channels: vec!(msg.contents.short_channel_id),
615 lowest_inbound_channel_fees: None,
616 announcement_info: None,
623 add_channel_to_node!(msg.contents.node_id_1);
624 add_channel_to_node!(msg.contents.node_id_2);
629 /// Close a channel if a corresponding HTLC fail was sent.
630 /// If permanent, removes a channel from the local storage.
631 /// May cause the removal of nodes too, if this was their last channel.
632 /// If not permanent, makes channels unavailable for routing.
633 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
635 if let Some(chan) = self.channels.remove(short_channel_id) {
636 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
639 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
640 if let Some(one_to_two) = chan.one_to_two.as_mut() {
641 one_to_two.enabled = false;
643 if let Some(two_to_one) = chan.two_to_one.as_mut() {
644 two_to_one.enabled = false;
650 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
652 // TODO: Wholly remove the node
654 // TODO: downgrade the node
658 /// For an already known (from announcement) channel, update info regarding one of the directions of a channel.
659 /// Announcement signatures are checked here only if Secp256k1 object is provided.
660 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
662 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
663 let chan_was_enabled;
665 match self.channels.get_mut(&msg.contents.short_channel_id) {
666 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
668 macro_rules! maybe_update_channel_info {
669 ( $target: expr, $src_node: expr) => {
670 if let Some(existing_chan_info) = $target.as_ref() {
671 if existing_chan_info.last_update >= msg.contents.timestamp {
672 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
674 chan_was_enabled = existing_chan_info.enabled;
676 chan_was_enabled = false;
679 let last_update_message = if msg.contents.excess_data.is_empty() {
685 let updated_channel_dir_info = DirectionalChannelInfo {
686 enabled: chan_enabled,
687 last_update: msg.contents.timestamp,
688 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
689 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
691 base_msat: msg.contents.fee_base_msat,
692 proportional_millionths: msg.contents.fee_proportional_millionths,
696 $target = Some(updated_channel_dir_info);
700 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
701 if msg.contents.flags & 1 == 1 {
702 dest_node_id = channel.node_one.clone();
703 if let Some(sig_verifier) = secp_ctx {
704 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
706 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
708 dest_node_id = channel.node_two.clone();
709 if let Some(sig_verifier) = secp_ctx {
710 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
712 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
718 let node = self.nodes.get_mut(&dest_node_id).unwrap();
719 let mut base_msat = msg.contents.fee_base_msat;
720 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
721 if let Some(fees) = node.lowest_inbound_channel_fees {
722 base_msat = cmp::min(base_msat, fees.base_msat);
723 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
725 node.lowest_inbound_channel_fees = Some(RoutingFees {
727 proportional_millionths
729 } else if chan_was_enabled {
730 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
731 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
734 let node = self.nodes.get(&dest_node_id).unwrap();
736 for chan_id in node.channels.iter() {
737 let chan = self.channels.get(chan_id).unwrap();
738 // Since direction was enabled, the channel indeed had directional info
740 if chan.node_one == dest_node_id {
741 chan_info = chan.two_to_one.as_ref().unwrap();
743 chan_info = chan.one_to_two.as_ref().unwrap();
745 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan_info.fees.base_msat);
746 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan_info.fees.proportional_millionths);
750 //TODO: satisfy the borrow-checker without a double-map-lookup :(
751 let mut_node = self.nodes.get_mut(&dest_node_id).unwrap();
752 if mut_node.channels.len() > 0 {
753 mut_node.lowest_inbound_channel_fees = Some(RoutingFees {
754 base_msat: lowest_inbound_channel_fee_base_msat,
755 proportional_millionths: lowest_inbound_channel_fee_proportional_millionths
760 Ok(msg.contents.excess_data.is_empty())
763 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
764 macro_rules! remove_from_node {
765 ($node_id: expr) => {
766 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
767 entry.get_mut().channels.retain(|chan_id| {
768 short_channel_id != *chan_id
770 if entry.get().channels.is_empty() {
771 entry.remove_entry();
774 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
779 remove_from_node!(chan.node_one);
780 remove_from_node!(chan.node_two);
786 use chain::chaininterface;
787 use ln::features::{ChannelFeatures, NodeFeatures};
788 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
789 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
790 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
791 use util::test_utils;
792 use util::logger::Logger;
793 use util::ser::{Readable, Writeable};
795 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
796 use bitcoin::hashes::Hash;
797 use bitcoin::network::constants::Network;
798 use bitcoin::blockdata::constants::genesis_block;
799 use bitcoin::blockdata::script::Builder;
800 use bitcoin::blockdata::opcodes;
801 use bitcoin::util::hash::BitcoinHash;
805 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
806 use bitcoin::secp256k1::{All, Secp256k1};
810 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
811 let secp_ctx = Secp256k1::new();
812 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
813 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
814 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
815 (secp_ctx, net_graph_msg_handler)
819 fn request_full_sync_finite_times() {
820 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
821 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
823 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
824 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
825 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
826 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
827 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
828 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
832 fn handling_node_announcements() {
833 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
835 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
836 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
837 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
838 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
839 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
840 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
841 let zero_hash = Sha256dHash::hash(&[0; 32]);
842 let first_announcement_time = 500;
844 let mut unsigned_announcement = UnsignedNodeAnnouncement {
845 features: NodeFeatures::known(),
846 timestamp: first_announcement_time,
850 addresses: Vec::new(),
851 excess_address_data: Vec::new(),
852 excess_data: Vec::new(),
854 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
855 let valid_announcement = NodeAnnouncement {
856 signature: secp_ctx.sign(&msghash, node_1_privkey),
857 contents: unsigned_announcement.clone()
860 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
862 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
866 // Announce a channel to add a corresponding node.
867 let unsigned_announcement = UnsignedChannelAnnouncement {
868 features: ChannelFeatures::known(),
869 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
873 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
874 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
875 excess_data: Vec::new(),
878 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
879 let valid_announcement = ChannelAnnouncement {
880 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
881 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
882 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
883 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
884 contents: unsigned_announcement.clone(),
886 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
887 Ok(res) => assert!(res),
892 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
893 Ok(res) => assert!(res),
897 let fake_msghash = hash_to_message!(&zero_hash);
898 match net_graph_msg_handler.handle_node_announcement(
900 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
901 contents: unsigned_announcement.clone()
904 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
907 unsigned_announcement.timestamp += 1000;
908 unsigned_announcement.excess_data.push(1);
909 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
910 let announcement_with_data = NodeAnnouncement {
911 signature: secp_ctx.sign(&msghash, node_1_privkey),
912 contents: unsigned_announcement.clone()
914 // Return false because contains excess data.
915 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
916 Ok(res) => assert!(!res),
919 unsigned_announcement.excess_data = Vec::new();
921 // Even though previous announcement was not relayed further, we still accepted it,
922 // so we now won't accept announcements before the previous one.
923 unsigned_announcement.timestamp -= 10;
924 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
925 let outdated_announcement = NodeAnnouncement {
926 signature: secp_ctx.sign(&msghash, node_1_privkey),
927 contents: unsigned_announcement.clone()
929 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
931 Err(e) => assert_eq!(e.err, "Update older than last processed update")
936 fn handling_channel_announcements() {
937 let secp_ctx = Secp256k1::new();
938 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
939 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
940 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
943 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
944 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
945 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
946 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
947 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
948 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
950 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
951 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
952 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
953 .push_opcode(opcodes::all::OP_PUSHNUM_2)
954 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
957 let mut unsigned_announcement = UnsignedChannelAnnouncement {
958 features: ChannelFeatures::known(),
959 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
963 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
964 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
965 excess_data: Vec::new(),
968 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
969 let valid_announcement = ChannelAnnouncement {
970 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
971 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
972 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
973 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
974 contents: unsigned_announcement.clone(),
977 // Test if the UTXO lookups were not supported
978 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
980 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
981 Ok(res) => assert!(res),
986 let network = net_graph_msg_handler.network_graph.read().unwrap();
987 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
994 // If we receive announcement for the same channel (with UTXO lookups disabled),
995 // drop new one on the floor, since we can't see any changes.
996 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
998 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1002 // Test if an associated transaction were not on-chain (or not confirmed).
1003 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1004 unsigned_announcement.short_channel_id += 1;
1006 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1007 let valid_announcement = ChannelAnnouncement {
1008 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1009 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1010 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1011 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1012 contents: unsigned_announcement.clone(),
1015 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1017 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1021 // Now test if the transaction is found in the UTXO set and the script is correct.
1022 unsigned_announcement.short_channel_id += 1;
1023 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1025 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1026 let valid_announcement = ChannelAnnouncement {
1027 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1028 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1029 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1030 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1031 contents: unsigned_announcement.clone(),
1033 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1034 Ok(res) => assert!(res),
1039 let network = net_graph_msg_handler.network_graph.read().unwrap();
1040 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1046 // If we receive announcement for the same channel (but TX is not confirmed),
1047 // drop new one on the floor, since we can't see any changes.
1048 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1049 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1051 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1054 // But if it is confirmed, replace the channel
1055 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1056 unsigned_announcement.features = ChannelFeatures::empty();
1057 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1058 let valid_announcement = ChannelAnnouncement {
1059 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1060 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1061 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1062 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1063 contents: unsigned_announcement.clone(),
1065 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1066 Ok(res) => assert!(res),
1070 let network = net_graph_msg_handler.network_graph.read().unwrap();
1071 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1072 Some(channel_entry) => {
1073 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1079 // Don't relay valid channels with excess data
1080 unsigned_announcement.short_channel_id += 1;
1081 unsigned_announcement.excess_data.push(1);
1082 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1083 let valid_announcement = ChannelAnnouncement {
1084 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1085 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1086 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1087 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1088 contents: unsigned_announcement.clone(),
1090 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1091 Ok(res) => assert!(!res),
1095 unsigned_announcement.excess_data = Vec::new();
1096 let invalid_sig_announcement = ChannelAnnouncement {
1097 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1098 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1099 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1100 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1101 contents: unsigned_announcement.clone(),
1103 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1105 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1108 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1109 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1110 let channel_to_itself_announcement = ChannelAnnouncement {
1111 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1112 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1113 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1114 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1115 contents: unsigned_announcement.clone(),
1117 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1119 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1124 fn handling_channel_update() {
1125 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1126 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1127 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1128 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1129 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1130 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1131 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1133 let zero_hash = Sha256dHash::hash(&[0; 32]);
1134 let short_channel_id = 0;
1135 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1137 // Announce a channel we will update
1138 let unsigned_announcement = UnsignedChannelAnnouncement {
1139 features: ChannelFeatures::empty(),
1144 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1145 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1146 excess_data: Vec::new(),
1149 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1150 let valid_channel_announcement = ChannelAnnouncement {
1151 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1152 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1153 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1154 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1155 contents: unsigned_announcement.clone(),
1157 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1164 let mut unsigned_channel_update = UnsignedChannelUpdate {
1169 cltv_expiry_delta: 144,
1170 htlc_minimum_msat: 1000000,
1171 fee_base_msat: 10000,
1172 fee_proportional_millionths: 20,
1173 excess_data: Vec::new()
1175 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1176 let valid_channel_update = ChannelUpdate {
1177 signature: secp_ctx.sign(&msghash, node_1_privkey),
1178 contents: unsigned_channel_update.clone()
1181 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1182 Ok(res) => assert!(res),
1187 let network = net_graph_msg_handler.network_graph.read().unwrap();
1188 match network.get_channels().get(&short_channel_id) {
1190 Some(channel_info) => {
1191 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1192 assert!(channel_info.two_to_one.is_none());
1197 unsigned_channel_update.timestamp += 100;
1198 unsigned_channel_update.excess_data.push(1);
1199 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1200 let valid_channel_update = ChannelUpdate {
1201 signature: secp_ctx.sign(&msghash, node_1_privkey),
1202 contents: unsigned_channel_update.clone()
1204 // Return false because contains excess data
1205 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1206 Ok(res) => assert!(!res),
1210 unsigned_channel_update.short_channel_id += 1;
1211 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1212 let valid_channel_update = ChannelUpdate {
1213 signature: secp_ctx.sign(&msghash, node_1_privkey),
1214 contents: unsigned_channel_update.clone()
1217 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1219 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1221 unsigned_channel_update.short_channel_id = short_channel_id;
1224 // Even though previous update was not relayed further, we still accepted it,
1225 // so we now won't accept update before the previous one.
1226 unsigned_channel_update.timestamp -= 10;
1227 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1228 let valid_channel_update = ChannelUpdate {
1229 signature: secp_ctx.sign(&msghash, node_1_privkey),
1230 contents: unsigned_channel_update.clone()
1233 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1235 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1237 unsigned_channel_update.timestamp += 500;
1239 let fake_msghash = hash_to_message!(&zero_hash);
1240 let invalid_sig_channel_update = ChannelUpdate {
1241 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1242 contents: unsigned_channel_update.clone()
1245 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1247 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1253 fn handling_htlc_fail_channel_update() {
1254 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1255 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1256 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1257 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1258 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1259 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1260 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1262 let short_channel_id = 0;
1263 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1266 // There is no nodes in the table at the beginning.
1267 let network = net_graph_msg_handler.network_graph.read().unwrap();
1268 assert_eq!(network.get_nodes().len(), 0);
1272 // Announce a channel we will update
1273 let unsigned_announcement = UnsignedChannelAnnouncement {
1274 features: ChannelFeatures::empty(),
1279 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1280 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1281 excess_data: Vec::new(),
1284 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1285 let valid_channel_announcement = ChannelAnnouncement {
1286 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1287 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1288 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1289 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1290 contents: unsigned_announcement.clone(),
1292 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1297 let unsigned_channel_update = UnsignedChannelUpdate {
1302 cltv_expiry_delta: 144,
1303 htlc_minimum_msat: 1000000,
1304 fee_base_msat: 10000,
1305 fee_proportional_millionths: 20,
1306 excess_data: Vec::new()
1308 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1309 let valid_channel_update = ChannelUpdate {
1310 signature: secp_ctx.sign(&msghash, node_1_privkey),
1311 contents: unsigned_channel_update.clone()
1314 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1315 Ok(res) => assert!(res),
1320 // Non-permanent closing just disables a channel
1322 let network = net_graph_msg_handler.network_graph.read().unwrap();
1323 match network.get_channels().get(&short_channel_id) {
1325 Some(channel_info) => {
1326 assert!(channel_info.one_to_two.is_some());
1331 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1336 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1338 // Non-permanent closing just disables a channel
1340 let network = net_graph_msg_handler.network_graph.read().unwrap();
1341 match network.get_channels().get(&short_channel_id) {
1343 Some(channel_info) => {
1344 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1349 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1354 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1356 // Permanent closing deletes a channel
1358 let network = net_graph_msg_handler.network_graph.read().unwrap();
1359 assert_eq!(network.get_channels().len(), 0);
1360 // Nodes are also deleted because there are no associated channels anymore
1361 assert_eq!(network.get_nodes().len(), 0);
1363 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1367 fn getting_next_channel_announcements() {
1368 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1369 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1370 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1371 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1372 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1373 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1374 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1376 let short_channel_id = 1;
1377 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1379 // Channels were not announced yet.
1380 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1381 assert_eq!(channels_with_announcements.len(), 0);
1384 // Announce a channel we will update
1385 let unsigned_announcement = UnsignedChannelAnnouncement {
1386 features: ChannelFeatures::empty(),
1391 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1392 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1393 excess_data: Vec::new(),
1396 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1397 let valid_channel_announcement = ChannelAnnouncement {
1398 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1399 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1400 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1401 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1402 contents: unsigned_announcement.clone(),
1404 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1410 // Contains initial channel announcement now.
1411 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1412 assert_eq!(channels_with_announcements.len(), 1);
1413 if let Some(channel_announcements) = channels_with_announcements.first() {
1414 let &(_, ref update_1, ref update_2) = channel_announcements;
1415 assert_eq!(update_1, &None);
1416 assert_eq!(update_2, &None);
1423 // Valid channel update
1424 let unsigned_channel_update = UnsignedChannelUpdate {
1429 cltv_expiry_delta: 144,
1430 htlc_minimum_msat: 1000000,
1431 fee_base_msat: 10000,
1432 fee_proportional_millionths: 20,
1433 excess_data: Vec::new()
1435 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1436 let valid_channel_update = ChannelUpdate {
1437 signature: secp_ctx.sign(&msghash, node_1_privkey),
1438 contents: unsigned_channel_update.clone()
1440 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1446 // Now contains an initial announcement and an update.
1447 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1448 assert_eq!(channels_with_announcements.len(), 1);
1449 if let Some(channel_announcements) = channels_with_announcements.first() {
1450 let &(_, ref update_1, ref update_2) = channel_announcements;
1451 assert_ne!(update_1, &None);
1452 assert_eq!(update_2, &None);
1459 // Channel update with excess data.
1460 let unsigned_channel_update = UnsignedChannelUpdate {
1465 cltv_expiry_delta: 144,
1466 htlc_minimum_msat: 1000000,
1467 fee_base_msat: 10000,
1468 fee_proportional_millionths: 20,
1469 excess_data: [1; 3].to_vec()
1471 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1472 let valid_channel_update = ChannelUpdate {
1473 signature: secp_ctx.sign(&msghash, node_1_privkey),
1474 contents: unsigned_channel_update.clone()
1476 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1482 // Test that announcements with excess data won't be returned
1483 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1484 assert_eq!(channels_with_announcements.len(), 1);
1485 if let Some(channel_announcements) = channels_with_announcements.first() {
1486 let &(_, ref update_1, ref update_2) = channel_announcements;
1487 assert_eq!(update_1, &None);
1488 assert_eq!(update_2, &None);
1493 // Further starting point have no channels after it
1494 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1495 assert_eq!(channels_with_announcements.len(), 0);
1499 fn getting_next_node_announcements() {
1500 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1501 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1502 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1503 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1504 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1505 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1506 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1508 let short_channel_id = 1;
1509 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1512 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1513 assert_eq!(next_announcements.len(), 0);
1516 // Announce a channel to add 2 nodes
1517 let unsigned_announcement = UnsignedChannelAnnouncement {
1518 features: ChannelFeatures::empty(),
1523 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1524 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1525 excess_data: Vec::new(),
1528 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1529 let valid_channel_announcement = ChannelAnnouncement {
1530 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1531 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1532 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1533 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1534 contents: unsigned_announcement.clone(),
1536 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1543 // Nodes were never announced
1544 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1545 assert_eq!(next_announcements.len(), 0);
1548 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1549 features: NodeFeatures::known(),
1554 addresses: Vec::new(),
1555 excess_address_data: Vec::new(),
1556 excess_data: Vec::new(),
1558 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1559 let valid_announcement = NodeAnnouncement {
1560 signature: secp_ctx.sign(&msghash, node_1_privkey),
1561 contents: unsigned_announcement.clone()
1563 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1568 unsigned_announcement.node_id = node_id_2;
1569 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1570 let valid_announcement = NodeAnnouncement {
1571 signature: secp_ctx.sign(&msghash, node_2_privkey),
1572 contents: unsigned_announcement.clone()
1575 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1581 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1582 assert_eq!(next_announcements.len(), 2);
1584 // Skip the first node.
1585 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1586 assert_eq!(next_announcements.len(), 1);
1589 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1590 let unsigned_announcement = UnsignedNodeAnnouncement {
1591 features: NodeFeatures::known(),
1596 addresses: Vec::new(),
1597 excess_address_data: Vec::new(),
1598 excess_data: [1; 3].to_vec(),
1600 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1601 let valid_announcement = NodeAnnouncement {
1602 signature: secp_ctx.sign(&msghash, node_2_privkey),
1603 contents: unsigned_announcement.clone()
1605 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1606 Ok(res) => assert!(!res),
1611 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1612 assert_eq!(next_announcements.len(), 0);
1616 fn network_graph_serialization() {
1617 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1619 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1620 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1621 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1622 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1624 // Announce a channel to add a corresponding node.
1625 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1626 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1627 let unsigned_announcement = UnsignedChannelAnnouncement {
1628 features: ChannelFeatures::known(),
1629 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1630 short_channel_id: 0,
1633 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1634 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1635 excess_data: Vec::new(),
1638 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1639 let valid_announcement = ChannelAnnouncement {
1640 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1641 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1642 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1643 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1644 contents: unsigned_announcement.clone(),
1646 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1647 Ok(res) => assert!(res),
1652 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1653 let unsigned_announcement = UnsignedNodeAnnouncement {
1654 features: NodeFeatures::known(),
1659 addresses: Vec::new(),
1660 excess_address_data: Vec::new(),
1661 excess_data: Vec::new(),
1663 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1664 let valid_announcement = NodeAnnouncement {
1665 signature: secp_ctx.sign(&msghash, node_1_privkey),
1666 contents: unsigned_announcement.clone()
1669 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1674 let network = net_graph_msg_handler.network_graph.write().unwrap();
1675 let mut w = test_utils::TestVecWriter(Vec::new());
1676 assert!(!network.get_nodes().is_empty());
1677 assert!(!network.get_channels().is_empty());
1678 network.write(&mut w).unwrap();
1679 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);