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 network.get_nodes().get(pubkey).map(|n| n.addresses.clone())
57 /// Dumps the entire network view of this NetGraphMsgHandler to the logger provided in the constructor at
59 pub fn trace_state(&self) {
60 log_trace!(self, "{}", self.network_graph.read().unwrap());
65 macro_rules! secp_verify_sig {
66 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
67 match $secp_ctx.verify($msg, $sig, $pubkey) {
69 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
74 impl RoutingMessageHandler for NetGraphMsgHandler {
75 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
76 self.network_graph.write().unwrap().process_node_announcement(msg, Some(&self.secp_ctx))
79 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
80 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
81 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
84 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
85 Ok((script_pubkey, _value)) => {
86 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
87 .push_slice(&msg.contents.bitcoin_key_1.serialize())
88 .push_slice(&msg.contents.bitcoin_key_2.serialize())
89 .push_opcode(opcodes::all::OP_PUSHNUM_2)
90 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
91 if script_pubkey != expected_script {
92 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
94 //TODO: Check if value is worth storing, use it to inform routing, and compare it
95 //to the new HTLC max field in channel_update
98 Err(ChainError::NotSupported) => {
99 // Tentatively accept, potentially exposing us to DoS attacks
102 Err(ChainError::NotWatched) => {
103 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
105 Err(ChainError::UnknownTx) => {
106 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
109 let result = self.network_graph.write().unwrap().process_channel_announcement(msg, checked_utxo, Some(&self.secp_ctx));
110 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
114 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
116 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
117 let _ = self.network_graph.write().unwrap().process_channel_update(msg, Some(&self.secp_ctx));
119 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
120 self.network_graph.write().unwrap().process_channel_closing(short_channel_id, &is_permanent);
122 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
123 self.network_graph.write().unwrap().process_node_failure(node_id, &is_permanent);
128 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
129 self.network_graph.write().unwrap().process_channel_update(msg, Some(&self.secp_ctx))
132 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
133 let network_graph = self.network_graph.read().unwrap();
134 let mut result = Vec::with_capacity(batch_amount as usize);
135 let mut iter = network_graph.get_channels().range(starting_point..);
136 while result.len() < batch_amount as usize {
137 if let Some((_, ref chan)) = iter.next() {
138 if chan.announcement_message.is_some() {
139 result.push((chan.announcement_message.clone().unwrap(),
140 chan.one_to_two.last_update_message.clone(),
141 chan.two_to_one.last_update_message.clone()));
143 // TODO: We may end up sending un-announced channel_updates if we are sending
144 // initial sync data while receiving announce/updates for this channel.
153 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
154 let network_graph = self.network_graph.read().unwrap();
155 let mut result = Vec::with_capacity(batch_amount as usize);
156 let mut iter = if let Some(pubkey) = starting_point {
157 let mut iter = network_graph.get_nodes().range((*pubkey)..);
161 network_graph.get_nodes().range(..)
163 while result.len() < batch_amount as usize {
164 if let Some((_, ref node)) = iter.next() {
165 if node.announcement_message.is_some() {
166 result.push(node.announcement_message.clone().unwrap());
175 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
176 //TODO: Determine whether to request a full sync based on the network map.
177 const FULL_SYNCS_TO_REQUEST: usize = 5;
178 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
179 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
188 const SERIALIZATION_VERSION: u8 = 1;
189 const MIN_SERIALIZATION_VERSION: u8 = 1;
191 impl Writeable for NetGraphMsgHandler {
192 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
193 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
194 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
196 let network = self.network_graph.read().unwrap();
197 network.write(writer)?;
202 /// Arguments for the creation of a NetGraphMsgHandler that are not deserialized.
203 /// At a high-level, the process for deserializing a NetGraphMsgHandler and resuming normal operation is:
204 /// 1) Deserialize the NetGraphMsgHandler by filling in this struct and calling <NetGraphMsgHandler>::read(reaser, args).
205 /// 2) Register the new NetGraphMsgHandler with your ChainWatchInterface
206 pub struct NetGraphMsgHandlerReadArgs {
207 /// The ChainWatchInterface for use in the NetGraphMsgHandler in the future.
209 /// No calls to the ChainWatchInterface will be made during deserialization.
210 pub chain_monitor: Arc<ChainWatchInterface>,
211 /// The Logger for use in the ChannelManager and which may be used to log information during
213 pub logger: Arc<Logger>,
216 impl ReadableArgs<NetGraphMsgHandlerReadArgs> for NetGraphMsgHandler {
217 fn read<R: ::std::io::Read>(reader: &mut R, args: NetGraphMsgHandlerReadArgs) -> Result<NetGraphMsgHandler, DecodeError> {
218 let _ver: u8 = Readable::read(reader)?;
219 let min_ver: u8 = Readable::read(reader)?;
220 if min_ver > SERIALIZATION_VERSION {
221 return Err(DecodeError::UnknownVersion);
223 let network_graph = Readable::read(reader)?;
224 Ok(NetGraphMsgHandler {
225 secp_ctx: Secp256k1::verification_only(),
226 network_graph: RwLock::new(network_graph),
227 chain_monitor: args.chain_monitor,
228 full_syncs_requested: AtomicUsize::new(0),
229 logger: args.logger.clone(),
235 /// Details regarding one direction of a channel
236 pub struct DirectionalChannelInfo {
237 /// A node from which the channel direction starts
238 pub src_node_id: PublicKey,
239 /// When the last update to the channel direction was issued
240 pub last_update: u32,
241 /// Whether the channel can be currently used for payments
243 /// The difference in CLTV values between the source and the destination node of the channel
244 pub cltv_expiry_delta: u16,
245 /// The minimum value, which must be relayed to the next hop via the channel
246 pub htlc_minimum_msat: u64,
247 /// Fees charged when the channel is used for routing
248 pub fees: RoutingFees,
249 /// Most recent update for the channel received from the network
250 pub last_update_message: Option<msgs::ChannelUpdate>,
253 impl std::fmt::Display for DirectionalChannelInfo {
254 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
255 write!(f, "src_node_id {}, last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", log_pubkey!(self.src_node_id), self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
260 impl_writeable!(DirectionalChannelInfo, 0, {
271 /// Details regarding a channel (both directions)
272 pub struct ChannelInfo {
273 /// Protocol features of a channel communicated during its announcement
274 pub features: ChannelFeatures,
275 /// Details regarding one of the directions of a channel
276 pub one_to_two: DirectionalChannelInfo,
277 /// Details regarding another direction of a channel
278 pub two_to_one: DirectionalChannelInfo,
279 /// An initial announcement of the channel
280 //this is cached here so we can send out it later if required by initial routing sync
281 //keep an eye on this to see if the extra memory is a problem
282 pub announcement_message: Option<msgs::ChannelAnnouncement>,
285 impl std::fmt::Display for ChannelInfo {
286 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
287 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
292 impl_writeable!(ChannelInfo, 0, {
300 /// Fees for routing via a given channel or a node
301 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
302 pub struct RoutingFees {
305 /// Liquidity-based routing fee
306 pub proportional_millionths: u32,
309 impl Readable for RoutingFees{
310 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
311 let base_msat: u32 = Readable::read(reader)?;
312 let proportional_millionths: u32 = Readable::read(reader)?;
315 proportional_millionths,
320 impl Writeable for RoutingFees {
321 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
322 self.base_msat.write(writer)?;
323 self.proportional_millionths.write(writer)?;
330 /// Details regarding a node in the network
331 pub struct NodeInfo {
332 /// All valid channels a node has announced
333 pub channels: Vec<u64>,
334 /// Lowest fees enabling routing via any of the known channels to a node
335 pub lowest_inbound_channel_fees: Option<RoutingFees>,
336 /// Protocol features the node announced support for
337 pub features: NodeFeatures,
338 /// When the last known update to the node state was issued
339 /// Unlike for channels, we may have a NodeInfo entry before having received a node_update.
340 /// Thus, we have to be able to capture "no update has been received", which we do with an
342 pub last_update: Option<u32>,
343 /// Color assigned to the node
345 /// Moniker assigned to the node
347 /// Internet-level addresses via which one can connect to the node
348 pub addresses: Vec<NetAddress>,
349 /// An initial announcement of the node
350 //this is cached here so we can send out it later if required by initial routing sync
351 //keep an eye on this to see if the extra memory is a problem
352 pub announcement_message: Option<msgs::NodeAnnouncement>,
355 impl std::fmt::Display for NodeInfo {
356 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
357 write!(f, "features: {}, last_update: {:?}, lowest_inbound_channel_fees: {:?}, channels: {:?}", log_bytes!(self.features.encode()), self.last_update, self.lowest_inbound_channel_fees, &self.channels[..])?;
362 impl Writeable for NodeInfo {
363 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
364 (self.channels.len() as u64).write(writer)?;
365 for ref chan in self.channels.iter() {
368 self.lowest_inbound_channel_fees.write(writer)?;
369 self.features.write(writer)?;
370 self.last_update.write(writer)?;
371 self.rgb.write(writer)?;
372 self.alias.write(writer)?;
373 (self.addresses.len() as u64).write(writer)?;
374 for ref addr in &self.addresses {
377 self.announcement_message.write(writer)?;
382 const MAX_ALLOC_SIZE: u64 = 64*1024;
384 impl Readable for NodeInfo {
385 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
386 let channels_count: u64 = Readable::read(reader)?;
387 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
388 for _ in 0..channels_count {
389 channels.push(Readable::read(reader)?);
391 let lowest_inbound_channel_fees = Readable::read(reader)?;
392 let features = Readable::read(reader)?;
393 let last_update = Readable::read(reader)?;
394 let rgb = Readable::read(reader)?;
395 let alias = Readable::read(reader)?;
396 let addresses_count: u64 = Readable::read(reader)?;
397 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
398 for _ in 0..addresses_count {
399 match Readable::read(reader) {
400 Ok(Ok(addr)) => { addresses.push(addr); },
401 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
402 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
406 let announcement_message = Readable::read(reader)?;
409 lowest_inbound_channel_fees,
420 /// Represents the network as nodes and channels between them
422 pub struct NetworkGraph {
423 channels: BTreeMap<u64, ChannelInfo>,
424 nodes: BTreeMap<PublicKey, NodeInfo>,
427 impl Writeable for NetworkGraph {
428 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
429 (self.channels.len() as u64).write(writer)?;
430 for (ref chan_id, ref chan_info) in self.channels.iter() {
431 (*chan_id).write(writer)?;
432 chan_info.write(writer)?;
434 (self.nodes.len() as u64).write(writer)?;
435 for (ref node_id, ref node_info) in self.nodes.iter() {
436 node_id.write(writer)?;
437 node_info.write(writer)?;
443 impl Readable for NetworkGraph {
444 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
445 let channels_count: u64 = Readable::read(reader)?;
446 let mut channels = BTreeMap::new();
447 for _ in 0..channels_count {
448 let chan_id: u64 = Readable::read(reader)?;
449 let chan_info = Readable::read(reader)?;
450 channels.insert(chan_id, chan_info);
452 let nodes_count: u64 = Readable::read(reader)?;
453 let mut nodes = BTreeMap::new();
454 for _ in 0..nodes_count {
455 let node_id = Readable::read(reader)?;
456 let node_info = Readable::read(reader)?;
457 nodes.insert(node_id, node_info);
466 impl std::fmt::Display for NetworkGraph {
467 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
468 write!(f, "Network map\n[Channels]\n")?;
469 for (key, val) in self.channels.iter() {
470 write!(f, " {}: {}\n", key, val)?;
472 write!(f, "[Nodes]\n")?;
473 for (key, val) in self.nodes.iter() {
474 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
481 /// Returns all known valid channels
482 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
483 /// Returns all known nodes
484 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
486 fn process_node_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
487 if let Some(sig_verifier) = secp_ctx {
488 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
489 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
492 match self.nodes.get_mut(&msg.contents.node_id) {
493 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
495 match node.last_update {
496 Some(last_update) => if last_update >= msg.contents.timestamp {
497 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
502 node.features = msg.contents.features.clone();
503 node.last_update = Some(msg.contents.timestamp);
504 node.rgb = msg.contents.rgb;
505 node.alias = msg.contents.alias;
506 node.addresses = msg.contents.addresses.clone();
508 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
509 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
515 fn process_channel_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
516 if let Some(sig_verifier) = secp_ctx {
517 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
518 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
519 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
520 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
521 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
524 let should_relay = msg.contents.excess_data.is_empty();
526 let chan_info = ChannelInfo {
527 features: msg.contents.features.clone(),
528 one_to_two: DirectionalChannelInfo {
529 src_node_id: msg.contents.node_id_1.clone(),
532 cltv_expiry_delta: u16::max_value(),
533 htlc_minimum_msat: u64::max_value(),
535 base_msat: u32::max_value(),
536 proportional_millionths: u32::max_value(),
538 last_update_message: None,
540 two_to_one: DirectionalChannelInfo {
541 src_node_id: msg.contents.node_id_2.clone(),
544 cltv_expiry_delta: u16::max_value(),
545 htlc_minimum_msat: u64::max_value(),
547 base_msat: u32::max_value(),
548 proportional_millionths: u32::max_value(),
550 last_update_message: None,
552 announcement_message: if should_relay { Some(msg.clone()) } else { None },
555 match self.channels.entry(msg.contents.short_channel_id) {
556 BtreeEntry::Occupied(mut entry) => {
557 //TODO: because asking the blockchain if short_channel_id is valid is only optional
558 //in the blockchain API, we need to handle it smartly here, though it's unclear
561 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
562 // only sometimes returns results. In any case remove the previous entry. Note
563 // that the spec expects us to "blacklist" the node_ids involved, but we can't
565 // a) we don't *require* a UTXO provider that always returns results.
566 // b) we don't track UTXOs of channels we know about and remove them if they
568 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
569 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
570 *entry.get_mut() = chan_info;
572 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
575 BtreeEntry::Vacant(entry) => {
576 entry.insert(chan_info);
580 macro_rules! add_channel_to_node {
581 ( $node_id: expr ) => {
582 match self.nodes.entry($node_id) {
583 BtreeEntry::Occupied(node_entry) => {
584 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
586 BtreeEntry::Vacant(node_entry) => {
587 node_entry.insert(NodeInfo {
588 channels: vec!(msg.contents.short_channel_id),
589 lowest_inbound_channel_fees: None,
590 features: NodeFeatures::empty(),
594 addresses: Vec::new(),
595 announcement_message: None,
602 add_channel_to_node!(msg.contents.node_id_1);
603 add_channel_to_node!(msg.contents.node_id_2);
608 fn process_channel_closing(&mut self, short_channel_id: &u64, is_permanent: &bool) {
610 if let Some(chan) = self.channels.remove(short_channel_id) {
611 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
614 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
615 chan.one_to_two.enabled = false;
616 chan.two_to_one.enabled = false;
621 fn process_node_failure(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
623 // TODO: Wholly remove the node
625 // TODO: downgrade the node
629 fn process_channel_update(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
631 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
632 let chan_was_enabled;
634 match self.channels.get_mut(&msg.contents.short_channel_id) {
635 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
637 macro_rules! maybe_update_channel_info {
638 ( $target: expr) => {
639 if $target.last_update >= msg.contents.timestamp {
640 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
642 chan_was_enabled = $target.enabled;
643 $target.last_update = msg.contents.timestamp;
644 $target.enabled = chan_enabled;
645 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
646 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
647 $target.fees.base_msat = msg.contents.fee_base_msat;
648 $target.fees.proportional_millionths = msg.contents.fee_proportional_millionths;
649 $target.last_update_message = if msg.contents.excess_data.is_empty() {
656 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
657 if msg.contents.flags & 1 == 1 {
658 dest_node_id = channel.one_to_two.src_node_id.clone();
659 if let Some(sig_verifier) = secp_ctx {
660 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
662 maybe_update_channel_info!(channel.two_to_one);
664 dest_node_id = channel.two_to_one.src_node_id.clone();
665 if let Some(sig_verifier) = secp_ctx {
666 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
668 maybe_update_channel_info!(channel.one_to_two);
674 let node = self.nodes.get_mut(&dest_node_id).unwrap();
675 let mut base_msat = msg.contents.fee_base_msat;
676 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
677 if let Some(fees) = node.lowest_inbound_channel_fees {
678 base_msat = cmp::min(base_msat, fees.base_msat);
679 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
681 node.lowest_inbound_channel_fees = Some(RoutingFees {
683 proportional_millionths
685 } else if chan_was_enabled {
686 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
687 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
690 let node = self.nodes.get(&dest_node_id).unwrap();
692 for chan_id in node.channels.iter() {
693 let chan = self.channels.get(chan_id).unwrap();
694 if chan.one_to_two.src_node_id == dest_node_id {
695 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fees.base_msat);
696 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fees.proportional_millionths);
698 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fees.base_msat);
699 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fees.proportional_millionths);
704 //TODO: satisfy the borrow-checker without a double-map-lookup :(
705 let mut_node = self.nodes.get_mut(&dest_node_id).unwrap();
706 if mut_node.channels.len() > 0 {
707 mut_node.lowest_inbound_channel_fees = Some(RoutingFees {
708 base_msat: lowest_inbound_channel_fee_base_msat,
709 proportional_millionths: lowest_inbound_channel_fee_proportional_millionths
714 Ok(msg.contents.excess_data.is_empty())
717 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
718 macro_rules! remove_from_node {
719 ($node_id: expr) => {
720 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
721 entry.get_mut().channels.retain(|chan_id| {
722 short_channel_id != *chan_id
724 if entry.get().channels.is_empty() {
725 entry.remove_entry();
728 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
732 remove_from_node!(chan.one_to_two.src_node_id);
733 remove_from_node!(chan.two_to_one.src_node_id);
739 use chain::chaininterface;
740 use ln::features::{ChannelFeatures, NodeFeatures};
741 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
742 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
743 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
744 use util::test_utils;
745 use util::logger::Logger;
746 use util::ser::{Readable, Writeable};
748 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
749 use bitcoin::hashes::Hash;
750 use bitcoin::network::constants::Network;
751 use bitcoin::blockdata::constants::genesis_block;
752 use bitcoin::blockdata::script::Builder;
753 use bitcoin::blockdata::opcodes;
754 use bitcoin::util::hash::BitcoinHash;
758 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
759 use bitcoin::secp256k1::{All, Secp256k1};
763 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
764 let secp_ctx = Secp256k1::new();
765 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
766 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
767 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
768 (secp_ctx, net_graph_msg_handler)
772 fn request_full_sync_finite_times() {
773 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
774 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
776 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
777 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
778 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
779 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
780 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
781 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
785 fn handling_node_announcements() {
786 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
788 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
789 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
790 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
791 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
792 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
793 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
794 let zero_hash = Sha256dHash::hash(&[0; 32]);
795 let first_announcement_time = 500;
797 let mut unsigned_announcement = UnsignedNodeAnnouncement {
798 features: NodeFeatures::known(),
799 timestamp: first_announcement_time,
803 addresses: Vec::new(),
804 excess_address_data: Vec::new(),
805 excess_data: Vec::new(),
807 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
808 let valid_announcement = NodeAnnouncement {
809 signature: secp_ctx.sign(&msghash, node_1_privkey),
810 contents: unsigned_announcement.clone()
813 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
815 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
819 // Announce a channel to add a corresponding node.
820 let unsigned_announcement = UnsignedChannelAnnouncement {
821 features: ChannelFeatures::known(),
822 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
826 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
827 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
828 excess_data: Vec::new(),
831 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
832 let valid_announcement = ChannelAnnouncement {
833 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
834 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
835 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
836 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
837 contents: unsigned_announcement.clone(),
839 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
840 Ok(res) => assert!(res),
845 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
846 Ok(res) => assert!(res),
850 let fake_msghash = hash_to_message!(&zero_hash);
851 match net_graph_msg_handler.handle_node_announcement(
853 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
854 contents: unsigned_announcement.clone()
857 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
860 unsigned_announcement.timestamp += 1000;
861 unsigned_announcement.excess_data.push(1);
862 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
863 let announcement_with_data = NodeAnnouncement {
864 signature: secp_ctx.sign(&msghash, node_1_privkey),
865 contents: unsigned_announcement.clone()
867 // Return false because contains excess data.
868 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
869 Ok(res) => assert!(!res),
872 unsigned_announcement.excess_data = Vec::new();
874 // Even though previous announcement was not relayed further, we still accepted it,
875 // so we now won't accept announcements before the previous one.
876 unsigned_announcement.timestamp -= 10;
877 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
878 let outdated_announcement = NodeAnnouncement {
879 signature: secp_ctx.sign(&msghash, node_1_privkey),
880 contents: unsigned_announcement.clone()
882 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
884 Err(e) => assert_eq!(e.err, "Update older than last processed update")
889 fn handling_channel_announcements() {
890 let secp_ctx = Secp256k1::new();
891 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
892 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
893 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
896 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
897 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
898 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
899 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
900 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
901 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
903 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
904 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
905 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
906 .push_opcode(opcodes::all::OP_PUSHNUM_2)
907 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
910 let mut unsigned_announcement = UnsignedChannelAnnouncement {
911 features: ChannelFeatures::known(),
912 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
916 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
917 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
918 excess_data: Vec::new(),
921 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
922 let valid_announcement = ChannelAnnouncement {
923 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
924 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
925 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
926 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
927 contents: unsigned_announcement.clone(),
930 // Test if the UTXO lookups were not supported
931 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
933 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
934 Ok(res) => assert!(res),
939 let network = net_graph_msg_handler.network_graph.read().unwrap();
940 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
947 // If we receive announcement for the same channel (with UTXO lookups disabled),
948 // drop new one on the floor, since we can't see any changes.
949 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
951 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
955 // Test if an associated transaction were not on-chain (or not confirmed).
956 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
957 unsigned_announcement.short_channel_id += 1;
959 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
960 let valid_announcement = ChannelAnnouncement {
961 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
962 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
963 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
964 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
965 contents: unsigned_announcement.clone(),
968 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
970 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
974 // Now test if the transaction is found in the UTXO set and the script is correct.
975 unsigned_announcement.short_channel_id += 1;
976 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
978 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
979 let valid_announcement = ChannelAnnouncement {
980 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
981 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
982 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
983 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
984 contents: unsigned_announcement.clone(),
986 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
987 Ok(res) => assert!(res),
992 let network = net_graph_msg_handler.network_graph.read().unwrap();
993 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
999 // If we receive announcement for the same channel (but TX is not confirmed),
1000 // drop new one on the floor, since we can't see any changes.
1001 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1002 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1004 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1007 // But if it is confirmed, replace the channel
1008 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1009 unsigned_announcement.features = ChannelFeatures::empty();
1010 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1011 let valid_announcement = ChannelAnnouncement {
1012 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1013 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1014 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1015 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1016 contents: unsigned_announcement.clone(),
1018 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1019 Ok(res) => assert!(res),
1023 let network = net_graph_msg_handler.network_graph.read().unwrap();
1024 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1025 Some(channel_entry) => {
1026 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1032 // Don't relay valid channels with excess data
1033 unsigned_announcement.short_channel_id += 1;
1034 unsigned_announcement.excess_data.push(1);
1035 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1036 let valid_announcement = ChannelAnnouncement {
1037 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1038 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1039 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1040 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1041 contents: unsigned_announcement.clone(),
1043 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1044 Ok(res) => assert!(!res),
1048 unsigned_announcement.excess_data = Vec::new();
1049 let invalid_sig_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_1_btckey),
1054 contents: unsigned_announcement.clone(),
1056 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1058 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1061 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1062 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1063 let channel_to_itself_announcement = ChannelAnnouncement {
1064 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1065 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1066 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1067 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1068 contents: unsigned_announcement.clone(),
1070 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1072 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1077 fn handling_channel_update() {
1078 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1079 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1080 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1081 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1082 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1083 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1084 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1086 let zero_hash = Sha256dHash::hash(&[0; 32]);
1087 let short_channel_id = 0;
1088 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1090 // Announce a channel we will update
1091 let unsigned_announcement = UnsignedChannelAnnouncement {
1092 features: ChannelFeatures::empty(),
1097 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1098 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1099 excess_data: Vec::new(),
1102 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1103 let valid_channel_announcement = ChannelAnnouncement {
1104 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1105 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1106 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1107 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1108 contents: unsigned_announcement.clone(),
1110 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1117 let mut unsigned_channel_update = UnsignedChannelUpdate {
1122 cltv_expiry_delta: 144,
1123 htlc_minimum_msat: 1000000,
1124 fee_base_msat: 10000,
1125 fee_proportional_millionths: 20,
1126 excess_data: Vec::new()
1128 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1129 let valid_channel_update = ChannelUpdate {
1130 signature: secp_ctx.sign(&msghash, node_1_privkey),
1131 contents: unsigned_channel_update.clone()
1134 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1135 Ok(res) => assert!(res),
1140 let network = net_graph_msg_handler.network_graph.read().unwrap();
1141 match network.get_channels().get(&short_channel_id) {
1143 Some(channel_info) => {
1144 assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
1145 assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
1150 unsigned_channel_update.timestamp += 100;
1151 unsigned_channel_update.excess_data.push(1);
1152 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1153 let valid_channel_update = ChannelUpdate {
1154 signature: secp_ctx.sign(&msghash, node_1_privkey),
1155 contents: unsigned_channel_update.clone()
1157 // Return false because contains excess data
1158 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1159 Ok(res) => assert!(!res),
1163 unsigned_channel_update.short_channel_id += 1;
1164 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1165 let valid_channel_update = ChannelUpdate {
1166 signature: secp_ctx.sign(&msghash, node_1_privkey),
1167 contents: unsigned_channel_update.clone()
1170 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1172 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1174 unsigned_channel_update.short_channel_id = short_channel_id;
1177 // Even though previous update was not relayed further, we still accepted it,
1178 // so we now won't accept update before the previous one.
1179 unsigned_channel_update.timestamp -= 10;
1180 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1181 let valid_channel_update = ChannelUpdate {
1182 signature: secp_ctx.sign(&msghash, node_1_privkey),
1183 contents: unsigned_channel_update.clone()
1186 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1188 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1190 unsigned_channel_update.timestamp += 500;
1192 let fake_msghash = hash_to_message!(&zero_hash);
1193 let invalid_sig_channel_update = ChannelUpdate {
1194 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1195 contents: unsigned_channel_update.clone()
1198 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1200 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1206 fn handling_htlc_fail_channel_update() {
1207 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1208 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1209 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1210 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1211 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1212 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1213 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1215 let short_channel_id = 0;
1216 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1219 // There is no nodes in the table at the beginning.
1220 let network = net_graph_msg_handler.network_graph.read().unwrap();
1221 assert_eq!(network.get_nodes().len(), 0);
1225 // Announce a channel we will update
1226 let unsigned_announcement = UnsignedChannelAnnouncement {
1227 features: ChannelFeatures::empty(),
1232 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1233 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1234 excess_data: Vec::new(),
1237 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1238 let valid_channel_announcement = ChannelAnnouncement {
1239 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1240 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1241 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1242 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1243 contents: unsigned_announcement.clone(),
1245 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1252 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1257 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1259 // Non-permanent closing just disables a channel
1261 let network = net_graph_msg_handler.network_graph.read().unwrap();
1262 match network.get_channels().get(&short_channel_id) {
1264 Some(channel_info) => {
1265 assert!(!channel_info.one_to_two.enabled);
1266 assert!(!channel_info.two_to_one.enabled);
1271 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1276 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1278 // Permanent closing deletes a channel
1280 let network = net_graph_msg_handler.network_graph.read().unwrap();
1281 assert_eq!(network.get_channels().len(), 0);
1282 // Nodes are also deleted because there are no associated channels anymore
1283 assert_eq!(network.get_nodes().len(), 0);
1285 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1289 fn getting_next_channel_announcements() {
1290 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1291 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1292 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1293 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1294 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1295 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1296 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1298 let short_channel_id = 1;
1299 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1301 // Channels were not announced yet.
1302 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1303 assert_eq!(channels_with_announcements.len(), 0);
1306 // Announce a channel we will update
1307 let unsigned_announcement = UnsignedChannelAnnouncement {
1308 features: ChannelFeatures::empty(),
1313 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1314 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1315 excess_data: Vec::new(),
1318 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1319 let valid_channel_announcement = ChannelAnnouncement {
1320 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1321 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1322 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1323 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1324 contents: unsigned_announcement.clone(),
1326 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1332 // Contains initial channel announcement now.
1333 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1334 assert_eq!(channels_with_announcements.len(), 1);
1335 if let Some(channel_announcements) = channels_with_announcements.first() {
1336 let &(_, ref update_1, ref update_2) = channel_announcements;
1337 assert_eq!(update_1, &None);
1338 assert_eq!(update_2, &None);
1345 // Valid channel update
1346 let unsigned_channel_update = UnsignedChannelUpdate {
1351 cltv_expiry_delta: 144,
1352 htlc_minimum_msat: 1000000,
1353 fee_base_msat: 10000,
1354 fee_proportional_millionths: 20,
1355 excess_data: Vec::new()
1357 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1358 let valid_channel_update = ChannelUpdate {
1359 signature: secp_ctx.sign(&msghash, node_1_privkey),
1360 contents: unsigned_channel_update.clone()
1362 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1368 // Now contains an initial announcement and an update.
1369 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1370 assert_eq!(channels_with_announcements.len(), 1);
1371 if let Some(channel_announcements) = channels_with_announcements.first() {
1372 let &(_, ref update_1, ref update_2) = channel_announcements;
1373 assert_ne!(update_1, &None);
1374 assert_eq!(update_2, &None);
1381 // Channel update with excess data.
1382 let unsigned_channel_update = UnsignedChannelUpdate {
1387 cltv_expiry_delta: 144,
1388 htlc_minimum_msat: 1000000,
1389 fee_base_msat: 10000,
1390 fee_proportional_millionths: 20,
1391 excess_data: [1; 3].to_vec()
1393 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1394 let valid_channel_update = ChannelUpdate {
1395 signature: secp_ctx.sign(&msghash, node_1_privkey),
1396 contents: unsigned_channel_update.clone()
1398 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1404 // Test that announcements with excess data won't be returned
1405 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1406 assert_eq!(channels_with_announcements.len(), 1);
1407 if let Some(channel_announcements) = channels_with_announcements.first() {
1408 let &(_, ref update_1, ref update_2) = channel_announcements;
1409 assert_eq!(update_1, &None);
1410 assert_eq!(update_2, &None);
1415 // Further starting point have no channels after it
1416 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1417 assert_eq!(channels_with_announcements.len(), 0);
1421 fn getting_next_node_announcements() {
1422 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1423 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1424 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1425 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1426 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1427 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1428 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1430 let short_channel_id = 1;
1431 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1434 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1435 assert_eq!(next_announcements.len(), 0);
1438 // Announce a channel to add 2 nodes
1439 let unsigned_announcement = UnsignedChannelAnnouncement {
1440 features: ChannelFeatures::empty(),
1445 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1446 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1447 excess_data: Vec::new(),
1450 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1451 let valid_channel_announcement = ChannelAnnouncement {
1452 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1453 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1454 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1455 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1456 contents: unsigned_announcement.clone(),
1458 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1465 // Nodes were never announced
1466 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1467 assert_eq!(next_announcements.len(), 0);
1470 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1471 features: NodeFeatures::known(),
1476 addresses: Vec::new(),
1477 excess_address_data: Vec::new(),
1478 excess_data: Vec::new(),
1480 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1481 let valid_announcement = NodeAnnouncement {
1482 signature: secp_ctx.sign(&msghash, node_1_privkey),
1483 contents: unsigned_announcement.clone()
1485 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1490 unsigned_announcement.node_id = node_id_2;
1491 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1492 let valid_announcement = NodeAnnouncement {
1493 signature: secp_ctx.sign(&msghash, node_2_privkey),
1494 contents: unsigned_announcement.clone()
1497 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1503 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1504 assert_eq!(next_announcements.len(), 2);
1506 // Skip the first node.
1507 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1508 assert_eq!(next_announcements.len(), 1);
1511 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1512 let unsigned_announcement = UnsignedNodeAnnouncement {
1513 features: NodeFeatures::known(),
1518 addresses: Vec::new(),
1519 excess_address_data: Vec::new(),
1520 excess_data: [1; 3].to_vec(),
1522 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1523 let valid_announcement = NodeAnnouncement {
1524 signature: secp_ctx.sign(&msghash, node_2_privkey),
1525 contents: unsigned_announcement.clone()
1527 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1528 Ok(res) => assert!(!res),
1533 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1534 assert_eq!(next_announcements.len(), 0);
1538 fn network_graph_serialization() {
1539 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1541 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1542 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1543 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1544 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1546 // Announce a channel to add a corresponding node.
1547 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1548 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1549 let unsigned_announcement = UnsignedChannelAnnouncement {
1550 features: ChannelFeatures::known(),
1551 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1552 short_channel_id: 0,
1555 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1556 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1557 excess_data: Vec::new(),
1560 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1561 let valid_announcement = ChannelAnnouncement {
1562 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1563 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1564 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1565 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1566 contents: unsigned_announcement.clone(),
1568 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1569 Ok(res) => assert!(res),
1574 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1575 let unsigned_announcement = UnsignedNodeAnnouncement {
1576 features: NodeFeatures::known(),
1581 addresses: Vec::new(),
1582 excess_address_data: Vec::new(),
1583 excess_data: Vec::new(),
1585 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1586 let valid_announcement = NodeAnnouncement {
1587 signature: secp_ctx.sign(&msghash, node_1_privkey),
1588 contents: unsigned_announcement.clone()
1591 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1596 let network = net_graph_msg_handler.network_graph.write().unwrap();
1597 let mut w = test_utils::TestVecWriter(Vec::new());
1598 assert!(!network.get_nodes().is_empty());
1599 assert!(!network.get_channels().is_empty());
1600 network.write(&mut w).unwrap();
1601 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);