1 //! The top-level network map tracking logic lives here.
3 use bitcoin::secp256k1::key::PublicKey;
4 use bitcoin::secp256k1::Secp256k1;
5 use bitcoin::secp256k1;
7 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
8 use bitcoin::hashes::Hash;
9 use bitcoin::blockdata::script::Builder;
10 use bitcoin::blockdata::opcodes;
12 use chain::chaininterface::{ChainError, ChainWatchInterface};
13 use ln::features::{ChannelFeatures, NodeFeatures};
14 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress};
16 use util::ser::{Writeable, Readable, Writer};
17 use util::logger::Logger;
20 use std::sync::{RwLock,Arc};
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
26 /// Receives and validates network updates from peers,
27 /// stores authentic and relevant data as a network graph.
28 /// This network graph is then used for routing payments.
29 /// Provides interface to help with initial routing sync by
30 /// serving historical announcements.
31 pub struct NetGraphMsgHandler {
32 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
33 /// Representation of the payment channel network
34 pub network_graph: RwLock<NetworkGraph>,
35 chain_monitor: Arc<ChainWatchInterface>,
36 full_syncs_requested: AtomicUsize,
40 impl NetGraphMsgHandler {
41 /// Creates a new tracker of the actual state of the network of channels and nodes,
42 /// assuming a fresh network graph.
43 /// Chain monitor is used to make sure announced channels exist on-chain,
44 /// channel data is correct, and that the announcement is signed with
45 /// channel owners' keys.
46 pub fn new(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Self {
48 secp_ctx: Secp256k1::verification_only(),
49 network_graph: RwLock::new(NetworkGraph {
50 channels: BTreeMap::new(),
51 nodes: BTreeMap::new(),
53 full_syncs_requested: AtomicUsize::new(0),
55 logger: logger.clone(),
59 /// Creates a new tracker of the actual state of the network of channels and nodes,
60 /// assuming an existing Network Graph.
61 pub fn from_net_graph(chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>, network_graph: RwLock<NetworkGraph>) -> Self {
63 secp_ctx: Secp256k1::verification_only(),
64 network_graph: network_graph,
65 full_syncs_requested: AtomicUsize::new(0),
67 logger: logger.clone(),
73 macro_rules! secp_verify_sig {
74 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
75 match $secp_ctx.verify($msg, $sig, $pubkey) {
77 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
82 impl RoutingMessageHandler for NetGraphMsgHandler {
83 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
84 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
87 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
88 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
89 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
92 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
93 Ok((script_pubkey, _value)) => {
94 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
95 .push_slice(&msg.contents.bitcoin_key_1.serialize())
96 .push_slice(&msg.contents.bitcoin_key_2.serialize())
97 .push_opcode(opcodes::all::OP_PUSHNUM_2)
98 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
99 if script_pubkey != expected_script {
100 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
102 //TODO: Check if value is worth storing, use it to inform routing, and compare it
103 //to the new HTLC max field in channel_update
106 Err(ChainError::NotSupported) => {
107 // Tentatively accept, potentially exposing us to DoS attacks
110 Err(ChainError::NotWatched) => {
111 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
113 Err(ChainError::UnknownTx) => {
114 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
117 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, checked_utxo, Some(&self.secp_ctx));
118 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
122 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
124 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
125 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
127 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
128 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, &is_permanent);
130 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
131 self.network_graph.write().unwrap().fail_node(node_id, &is_permanent);
136 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
137 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
140 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
141 let network_graph = self.network_graph.read().unwrap();
142 let mut result = Vec::with_capacity(batch_amount as usize);
143 let mut iter = network_graph.get_channels().range(starting_point..);
144 while result.len() < batch_amount as usize {
145 if let Some((_, ref chan)) = iter.next() {
146 if chan.announcement_message.is_some() {
147 let chan_announcement = chan.announcement_message.clone().unwrap();
148 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
149 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
150 if let Some(one_to_two) = chan.one_to_two.as_ref() {
151 one_to_two_announcement = one_to_two.last_update_message.clone();
153 if let Some(two_to_one) = chan.two_to_one.as_ref() {
154 two_to_one_announcement = two_to_one.last_update_message.clone();
156 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
158 // TODO: We may end up sending un-announced channel_updates if we are sending
159 // initial sync data while receiving announce/updates for this channel.
168 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
169 let network_graph = self.network_graph.read().unwrap();
170 let mut result = Vec::with_capacity(batch_amount as usize);
171 let mut iter = if let Some(pubkey) = starting_point {
172 let mut iter = network_graph.get_nodes().range((*pubkey)..);
176 network_graph.get_nodes().range(..)
178 while result.len() < batch_amount as usize {
179 if let Some((_, ref node)) = iter.next() {
180 if let Some(node_info) = node.announcement_info.as_ref() {
181 if node_info.announcement_message.is_some() {
182 result.push(node_info.announcement_message.clone().unwrap());
192 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
193 //TODO: Determine whether to request a full sync based on the network map.
194 const FULL_SYNCS_TO_REQUEST: usize = 5;
195 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
196 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
204 #[derive(PartialEq, Debug)]
205 /// Details about one direction of a channel. Received
206 /// within a channel update.
207 pub struct DirectionalChannelInfo {
208 /// When the last update to the channel direction was issued.
209 /// Value is opaque, as set in the announcement.
210 pub last_update: u32,
211 /// Whether the channel can be currently used for payments (in this one direction).
213 /// The difference in CLTV values that you must have when routing through this channel.
214 pub cltv_expiry_delta: u16,
215 /// The minimum value, which must be relayed to the next hop via the channel
216 pub htlc_minimum_msat: u64,
217 /// Fees charged when the channel is used for routing
218 pub fees: RoutingFees,
219 /// Most recent update for the channel received from the network
220 /// Mostly redundant with the data we store in fields explicitly.
221 /// Everything else is useful only for sending out for initial routing sync.
222 /// Not stored if contains excess data to prevent DoS.
223 pub last_update_message: Option<msgs::ChannelUpdate>,
226 impl std::fmt::Display for DirectionalChannelInfo {
227 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
228 write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
233 impl_writeable!(DirectionalChannelInfo, 0, {
243 /// Details about a channel (both directions).
244 /// Received within a channel announcement.
245 pub struct ChannelInfo {
246 /// Protocol features of a channel communicated during its announcement
247 pub features: ChannelFeatures,
248 /// Source node of the first direction of a channel
249 pub node_one: PublicKey,
250 /// Details about the first direction of a channel
251 pub one_to_two: Option<DirectionalChannelInfo>,
252 /// Source node of the second direction of a channel
253 pub node_two: PublicKey,
254 /// Details about the second direction of a channel
255 pub two_to_one: Option<DirectionalChannelInfo>,
256 /// An initial announcement of the channel
257 /// Mostly redundant with the data we store in fields explicitly.
258 /// Everything else is useful only for sending out for initial routing sync.
259 /// Not stored if contains excess data to prevent DoS.
260 pub announcement_message: Option<msgs::ChannelAnnouncement>,
263 impl std::fmt::Display for ChannelInfo {
264 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
265 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
266 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
271 impl_writeable!(ChannelInfo, 0, {
281 /// Fees for routing via a given channel or a node
282 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
283 pub struct RoutingFees {
284 /// Flat routing fee in satoshis
286 /// Liquidity-based routing fee in millionths of a routed amount.
287 /// In other words, 10000 is 1%.
288 pub proportional_millionths: u32,
291 impl Readable for RoutingFees{
292 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
293 let base_msat: u32 = Readable::read(reader)?;
294 let proportional_millionths: u32 = Readable::read(reader)?;
297 proportional_millionths,
302 impl Writeable for RoutingFees {
303 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
304 self.base_msat.write(writer)?;
305 self.proportional_millionths.write(writer)?;
310 #[derive(PartialEq, Debug)]
311 /// Information received in the latest node_announcement from this node.
312 pub struct NodeAnnouncementInfo {
313 /// Protocol features the node announced support for
314 pub features: NodeFeatures,
315 /// When the last known update to the node state was issued.
316 /// Value is opaque, as set in the announcement.
317 pub last_update: u32,
318 /// Color assigned to the node
320 /// Moniker assigned to the node.
321 /// May be invalid or malicious (eg control chars),
322 /// should not be exposed to the user.
324 /// Internet-level addresses via which one can connect to the node
325 pub addresses: Vec<NetAddress>,
326 /// An initial announcement of the node
327 /// Mostly redundant with the data we store in fields explicitly.
328 /// Everything else is useful only for sending out for initial routing sync.
329 /// Not stored if contains excess data to prevent DoS.
330 pub announcement_message: Option<msgs::NodeAnnouncement>
333 impl Writeable for NodeAnnouncementInfo {
334 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
335 self.features.write(writer)?;
336 self.last_update.write(writer)?;
337 self.rgb.write(writer)?;
338 self.alias.write(writer)?;
339 (self.addresses.len() as u64).write(writer)?;
340 for ref addr in &self.addresses {
343 self.announcement_message.write(writer)?;
348 impl Readable for NodeAnnouncementInfo {
349 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
350 let features = Readable::read(reader)?;
351 let last_update = Readable::read(reader)?;
352 let rgb = Readable::read(reader)?;
353 let alias = Readable::read(reader)?;
354 let addresses_count: u64 = Readable::read(reader)?;
355 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
356 for _ in 0..addresses_count {
357 match Readable::read(reader) {
358 Ok(Ok(addr)) => { addresses.push(addr); },
359 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
360 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
364 let announcement_message = Readable::read(reader)?;
365 Ok(NodeAnnouncementInfo {
377 /// Details about a node in the network, known from the network announcement.
378 pub struct NodeInfo {
379 /// All valid channels a node has announced
380 pub channels: Vec<u64>,
381 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
382 /// The two fields (flat and proportional fee) are independent,
383 /// meaning they don't have to refer to the same channel.
384 pub lowest_inbound_channel_fees: Option<RoutingFees>,
385 /// More information about a node from node_announcement.
386 /// Optional because we store a Node entry after learning about it from
387 /// a channel announcement, but before receiving a node announcement.
388 pub announcement_info: Option<NodeAnnouncementInfo>
391 impl std::fmt::Display for NodeInfo {
392 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
393 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
394 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
399 impl Writeable for NodeInfo {
400 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
401 (self.channels.len() as u64).write(writer)?;
402 for ref chan in self.channels.iter() {
405 self.lowest_inbound_channel_fees.write(writer)?;
406 self.announcement_info.write(writer)?;
411 const MAX_ALLOC_SIZE: u64 = 64*1024;
413 impl Readable for NodeInfo {
414 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
415 let channels_count: u64 = Readable::read(reader)?;
416 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
417 for _ in 0..channels_count {
418 channels.push(Readable::read(reader)?);
420 let lowest_inbound_channel_fees = Readable::read(reader)?;
421 let announcement_info = Readable::read(reader)?;
424 lowest_inbound_channel_fees,
430 /// Represents the network as nodes and channels between them
432 pub struct NetworkGraph {
433 channels: BTreeMap<u64, ChannelInfo>,
434 nodes: BTreeMap<PublicKey, NodeInfo>,
437 impl Writeable for NetworkGraph {
438 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
439 (self.channels.len() as u64).write(writer)?;
440 for (ref chan_id, ref chan_info) in self.channels.iter() {
441 (*chan_id).write(writer)?;
442 chan_info.write(writer)?;
444 (self.nodes.len() as u64).write(writer)?;
445 for (ref node_id, ref node_info) in self.nodes.iter() {
446 node_id.write(writer)?;
447 node_info.write(writer)?;
453 impl Readable for NetworkGraph {
454 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
455 let channels_count: u64 = Readable::read(reader)?;
456 let mut channels = BTreeMap::new();
457 for _ in 0..channels_count {
458 let chan_id: u64 = Readable::read(reader)?;
459 let chan_info = Readable::read(reader)?;
460 channels.insert(chan_id, chan_info);
462 let nodes_count: u64 = Readable::read(reader)?;
463 let mut nodes = BTreeMap::new();
464 for _ in 0..nodes_count {
465 let node_id = Readable::read(reader)?;
466 let node_info = Readable::read(reader)?;
467 nodes.insert(node_id, node_info);
476 impl std::fmt::Display for NetworkGraph {
477 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
478 write!(f, "Network map\n[Channels]\n")?;
479 for (key, val) in self.channels.iter() {
480 write!(f, " {}: {}\n", key, val)?;
482 write!(f, "[Nodes]\n")?;
483 for (key, val) in self.nodes.iter() {
484 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
491 /// Returns all known valid channels' short ids along with announced channel info.
492 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
493 /// Returns all known nodes' public keys along with announced node info.
494 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
496 /// Get network addresses by node id.
497 /// Returns None if the requested node is completely unknown,
498 /// or if node announcement for the node was never received.
499 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
500 if let Some(node) = self.nodes.get(pubkey) {
501 if let Some(node_info) = node.announcement_info.as_ref() {
502 return Some(&node_info.addresses)
508 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
509 /// Announcement signatures are checked here only if Secp256k1 object is provided.
510 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
511 if let Some(sig_verifier) = secp_ctx {
512 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
513 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
516 match self.nodes.get_mut(&msg.contents.node_id) {
517 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
519 if let Some(node_info) = node.announcement_info.as_ref() {
520 if node_info.last_update >= msg.contents.timestamp {
521 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
525 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
526 node.announcement_info = Some(NodeAnnouncementInfo {
527 features: msg.contents.features.clone(),
528 last_update: msg.contents.timestamp,
529 rgb: msg.contents.rgb,
530 alias: msg.contents.alias,
531 addresses: msg.contents.addresses.clone(),
532 announcement_message: if should_relay { Some(msg.clone()) } else { None },
540 /// For a new or already known (from previous announcement) channel, store or update channel info.
541 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
542 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
543 /// which is probably result of a reorg. In that case, we update channel info only if the
544 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
545 /// Announcement signatures are checked here only if Secp256k1 object is provided.
546 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, checked_utxo: bool, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
547 if let Some(sig_verifier) = secp_ctx {
548 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
549 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
550 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
551 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
552 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
555 let should_relay = msg.contents.excess_data.is_empty();
557 let chan_info = ChannelInfo {
558 features: msg.contents.features.clone(),
559 node_one: msg.contents.node_id_1.clone(),
561 node_two: msg.contents.node_id_2.clone(),
563 announcement_message: if should_relay { Some(msg.clone()) } else { None },
566 match self.channels.entry(msg.contents.short_channel_id) {
567 BtreeEntry::Occupied(mut entry) => {
568 //TODO: because asking the blockchain if short_channel_id is valid is only optional
569 //in the blockchain API, we need to handle it smartly here, though it's unclear
572 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
573 // only sometimes returns results. In any case remove the previous entry. Note
574 // that the spec expects us to "blacklist" the node_ids involved, but we can't
576 // a) we don't *require* a UTXO provider that always returns results.
577 // b) we don't track UTXOs of channels we know about and remove them if they
579 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
580 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
581 *entry.get_mut() = chan_info;
583 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
586 BtreeEntry::Vacant(entry) => {
587 entry.insert(chan_info);
591 macro_rules! add_channel_to_node {
592 ( $node_id: expr ) => {
593 match self.nodes.entry($node_id) {
594 BtreeEntry::Occupied(node_entry) => {
595 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
597 BtreeEntry::Vacant(node_entry) => {
598 node_entry.insert(NodeInfo {
599 channels: vec!(msg.contents.short_channel_id),
600 lowest_inbound_channel_fees: None,
601 announcement_info: 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 if let Some(one_to_two) = chan.one_to_two.as_mut() {
626 one_to_two.enabled = false;
628 if let Some(two_to_one) = chan.two_to_one.as_mut() {
629 two_to_one.enabled = false;
635 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: &bool) {
637 // TODO: Wholly remove the node
639 // TODO: downgrade the node
643 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
644 /// Announcement signatures are checked here only if Secp256k1 object is provided.
645 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
647 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
648 let chan_was_enabled;
650 match self.channels.get_mut(&msg.contents.short_channel_id) {
651 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
653 macro_rules! maybe_update_channel_info {
654 ( $target: expr, $src_node: expr) => {
655 if let Some(existing_chan_info) = $target.as_ref() {
656 if existing_chan_info.last_update >= msg.contents.timestamp {
657 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
659 chan_was_enabled = existing_chan_info.enabled;
661 chan_was_enabled = false;
664 let last_update_message = if msg.contents.excess_data.is_empty() {
670 let updated_channel_dir_info = DirectionalChannelInfo {
671 enabled: chan_enabled,
672 last_update: msg.contents.timestamp,
673 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
674 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
676 base_msat: msg.contents.fee_base_msat,
677 proportional_millionths: msg.contents.fee_proportional_millionths,
681 $target = Some(updated_channel_dir_info);
685 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
686 if msg.contents.flags & 1 == 1 {
687 dest_node_id = channel.node_one.clone();
688 if let Some(sig_verifier) = secp_ctx {
689 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
691 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
693 dest_node_id = channel.node_two.clone();
694 if let Some(sig_verifier) = secp_ctx {
695 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
697 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
703 let node = self.nodes.get_mut(&dest_node_id).unwrap();
704 let mut base_msat = msg.contents.fee_base_msat;
705 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
706 if let Some(fees) = node.lowest_inbound_channel_fees {
707 base_msat = cmp::min(base_msat, fees.base_msat);
708 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
710 node.lowest_inbound_channel_fees = Some(RoutingFees {
712 proportional_millionths
714 } else if chan_was_enabled {
715 let mut node = self.nodes.get_mut(&dest_node_id).unwrap();
716 let mut lowest_inbound_channel_fees = None;
718 for chan_id in node.channels.iter() {
719 let chan = self.channels.get(chan_id).unwrap();
721 if chan.node_one == dest_node_id {
722 chan_info_opt = chan.two_to_one.as_ref();
724 chan_info_opt = chan.one_to_two.as_ref();
726 if let Some(chan_info) = chan_info_opt {
727 if chan_info.enabled {
728 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
729 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
730 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
731 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
736 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
739 Ok(msg.contents.excess_data.is_empty())
742 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
743 macro_rules! remove_from_node {
744 ($node_id: expr) => {
745 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
746 entry.get_mut().channels.retain(|chan_id| {
747 short_channel_id != *chan_id
749 if entry.get().channels.is_empty() {
750 entry.remove_entry();
753 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
758 remove_from_node!(chan.node_one);
759 remove_from_node!(chan.node_two);
765 use chain::chaininterface;
766 use ln::features::{ChannelFeatures, NodeFeatures};
767 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
768 use ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
769 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
770 use util::test_utils;
771 use util::logger::Logger;
772 use util::ser::{Readable, Writeable};
774 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
775 use bitcoin::hashes::Hash;
776 use bitcoin::network::constants::Network;
777 use bitcoin::blockdata::constants::genesis_block;
778 use bitcoin::blockdata::script::Builder;
779 use bitcoin::blockdata::opcodes;
780 use bitcoin::util::hash::BitcoinHash;
784 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
785 use bitcoin::secp256k1::{All, Secp256k1};
789 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler) {
790 let secp_ctx = Secp256k1::new();
791 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
792 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
793 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
794 (secp_ctx, net_graph_msg_handler)
798 fn request_full_sync_finite_times() {
799 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
800 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
802 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
803 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
804 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
805 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
806 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
807 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
811 fn handling_node_announcements() {
812 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
814 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
815 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
816 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
817 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
818 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
819 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
820 let zero_hash = Sha256dHash::hash(&[0; 32]);
821 let first_announcement_time = 500;
823 let mut unsigned_announcement = UnsignedNodeAnnouncement {
824 features: NodeFeatures::known(),
825 timestamp: first_announcement_time,
829 addresses: Vec::new(),
830 excess_address_data: Vec::new(),
831 excess_data: Vec::new(),
833 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
834 let valid_announcement = NodeAnnouncement {
835 signature: secp_ctx.sign(&msghash, node_1_privkey),
836 contents: unsigned_announcement.clone()
839 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
841 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
845 // Announce a channel to add a corresponding node.
846 let unsigned_announcement = UnsignedChannelAnnouncement {
847 features: ChannelFeatures::known(),
848 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
852 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
853 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
854 excess_data: Vec::new(),
857 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
858 let valid_announcement = ChannelAnnouncement {
859 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
860 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
861 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
862 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
863 contents: unsigned_announcement.clone(),
865 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
866 Ok(res) => assert!(res),
871 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
872 Ok(res) => assert!(res),
876 let fake_msghash = hash_to_message!(&zero_hash);
877 match net_graph_msg_handler.handle_node_announcement(
879 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
880 contents: unsigned_announcement.clone()
883 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
886 unsigned_announcement.timestamp += 1000;
887 unsigned_announcement.excess_data.push(1);
888 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
889 let announcement_with_data = NodeAnnouncement {
890 signature: secp_ctx.sign(&msghash, node_1_privkey),
891 contents: unsigned_announcement.clone()
893 // Return false because contains excess data.
894 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
895 Ok(res) => assert!(!res),
898 unsigned_announcement.excess_data = Vec::new();
900 // Even though previous announcement was not relayed further, we still accepted it,
901 // so we now won't accept announcements before the previous one.
902 unsigned_announcement.timestamp -= 10;
903 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
904 let outdated_announcement = NodeAnnouncement {
905 signature: secp_ctx.sign(&msghash, node_1_privkey),
906 contents: unsigned_announcement.clone()
908 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
910 Err(e) => assert_eq!(e.err, "Update older than last processed update")
915 fn handling_channel_announcements() {
916 let secp_ctx = Secp256k1::new();
917 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
918 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
919 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
922 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
923 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
924 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
925 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
926 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
927 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
929 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
930 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
931 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
932 .push_opcode(opcodes::all::OP_PUSHNUM_2)
933 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
936 let mut unsigned_announcement = UnsignedChannelAnnouncement {
937 features: ChannelFeatures::known(),
938 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
942 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
943 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
944 excess_data: Vec::new(),
947 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
948 let valid_announcement = ChannelAnnouncement {
949 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
950 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
951 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
952 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
953 contents: unsigned_announcement.clone(),
956 // Test if the UTXO lookups were not supported
957 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
959 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
960 Ok(res) => assert!(res),
965 let network = net_graph_msg_handler.network_graph.read().unwrap();
966 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
973 // If we receive announcement for the same channel (with UTXO lookups disabled),
974 // drop new one on the floor, since we can't see any changes.
975 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
977 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
981 // Test if an associated transaction were not on-chain (or not confirmed).
982 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
983 unsigned_announcement.short_channel_id += 1;
985 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
986 let valid_announcement = ChannelAnnouncement {
987 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
988 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
989 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
990 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
991 contents: unsigned_announcement.clone(),
994 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
996 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1000 // Now test if the transaction is found in the UTXO set and the script is correct.
1001 unsigned_announcement.short_channel_id += 1;
1002 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1004 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1005 let valid_announcement = ChannelAnnouncement {
1006 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1007 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1008 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1009 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1010 contents: unsigned_announcement.clone(),
1012 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1013 Ok(res) => assert!(res),
1018 let network = net_graph_msg_handler.network_graph.read().unwrap();
1019 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1025 // If we receive announcement for the same channel (but TX is not confirmed),
1026 // drop new one on the floor, since we can't see any changes.
1027 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1028 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1030 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1033 // But if it is confirmed, replace the channel
1034 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1035 unsigned_announcement.features = ChannelFeatures::empty();
1036 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1037 let valid_announcement = ChannelAnnouncement {
1038 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1039 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1040 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1041 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1042 contents: unsigned_announcement.clone(),
1044 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1045 Ok(res) => assert!(res),
1049 let network = net_graph_msg_handler.network_graph.read().unwrap();
1050 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1051 Some(channel_entry) => {
1052 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1058 // Don't relay valid channels with excess data
1059 unsigned_announcement.short_channel_id += 1;
1060 unsigned_announcement.excess_data.push(1);
1061 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1062 let valid_announcement = ChannelAnnouncement {
1063 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1064 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1065 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1066 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1067 contents: unsigned_announcement.clone(),
1069 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1070 Ok(res) => assert!(!res),
1074 unsigned_announcement.excess_data = Vec::new();
1075 let invalid_sig_announcement = ChannelAnnouncement {
1076 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1077 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1078 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1079 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1080 contents: unsigned_announcement.clone(),
1082 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1084 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1087 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1088 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1089 let channel_to_itself_announcement = ChannelAnnouncement {
1090 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1091 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1092 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1093 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1094 contents: unsigned_announcement.clone(),
1096 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1098 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1103 fn handling_channel_update() {
1104 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1105 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1106 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1107 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1108 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1109 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1110 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1112 let zero_hash = Sha256dHash::hash(&[0; 32]);
1113 let short_channel_id = 0;
1114 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1116 // Announce a channel we will update
1117 let unsigned_announcement = UnsignedChannelAnnouncement {
1118 features: ChannelFeatures::empty(),
1123 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1124 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1125 excess_data: Vec::new(),
1128 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1129 let valid_channel_announcement = ChannelAnnouncement {
1130 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1131 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1132 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1133 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1134 contents: unsigned_announcement.clone(),
1136 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1143 let mut unsigned_channel_update = UnsignedChannelUpdate {
1148 cltv_expiry_delta: 144,
1149 htlc_minimum_msat: 1000000,
1150 fee_base_msat: 10000,
1151 fee_proportional_millionths: 20,
1152 excess_data: Vec::new()
1154 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1155 let valid_channel_update = ChannelUpdate {
1156 signature: secp_ctx.sign(&msghash, node_1_privkey),
1157 contents: unsigned_channel_update.clone()
1160 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1161 Ok(res) => assert!(res),
1166 let network = net_graph_msg_handler.network_graph.read().unwrap();
1167 match network.get_channels().get(&short_channel_id) {
1169 Some(channel_info) => {
1170 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1171 assert!(channel_info.two_to_one.is_none());
1176 unsigned_channel_update.timestamp += 100;
1177 unsigned_channel_update.excess_data.push(1);
1178 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1179 let valid_channel_update = ChannelUpdate {
1180 signature: secp_ctx.sign(&msghash, node_1_privkey),
1181 contents: unsigned_channel_update.clone()
1183 // Return false because contains excess data
1184 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1185 Ok(res) => assert!(!res),
1189 unsigned_channel_update.short_channel_id += 1;
1190 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1191 let valid_channel_update = ChannelUpdate {
1192 signature: secp_ctx.sign(&msghash, node_1_privkey),
1193 contents: unsigned_channel_update.clone()
1196 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1198 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1200 unsigned_channel_update.short_channel_id = short_channel_id;
1203 // Even though previous update was not relayed further, we still accepted it,
1204 // so we now won't accept update before the previous one.
1205 unsigned_channel_update.timestamp -= 10;
1206 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1207 let valid_channel_update = ChannelUpdate {
1208 signature: secp_ctx.sign(&msghash, node_1_privkey),
1209 contents: unsigned_channel_update.clone()
1212 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1214 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1216 unsigned_channel_update.timestamp += 500;
1218 let fake_msghash = hash_to_message!(&zero_hash);
1219 let invalid_sig_channel_update = ChannelUpdate {
1220 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1221 contents: unsigned_channel_update.clone()
1224 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1226 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1232 fn handling_htlc_fail_channel_update() {
1233 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1234 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1235 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1236 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1237 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1238 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1239 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1241 let short_channel_id = 0;
1242 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1245 // There is no nodes in the table at the beginning.
1246 let network = net_graph_msg_handler.network_graph.read().unwrap();
1247 assert_eq!(network.get_nodes().len(), 0);
1251 // Announce a channel we will update
1252 let unsigned_announcement = UnsignedChannelAnnouncement {
1253 features: ChannelFeatures::empty(),
1258 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1259 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1260 excess_data: Vec::new(),
1263 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1264 let valid_channel_announcement = ChannelAnnouncement {
1265 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1266 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1267 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1268 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1269 contents: unsigned_announcement.clone(),
1271 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1276 let unsigned_channel_update = UnsignedChannelUpdate {
1281 cltv_expiry_delta: 144,
1282 htlc_minimum_msat: 1000000,
1283 fee_base_msat: 10000,
1284 fee_proportional_millionths: 20,
1285 excess_data: Vec::new()
1287 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1288 let valid_channel_update = ChannelUpdate {
1289 signature: secp_ctx.sign(&msghash, node_1_privkey),
1290 contents: unsigned_channel_update.clone()
1293 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1294 Ok(res) => assert!(res),
1299 // Non-permanent closing just disables a channel
1301 let network = net_graph_msg_handler.network_graph.read().unwrap();
1302 match network.get_channels().get(&short_channel_id) {
1304 Some(channel_info) => {
1305 assert!(channel_info.one_to_two.is_some());
1310 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1315 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1317 // Non-permanent closing just disables a channel
1319 let network = net_graph_msg_handler.network_graph.read().unwrap();
1320 match network.get_channels().get(&short_channel_id) {
1322 Some(channel_info) => {
1323 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1328 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1333 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1335 // Permanent closing deletes a channel
1337 let network = net_graph_msg_handler.network_graph.read().unwrap();
1338 assert_eq!(network.get_channels().len(), 0);
1339 // Nodes are also deleted because there are no associated channels anymore
1340 assert_eq!(network.get_nodes().len(), 0);
1342 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1346 fn getting_next_channel_announcements() {
1347 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1348 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1349 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1350 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1351 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1352 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1353 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1355 let short_channel_id = 1;
1356 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1358 // Channels were not announced yet.
1359 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1360 assert_eq!(channels_with_announcements.len(), 0);
1363 // Announce a channel we will update
1364 let unsigned_announcement = UnsignedChannelAnnouncement {
1365 features: ChannelFeatures::empty(),
1370 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1371 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1372 excess_data: Vec::new(),
1375 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1376 let valid_channel_announcement = ChannelAnnouncement {
1377 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1378 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1379 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1380 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1381 contents: unsigned_announcement.clone(),
1383 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1389 // Contains initial channel announcement now.
1390 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1391 assert_eq!(channels_with_announcements.len(), 1);
1392 if let Some(channel_announcements) = channels_with_announcements.first() {
1393 let &(_, ref update_1, ref update_2) = channel_announcements;
1394 assert_eq!(update_1, &None);
1395 assert_eq!(update_2, &None);
1402 // Valid channel update
1403 let unsigned_channel_update = UnsignedChannelUpdate {
1408 cltv_expiry_delta: 144,
1409 htlc_minimum_msat: 1000000,
1410 fee_base_msat: 10000,
1411 fee_proportional_millionths: 20,
1412 excess_data: Vec::new()
1414 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1415 let valid_channel_update = ChannelUpdate {
1416 signature: secp_ctx.sign(&msghash, node_1_privkey),
1417 contents: unsigned_channel_update.clone()
1419 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1425 // Now contains an initial announcement and an update.
1426 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1427 assert_eq!(channels_with_announcements.len(), 1);
1428 if let Some(channel_announcements) = channels_with_announcements.first() {
1429 let &(_, ref update_1, ref update_2) = channel_announcements;
1430 assert_ne!(update_1, &None);
1431 assert_eq!(update_2, &None);
1438 // Channel update with excess data.
1439 let unsigned_channel_update = UnsignedChannelUpdate {
1444 cltv_expiry_delta: 144,
1445 htlc_minimum_msat: 1000000,
1446 fee_base_msat: 10000,
1447 fee_proportional_millionths: 20,
1448 excess_data: [1; 3].to_vec()
1450 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1451 let valid_channel_update = ChannelUpdate {
1452 signature: secp_ctx.sign(&msghash, node_1_privkey),
1453 contents: unsigned_channel_update.clone()
1455 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1461 // Test that announcements with excess data won't be returned
1462 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1463 assert_eq!(channels_with_announcements.len(), 1);
1464 if let Some(channel_announcements) = channels_with_announcements.first() {
1465 let &(_, ref update_1, ref update_2) = channel_announcements;
1466 assert_eq!(update_1, &None);
1467 assert_eq!(update_2, &None);
1472 // Further starting point have no channels after it
1473 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1474 assert_eq!(channels_with_announcements.len(), 0);
1478 fn getting_next_node_announcements() {
1479 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1480 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1481 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1482 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1483 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1484 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1485 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1487 let short_channel_id = 1;
1488 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1491 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1492 assert_eq!(next_announcements.len(), 0);
1495 // Announce a channel to add 2 nodes
1496 let unsigned_announcement = UnsignedChannelAnnouncement {
1497 features: ChannelFeatures::empty(),
1502 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1503 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1504 excess_data: Vec::new(),
1507 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1508 let valid_channel_announcement = ChannelAnnouncement {
1509 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1510 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1511 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1512 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1513 contents: unsigned_announcement.clone(),
1515 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1522 // Nodes were never announced
1523 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1524 assert_eq!(next_announcements.len(), 0);
1527 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1528 features: NodeFeatures::known(),
1533 addresses: Vec::new(),
1534 excess_address_data: Vec::new(),
1535 excess_data: Vec::new(),
1537 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1538 let valid_announcement = NodeAnnouncement {
1539 signature: secp_ctx.sign(&msghash, node_1_privkey),
1540 contents: unsigned_announcement.clone()
1542 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1547 unsigned_announcement.node_id = node_id_2;
1548 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1549 let valid_announcement = NodeAnnouncement {
1550 signature: secp_ctx.sign(&msghash, node_2_privkey),
1551 contents: unsigned_announcement.clone()
1554 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1560 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1561 assert_eq!(next_announcements.len(), 2);
1563 // Skip the first node.
1564 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1565 assert_eq!(next_announcements.len(), 1);
1568 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1569 let unsigned_announcement = UnsignedNodeAnnouncement {
1570 features: NodeFeatures::known(),
1575 addresses: Vec::new(),
1576 excess_address_data: Vec::new(),
1577 excess_data: [1; 3].to_vec(),
1579 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1580 let valid_announcement = NodeAnnouncement {
1581 signature: secp_ctx.sign(&msghash, node_2_privkey),
1582 contents: unsigned_announcement.clone()
1584 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1585 Ok(res) => assert!(!res),
1590 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1591 assert_eq!(next_announcements.len(), 0);
1595 fn network_graph_serialization() {
1596 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1598 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1599 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1600 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1601 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1603 // Announce a channel to add a corresponding node.
1604 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1605 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1606 let unsigned_announcement = UnsignedChannelAnnouncement {
1607 features: ChannelFeatures::known(),
1608 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1609 short_channel_id: 0,
1612 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1613 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1614 excess_data: Vec::new(),
1617 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1618 let valid_announcement = ChannelAnnouncement {
1619 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1620 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1621 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1622 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1623 contents: unsigned_announcement.clone(),
1625 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1626 Ok(res) => assert!(res),
1631 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1632 let unsigned_announcement = UnsignedNodeAnnouncement {
1633 features: NodeFeatures::known(),
1638 addresses: Vec::new(),
1639 excess_address_data: Vec::new(),
1640 excess_data: Vec::new(),
1642 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1643 let valid_announcement = NodeAnnouncement {
1644 signature: secp_ctx.sign(&msghash, node_1_privkey),
1645 contents: unsigned_announcement.clone()
1648 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1653 let network = net_graph_msg_handler.network_graph.write().unwrap();
1654 let mut w = test_utils::TestVecWriter(Vec::new());
1655 assert!(!network.get_nodes().is_empty());
1656 assert!(!network.get_channels().is_empty());
1657 network.write(&mut w).unwrap();
1658 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);