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, OptionalField};
16 use util::ser::{Writeable, Readable, Writer};
17 use util::logger::Logger;
20 use std::sync::RwLock;
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
25 use bitcoin::hashes::hex::ToHex;
27 /// Receives and validates network updates from peers,
28 /// stores authentic and relevant data as a network graph.
29 /// This network graph is then used for routing payments.
30 /// Provides interface to help with initial routing sync by
31 /// serving historical announcements.
32 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
33 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
34 /// Representation of the payment channel network
35 pub network_graph: RwLock<NetworkGraph>,
37 full_syncs_requested: AtomicUsize,
41 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
42 /// Creates a new tracker of the actual state of the network of channels and nodes,
43 /// assuming a fresh network graph.
44 /// Chain monitor is used to make sure announced channels exist on-chain,
45 /// channel data is correct, and that the announcement is signed with
46 /// channel owners' keys.
47 pub fn new(chain_monitor: C, logger: L) -> Self {
49 secp_ctx: Secp256k1::verification_only(),
50 network_graph: RwLock::new(NetworkGraph {
51 channels: BTreeMap::new(),
52 nodes: BTreeMap::new(),
54 full_syncs_requested: AtomicUsize::new(0),
60 /// Creates a new tracker of the actual state of the network of channels and nodes,
61 /// assuming an existing Network Graph.
62 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
64 secp_ctx: Secp256k1::verification_only(),
65 network_graph: RwLock::new(network_graph),
66 full_syncs_requested: AtomicUsize::new(0),
74 macro_rules! secp_verify_sig {
75 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
76 match $secp_ctx.verify($msg, $sig, $pubkey) {
78 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
83 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
84 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
85 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
88 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
89 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
90 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
93 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
94 Ok((script_pubkey, value)) => {
95 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
96 .push_slice(&msg.contents.bitcoin_key_1.serialize())
97 .push_slice(&msg.contents.bitcoin_key_2.serialize())
98 .push_opcode(opcodes::all::OP_PUSHNUM_2)
99 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
100 if script_pubkey != expected_script {
101 return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
103 //TODO: Check if value is worth storing, use it to inform routing, and compare it
104 //to the new HTLC max field in channel_update
107 Err(ChainError::NotSupported) => {
108 // Tentatively accept, potentially exposing us to DoS attacks
111 Err(ChainError::NotWatched) => {
112 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
114 Err(ChainError::UnknownTx) => {
115 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
118 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
119 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
123 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
125 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
126 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
128 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
129 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
131 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
132 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
137 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
138 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
141 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
142 let network_graph = self.network_graph.read().unwrap();
143 let mut result = Vec::with_capacity(batch_amount as usize);
144 let mut iter = network_graph.get_channels().range(starting_point..);
145 while result.len() < batch_amount as usize {
146 if let Some((_, ref chan)) = iter.next() {
147 if chan.announcement_message.is_some() {
148 let chan_announcement = chan.announcement_message.clone().unwrap();
149 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
150 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
151 if let Some(one_to_two) = chan.one_to_two.as_ref() {
152 one_to_two_announcement = one_to_two.last_update_message.clone();
154 if let Some(two_to_one) = chan.two_to_one.as_ref() {
155 two_to_one_announcement = two_to_one.last_update_message.clone();
157 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
159 // TODO: We may end up sending un-announced channel_updates if we are sending
160 // initial sync data while receiving announce/updates for this channel.
169 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
170 let network_graph = self.network_graph.read().unwrap();
171 let mut result = Vec::with_capacity(batch_amount as usize);
172 let mut iter = if let Some(pubkey) = starting_point {
173 let mut iter = network_graph.get_nodes().range((*pubkey)..);
177 network_graph.get_nodes().range(..)
179 while result.len() < batch_amount as usize {
180 if let Some((_, ref node)) = iter.next() {
181 if let Some(node_info) = node.announcement_info.as_ref() {
182 if node_info.announcement_message.is_some() {
183 result.push(node_info.announcement_message.clone().unwrap());
193 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
194 //TODO: Determine whether to request a full sync based on the network map.
195 const FULL_SYNCS_TO_REQUEST: usize = 5;
196 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
197 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
205 #[derive(PartialEq, Debug)]
206 /// Details about one direction of a channel. Received
207 /// within a channel update.
208 pub struct DirectionalChannelInfo {
209 /// When the last update to the channel direction was issued.
210 /// Value is opaque, as set in the announcement.
211 pub last_update: u32,
212 /// Whether the channel can be currently used for payments (in this one direction).
214 /// The difference in CLTV values that you must have when routing through this channel.
215 pub cltv_expiry_delta: u16,
216 /// The minimum value, which must be relayed to the next hop via the channel
217 pub htlc_minimum_msat: u64,
218 /// The maximum value which may be relayed to the next hop via the channel.
219 pub htlc_maximum_msat: Option<u64>,
220 /// Fees charged when the channel is used for routing
221 pub fees: RoutingFees,
222 /// Most recent update for the channel received from the network
223 /// Mostly redundant with the data we store in fields explicitly.
224 /// Everything else is useful only for sending out for initial routing sync.
225 /// Not stored if contains excess data to prevent DoS.
226 pub last_update_message: Option<msgs::ChannelUpdate>,
229 impl fmt::Display for DirectionalChannelInfo {
230 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
231 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)?;
236 impl_writeable!(DirectionalChannelInfo, 0, {
247 /// Details about a channel (both directions).
248 /// Received within a channel announcement.
249 pub struct ChannelInfo {
250 /// Protocol features of a channel communicated during its announcement
251 pub features: ChannelFeatures,
252 /// Source node of the first direction of a channel
253 pub node_one: PublicKey,
254 /// Details about the first direction of a channel
255 pub one_to_two: Option<DirectionalChannelInfo>,
256 /// Source node of the second direction of a channel
257 pub node_two: PublicKey,
258 /// Details about the second direction of a channel
259 pub two_to_one: Option<DirectionalChannelInfo>,
260 /// The channel capacity as seen on-chain, if chain lookup is available.
261 pub capacity_sats: Option<u64>,
262 /// An initial announcement of the channel
263 /// Mostly redundant with the data we store in fields explicitly.
264 /// Everything else is useful only for sending out for initial routing sync.
265 /// Not stored if contains excess data to prevent DoS.
266 pub announcement_message: Option<msgs::ChannelAnnouncement>,
269 impl fmt::Display for ChannelInfo {
270 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
271 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
272 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
277 impl_writeable!(ChannelInfo, 0, {
288 /// Fees for routing via a given channel or a node
289 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
290 pub struct RoutingFees {
291 /// Flat routing fee in satoshis
293 /// Liquidity-based routing fee in millionths of a routed amount.
294 /// In other words, 10000 is 1%.
295 pub proportional_millionths: u32,
298 impl Readable for RoutingFees{
299 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
300 let base_msat: u32 = Readable::read(reader)?;
301 let proportional_millionths: u32 = Readable::read(reader)?;
304 proportional_millionths,
309 impl Writeable for RoutingFees {
310 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
311 self.base_msat.write(writer)?;
312 self.proportional_millionths.write(writer)?;
317 #[derive(PartialEq, Debug)]
318 /// Information received in the latest node_announcement from this node.
319 pub struct NodeAnnouncementInfo {
320 /// Protocol features the node announced support for
321 pub features: NodeFeatures,
322 /// When the last known update to the node state was issued.
323 /// Value is opaque, as set in the announcement.
324 pub last_update: u32,
325 /// Color assigned to the node
327 /// Moniker assigned to the node.
328 /// May be invalid or malicious (eg control chars),
329 /// should not be exposed to the user.
331 /// Internet-level addresses via which one can connect to the node
332 pub addresses: Vec<NetAddress>,
333 /// An initial announcement of the node
334 /// Mostly redundant with the data we store in fields explicitly.
335 /// Everything else is useful only for sending out for initial routing sync.
336 /// Not stored if contains excess data to prevent DoS.
337 pub announcement_message: Option<msgs::NodeAnnouncement>
340 impl Writeable for NodeAnnouncementInfo {
341 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
342 self.features.write(writer)?;
343 self.last_update.write(writer)?;
344 self.rgb.write(writer)?;
345 self.alias.write(writer)?;
346 (self.addresses.len() as u64).write(writer)?;
347 for ref addr in &self.addresses {
350 self.announcement_message.write(writer)?;
355 impl Readable for NodeAnnouncementInfo {
356 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
357 let features = Readable::read(reader)?;
358 let last_update = Readable::read(reader)?;
359 let rgb = Readable::read(reader)?;
360 let alias = Readable::read(reader)?;
361 let addresses_count: u64 = Readable::read(reader)?;
362 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
363 for _ in 0..addresses_count {
364 match Readable::read(reader) {
365 Ok(Ok(addr)) => { addresses.push(addr); },
366 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
367 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
371 let announcement_message = Readable::read(reader)?;
372 Ok(NodeAnnouncementInfo {
384 /// Details about a node in the network, known from the network announcement.
385 pub struct NodeInfo {
386 /// All valid channels a node has announced
387 pub channels: Vec<u64>,
388 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
389 /// The two fields (flat and proportional fee) are independent,
390 /// meaning they don't have to refer to the same channel.
391 pub lowest_inbound_channel_fees: Option<RoutingFees>,
392 /// More information about a node from node_announcement.
393 /// Optional because we store a Node entry after learning about it from
394 /// a channel announcement, but before receiving a node announcement.
395 pub announcement_info: Option<NodeAnnouncementInfo>
398 impl fmt::Display for NodeInfo {
399 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
400 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
401 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
406 impl Writeable for NodeInfo {
407 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
408 (self.channels.len() as u64).write(writer)?;
409 for ref chan in self.channels.iter() {
412 self.lowest_inbound_channel_fees.write(writer)?;
413 self.announcement_info.write(writer)?;
418 const MAX_ALLOC_SIZE: u64 = 64*1024;
420 impl Readable for NodeInfo {
421 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
422 let channels_count: u64 = Readable::read(reader)?;
423 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
424 for _ in 0..channels_count {
425 channels.push(Readable::read(reader)?);
427 let lowest_inbound_channel_fees = Readable::read(reader)?;
428 let announcement_info = Readable::read(reader)?;
431 lowest_inbound_channel_fees,
437 /// Represents the network as nodes and channels between them
439 pub struct NetworkGraph {
440 channels: BTreeMap<u64, ChannelInfo>,
441 nodes: BTreeMap<PublicKey, NodeInfo>,
444 impl Writeable for NetworkGraph {
445 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
446 (self.channels.len() as u64).write(writer)?;
447 for (ref chan_id, ref chan_info) in self.channels.iter() {
448 (*chan_id).write(writer)?;
449 chan_info.write(writer)?;
451 (self.nodes.len() as u64).write(writer)?;
452 for (ref node_id, ref node_info) in self.nodes.iter() {
453 node_id.write(writer)?;
454 node_info.write(writer)?;
460 impl Readable for NetworkGraph {
461 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
462 let channels_count: u64 = Readable::read(reader)?;
463 let mut channels = BTreeMap::new();
464 for _ in 0..channels_count {
465 let chan_id: u64 = Readable::read(reader)?;
466 let chan_info = Readable::read(reader)?;
467 channels.insert(chan_id, chan_info);
469 let nodes_count: u64 = Readable::read(reader)?;
470 let mut nodes = BTreeMap::new();
471 for _ in 0..nodes_count {
472 let node_id = Readable::read(reader)?;
473 let node_info = Readable::read(reader)?;
474 nodes.insert(node_id, node_info);
483 impl fmt::Display for NetworkGraph {
484 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
485 write!(f, "Network map\n[Channels]\n")?;
486 for (key, val) in self.channels.iter() {
487 write!(f, " {}: {}\n", key, val)?;
489 write!(f, "[Nodes]\n")?;
490 for (key, val) in self.nodes.iter() {
491 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
498 /// Returns all known valid channels' short ids along with announced channel info.
499 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
500 /// Returns all known nodes' public keys along with announced node info.
501 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
503 /// Get network addresses by node id.
504 /// Returns None if the requested node is completely unknown,
505 /// or if node announcement for the node was never received.
506 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
507 if let Some(node) = self.nodes.get(pubkey) {
508 if let Some(node_info) = node.announcement_info.as_ref() {
509 return Some(&node_info.addresses)
515 /// Creates a new, empty, network graph.
516 pub fn new() -> NetworkGraph {
518 channels: BTreeMap::new(),
519 nodes: BTreeMap::new(),
523 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
524 /// Announcement signatures are checked here only if Secp256k1 object is provided.
525 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
526 if let Some(sig_verifier) = secp_ctx {
527 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
528 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
531 match self.nodes.get_mut(&msg.contents.node_id) {
532 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
534 if let Some(node_info) = node.announcement_info.as_ref() {
535 if node_info.last_update >= msg.contents.timestamp {
536 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
540 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
541 node.announcement_info = Some(NodeAnnouncementInfo {
542 features: msg.contents.features.clone(),
543 last_update: msg.contents.timestamp,
544 rgb: msg.contents.rgb,
545 alias: msg.contents.alias,
546 addresses: msg.contents.addresses.clone(),
547 announcement_message: if should_relay { Some(msg.clone()) } else { None },
555 /// For a new or already known (from previous announcement) channel, store or update channel info.
556 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
557 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
558 /// which is probably result of a reorg. In that case, we update channel info only if the
559 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
560 /// Announcement signatures are checked here only if Secp256k1 object is provided.
561 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
562 if let Some(sig_verifier) = secp_ctx {
563 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
564 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
565 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
566 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
567 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
570 let should_relay = msg.contents.excess_data.is_empty();
572 let chan_info = ChannelInfo {
573 features: msg.contents.features.clone(),
574 node_one: msg.contents.node_id_1.clone(),
576 node_two: msg.contents.node_id_2.clone(),
578 capacity_sats: utxo_value,
579 announcement_message: if should_relay { Some(msg.clone()) } else { None },
582 match self.channels.entry(msg.contents.short_channel_id) {
583 BtreeEntry::Occupied(mut entry) => {
584 //TODO: because asking the blockchain if short_channel_id is valid is only optional
585 //in the blockchain API, we need to handle it smartly here, though it's unclear
587 if utxo_value.is_some() {
588 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
589 // only sometimes returns results. In any case remove the previous entry. Note
590 // that the spec expects us to "blacklist" the node_ids involved, but we can't
592 // a) we don't *require* a UTXO provider that always returns results.
593 // b) we don't track UTXOs of channels we know about and remove them if they
595 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
596 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
597 *entry.get_mut() = chan_info;
599 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
602 BtreeEntry::Vacant(entry) => {
603 entry.insert(chan_info);
607 macro_rules! add_channel_to_node {
608 ( $node_id: expr ) => {
609 match self.nodes.entry($node_id) {
610 BtreeEntry::Occupied(node_entry) => {
611 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
613 BtreeEntry::Vacant(node_entry) => {
614 node_entry.insert(NodeInfo {
615 channels: vec!(msg.contents.short_channel_id),
616 lowest_inbound_channel_fees: None,
617 announcement_info: None,
624 add_channel_to_node!(msg.contents.node_id_1);
625 add_channel_to_node!(msg.contents.node_id_2);
630 /// Close a channel if a corresponding HTLC fail was sent.
631 /// If permanent, removes a channel from the local storage.
632 /// May cause the removal of nodes too, if this was their last channel.
633 /// If not permanent, makes channels unavailable for routing.
634 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
636 if let Some(chan) = self.channels.remove(&short_channel_id) {
637 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
640 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
641 if let Some(one_to_two) = chan.one_to_two.as_mut() {
642 one_to_two.enabled = false;
644 if let Some(two_to_one) = chan.two_to_one.as_mut() {
645 two_to_one.enabled = false;
651 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
653 // TODO: Wholly remove the node
655 // TODO: downgrade the node
659 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
660 /// Announcement signatures are checked here only if Secp256k1 object is provided.
661 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
663 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
664 let chan_was_enabled;
666 match self.channels.get_mut(&msg.contents.short_channel_id) {
667 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
669 macro_rules! maybe_update_channel_info {
670 ( $target: expr, $src_node: expr) => {
671 if let Some(existing_chan_info) = $target.as_ref() {
672 if existing_chan_info.last_update >= msg.contents.timestamp {
673 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
675 chan_was_enabled = existing_chan_info.enabled;
677 chan_was_enabled = false;
680 let last_update_message = if msg.contents.excess_data.is_empty() {
686 let updated_channel_dir_info = DirectionalChannelInfo {
687 enabled: chan_enabled,
688 last_update: msg.contents.timestamp,
689 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
690 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
691 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
693 base_msat: msg.contents.fee_base_msat,
694 proportional_millionths: msg.contents.fee_proportional_millionths,
698 $target = Some(updated_channel_dir_info);
702 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
703 if msg.contents.flags & 1 == 1 {
704 dest_node_id = channel.node_one.clone();
705 if let Some(sig_verifier) = secp_ctx {
706 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
708 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
710 dest_node_id = channel.node_two.clone();
711 if let Some(sig_verifier) = secp_ctx {
712 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
714 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
720 let node = self.nodes.get_mut(&dest_node_id).unwrap();
721 let mut base_msat = msg.contents.fee_base_msat;
722 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
723 if let Some(fees) = node.lowest_inbound_channel_fees {
724 base_msat = cmp::min(base_msat, fees.base_msat);
725 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
727 node.lowest_inbound_channel_fees = Some(RoutingFees {
729 proportional_millionths
731 } else if chan_was_enabled {
732 let node = self.nodes.get_mut(&dest_node_id).unwrap();
733 let mut lowest_inbound_channel_fees = None;
735 for chan_id in node.channels.iter() {
736 let chan = self.channels.get(chan_id).unwrap();
738 if chan.node_one == dest_node_id {
739 chan_info_opt = chan.two_to_one.as_ref();
741 chan_info_opt = chan.one_to_two.as_ref();
743 if let Some(chan_info) = chan_info_opt {
744 if chan_info.enabled {
745 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
746 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
747 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
748 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
753 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
756 Ok(msg.contents.excess_data.is_empty())
759 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
760 macro_rules! remove_from_node {
761 ($node_id: expr) => {
762 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
763 entry.get_mut().channels.retain(|chan_id| {
764 short_channel_id != *chan_id
766 if entry.get().channels.is_empty() {
767 entry.remove_entry();
770 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
775 remove_from_node!(chan.node_one);
776 remove_from_node!(chan.node_two);
782 use chain::chaininterface;
783 use ln::features::{ChannelFeatures, NodeFeatures};
784 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
785 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
786 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
787 use util::test_utils;
788 use util::logger::Logger;
789 use util::ser::{Readable, Writeable};
791 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
792 use bitcoin::hashes::Hash;
793 use bitcoin::network::constants::Network;
794 use bitcoin::blockdata::constants::genesis_block;
795 use bitcoin::blockdata::script::Builder;
796 use bitcoin::blockdata::opcodes;
797 use bitcoin::util::hash::BitcoinHash;
801 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
802 use bitcoin::secp256k1::{All, Secp256k1};
806 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
807 let secp_ctx = Secp256k1::new();
808 let logger = Arc::new(test_utils::TestLogger::new());
809 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
810 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
811 (secp_ctx, net_graph_msg_handler)
815 fn request_full_sync_finite_times() {
816 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
817 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
819 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
820 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
821 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
822 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
823 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
824 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
828 fn handling_node_announcements() {
829 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
831 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
832 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
833 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
834 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
835 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
836 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
837 let zero_hash = Sha256dHash::hash(&[0; 32]);
838 let first_announcement_time = 500;
840 let mut unsigned_announcement = UnsignedNodeAnnouncement {
841 features: NodeFeatures::known(),
842 timestamp: first_announcement_time,
846 addresses: Vec::new(),
847 excess_address_data: Vec::new(),
848 excess_data: Vec::new(),
850 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
851 let valid_announcement = NodeAnnouncement {
852 signature: secp_ctx.sign(&msghash, node_1_privkey),
853 contents: unsigned_announcement.clone()
856 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
858 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
862 // Announce a channel to add a corresponding node.
863 let unsigned_announcement = UnsignedChannelAnnouncement {
864 features: ChannelFeatures::known(),
865 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
869 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
870 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
871 excess_data: Vec::new(),
874 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
875 let valid_announcement = ChannelAnnouncement {
876 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
877 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
878 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
879 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
880 contents: unsigned_announcement.clone(),
882 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
883 Ok(res) => assert!(res),
888 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
889 Ok(res) => assert!(res),
893 let fake_msghash = hash_to_message!(&zero_hash);
894 match net_graph_msg_handler.handle_node_announcement(
896 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
897 contents: unsigned_announcement.clone()
900 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
903 unsigned_announcement.timestamp += 1000;
904 unsigned_announcement.excess_data.push(1);
905 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
906 let announcement_with_data = NodeAnnouncement {
907 signature: secp_ctx.sign(&msghash, node_1_privkey),
908 contents: unsigned_announcement.clone()
910 // Return false because contains excess data.
911 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
912 Ok(res) => assert!(!res),
915 unsigned_announcement.excess_data = Vec::new();
917 // Even though previous announcement was not relayed further, we still accepted it,
918 // so we now won't accept announcements before the previous one.
919 unsigned_announcement.timestamp -= 10;
920 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
921 let outdated_announcement = NodeAnnouncement {
922 signature: secp_ctx.sign(&msghash, node_1_privkey),
923 contents: unsigned_announcement.clone()
925 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
927 Err(e) => assert_eq!(e.err, "Update older than last processed update")
932 fn handling_channel_announcements() {
933 let secp_ctx = Secp256k1::new();
934 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
935 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
936 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
939 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
940 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
941 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
942 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
943 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
944 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
946 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
947 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
948 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
949 .push_opcode(opcodes::all::OP_PUSHNUM_2)
950 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
953 let mut unsigned_announcement = UnsignedChannelAnnouncement {
954 features: ChannelFeatures::known(),
955 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
959 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
960 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
961 excess_data: Vec::new(),
964 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
965 let valid_announcement = ChannelAnnouncement {
966 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
967 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
968 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
969 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
970 contents: unsigned_announcement.clone(),
973 // Test if the UTXO lookups were not supported
974 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
976 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
977 Ok(res) => assert!(res),
982 let network = net_graph_msg_handler.network_graph.read().unwrap();
983 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
990 // If we receive announcement for the same channel (with UTXO lookups disabled),
991 // drop new one on the floor, since we can't see any changes.
992 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
994 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
998 // Test if an associated transaction were not on-chain (or not confirmed).
999 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1000 unsigned_announcement.short_channel_id += 1;
1002 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1003 let valid_announcement = ChannelAnnouncement {
1004 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1005 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1006 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1007 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1008 contents: unsigned_announcement.clone(),
1011 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1013 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1017 // Now test if the transaction is found in the UTXO set and the script is correct.
1018 unsigned_announcement.short_channel_id += 1;
1019 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1021 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1022 let valid_announcement = ChannelAnnouncement {
1023 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1024 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1025 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1026 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1027 contents: unsigned_announcement.clone(),
1029 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1030 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) {
1042 // If we receive announcement for the same channel (but TX is not confirmed),
1043 // drop new one on the floor, since we can't see any changes.
1044 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1045 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1047 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1050 // But if it is confirmed, replace the channel
1051 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1052 unsigned_announcement.features = ChannelFeatures::empty();
1053 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1054 let valid_announcement = ChannelAnnouncement {
1055 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1056 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1057 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1058 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1059 contents: unsigned_announcement.clone(),
1061 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1062 Ok(res) => assert!(res),
1066 let network = net_graph_msg_handler.network_graph.read().unwrap();
1067 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1068 Some(channel_entry) => {
1069 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1075 // Don't relay valid channels with excess data
1076 unsigned_announcement.short_channel_id += 1;
1077 unsigned_announcement.excess_data.push(1);
1078 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1079 let valid_announcement = ChannelAnnouncement {
1080 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1081 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1082 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1083 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1084 contents: unsigned_announcement.clone(),
1086 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1087 Ok(res) => assert!(!res),
1091 unsigned_announcement.excess_data = Vec::new();
1092 let invalid_sig_announcement = ChannelAnnouncement {
1093 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1094 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1095 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1096 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1097 contents: unsigned_announcement.clone(),
1099 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1101 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1104 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1105 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1106 let channel_to_itself_announcement = ChannelAnnouncement {
1107 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1108 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1109 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1110 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1111 contents: unsigned_announcement.clone(),
1113 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1115 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1120 fn handling_channel_update() {
1121 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1122 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1123 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1124 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1125 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1126 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1127 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1129 let zero_hash = Sha256dHash::hash(&[0; 32]);
1130 let short_channel_id = 0;
1131 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1133 // Announce a channel we will update
1134 let unsigned_announcement = UnsignedChannelAnnouncement {
1135 features: ChannelFeatures::empty(),
1140 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1141 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1142 excess_data: Vec::new(),
1145 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1146 let valid_channel_announcement = ChannelAnnouncement {
1147 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1148 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1149 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1150 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1151 contents: unsigned_announcement.clone(),
1153 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1160 let mut unsigned_channel_update = UnsignedChannelUpdate {
1165 cltv_expiry_delta: 144,
1166 htlc_minimum_msat: 1000000,
1167 htlc_maximum_msat: OptionalField::Absent,
1168 fee_base_msat: 10000,
1169 fee_proportional_millionths: 20,
1170 excess_data: Vec::new()
1172 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1173 let valid_channel_update = ChannelUpdate {
1174 signature: secp_ctx.sign(&msghash, node_1_privkey),
1175 contents: unsigned_channel_update.clone()
1178 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1179 Ok(res) => assert!(res),
1184 let network = net_graph_msg_handler.network_graph.read().unwrap();
1185 match network.get_channels().get(&short_channel_id) {
1187 Some(channel_info) => {
1188 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1189 assert!(channel_info.two_to_one.is_none());
1194 unsigned_channel_update.timestamp += 100;
1195 unsigned_channel_update.excess_data.push(1);
1196 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1197 let valid_channel_update = ChannelUpdate {
1198 signature: secp_ctx.sign(&msghash, node_1_privkey),
1199 contents: unsigned_channel_update.clone()
1201 // Return false because contains excess data
1202 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1203 Ok(res) => assert!(!res),
1206 unsigned_channel_update.timestamp += 10;
1208 unsigned_channel_update.short_channel_id += 1;
1209 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1210 let valid_channel_update = ChannelUpdate {
1211 signature: secp_ctx.sign(&msghash, node_1_privkey),
1212 contents: unsigned_channel_update.clone()
1215 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1217 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1219 unsigned_channel_update.short_channel_id = short_channel_id;
1222 // Even though previous update was not relayed further, we still accepted it,
1223 // so we now won't accept update before the previous one.
1224 unsigned_channel_update.timestamp -= 10;
1225 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1226 let valid_channel_update = ChannelUpdate {
1227 signature: secp_ctx.sign(&msghash, node_1_privkey),
1228 contents: unsigned_channel_update.clone()
1231 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1233 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1235 unsigned_channel_update.timestamp += 500;
1237 let fake_msghash = hash_to_message!(&zero_hash);
1238 let invalid_sig_channel_update = ChannelUpdate {
1239 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1240 contents: unsigned_channel_update.clone()
1243 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1245 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1251 fn handling_htlc_fail_channel_update() {
1252 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1253 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1254 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1255 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1256 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1257 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1258 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1260 let short_channel_id = 0;
1261 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1264 // There is no nodes in the table at the beginning.
1265 let network = net_graph_msg_handler.network_graph.read().unwrap();
1266 assert_eq!(network.get_nodes().len(), 0);
1270 // Announce a channel we will update
1271 let unsigned_announcement = UnsignedChannelAnnouncement {
1272 features: ChannelFeatures::empty(),
1277 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1278 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1279 excess_data: Vec::new(),
1282 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1283 let valid_channel_announcement = ChannelAnnouncement {
1284 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1285 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1286 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1287 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1288 contents: unsigned_announcement.clone(),
1290 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1295 let unsigned_channel_update = UnsignedChannelUpdate {
1300 cltv_expiry_delta: 144,
1301 htlc_minimum_msat: 1000000,
1302 htlc_maximum_msat: OptionalField::Absent,
1303 fee_base_msat: 10000,
1304 fee_proportional_millionths: 20,
1305 excess_data: Vec::new()
1307 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1308 let valid_channel_update = ChannelUpdate {
1309 signature: secp_ctx.sign(&msghash, node_1_privkey),
1310 contents: unsigned_channel_update.clone()
1313 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1314 Ok(res) => assert!(res),
1319 // Non-permanent closing just disables a channel
1321 let network = net_graph_msg_handler.network_graph.read().unwrap();
1322 match network.get_channels().get(&short_channel_id) {
1324 Some(channel_info) => {
1325 assert!(channel_info.one_to_two.is_some());
1330 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1335 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1337 // Non-permanent closing just disables a channel
1339 let network = net_graph_msg_handler.network_graph.read().unwrap();
1340 match network.get_channels().get(&short_channel_id) {
1342 Some(channel_info) => {
1343 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1348 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1353 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1355 // Permanent closing deletes a channel
1357 let network = net_graph_msg_handler.network_graph.read().unwrap();
1358 assert_eq!(network.get_channels().len(), 0);
1359 // Nodes are also deleted because there are no associated channels anymore
1360 assert_eq!(network.get_nodes().len(), 0);
1362 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1366 fn getting_next_channel_announcements() {
1367 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1368 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1369 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1370 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1371 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1372 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1373 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1375 let short_channel_id = 1;
1376 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1378 // Channels were not announced yet.
1379 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1380 assert_eq!(channels_with_announcements.len(), 0);
1383 // Announce a channel we will update
1384 let unsigned_announcement = UnsignedChannelAnnouncement {
1385 features: ChannelFeatures::empty(),
1390 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1391 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1392 excess_data: Vec::new(),
1395 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1396 let valid_channel_announcement = ChannelAnnouncement {
1397 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1398 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1399 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1400 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1401 contents: unsigned_announcement.clone(),
1403 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1409 // Contains initial channel announcement now.
1410 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1411 assert_eq!(channels_with_announcements.len(), 1);
1412 if let Some(channel_announcements) = channels_with_announcements.first() {
1413 let &(_, ref update_1, ref update_2) = channel_announcements;
1414 assert_eq!(update_1, &None);
1415 assert_eq!(update_2, &None);
1422 // Valid channel update
1423 let unsigned_channel_update = UnsignedChannelUpdate {
1428 cltv_expiry_delta: 144,
1429 htlc_minimum_msat: 1000000,
1430 htlc_maximum_msat: OptionalField::Absent,
1431 fee_base_msat: 10000,
1432 fee_proportional_millionths: 20,
1433 excess_data: Vec::new()
1435 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1436 let valid_channel_update = ChannelUpdate {
1437 signature: secp_ctx.sign(&msghash, node_1_privkey),
1438 contents: unsigned_channel_update.clone()
1440 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1446 // Now contains an initial announcement and an update.
1447 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1448 assert_eq!(channels_with_announcements.len(), 1);
1449 if let Some(channel_announcements) = channels_with_announcements.first() {
1450 let &(_, ref update_1, ref update_2) = channel_announcements;
1451 assert_ne!(update_1, &None);
1452 assert_eq!(update_2, &None);
1459 // Channel update with excess data.
1460 let unsigned_channel_update = UnsignedChannelUpdate {
1465 cltv_expiry_delta: 144,
1466 htlc_minimum_msat: 1000000,
1467 htlc_maximum_msat: OptionalField::Absent,
1468 fee_base_msat: 10000,
1469 fee_proportional_millionths: 20,
1470 excess_data: [1; 3].to_vec()
1472 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1473 let valid_channel_update = ChannelUpdate {
1474 signature: secp_ctx.sign(&msghash, node_1_privkey),
1475 contents: unsigned_channel_update.clone()
1477 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1483 // Test that announcements with excess data won't be returned
1484 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1485 assert_eq!(channels_with_announcements.len(), 1);
1486 if let Some(channel_announcements) = channels_with_announcements.first() {
1487 let &(_, ref update_1, ref update_2) = channel_announcements;
1488 assert_eq!(update_1, &None);
1489 assert_eq!(update_2, &None);
1494 // Further starting point have no channels after it
1495 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1496 assert_eq!(channels_with_announcements.len(), 0);
1500 fn getting_next_node_announcements() {
1501 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1502 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1503 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1504 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1505 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1506 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1507 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1509 let short_channel_id = 1;
1510 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1513 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1514 assert_eq!(next_announcements.len(), 0);
1517 // Announce a channel to add 2 nodes
1518 let unsigned_announcement = UnsignedChannelAnnouncement {
1519 features: ChannelFeatures::empty(),
1524 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1525 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1526 excess_data: Vec::new(),
1529 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1530 let valid_channel_announcement = ChannelAnnouncement {
1531 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1532 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1533 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1534 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1535 contents: unsigned_announcement.clone(),
1537 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1544 // Nodes were never announced
1545 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1546 assert_eq!(next_announcements.len(), 0);
1549 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1550 features: NodeFeatures::known(),
1555 addresses: Vec::new(),
1556 excess_address_data: Vec::new(),
1557 excess_data: Vec::new(),
1559 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1560 let valid_announcement = NodeAnnouncement {
1561 signature: secp_ctx.sign(&msghash, node_1_privkey),
1562 contents: unsigned_announcement.clone()
1564 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1569 unsigned_announcement.node_id = node_id_2;
1570 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1571 let valid_announcement = NodeAnnouncement {
1572 signature: secp_ctx.sign(&msghash, node_2_privkey),
1573 contents: unsigned_announcement.clone()
1576 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1582 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1583 assert_eq!(next_announcements.len(), 2);
1585 // Skip the first node.
1586 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1587 assert_eq!(next_announcements.len(), 1);
1590 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1591 let unsigned_announcement = UnsignedNodeAnnouncement {
1592 features: NodeFeatures::known(),
1597 addresses: Vec::new(),
1598 excess_address_data: Vec::new(),
1599 excess_data: [1; 3].to_vec(),
1601 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1602 let valid_announcement = NodeAnnouncement {
1603 signature: secp_ctx.sign(&msghash, node_2_privkey),
1604 contents: unsigned_announcement.clone()
1606 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1607 Ok(res) => assert!(!res),
1612 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1613 assert_eq!(next_announcements.len(), 0);
1617 fn network_graph_serialization() {
1618 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1620 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1621 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1622 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1623 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1625 // Announce a channel to add a corresponding node.
1626 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1627 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1628 let unsigned_announcement = UnsignedChannelAnnouncement {
1629 features: ChannelFeatures::known(),
1630 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1631 short_channel_id: 0,
1634 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1635 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1636 excess_data: Vec::new(),
1639 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1640 let valid_announcement = ChannelAnnouncement {
1641 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1642 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1643 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1644 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1645 contents: unsigned_announcement.clone(),
1647 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1648 Ok(res) => assert!(res),
1653 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1654 let unsigned_announcement = UnsignedNodeAnnouncement {
1655 features: NodeFeatures::known(),
1660 addresses: Vec::new(),
1661 excess_address_data: Vec::new(),
1662 excess_data: Vec::new(),
1664 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1665 let valid_announcement = NodeAnnouncement {
1666 signature: secp_ctx.sign(&msghash, node_1_privkey),
1667 contents: unsigned_announcement.clone()
1670 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1675 let network = net_graph_msg_handler.network_graph.write().unwrap();
1676 let mut w = test_utils::TestVecWriter(Vec::new());
1677 assert!(!network.get_nodes().is_empty());
1678 assert!(!network.get_channels().is_empty());
1679 network.write(&mut w).unwrap();
1680 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);