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().update_node_from_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().update_channel_from_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().update_channel(msg, Some(&self.secp_ctx));
119 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
120 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
122 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
123 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
128 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
129 self.network_graph.write().unwrap().update_channel(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 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
487 /// Announcement signatures are checked here only if Secp256k1 object is provided.
488 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
489 if let Some(sig_verifier) = secp_ctx {
490 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
491 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
494 match self.nodes.get_mut(&msg.contents.node_id) {
495 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
497 match node.last_update {
498 Some(last_update) => if last_update >= msg.contents.timestamp {
499 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
504 node.features = msg.contents.features.clone();
505 node.last_update = Some(msg.contents.timestamp);
506 node.rgb = msg.contents.rgb;
507 node.alias = msg.contents.alias;
508 node.addresses = msg.contents.addresses.clone();
510 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
511 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
517 /// For a new or already known (from previous announcement) channel, store or update channel info,
518 /// after making sure it corresponds to a real transaction on-chain.
519 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
520 /// Announcement signatures are checked here only if Secp256k1 object is provided.
521 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
522 if let Some(sig_verifier) = secp_ctx {
523 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
524 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
525 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
526 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
527 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
530 let should_relay = msg.contents.excess_data.is_empty();
532 let chan_info = ChannelInfo {
533 features: msg.contents.features.clone(),
534 one_to_two: DirectionalChannelInfo {
535 src_node_id: msg.contents.node_id_1.clone(),
538 cltv_expiry_delta: u16::max_value(),
539 htlc_minimum_msat: u64::max_value(),
541 base_msat: u32::max_value(),
542 proportional_millionths: u32::max_value(),
544 last_update_message: None,
546 two_to_one: DirectionalChannelInfo {
547 src_node_id: msg.contents.node_id_2.clone(),
550 cltv_expiry_delta: u16::max_value(),
551 htlc_minimum_msat: u64::max_value(),
553 base_msat: u32::max_value(),
554 proportional_millionths: u32::max_value(),
556 last_update_message: None,
558 announcement_message: if should_relay { Some(msg.clone()) } else { None },
561 match self.channels.entry(msg.contents.short_channel_id) {
562 BtreeEntry::Occupied(mut entry) => {
563 //TODO: because asking the blockchain if short_channel_id is valid is only optional
564 //in the blockchain API, we need to handle it smartly here, though it's unclear
567 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
568 // only sometimes returns results. In any case remove the previous entry. Note
569 // that the spec expects us to "blacklist" the node_ids involved, but we can't
571 // a) we don't *require* a UTXO provider that always returns results.
572 // b) we don't track UTXOs of channels we know about and remove them if they
574 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
575 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
576 *entry.get_mut() = chan_info;
578 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
581 BtreeEntry::Vacant(entry) => {
582 entry.insert(chan_info);
586 macro_rules! add_channel_to_node {
587 ( $node_id: expr ) => {
588 match self.nodes.entry($node_id) {
589 BtreeEntry::Occupied(node_entry) => {
590 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
592 BtreeEntry::Vacant(node_entry) => {
593 node_entry.insert(NodeInfo {
594 channels: vec!(msg.contents.short_channel_id),
595 lowest_inbound_channel_fees: None,
596 features: NodeFeatures::empty(),
600 addresses: Vec::new(),
601 announcement_message: None,
608 add_channel_to_node!(msg.contents.node_id_1);
609 add_channel_to_node!(msg.contents.node_id_2);
614 /// Close a channel if a corresponding HTLC fail was sent.
615 /// If permanent, removes a channel from the local storage.
616 /// May cause the removal of nodes too, if this was their last channel.
617 /// If not permanent, makes channels unavailable for routing.
618 pub fn close_channel_from_update(&mut self, short_channel_id: &u64, is_permanent: &bool) {
620 if let Some(chan) = self.channels.remove(short_channel_id) {
621 Self::remove_channel_in_nodes(&mut self.nodes, &chan, *short_channel_id);
624 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
625 chan.one_to_two.enabled = false;
626 chan.two_to_one.enabled = false;
631 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
633 // TODO: Wholly remove the node
635 // TODO: downgrade the node
639 /// For an already known (from announcement) channel, update info regarding one of the directions of a channel.
640 /// Announcement signatures are checked here only if Secp256k1 object is provided.
641 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
643 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
644 let chan_was_enabled;
646 match self.channels.get_mut(&msg.contents.short_channel_id) {
647 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
649 macro_rules! maybe_update_channel_info {
650 ( $target: expr) => {
651 if $target.last_update >= msg.contents.timestamp {
652 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
654 chan_was_enabled = $target.enabled;
655 $target.last_update = msg.contents.timestamp;
656 $target.enabled = chan_enabled;
657 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
658 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
659 $target.fees.base_msat = msg.contents.fee_base_msat;
660 $target.fees.proportional_millionths = msg.contents.fee_proportional_millionths;
661 $target.last_update_message = if msg.contents.excess_data.is_empty() {
668 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
669 if msg.contents.flags & 1 == 1 {
670 dest_node_id = channel.one_to_two.src_node_id.clone();
671 if let Some(sig_verifier) = secp_ctx {
672 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
674 maybe_update_channel_info!(channel.two_to_one);
676 dest_node_id = channel.two_to_one.src_node_id.clone();
677 if let Some(sig_verifier) = secp_ctx {
678 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
680 maybe_update_channel_info!(channel.one_to_two);
686 let node = self.nodes.get_mut(&dest_node_id).unwrap();
687 let mut base_msat = msg.contents.fee_base_msat;
688 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
689 if let Some(fees) = node.lowest_inbound_channel_fees {
690 base_msat = cmp::min(base_msat, fees.base_msat);
691 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
693 node.lowest_inbound_channel_fees = Some(RoutingFees {
695 proportional_millionths
697 } else if chan_was_enabled {
698 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
699 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
702 let node = self.nodes.get(&dest_node_id).unwrap();
704 for chan_id in node.channels.iter() {
705 let chan = self.channels.get(chan_id).unwrap();
706 if chan.one_to_two.src_node_id == dest_node_id {
707 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fees.base_msat);
708 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fees.proportional_millionths);
710 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fees.base_msat);
711 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.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)!");
744 remove_from_node!(chan.one_to_two.src_node_id);
745 remove_from_node!(chan.two_to_one.src_node_id);
751 use chain::chaininterface;
752 use ln::features::{ChannelFeatures, NodeFeatures};
753 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
754 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
755 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
756 use util::test_utils;
757 use util::logger::Logger;
758 use util::ser::{Readable, Writeable};
760 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
761 use bitcoin::hashes::Hash;
762 use bitcoin::network::constants::Network;
763 use bitcoin::blockdata::constants::genesis_block;
764 use bitcoin::blockdata::script::Builder;
765 use bitcoin::blockdata::opcodes;
766 use bitcoin::util::hash::BitcoinHash;
770 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
771 use bitcoin::secp256k1::{All, Secp256k1};
775 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
776 let secp_ctx = Secp256k1::new();
777 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
778 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
779 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
780 (secp_ctx, net_graph_msg_handler)
784 fn request_full_sync_finite_times() {
785 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
786 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
788 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
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));
797 fn handling_node_announcements() {
798 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
800 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
801 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
802 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
803 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
804 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
805 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
806 let zero_hash = Sha256dHash::hash(&[0; 32]);
807 let first_announcement_time = 500;
809 let mut unsigned_announcement = UnsignedNodeAnnouncement {
810 features: NodeFeatures::known(),
811 timestamp: first_announcement_time,
815 addresses: Vec::new(),
816 excess_address_data: Vec::new(),
817 excess_data: Vec::new(),
819 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
820 let valid_announcement = NodeAnnouncement {
821 signature: secp_ctx.sign(&msghash, node_1_privkey),
822 contents: unsigned_announcement.clone()
825 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
827 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
831 // Announce a channel to add a corresponding node.
832 let unsigned_announcement = UnsignedChannelAnnouncement {
833 features: ChannelFeatures::known(),
834 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
838 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
839 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
840 excess_data: Vec::new(),
843 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
844 let valid_announcement = ChannelAnnouncement {
845 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
846 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
847 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
848 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
849 contents: unsigned_announcement.clone(),
851 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
852 Ok(res) => assert!(res),
857 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
858 Ok(res) => assert!(res),
862 let fake_msghash = hash_to_message!(&zero_hash);
863 match net_graph_msg_handler.handle_node_announcement(
865 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
866 contents: unsigned_announcement.clone()
869 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
872 unsigned_announcement.timestamp += 1000;
873 unsigned_announcement.excess_data.push(1);
874 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
875 let announcement_with_data = NodeAnnouncement {
876 signature: secp_ctx.sign(&msghash, node_1_privkey),
877 contents: unsigned_announcement.clone()
879 // Return false because contains excess data.
880 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
881 Ok(res) => assert!(!res),
884 unsigned_announcement.excess_data = Vec::new();
886 // Even though previous announcement was not relayed further, we still accepted it,
887 // so we now won't accept announcements before the previous one.
888 unsigned_announcement.timestamp -= 10;
889 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
890 let outdated_announcement = NodeAnnouncement {
891 signature: secp_ctx.sign(&msghash, node_1_privkey),
892 contents: unsigned_announcement.clone()
894 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
896 Err(e) => assert_eq!(e.err, "Update older than last processed update")
901 fn handling_channel_announcements() {
902 let secp_ctx = Secp256k1::new();
903 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
904 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
905 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
908 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
909 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
910 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
911 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
912 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
913 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
915 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
916 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
917 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
918 .push_opcode(opcodes::all::OP_PUSHNUM_2)
919 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
922 let mut unsigned_announcement = UnsignedChannelAnnouncement {
923 features: ChannelFeatures::known(),
924 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
928 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
929 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
930 excess_data: Vec::new(),
933 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
934 let valid_announcement = ChannelAnnouncement {
935 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
936 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
937 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
938 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
939 contents: unsigned_announcement.clone(),
942 // Test if the UTXO lookups were not supported
943 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
945 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
946 Ok(res) => assert!(res),
951 let network = net_graph_msg_handler.network_graph.read().unwrap();
952 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
959 // If we receive announcement for the same channel (with UTXO lookups disabled),
960 // drop new one on the floor, since we can't see any changes.
961 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
963 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
967 // Test if an associated transaction were not on-chain (or not confirmed).
968 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
969 unsigned_announcement.short_channel_id += 1;
971 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
972 let valid_announcement = ChannelAnnouncement {
973 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
974 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
975 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
976 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
977 contents: unsigned_announcement.clone(),
980 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
982 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
986 // Now test if the transaction is found in the UTXO set and the script is correct.
987 unsigned_announcement.short_channel_id += 1;
988 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
990 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
991 let valid_announcement = ChannelAnnouncement {
992 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
993 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
994 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
995 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
996 contents: unsigned_announcement.clone(),
998 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
999 Ok(res) => assert!(res),
1004 let network = net_graph_msg_handler.network_graph.read().unwrap();
1005 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1011 // If we receive announcement for the same channel (but TX is not confirmed),
1012 // drop new one on the floor, since we can't see any changes.
1013 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1014 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1016 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1019 // But if it is confirmed, replace the channel
1020 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1021 unsigned_announcement.features = ChannelFeatures::empty();
1022 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1023 let valid_announcement = ChannelAnnouncement {
1024 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1025 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1026 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1027 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1028 contents: unsigned_announcement.clone(),
1030 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1031 Ok(res) => assert!(res),
1035 let network = net_graph_msg_handler.network_graph.read().unwrap();
1036 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1037 Some(channel_entry) => {
1038 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1044 // Don't relay valid channels with excess data
1045 unsigned_announcement.short_channel_id += 1;
1046 unsigned_announcement.excess_data.push(1);
1047 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1048 let valid_announcement = ChannelAnnouncement {
1049 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1050 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1051 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1052 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1053 contents: unsigned_announcement.clone(),
1055 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1056 Ok(res) => assert!(!res),
1060 unsigned_announcement.excess_data = Vec::new();
1061 let invalid_sig_announcement = ChannelAnnouncement {
1062 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1063 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1064 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1065 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1066 contents: unsigned_announcement.clone(),
1068 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1070 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1073 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1074 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1075 let channel_to_itself_announcement = ChannelAnnouncement {
1076 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1077 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1078 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1079 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1080 contents: unsigned_announcement.clone(),
1082 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1084 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1089 fn handling_channel_update() {
1090 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1091 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1092 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1093 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1094 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1095 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1096 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1098 let zero_hash = Sha256dHash::hash(&[0; 32]);
1099 let short_channel_id = 0;
1100 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1102 // Announce a channel we will update
1103 let unsigned_announcement = UnsignedChannelAnnouncement {
1104 features: ChannelFeatures::empty(),
1109 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1110 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1111 excess_data: Vec::new(),
1114 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1115 let valid_channel_announcement = ChannelAnnouncement {
1116 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1117 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1118 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1119 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1120 contents: unsigned_announcement.clone(),
1122 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1129 let mut unsigned_channel_update = UnsignedChannelUpdate {
1134 cltv_expiry_delta: 144,
1135 htlc_minimum_msat: 1000000,
1136 fee_base_msat: 10000,
1137 fee_proportional_millionths: 20,
1138 excess_data: Vec::new()
1140 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1141 let valid_channel_update = ChannelUpdate {
1142 signature: secp_ctx.sign(&msghash, node_1_privkey),
1143 contents: unsigned_channel_update.clone()
1146 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1147 Ok(res) => assert!(res),
1152 let network = net_graph_msg_handler.network_graph.read().unwrap();
1153 match network.get_channels().get(&short_channel_id) {
1155 Some(channel_info) => {
1156 assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
1157 assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
1162 unsigned_channel_update.timestamp += 100;
1163 unsigned_channel_update.excess_data.push(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()
1169 // Return false because contains excess data
1170 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1171 Ok(res) => assert!(!res),
1175 unsigned_channel_update.short_channel_id += 1;
1176 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1177 let valid_channel_update = ChannelUpdate {
1178 signature: secp_ctx.sign(&msghash, node_1_privkey),
1179 contents: unsigned_channel_update.clone()
1182 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1184 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1186 unsigned_channel_update.short_channel_id = short_channel_id;
1189 // Even though previous update was not relayed further, we still accepted it,
1190 // so we now won't accept update before the previous one.
1191 unsigned_channel_update.timestamp -= 10;
1192 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1193 let valid_channel_update = ChannelUpdate {
1194 signature: secp_ctx.sign(&msghash, node_1_privkey),
1195 contents: unsigned_channel_update.clone()
1198 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1200 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1202 unsigned_channel_update.timestamp += 500;
1204 let fake_msghash = hash_to_message!(&zero_hash);
1205 let invalid_sig_channel_update = ChannelUpdate {
1206 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1207 contents: unsigned_channel_update.clone()
1210 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1212 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1218 fn handling_htlc_fail_channel_update() {
1219 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1220 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1221 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1222 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1223 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1224 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1225 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1227 let short_channel_id = 0;
1228 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1231 // There is no nodes in the table at the beginning.
1232 let network = net_graph_msg_handler.network_graph.read().unwrap();
1233 assert_eq!(network.get_nodes().len(), 0);
1237 // Announce a channel we will update
1238 let unsigned_announcement = UnsignedChannelAnnouncement {
1239 features: ChannelFeatures::empty(),
1244 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1245 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1246 excess_data: Vec::new(),
1249 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1250 let valid_channel_announcement = ChannelAnnouncement {
1251 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1252 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1253 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1254 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1255 contents: unsigned_announcement.clone(),
1257 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1264 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1269 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1271 // Non-permanent closing just disables a channel
1273 let network = net_graph_msg_handler.network_graph.read().unwrap();
1274 match network.get_channels().get(&short_channel_id) {
1276 Some(channel_info) => {
1277 assert!(!channel_info.one_to_two.enabled);
1278 assert!(!channel_info.two_to_one.enabled);
1283 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1288 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1290 // Permanent closing deletes a channel
1292 let network = net_graph_msg_handler.network_graph.read().unwrap();
1293 assert_eq!(network.get_channels().len(), 0);
1294 // Nodes are also deleted because there are no associated channels anymore
1295 assert_eq!(network.get_nodes().len(), 0);
1297 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1301 fn getting_next_channel_announcements() {
1302 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1303 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1304 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1305 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1306 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1307 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1308 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1310 let short_channel_id = 1;
1311 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1313 // Channels were not announced yet.
1314 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1315 assert_eq!(channels_with_announcements.len(), 0);
1318 // Announce a channel we will update
1319 let unsigned_announcement = UnsignedChannelAnnouncement {
1320 features: ChannelFeatures::empty(),
1325 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1326 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1327 excess_data: Vec::new(),
1330 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1331 let valid_channel_announcement = ChannelAnnouncement {
1332 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1333 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1334 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1335 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1336 contents: unsigned_announcement.clone(),
1338 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1344 // Contains initial channel announcement now.
1345 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1346 assert_eq!(channels_with_announcements.len(), 1);
1347 if let Some(channel_announcements) = channels_with_announcements.first() {
1348 let &(_, ref update_1, ref update_2) = channel_announcements;
1349 assert_eq!(update_1, &None);
1350 assert_eq!(update_2, &None);
1357 // Valid channel update
1358 let unsigned_channel_update = UnsignedChannelUpdate {
1363 cltv_expiry_delta: 144,
1364 htlc_minimum_msat: 1000000,
1365 fee_base_msat: 10000,
1366 fee_proportional_millionths: 20,
1367 excess_data: Vec::new()
1369 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1370 let valid_channel_update = ChannelUpdate {
1371 signature: secp_ctx.sign(&msghash, node_1_privkey),
1372 contents: unsigned_channel_update.clone()
1374 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1380 // Now contains an initial announcement and an update.
1381 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1382 assert_eq!(channels_with_announcements.len(), 1);
1383 if let Some(channel_announcements) = channels_with_announcements.first() {
1384 let &(_, ref update_1, ref update_2) = channel_announcements;
1385 assert_ne!(update_1, &None);
1386 assert_eq!(update_2, &None);
1393 // Channel update with excess data.
1394 let unsigned_channel_update = UnsignedChannelUpdate {
1399 cltv_expiry_delta: 144,
1400 htlc_minimum_msat: 1000000,
1401 fee_base_msat: 10000,
1402 fee_proportional_millionths: 20,
1403 excess_data: [1; 3].to_vec()
1405 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1406 let valid_channel_update = ChannelUpdate {
1407 signature: secp_ctx.sign(&msghash, node_1_privkey),
1408 contents: unsigned_channel_update.clone()
1410 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1416 // Test that announcements with excess data won't be returned
1417 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1418 assert_eq!(channels_with_announcements.len(), 1);
1419 if let Some(channel_announcements) = channels_with_announcements.first() {
1420 let &(_, ref update_1, ref update_2) = channel_announcements;
1421 assert_eq!(update_1, &None);
1422 assert_eq!(update_2, &None);
1427 // Further starting point have no channels after it
1428 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1429 assert_eq!(channels_with_announcements.len(), 0);
1433 fn getting_next_node_announcements() {
1434 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1435 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1436 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1437 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1438 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1439 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1440 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1442 let short_channel_id = 1;
1443 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1446 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1447 assert_eq!(next_announcements.len(), 0);
1450 // Announce a channel to add 2 nodes
1451 let unsigned_announcement = UnsignedChannelAnnouncement {
1452 features: ChannelFeatures::empty(),
1457 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1458 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1459 excess_data: Vec::new(),
1462 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1463 let valid_channel_announcement = ChannelAnnouncement {
1464 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1465 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1466 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1467 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1468 contents: unsigned_announcement.clone(),
1470 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1477 // Nodes were never announced
1478 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1479 assert_eq!(next_announcements.len(), 0);
1482 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1483 features: NodeFeatures::known(),
1488 addresses: Vec::new(),
1489 excess_address_data: Vec::new(),
1490 excess_data: Vec::new(),
1492 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1493 let valid_announcement = NodeAnnouncement {
1494 signature: secp_ctx.sign(&msghash, node_1_privkey),
1495 contents: unsigned_announcement.clone()
1497 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1502 unsigned_announcement.node_id = node_id_2;
1503 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1504 let valid_announcement = NodeAnnouncement {
1505 signature: secp_ctx.sign(&msghash, node_2_privkey),
1506 contents: unsigned_announcement.clone()
1509 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1515 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1516 assert_eq!(next_announcements.len(), 2);
1518 // Skip the first node.
1519 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1520 assert_eq!(next_announcements.len(), 1);
1523 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1524 let unsigned_announcement = UnsignedNodeAnnouncement {
1525 features: NodeFeatures::known(),
1530 addresses: Vec::new(),
1531 excess_address_data: Vec::new(),
1532 excess_data: [1; 3].to_vec(),
1534 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1535 let valid_announcement = NodeAnnouncement {
1536 signature: secp_ctx.sign(&msghash, node_2_privkey),
1537 contents: unsigned_announcement.clone()
1539 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1540 Ok(res) => assert!(!res),
1545 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1546 assert_eq!(next_announcements.len(), 0);
1550 fn network_graph_serialization() {
1551 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1553 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1554 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1555 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1556 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1558 // Announce a channel to add a corresponding node.
1559 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1560 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1561 let unsigned_announcement = UnsignedChannelAnnouncement {
1562 features: ChannelFeatures::known(),
1563 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1564 short_channel_id: 0,
1567 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1568 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1569 excess_data: Vec::new(),
1572 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1573 let valid_announcement = ChannelAnnouncement {
1574 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1575 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1576 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1577 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1578 contents: unsigned_announcement.clone(),
1580 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1581 Ok(res) => assert!(res),
1586 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1587 let unsigned_announcement = UnsignedNodeAnnouncement {
1588 features: NodeFeatures::known(),
1593 addresses: Vec::new(),
1594 excess_address_data: Vec::new(),
1595 excess_data: Vec::new(),
1597 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1598 let valid_announcement = NodeAnnouncement {
1599 signature: secp_ctx.sign(&msghash, node_1_privkey),
1600 contents: unsigned_announcement.clone()
1603 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1608 let network = net_graph_msg_handler.network_graph.write().unwrap();
1609 let mut w = test_utils::TestVecWriter(Vec::new());
1610 assert!(!network.get_nodes().is_empty());
1611 assert!(!network.get_channels().is_empty());
1612 network.write(&mut w).unwrap();
1613 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);