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 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 /// assuming fresh Network Graph
39 pub fn new(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Self {
41 secp_ctx: Secp256k1::verification_only(),
42 network_graph: RwLock::new(NetworkGraph {
43 channels: BTreeMap::new(),
44 nodes: BTreeMap::new(),
46 full_syncs_requested: AtomicUsize::new(0),
48 logger: logger.clone(),
52 /// Creates a new tracker of the actual state of the network of channels and nodes,
53 /// assuming an existing Network Graph.
54 pub fn from_net_graph(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>, network_graph: RwLock<NetworkGraph>) -> Self {
56 secp_ctx: Secp256k1::verification_only(),
57 network_graph: network_graph,
58 full_syncs_requested: AtomicUsize::new(0),
60 logger: logger.clone(),
64 /// Get network addresses by node id
65 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
66 let network = self.network_graph.read().unwrap();
67 if let Some(node) = network.get_nodes().get(pubkey) {
68 if let Some(node_info) = node.announcement_info.as_ref() {
69 return Some(node_info.addresses.clone())
75 /// Dumps the entire network view of this NetGraphMsgHandler to the logger provided in the constructor at
77 pub fn trace_state(&self) {
78 log_trace!(self, "{}", self.network_graph.read().unwrap());
83 macro_rules! secp_verify_sig {
84 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
85 match $secp_ctx.verify($msg, $sig, $pubkey) {
87 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
92 impl RoutingMessageHandler for NetGraphMsgHandler {
93 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
94 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
97 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
98 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
99 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
102 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
103 Ok((script_pubkey, _value)) => {
104 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
105 .push_slice(&msg.contents.bitcoin_key_1.serialize())
106 .push_slice(&msg.contents.bitcoin_key_2.serialize())
107 .push_opcode(opcodes::all::OP_PUSHNUM_2)
108 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
109 if script_pubkey != expected_script {
110 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
112 //TODO: Check if value is worth storing, use it to inform routing, and compare it
113 //to the new HTLC max field in channel_update
116 Err(ChainError::NotSupported) => {
117 // Tentatively accept, potentially exposing us to DoS attacks
120 Err(ChainError::NotWatched) => {
121 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
123 Err(ChainError::UnknownTx) => {
124 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
127 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
128 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
132 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
134 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
135 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
137 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
138 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
140 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
141 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
146 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
147 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
150 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
151 let network_graph = self.network_graph.read().unwrap();
152 let mut result = Vec::with_capacity(batch_amount as usize);
153 let mut iter = network_graph.get_channels().range(starting_point..);
154 while result.len() < batch_amount as usize {
155 if let Some((_, ref chan)) = iter.next() {
156 if chan.announcement_message.is_some() {
157 let chan_announcement = chan.announcement_message.clone().unwrap();
158 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
159 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
160 if let Some(one_to_two) = chan.one_to_two.as_ref() {
161 one_to_two_announcement = one_to_two.last_update_message.clone();
163 if let Some(two_to_one) = chan.two_to_one.as_ref() {
164 two_to_one_announcement = two_to_one.last_update_message.clone();
166 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
168 // TODO: We may end up sending un-announced channel_updates if we are sending
169 // initial sync data while receiving announce/updates for this channel.
178 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
179 let network_graph = self.network_graph.read().unwrap();
180 let mut result = Vec::with_capacity(batch_amount as usize);
181 let mut iter = if let Some(pubkey) = starting_point {
182 let mut iter = network_graph.get_nodes().range((*pubkey)..);
186 network_graph.get_nodes().range(..)
188 while result.len() < batch_amount as usize {
189 if let Some((_, ref node)) = iter.next() {
190 if let Some(node_info) = node.announcement_info.as_ref() {
191 if node_info.announcement_message.is_some() {
192 result.push(node_info.announcement_message.clone().unwrap());
202 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
203 //TODO: Determine whether to request a full sync based on the network map.
204 const FULL_SYNCS_TO_REQUEST: usize = 5;
205 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
206 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
214 #[derive(PartialEq, Debug)]
215 /// Details regarding one direction of a channel
216 pub struct DirectionalChannelInfo {
217 /// When the last update to the channel direction was issued
218 pub last_update: u32,
219 /// Whether the channel can be currently used for payments
221 /// The difference in CLTV values between the source and the destination node of the channel
222 pub cltv_expiry_delta: u16,
223 /// The minimum value, which must be relayed to the next hop via the channel
224 pub htlc_minimum_msat: u64,
225 /// Fees charged when the channel is used for routing
226 pub fees: RoutingFees,
227 /// Most recent update for the channel received from the network
228 pub last_update_message: Option<msgs::ChannelUpdate>,
231 impl std::fmt::Display for DirectionalChannelInfo {
232 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
233 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)?;
238 impl_writeable!(DirectionalChannelInfo, 0, {
248 /// Details regarding a channel (both directions)
249 pub struct ChannelInfo {
250 /// Protocol features of a channel communicated during its announcement
251 pub features: ChannelFeatures,
252 /// Source node of the first direction of a channel
253 pub node_one: PublicKey,
254 /// Details about the first direction of a channel
255 pub one_to_two: Option<DirectionalChannelInfo>,
256 /// Source node of the second direction of a channel
257 pub node_two: PublicKey,
258 /// Details about the second direction of a channel
259 pub two_to_one: Option<DirectionalChannelInfo>,
260 /// An initial announcement of the channel
261 //this is cached here so we can send out it later if required by initial routing sync
262 //keep an eye on this to see if the extra memory is a problem
263 pub announcement_message: Option<msgs::ChannelAnnouncement>,
266 impl std::fmt::Display for ChannelInfo {
267 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
268 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
269 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
274 impl_writeable!(ChannelInfo, 0, {
284 /// Fees for routing via a given channel or a node
285 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
286 pub struct RoutingFees {
289 /// Liquidity-based routing fee
290 pub proportional_millionths: u32,
293 impl Readable for RoutingFees{
294 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
295 let base_msat: u32 = Readable::read(reader)?;
296 let proportional_millionths: u32 = Readable::read(reader)?;
299 proportional_millionths,
304 impl Writeable for RoutingFees {
305 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
306 self.base_msat.write(writer)?;
307 self.proportional_millionths.write(writer)?;
312 #[derive(PartialEq, Debug)]
313 /// Information received in the latest node_announcement from this node.
314 pub struct NodeAnnouncementInfo {
315 /// Protocol features the node announced support for
316 pub features: NodeFeatures,
317 /// When the last known update to the node state was issued
318 pub last_update: u32,
319 /// Color assigned to the node
321 /// Moniker assigned to the node
323 /// Internet-level addresses via which one can connect to the node
324 pub addresses: Vec<NetAddress>,
325 /// An initial announcement of the node
326 // this is cached here so we can send out it later if required by initial routing sync
327 // keep an eye on this to see if the extra memory is a problem
328 pub announcement_message: Option<msgs::NodeAnnouncement>
331 impl Writeable for NodeAnnouncementInfo {
332 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
333 self.features.write(writer)?;
334 self.last_update.write(writer)?;
335 self.rgb.write(writer)?;
336 self.alias.write(writer)?;
337 (self.addresses.len() as u64).write(writer)?;
338 for ref addr in &self.addresses {
341 self.announcement_message.write(writer)?;
346 impl Readable for NodeAnnouncementInfo {
347 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
348 let features = Readable::read(reader)?;
349 let last_update = Readable::read(reader)?;
350 let rgb = Readable::read(reader)?;
351 let alias = Readable::read(reader)?;
352 let addresses_count: u64 = Readable::read(reader)?;
353 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
354 for _ in 0..addresses_count {
355 match Readable::read(reader) {
356 Ok(Ok(addr)) => { addresses.push(addr); },
357 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
358 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
362 let announcement_message = Readable::read(reader)?;
363 Ok(NodeAnnouncementInfo {
375 /// Details regarding a node in the network
376 pub struct NodeInfo {
377 /// All valid channels a node has announced
378 pub channels: Vec<u64>,
379 /// Lowest fees enabling routing via any of the known channels to a node
380 pub lowest_inbound_channel_fees: Option<RoutingFees>,
381 /// More information about a node from node_announcement
382 /// Optional because we may have a NodeInfo entry before having received the announcement
383 pub announcement_info: Option<NodeAnnouncementInfo>
386 impl std::fmt::Display for NodeInfo {
387 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
388 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
389 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
394 impl Writeable for NodeInfo {
395 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
396 (self.channels.len() as u64).write(writer)?;
397 for ref chan in self.channels.iter() {
400 self.lowest_inbound_channel_fees.write(writer)?;
401 self.announcement_info.write(writer)?;
406 const MAX_ALLOC_SIZE: u64 = 64*1024;
408 impl Readable for NodeInfo {
409 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
410 let channels_count: u64 = Readable::read(reader)?;
411 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
412 for _ in 0..channels_count {
413 channels.push(Readable::read(reader)?);
415 let lowest_inbound_channel_fees = Readable::read(reader)?;
416 let announcement_info = Readable::read(reader)?;
419 lowest_inbound_channel_fees,
425 /// Represents the network as nodes and channels between them
427 pub struct NetworkGraph {
428 channels: BTreeMap<u64, ChannelInfo>,
429 nodes: BTreeMap<PublicKey, NodeInfo>,
432 impl Writeable for NetworkGraph {
433 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
434 (self.channels.len() as u64).write(writer)?;
435 for (ref chan_id, ref chan_info) in self.channels.iter() {
436 (*chan_id).write(writer)?;
437 chan_info.write(writer)?;
439 (self.nodes.len() as u64).write(writer)?;
440 for (ref node_id, ref node_info) in self.nodes.iter() {
441 node_id.write(writer)?;
442 node_info.write(writer)?;
448 impl Readable for NetworkGraph {
449 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
450 let channels_count: u64 = Readable::read(reader)?;
451 let mut channels = BTreeMap::new();
452 for _ in 0..channels_count {
453 let chan_id: u64 = Readable::read(reader)?;
454 let chan_info = Readable::read(reader)?;
455 channels.insert(chan_id, chan_info);
457 let nodes_count: u64 = Readable::read(reader)?;
458 let mut nodes = BTreeMap::new();
459 for _ in 0..nodes_count {
460 let node_id = Readable::read(reader)?;
461 let node_info = Readable::read(reader)?;
462 nodes.insert(node_id, node_info);
471 impl std::fmt::Display for NetworkGraph {
472 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
473 write!(f, "Network map\n[Channels]\n")?;
474 for (key, val) in self.channels.iter() {
475 write!(f, " {}: {}\n", key, val)?;
477 write!(f, "[Nodes]\n")?;
478 for (key, val) in self.nodes.iter() {
479 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
486 /// Returns all known valid channels
487 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
488 /// Returns all known nodes
489 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
491 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
492 /// Announcement signatures are checked here only if Secp256k1 object is provided.
493 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
494 if let Some(sig_verifier) = secp_ctx {
495 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
496 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
499 match self.nodes.get_mut(&msg.contents.node_id) {
500 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
502 if let Some(node_info) = node.announcement_info.as_ref() {
503 if node_info.last_update >= msg.contents.timestamp {
504 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
508 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
509 node.announcement_info = Some(NodeAnnouncementInfo {
510 features: msg.contents.features.clone(),
511 last_update: msg.contents.timestamp,
512 rgb: msg.contents.rgb,
513 alias: msg.contents.alias,
514 addresses: msg.contents.addresses.clone(),
515 announcement_message: if should_relay { Some(msg.clone()) } else { None },
523 /// For a new or already known (from previous announcement) channel, store or update channel info,
524 /// after making sure it corresponds to a real transaction on-chain.
525 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
526 /// Announcement signatures are checked here only if Secp256k1 object is provided.
527 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, 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.node_signature_1, &msg.contents.node_id_1);
531 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
532 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
533 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
536 let should_relay = msg.contents.excess_data.is_empty();
538 let chan_info = ChannelInfo {
539 features: msg.contents.features.clone(),
540 node_one: msg.contents.node_id_1.clone(),
542 node_two: msg.contents.node_id_2.clone(),
544 announcement_message: if should_relay { Some(msg.clone()) } else { None },
547 match self.channels.entry(msg.contents.short_channel_id) {
548 BtreeEntry::Occupied(mut entry) => {
549 //TODO: because asking the blockchain if short_channel_id is valid is only optional
550 //in the blockchain API, we need to handle it smartly here, though it's unclear
553 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
554 // only sometimes returns results. In any case remove the previous entry. Note
555 // that the spec expects us to "blacklist" the node_ids involved, but we can't
557 // a) we don't *require* a UTXO provider that always returns results.
558 // b) we don't track UTXOs of channels we know about and remove them if they
560 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
561 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
562 *entry.get_mut() = chan_info;
564 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
567 BtreeEntry::Vacant(entry) => {
568 entry.insert(chan_info);
572 macro_rules! add_channel_to_node {
573 ( $node_id: expr ) => {
574 match self.nodes.entry($node_id) {
575 BtreeEntry::Occupied(node_entry) => {
576 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
578 BtreeEntry::Vacant(node_entry) => {
579 node_entry.insert(NodeInfo {
580 channels: vec!(msg.contents.short_channel_id),
581 lowest_inbound_channel_fees: None,
582 announcement_info: None,
589 add_channel_to_node!(msg.contents.node_id_1);
590 add_channel_to_node!(msg.contents.node_id_2);
595 /// Close a channel if a corresponding HTLC fail was sent.
596 /// If permanent, removes a channel from the local storage.
597 /// May cause the removal of nodes too, if this was their last channel.
598 /// If not permanent, makes channels unavailable for routing.
599 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
601 if let Some(chan) = self.channels.remove(short_channel_id) {
602 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
605 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
606 if let Some(one_to_two) = chan.one_to_two.as_mut() {
607 one_to_two.enabled = false;
609 if let Some(two_to_one) = chan.two_to_one.as_mut() {
610 two_to_one.enabled = false;
616 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
618 // TODO: Wholly remove the node
620 // TODO: downgrade the node
624 /// For an already known (from announcement) channel, update info regarding one of the directions of a channel.
625 /// Announcement signatures are checked here only if Secp256k1 object is provided.
626 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
628 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
629 let chan_was_enabled;
631 match self.channels.get_mut(&msg.contents.short_channel_id) {
632 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
634 macro_rules! maybe_update_channel_info {
635 ( $target: expr, $src_node: expr) => {
636 if let Some(existing_chan_info) = $target.as_ref() {
637 if existing_chan_info.last_update >= msg.contents.timestamp {
638 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
640 chan_was_enabled = existing_chan_info.enabled;
642 chan_was_enabled = false;
645 let last_update_message = if msg.contents.excess_data.is_empty() {
651 let updated_channel_dir_info = DirectionalChannelInfo {
652 enabled: chan_enabled,
653 last_update: msg.contents.timestamp,
654 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
655 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
657 base_msat: msg.contents.fee_base_msat,
658 proportional_millionths: msg.contents.fee_proportional_millionths,
662 $target = Some(updated_channel_dir_info);
666 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
667 if msg.contents.flags & 1 == 1 {
668 dest_node_id = channel.node_one.clone();
669 if let Some(sig_verifier) = secp_ctx {
670 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
672 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
674 dest_node_id = channel.node_two.clone();
675 if let Some(sig_verifier) = secp_ctx {
676 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
678 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
684 let node = self.nodes.get_mut(&dest_node_id).unwrap();
685 let mut base_msat = msg.contents.fee_base_msat;
686 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
687 if let Some(fees) = node.lowest_inbound_channel_fees {
688 base_msat = cmp::min(base_msat, fees.base_msat);
689 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
691 node.lowest_inbound_channel_fees = Some(RoutingFees {
693 proportional_millionths
695 } else if chan_was_enabled {
696 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
697 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
700 let node = self.nodes.get(&dest_node_id).unwrap();
702 for chan_id in node.channels.iter() {
703 let chan = self.channels.get(chan_id).unwrap();
704 // Since direction was enabled, the channel indeed had directional info
706 if chan.node_one == dest_node_id {
707 chan_info = chan.two_to_one.as_ref().unwrap();
709 chan_info = chan.one_to_two.as_ref().unwrap();
711 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan_info.fees.base_msat);
712 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan_info.fees.proportional_millionths);
716 //TODO: satisfy the borrow-checker without a double-map-lookup :(
717 let mut_node = self.nodes.get_mut(&dest_node_id).unwrap();
718 if mut_node.channels.len() > 0 {
719 mut_node.lowest_inbound_channel_fees = Some(RoutingFees {
720 base_msat: lowest_inbound_channel_fee_base_msat,
721 proportional_millionths: lowest_inbound_channel_fee_proportional_millionths
726 Ok(msg.contents.excess_data.is_empty())
729 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
730 macro_rules! remove_from_node {
731 ($node_id: expr) => {
732 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
733 entry.get_mut().channels.retain(|chan_id| {
734 short_channel_id != *chan_id
736 if entry.get().channels.is_empty() {
737 entry.remove_entry();
740 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
745 remove_from_node!(chan.node_one);
746 remove_from_node!(chan.node_two);
752 use chain::chaininterface;
753 use ln::features::{ChannelFeatures, NodeFeatures};
754 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
755 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
756 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
757 use util::test_utils;
758 use util::logger::Logger;
759 use util::ser::{Readable, Writeable};
761 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
762 use bitcoin::hashes::Hash;
763 use bitcoin::network::constants::Network;
764 use bitcoin::blockdata::constants::genesis_block;
765 use bitcoin::blockdata::script::Builder;
766 use bitcoin::blockdata::opcodes;
767 use bitcoin::util::hash::BitcoinHash;
771 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
772 use bitcoin::secp256k1::{All, Secp256k1};
776 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
777 let secp_ctx = Secp256k1::new();
778 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
779 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
780 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
781 (secp_ctx, net_graph_msg_handler)
785 fn request_full_sync_finite_times() {
786 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
787 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
789 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
790 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
791 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
792 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
793 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
794 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
798 fn handling_node_announcements() {
799 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
801 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
802 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
803 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
804 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
805 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
806 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
807 let zero_hash = Sha256dHash::hash(&[0; 32]);
808 let first_announcement_time = 500;
810 let mut unsigned_announcement = UnsignedNodeAnnouncement {
811 features: NodeFeatures::known(),
812 timestamp: first_announcement_time,
816 addresses: Vec::new(),
817 excess_address_data: Vec::new(),
818 excess_data: Vec::new(),
820 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
821 let valid_announcement = NodeAnnouncement {
822 signature: secp_ctx.sign(&msghash, node_1_privkey),
823 contents: unsigned_announcement.clone()
826 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
828 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
832 // Announce a channel to add a corresponding node.
833 let unsigned_announcement = UnsignedChannelAnnouncement {
834 features: ChannelFeatures::known(),
835 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
839 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
840 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
841 excess_data: Vec::new(),
844 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
845 let valid_announcement = ChannelAnnouncement {
846 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
847 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
848 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
849 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
850 contents: unsigned_announcement.clone(),
852 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
853 Ok(res) => assert!(res),
858 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
859 Ok(res) => assert!(res),
863 let fake_msghash = hash_to_message!(&zero_hash);
864 match net_graph_msg_handler.handle_node_announcement(
866 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
867 contents: unsigned_announcement.clone()
870 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
873 unsigned_announcement.timestamp += 1000;
874 unsigned_announcement.excess_data.push(1);
875 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
876 let announcement_with_data = NodeAnnouncement {
877 signature: secp_ctx.sign(&msghash, node_1_privkey),
878 contents: unsigned_announcement.clone()
880 // Return false because contains excess data.
881 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
882 Ok(res) => assert!(!res),
885 unsigned_announcement.excess_data = Vec::new();
887 // Even though previous announcement was not relayed further, we still accepted it,
888 // so we now won't accept announcements before the previous one.
889 unsigned_announcement.timestamp -= 10;
890 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
891 let outdated_announcement = NodeAnnouncement {
892 signature: secp_ctx.sign(&msghash, node_1_privkey),
893 contents: unsigned_announcement.clone()
895 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
897 Err(e) => assert_eq!(e.err, "Update older than last processed update")
902 fn handling_channel_announcements() {
903 let secp_ctx = Secp256k1::new();
904 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
905 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
906 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
909 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
910 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
911 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
912 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
913 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
914 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
916 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
917 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
918 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
919 .push_opcode(opcodes::all::OP_PUSHNUM_2)
920 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
923 let mut unsigned_announcement = UnsignedChannelAnnouncement {
924 features: ChannelFeatures::known(),
925 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
929 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
930 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
931 excess_data: Vec::new(),
934 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
935 let valid_announcement = ChannelAnnouncement {
936 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
937 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
938 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
939 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
940 contents: unsigned_announcement.clone(),
943 // Test if the UTXO lookups were not supported
944 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
946 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
947 Ok(res) => assert!(res),
952 let network = net_graph_msg_handler.network_graph.read().unwrap();
953 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
960 // If we receive announcement for the same channel (with UTXO lookups disabled),
961 // drop new one on the floor, since we can't see any changes.
962 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
964 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
968 // Test if an associated transaction were not on-chain (or not confirmed).
969 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
970 unsigned_announcement.short_channel_id += 1;
972 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
973 let valid_announcement = ChannelAnnouncement {
974 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
975 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
976 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
977 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
978 contents: unsigned_announcement.clone(),
981 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
983 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
987 // Now test if the transaction is found in the UTXO set and the script is correct.
988 unsigned_announcement.short_channel_id += 1;
989 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
991 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
992 let valid_announcement = ChannelAnnouncement {
993 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
994 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
995 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
996 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
997 contents: unsigned_announcement.clone(),
999 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1000 Ok(res) => assert!(res),
1005 let network = net_graph_msg_handler.network_graph.read().unwrap();
1006 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1012 // If we receive announcement for the same channel (but TX is not confirmed),
1013 // drop new one on the floor, since we can't see any changes.
1014 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1015 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1017 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1020 // But if it is confirmed, replace the channel
1021 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1022 unsigned_announcement.features = ChannelFeatures::empty();
1023 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1024 let valid_announcement = ChannelAnnouncement {
1025 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1026 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1027 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1028 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1029 contents: unsigned_announcement.clone(),
1031 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1032 Ok(res) => assert!(res),
1036 let network = net_graph_msg_handler.network_graph.read().unwrap();
1037 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1038 Some(channel_entry) => {
1039 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1045 // Don't relay valid channels with excess data
1046 unsigned_announcement.short_channel_id += 1;
1047 unsigned_announcement.excess_data.push(1);
1048 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1049 let valid_announcement = ChannelAnnouncement {
1050 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1051 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1052 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1053 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1054 contents: unsigned_announcement.clone(),
1056 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1057 Ok(res) => assert!(!res),
1061 unsigned_announcement.excess_data = Vec::new();
1062 let invalid_sig_announcement = ChannelAnnouncement {
1063 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1064 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1065 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1066 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1067 contents: unsigned_announcement.clone(),
1069 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1071 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1074 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1075 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1076 let channel_to_itself_announcement = ChannelAnnouncement {
1077 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1078 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1079 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1080 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1081 contents: unsigned_announcement.clone(),
1083 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1085 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1090 fn handling_channel_update() {
1091 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1092 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1093 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1094 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1095 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1096 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1097 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1099 let zero_hash = Sha256dHash::hash(&[0; 32]);
1100 let short_channel_id = 0;
1101 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1103 // Announce a channel we will update
1104 let unsigned_announcement = UnsignedChannelAnnouncement {
1105 features: ChannelFeatures::empty(),
1110 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1111 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1112 excess_data: Vec::new(),
1115 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1116 let valid_channel_announcement = ChannelAnnouncement {
1117 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1118 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1119 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1120 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1121 contents: unsigned_announcement.clone(),
1123 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1130 let mut unsigned_channel_update = UnsignedChannelUpdate {
1135 cltv_expiry_delta: 144,
1136 htlc_minimum_msat: 1000000,
1137 fee_base_msat: 10000,
1138 fee_proportional_millionths: 20,
1139 excess_data: Vec::new()
1141 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1142 let valid_channel_update = ChannelUpdate {
1143 signature: secp_ctx.sign(&msghash, node_1_privkey),
1144 contents: unsigned_channel_update.clone()
1147 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1148 Ok(res) => assert!(res),
1153 let network = net_graph_msg_handler.network_graph.read().unwrap();
1154 match network.get_channels().get(&short_channel_id) {
1156 Some(channel_info) => {
1157 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1158 assert!(channel_info.two_to_one.is_none());
1163 unsigned_channel_update.timestamp += 100;
1164 unsigned_channel_update.excess_data.push(1);
1165 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1166 let valid_channel_update = ChannelUpdate {
1167 signature: secp_ctx.sign(&msghash, node_1_privkey),
1168 contents: unsigned_channel_update.clone()
1170 // Return false because contains excess data
1171 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1172 Ok(res) => assert!(!res),
1176 unsigned_channel_update.short_channel_id += 1;
1177 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1178 let valid_channel_update = ChannelUpdate {
1179 signature: secp_ctx.sign(&msghash, node_1_privkey),
1180 contents: unsigned_channel_update.clone()
1183 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1185 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1187 unsigned_channel_update.short_channel_id = short_channel_id;
1190 // Even though previous update was not relayed further, we still accepted it,
1191 // so we now won't accept update before the previous one.
1192 unsigned_channel_update.timestamp -= 10;
1193 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1194 let valid_channel_update = ChannelUpdate {
1195 signature: secp_ctx.sign(&msghash, node_1_privkey),
1196 contents: unsigned_channel_update.clone()
1199 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1201 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1203 unsigned_channel_update.timestamp += 500;
1205 let fake_msghash = hash_to_message!(&zero_hash);
1206 let invalid_sig_channel_update = ChannelUpdate {
1207 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1208 contents: unsigned_channel_update.clone()
1211 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1213 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1219 fn handling_htlc_fail_channel_update() {
1220 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1221 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1222 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1223 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1224 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1225 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1226 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1228 let short_channel_id = 0;
1229 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1232 // There is no nodes in the table at the beginning.
1233 let network = net_graph_msg_handler.network_graph.read().unwrap();
1234 assert_eq!(network.get_nodes().len(), 0);
1238 // Announce a channel we will update
1239 let unsigned_announcement = UnsignedChannelAnnouncement {
1240 features: ChannelFeatures::empty(),
1245 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1246 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1247 excess_data: Vec::new(),
1250 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1251 let valid_channel_announcement = ChannelAnnouncement {
1252 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1253 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1254 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1255 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1256 contents: unsigned_announcement.clone(),
1258 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1263 let unsigned_channel_update = UnsignedChannelUpdate {
1268 cltv_expiry_delta: 144,
1269 htlc_minimum_msat: 1000000,
1270 fee_base_msat: 10000,
1271 fee_proportional_millionths: 20,
1272 excess_data: Vec::new()
1274 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1275 let valid_channel_update = ChannelUpdate {
1276 signature: secp_ctx.sign(&msghash, node_1_privkey),
1277 contents: unsigned_channel_update.clone()
1280 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1281 Ok(res) => assert!(res),
1286 // Non-permanent closing just disables a channel
1288 let network = net_graph_msg_handler.network_graph.read().unwrap();
1289 match network.get_channels().get(&short_channel_id) {
1291 Some(channel_info) => {
1292 assert!(channel_info.one_to_two.is_some());
1297 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1302 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1304 // Non-permanent closing just disables a channel
1306 let network = net_graph_msg_handler.network_graph.read().unwrap();
1307 match network.get_channels().get(&short_channel_id) {
1309 Some(channel_info) => {
1310 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1315 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1320 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1322 // Permanent closing deletes a channel
1324 let network = net_graph_msg_handler.network_graph.read().unwrap();
1325 assert_eq!(network.get_channels().len(), 0);
1326 // Nodes are also deleted because there are no associated channels anymore
1327 assert_eq!(network.get_nodes().len(), 0);
1329 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1333 fn getting_next_channel_announcements() {
1334 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1335 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1336 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1337 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1338 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1339 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1340 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1342 let short_channel_id = 1;
1343 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1345 // Channels were not announced yet.
1346 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1347 assert_eq!(channels_with_announcements.len(), 0);
1350 // Announce a channel we will update
1351 let unsigned_announcement = UnsignedChannelAnnouncement {
1352 features: ChannelFeatures::empty(),
1357 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1358 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1359 excess_data: Vec::new(),
1362 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1363 let valid_channel_announcement = ChannelAnnouncement {
1364 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1365 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1366 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1367 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1368 contents: unsigned_announcement.clone(),
1370 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1376 // Contains initial channel announcement now.
1377 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1378 assert_eq!(channels_with_announcements.len(), 1);
1379 if let Some(channel_announcements) = channels_with_announcements.first() {
1380 let &(_, ref update_1, ref update_2) = channel_announcements;
1381 assert_eq!(update_1, &None);
1382 assert_eq!(update_2, &None);
1389 // Valid channel update
1390 let unsigned_channel_update = UnsignedChannelUpdate {
1395 cltv_expiry_delta: 144,
1396 htlc_minimum_msat: 1000000,
1397 fee_base_msat: 10000,
1398 fee_proportional_millionths: 20,
1399 excess_data: Vec::new()
1401 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1402 let valid_channel_update = ChannelUpdate {
1403 signature: secp_ctx.sign(&msghash, node_1_privkey),
1404 contents: unsigned_channel_update.clone()
1406 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1412 // Now contains an initial announcement and an update.
1413 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1414 assert_eq!(channels_with_announcements.len(), 1);
1415 if let Some(channel_announcements) = channels_with_announcements.first() {
1416 let &(_, ref update_1, ref update_2) = channel_announcements;
1417 assert_ne!(update_1, &None);
1418 assert_eq!(update_2, &None);
1425 // Channel update with excess data.
1426 let unsigned_channel_update = UnsignedChannelUpdate {
1431 cltv_expiry_delta: 144,
1432 htlc_minimum_msat: 1000000,
1433 fee_base_msat: 10000,
1434 fee_proportional_millionths: 20,
1435 excess_data: [1; 3].to_vec()
1437 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1438 let valid_channel_update = ChannelUpdate {
1439 signature: secp_ctx.sign(&msghash, node_1_privkey),
1440 contents: unsigned_channel_update.clone()
1442 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1448 // Test that announcements with excess data won't be returned
1449 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1450 assert_eq!(channels_with_announcements.len(), 1);
1451 if let Some(channel_announcements) = channels_with_announcements.first() {
1452 let &(_, ref update_1, ref update_2) = channel_announcements;
1453 assert_eq!(update_1, &None);
1454 assert_eq!(update_2, &None);
1459 // Further starting point have no channels after it
1460 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1461 assert_eq!(channels_with_announcements.len(), 0);
1465 fn getting_next_node_announcements() {
1466 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1467 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1468 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1469 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1470 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1471 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1472 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1474 let short_channel_id = 1;
1475 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1478 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1479 assert_eq!(next_announcements.len(), 0);
1482 // Announce a channel to add 2 nodes
1483 let unsigned_announcement = UnsignedChannelAnnouncement {
1484 features: ChannelFeatures::empty(),
1489 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1490 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1491 excess_data: Vec::new(),
1494 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1495 let valid_channel_announcement = ChannelAnnouncement {
1496 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1497 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1498 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1499 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1500 contents: unsigned_announcement.clone(),
1502 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1509 // Nodes were never announced
1510 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1511 assert_eq!(next_announcements.len(), 0);
1514 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1515 features: NodeFeatures::known(),
1520 addresses: Vec::new(),
1521 excess_address_data: Vec::new(),
1522 excess_data: Vec::new(),
1524 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1525 let valid_announcement = NodeAnnouncement {
1526 signature: secp_ctx.sign(&msghash, node_1_privkey),
1527 contents: unsigned_announcement.clone()
1529 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1534 unsigned_announcement.node_id = node_id_2;
1535 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1536 let valid_announcement = NodeAnnouncement {
1537 signature: secp_ctx.sign(&msghash, node_2_privkey),
1538 contents: unsigned_announcement.clone()
1541 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1547 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1548 assert_eq!(next_announcements.len(), 2);
1550 // Skip the first node.
1551 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1552 assert_eq!(next_announcements.len(), 1);
1555 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1556 let unsigned_announcement = UnsignedNodeAnnouncement {
1557 features: NodeFeatures::known(),
1562 addresses: Vec::new(),
1563 excess_address_data: Vec::new(),
1564 excess_data: [1; 3].to_vec(),
1566 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1567 let valid_announcement = NodeAnnouncement {
1568 signature: secp_ctx.sign(&msghash, node_2_privkey),
1569 contents: unsigned_announcement.clone()
1571 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1572 Ok(res) => assert!(!res),
1577 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1578 assert_eq!(next_announcements.len(), 0);
1582 fn network_graph_serialization() {
1583 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1585 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1586 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1587 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1588 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1590 // Announce a channel to add a corresponding node.
1591 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1592 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1593 let unsigned_announcement = UnsignedChannelAnnouncement {
1594 features: ChannelFeatures::known(),
1595 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1596 short_channel_id: 0,
1599 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1600 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1601 excess_data: Vec::new(),
1604 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1605 let valid_announcement = ChannelAnnouncement {
1606 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1607 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1608 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1609 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1610 contents: unsigned_announcement.clone(),
1612 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1613 Ok(res) => assert!(res),
1618 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1619 let unsigned_announcement = UnsignedNodeAnnouncement {
1620 features: NodeFeatures::known(),
1625 addresses: Vec::new(),
1626 excess_address_data: Vec::new(),
1627 excess_data: Vec::new(),
1629 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1630 let valid_announcement = NodeAnnouncement {
1631 signature: secp_ctx.sign(&msghash, node_1_privkey),
1632 contents: unsigned_announcement.clone()
1635 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1640 let network = net_graph_msg_handler.network_graph.write().unwrap();
1641 let mut w = test_utils::TestVecWriter(Vec::new());
1642 assert!(!network.get_nodes().is_empty());
1643 assert!(!network.get_channels().is_empty());
1644 network.write(&mut w).unwrap();
1645 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);