1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
24 use ln::features::{ChannelFeatures, NodeFeatures};
25 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
26 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use util::ser::{Writeable, Readable, Writer};
29 use util::logger::Logger;
32 use std::sync::{RwLock, RwLockReadGuard};
33 use std::sync::atomic::{AtomicUsize, Ordering};
34 use std::collections::BTreeMap;
35 use std::collections::btree_map::Entry as BtreeEntry;
37 use bitcoin::hashes::hex::ToHex;
39 /// Represents the network as nodes and channels between them
41 pub struct NetworkGraph {
42 channels: BTreeMap<u64, ChannelInfo>,
43 nodes: BTreeMap<PublicKey, NodeInfo>,
46 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
47 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
48 /// the C bindings, as it can be done directly in Rust code.
49 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
51 /// Receives and validates network updates from peers,
52 /// stores authentic and relevant data as a network graph.
53 /// This network graph is then used for routing payments.
54 /// Provides interface to help with initial routing sync by
55 /// serving historical announcements.
56 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
57 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
58 /// Representation of the payment channel network
59 pub network_graph: RwLock<NetworkGraph>,
60 chain_access: Option<C>,
61 full_syncs_requested: AtomicUsize,
65 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
66 /// Creates a new tracker of the actual state of the network of channels and nodes,
67 /// assuming a fresh network graph.
68 /// Chain monitor is used to make sure announced channels exist on-chain,
69 /// channel data is correct, and that the announcement is signed with
70 /// channel owners' keys.
71 pub fn new(chain_access: Option<C>, logger: L) -> Self {
73 secp_ctx: Secp256k1::verification_only(),
74 network_graph: RwLock::new(NetworkGraph {
75 channels: BTreeMap::new(),
76 nodes: BTreeMap::new(),
78 full_syncs_requested: AtomicUsize::new(0),
84 /// Creates a new tracker of the actual state of the network of channels and nodes,
85 /// assuming an existing Network Graph.
86 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
88 secp_ctx: Secp256k1::verification_only(),
89 network_graph: RwLock::new(network_graph),
90 full_syncs_requested: AtomicUsize::new(0),
96 /// Take a read lock on the network_graph and return it in the C-bindings
97 /// newtype helper. This is likely only useful when called via the C
98 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
100 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
101 LockedNetworkGraph(self.network_graph.read().unwrap())
105 impl<'a> LockedNetworkGraph<'a> {
106 /// Get a reference to the NetworkGraph which this read-lock contains.
107 pub fn graph(&self) -> &NetworkGraph {
113 macro_rules! secp_verify_sig {
114 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
115 match $secp_ctx.verify($msg, $sig, $pubkey) {
117 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
122 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
123 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
124 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
127 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
128 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
129 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
132 let utxo_value = match &self.chain_access {
134 // Tentatively accept, potentially exposing us to DoS attacks
137 &Some(ref chain_access) => {
138 match chain_access.get_utxo(&msg.contents.chain_hash, msg.contents.short_channel_id) {
139 Ok(TxOut { value, script_pubkey }) => {
140 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
141 .push_slice(&msg.contents.bitcoin_key_1.serialize())
142 .push_slice(&msg.contents.bitcoin_key_2.serialize())
143 .push_opcode(opcodes::all::OP_PUSHNUM_2)
144 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
145 if script_pubkey != expected_script {
146 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});
148 //TODO: Check if value is worth storing, use it to inform routing, and compare it
149 //to the new HTLC max field in channel_update
152 Err(chain::AccessError::UnknownChain) => {
153 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
155 Err(chain::AccessError::UnknownTx) => {
156 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
161 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
162 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 { "" });
166 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
168 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
169 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
171 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
172 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
174 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
175 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
180 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
181 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
184 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
185 let network_graph = self.network_graph.read().unwrap();
186 let mut result = Vec::with_capacity(batch_amount as usize);
187 let mut iter = network_graph.get_channels().range(starting_point..);
188 while result.len() < batch_amount as usize {
189 if let Some((_, ref chan)) = iter.next() {
190 if chan.announcement_message.is_some() {
191 let chan_announcement = chan.announcement_message.clone().unwrap();
192 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
193 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
194 if let Some(one_to_two) = chan.one_to_two.as_ref() {
195 one_to_two_announcement = one_to_two.last_update_message.clone();
197 if let Some(two_to_one) = chan.two_to_one.as_ref() {
198 two_to_one_announcement = two_to_one.last_update_message.clone();
200 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
202 // TODO: We may end up sending un-announced channel_updates if we are sending
203 // initial sync data while receiving announce/updates for this channel.
212 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
213 let network_graph = self.network_graph.read().unwrap();
214 let mut result = Vec::with_capacity(batch_amount as usize);
215 let mut iter = if let Some(pubkey) = starting_point {
216 let mut iter = network_graph.get_nodes().range((*pubkey)..);
220 network_graph.get_nodes().range(..)
222 while result.len() < batch_amount as usize {
223 if let Some((_, ref node)) = iter.next() {
224 if let Some(node_info) = node.announcement_info.as_ref() {
225 if node_info.announcement_message.is_some() {
226 result.push(node_info.announcement_message.clone().unwrap());
236 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
237 //TODO: Determine whether to request a full sync based on the network map.
238 const FULL_SYNCS_TO_REQUEST: usize = 5;
239 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
240 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
248 #[derive(PartialEq, Debug)]
249 /// Details about one direction of a channel. Received
250 /// within a channel update.
251 pub struct DirectionalChannelInfo {
252 /// When the last update to the channel direction was issued.
253 /// Value is opaque, as set in the announcement.
254 pub last_update: u32,
255 /// Whether the channel can be currently used for payments (in this one direction).
257 /// The difference in CLTV values that you must have when routing through this channel.
258 pub cltv_expiry_delta: u16,
259 /// The minimum value, which must be relayed to the next hop via the channel
260 pub htlc_minimum_msat: u64,
261 /// The maximum value which may be relayed to the next hop via the channel.
262 pub htlc_maximum_msat: Option<u64>,
263 /// Fees charged when the channel is used for routing
264 pub fees: RoutingFees,
265 /// Most recent update for the channel received from the network
266 /// Mostly redundant with the data we store in fields explicitly.
267 /// Everything else is useful only for sending out for initial routing sync.
268 /// Not stored if contains excess data to prevent DoS.
269 pub last_update_message: Option<ChannelUpdate>,
272 impl fmt::Display for DirectionalChannelInfo {
273 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
274 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)?;
279 impl_writeable!(DirectionalChannelInfo, 0, {
290 /// Details about a channel (both directions).
291 /// Received within a channel announcement.
292 pub struct ChannelInfo {
293 /// Protocol features of a channel communicated during its announcement
294 pub features: ChannelFeatures,
295 /// Source node of the first direction of a channel
296 pub node_one: PublicKey,
297 /// Details about the first direction of a channel
298 pub one_to_two: Option<DirectionalChannelInfo>,
299 /// Source node of the second direction of a channel
300 pub node_two: PublicKey,
301 /// Details about the second direction of a channel
302 pub two_to_one: Option<DirectionalChannelInfo>,
303 /// The channel capacity as seen on-chain, if chain lookup is available.
304 pub capacity_sats: Option<u64>,
305 /// An initial announcement of the channel
306 /// Mostly redundant with the data we store in fields explicitly.
307 /// Everything else is useful only for sending out for initial routing sync.
308 /// Not stored if contains excess data to prevent DoS.
309 pub announcement_message: Option<ChannelAnnouncement>,
312 impl fmt::Display for ChannelInfo {
313 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
314 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
315 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
320 impl_writeable!(ChannelInfo, 0, {
331 /// Fees for routing via a given channel or a node
332 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
333 pub struct RoutingFees {
334 /// Flat routing fee in satoshis
336 /// Liquidity-based routing fee in millionths of a routed amount.
337 /// In other words, 10000 is 1%.
338 pub proportional_millionths: u32,
341 impl Readable for RoutingFees{
342 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
343 let base_msat: u32 = Readable::read(reader)?;
344 let proportional_millionths: u32 = Readable::read(reader)?;
347 proportional_millionths,
352 impl Writeable for RoutingFees {
353 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
354 self.base_msat.write(writer)?;
355 self.proportional_millionths.write(writer)?;
360 #[derive(PartialEq, Debug)]
361 /// Information received in the latest node_announcement from this node.
362 pub struct NodeAnnouncementInfo {
363 /// Protocol features the node announced support for
364 pub features: NodeFeatures,
365 /// When the last known update to the node state was issued.
366 /// Value is opaque, as set in the announcement.
367 pub last_update: u32,
368 /// Color assigned to the node
370 /// Moniker assigned to the node.
371 /// May be invalid or malicious (eg control chars),
372 /// should not be exposed to the user.
374 /// Internet-level addresses via which one can connect to the node
375 pub addresses: Vec<NetAddress>,
376 /// An initial announcement of the node
377 /// Mostly redundant with the data we store in fields explicitly.
378 /// Everything else is useful only for sending out for initial routing sync.
379 /// Not stored if contains excess data to prevent DoS.
380 pub announcement_message: Option<NodeAnnouncement>
383 impl Writeable for NodeAnnouncementInfo {
384 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
385 self.features.write(writer)?;
386 self.last_update.write(writer)?;
387 self.rgb.write(writer)?;
388 self.alias.write(writer)?;
389 (self.addresses.len() as u64).write(writer)?;
390 for ref addr in &self.addresses {
393 self.announcement_message.write(writer)?;
398 impl Readable for NodeAnnouncementInfo {
399 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
400 let features = Readable::read(reader)?;
401 let last_update = Readable::read(reader)?;
402 let rgb = Readable::read(reader)?;
403 let alias = Readable::read(reader)?;
404 let addresses_count: u64 = Readable::read(reader)?;
405 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
406 for _ in 0..addresses_count {
407 match Readable::read(reader) {
408 Ok(Ok(addr)) => { addresses.push(addr); },
409 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
410 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
414 let announcement_message = Readable::read(reader)?;
415 Ok(NodeAnnouncementInfo {
427 /// Details about a node in the network, known from the network announcement.
428 pub struct NodeInfo {
429 /// All valid channels a node has announced
430 pub channels: Vec<u64>,
431 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
432 /// The two fields (flat and proportional fee) are independent,
433 /// meaning they don't have to refer to the same channel.
434 pub lowest_inbound_channel_fees: Option<RoutingFees>,
435 /// More information about a node from node_announcement.
436 /// Optional because we store a Node entry after learning about it from
437 /// a channel announcement, but before receiving a node announcement.
438 pub announcement_info: Option<NodeAnnouncementInfo>
441 impl fmt::Display for NodeInfo {
442 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
443 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
444 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
449 impl Writeable for NodeInfo {
450 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
451 (self.channels.len() as u64).write(writer)?;
452 for ref chan in self.channels.iter() {
455 self.lowest_inbound_channel_fees.write(writer)?;
456 self.announcement_info.write(writer)?;
461 const MAX_ALLOC_SIZE: u64 = 64*1024;
463 impl Readable for NodeInfo {
464 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
465 let channels_count: u64 = Readable::read(reader)?;
466 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
467 for _ in 0..channels_count {
468 channels.push(Readable::read(reader)?);
470 let lowest_inbound_channel_fees = Readable::read(reader)?;
471 let announcement_info = Readable::read(reader)?;
474 lowest_inbound_channel_fees,
480 impl Writeable for NetworkGraph {
481 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
482 (self.channels.len() as u64).write(writer)?;
483 for (ref chan_id, ref chan_info) in self.channels.iter() {
484 (*chan_id).write(writer)?;
485 chan_info.write(writer)?;
487 (self.nodes.len() as u64).write(writer)?;
488 for (ref node_id, ref node_info) in self.nodes.iter() {
489 node_id.write(writer)?;
490 node_info.write(writer)?;
496 impl Readable for NetworkGraph {
497 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
498 let channels_count: u64 = Readable::read(reader)?;
499 let mut channels = BTreeMap::new();
500 for _ in 0..channels_count {
501 let chan_id: u64 = Readable::read(reader)?;
502 let chan_info = Readable::read(reader)?;
503 channels.insert(chan_id, chan_info);
505 let nodes_count: u64 = Readable::read(reader)?;
506 let mut nodes = BTreeMap::new();
507 for _ in 0..nodes_count {
508 let node_id = Readable::read(reader)?;
509 let node_info = Readable::read(reader)?;
510 nodes.insert(node_id, node_info);
519 impl fmt::Display for NetworkGraph {
520 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
521 write!(f, "Network map\n[Channels]\n")?;
522 for (key, val) in self.channels.iter() {
523 write!(f, " {}: {}\n", key, val)?;
525 write!(f, "[Nodes]\n")?;
526 for (key, val) in self.nodes.iter() {
527 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
534 /// Returns all known valid channels' short ids along with announced channel info.
536 /// (C-not exported) because we have no mapping for `BTreeMap`s
537 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
538 /// Returns all known nodes' public keys along with announced node info.
540 /// (C-not exported) because we have no mapping for `BTreeMap`s
541 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
543 /// Get network addresses by node id.
544 /// Returns None if the requested node is completely unknown,
545 /// or if node announcement for the node was never received.
547 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
548 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
549 if let Some(node) = self.nodes.get(pubkey) {
550 if let Some(node_info) = node.announcement_info.as_ref() {
551 return Some(&node_info.addresses)
557 /// Creates a new, empty, network graph.
558 pub fn new() -> NetworkGraph {
560 channels: BTreeMap::new(),
561 nodes: BTreeMap::new(),
565 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
566 /// Announcement signatures are checked here only if Secp256k1 object is provided.
567 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
568 if let Some(sig_verifier) = secp_ctx {
569 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
570 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
573 match self.nodes.get_mut(&msg.contents.node_id) {
574 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
576 if let Some(node_info) = node.announcement_info.as_ref() {
577 if node_info.last_update >= msg.contents.timestamp {
578 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
582 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
583 node.announcement_info = Some(NodeAnnouncementInfo {
584 features: msg.contents.features.clone(),
585 last_update: msg.contents.timestamp,
586 rgb: msg.contents.rgb,
587 alias: msg.contents.alias,
588 addresses: msg.contents.addresses.clone(),
589 announcement_message: if should_relay { Some(msg.clone()) } else { None },
597 /// For a new or already known (from previous announcement) channel, store or update channel info.
598 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
599 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
600 /// which is probably result of a reorg. In that case, we update channel info only if the
601 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
602 /// Announcement signatures are checked here only if Secp256k1 object is provided.
603 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
604 if let Some(sig_verifier) = secp_ctx {
605 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
606 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
607 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
608 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
609 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
612 let should_relay = msg.contents.excess_data.is_empty();
614 let chan_info = ChannelInfo {
615 features: msg.contents.features.clone(),
616 node_one: msg.contents.node_id_1.clone(),
618 node_two: msg.contents.node_id_2.clone(),
620 capacity_sats: utxo_value,
621 announcement_message: if should_relay { Some(msg.clone()) } else { None },
624 match self.channels.entry(msg.contents.short_channel_id) {
625 BtreeEntry::Occupied(mut entry) => {
626 //TODO: because asking the blockchain if short_channel_id is valid is only optional
627 //in the blockchain API, we need to handle it smartly here, though it's unclear
629 if utxo_value.is_some() {
630 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
631 // only sometimes returns results. In any case remove the previous entry. Note
632 // that the spec expects us to "blacklist" the node_ids involved, but we can't
634 // a) we don't *require* a UTXO provider that always returns results.
635 // b) we don't track UTXOs of channels we know about and remove them if they
637 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
638 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
639 *entry.get_mut() = chan_info;
641 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
644 BtreeEntry::Vacant(entry) => {
645 entry.insert(chan_info);
649 macro_rules! add_channel_to_node {
650 ( $node_id: expr ) => {
651 match self.nodes.entry($node_id) {
652 BtreeEntry::Occupied(node_entry) => {
653 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
655 BtreeEntry::Vacant(node_entry) => {
656 node_entry.insert(NodeInfo {
657 channels: vec!(msg.contents.short_channel_id),
658 lowest_inbound_channel_fees: None,
659 announcement_info: None,
666 add_channel_to_node!(msg.contents.node_id_1);
667 add_channel_to_node!(msg.contents.node_id_2);
672 /// Close a channel if a corresponding HTLC fail was sent.
673 /// If permanent, removes a channel from the local storage.
674 /// May cause the removal of nodes too, if this was their last channel.
675 /// If not permanent, makes channels unavailable for routing.
676 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
678 if let Some(chan) = self.channels.remove(&short_channel_id) {
679 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
682 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
683 if let Some(one_to_two) = chan.one_to_two.as_mut() {
684 one_to_two.enabled = false;
686 if let Some(two_to_one) = chan.two_to_one.as_mut() {
687 two_to_one.enabled = false;
693 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
695 // TODO: Wholly remove the node
697 // TODO: downgrade the node
701 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
702 /// Announcement signatures are checked here only if Secp256k1 object is provided.
703 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
705 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
706 let chan_was_enabled;
708 match self.channels.get_mut(&msg.contents.short_channel_id) {
709 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
711 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
712 if htlc_maximum_msat > MAX_VALUE_MSAT {
713 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
716 if let Some(capacity_sats) = channel.capacity_sats {
717 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
718 // Don't query UTXO set here to reduce DoS risks.
719 if htlc_maximum_msat > capacity_sats * 1000 {
720 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
724 macro_rules! maybe_update_channel_info {
725 ( $target: expr, $src_node: expr) => {
726 if let Some(existing_chan_info) = $target.as_ref() {
727 if existing_chan_info.last_update >= msg.contents.timestamp {
728 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
730 chan_was_enabled = existing_chan_info.enabled;
732 chan_was_enabled = false;
735 let last_update_message = if msg.contents.excess_data.is_empty() {
741 let updated_channel_dir_info = DirectionalChannelInfo {
742 enabled: chan_enabled,
743 last_update: msg.contents.timestamp,
744 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
745 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
746 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
748 base_msat: msg.contents.fee_base_msat,
749 proportional_millionths: msg.contents.fee_proportional_millionths,
753 $target = Some(updated_channel_dir_info);
757 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
758 if msg.contents.flags & 1 == 1 {
759 dest_node_id = channel.node_one.clone();
760 if let Some(sig_verifier) = secp_ctx {
761 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
763 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
765 dest_node_id = channel.node_two.clone();
766 if let Some(sig_verifier) = secp_ctx {
767 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
769 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
775 let node = self.nodes.get_mut(&dest_node_id).unwrap();
776 let mut base_msat = msg.contents.fee_base_msat;
777 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
778 if let Some(fees) = node.lowest_inbound_channel_fees {
779 base_msat = cmp::min(base_msat, fees.base_msat);
780 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
782 node.lowest_inbound_channel_fees = Some(RoutingFees {
784 proportional_millionths
786 } else if chan_was_enabled {
787 let node = self.nodes.get_mut(&dest_node_id).unwrap();
788 let mut lowest_inbound_channel_fees = None;
790 for chan_id in node.channels.iter() {
791 let chan = self.channels.get(chan_id).unwrap();
793 if chan.node_one == dest_node_id {
794 chan_info_opt = chan.two_to_one.as_ref();
796 chan_info_opt = chan.one_to_two.as_ref();
798 if let Some(chan_info) = chan_info_opt {
799 if chan_info.enabled {
800 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
801 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
802 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
803 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
808 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
811 Ok(msg.contents.excess_data.is_empty())
814 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
815 macro_rules! remove_from_node {
816 ($node_id: expr) => {
817 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
818 entry.get_mut().channels.retain(|chan_id| {
819 short_channel_id != *chan_id
821 if entry.get().channels.is_empty() {
822 entry.remove_entry();
825 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
830 remove_from_node!(chan.node_one);
831 remove_from_node!(chan.node_two);
838 use ln::features::{ChannelFeatures, NodeFeatures};
839 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
840 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
841 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
843 use util::test_utils;
844 use util::logger::Logger;
845 use util::ser::{Readable, Writeable};
847 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
848 use bitcoin::hashes::Hash;
849 use bitcoin::network::constants::Network;
850 use bitcoin::blockdata::constants::genesis_block;
851 use bitcoin::blockdata::script::Builder;
852 use bitcoin::blockdata::transaction::TxOut;
853 use bitcoin::blockdata::opcodes;
857 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
858 use bitcoin::secp256k1::{All, Secp256k1};
862 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
863 let secp_ctx = Secp256k1::new();
864 let logger = Arc::new(test_utils::TestLogger::new());
865 let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
866 (secp_ctx, net_graph_msg_handler)
870 fn request_full_sync_finite_times() {
871 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
872 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
874 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
875 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
876 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
877 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
878 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
879 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
883 fn handling_node_announcements() {
884 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
886 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
887 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
888 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
889 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
890 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
891 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
892 let zero_hash = Sha256dHash::hash(&[0; 32]);
893 let first_announcement_time = 500;
895 let mut unsigned_announcement = UnsignedNodeAnnouncement {
896 features: NodeFeatures::known(),
897 timestamp: first_announcement_time,
901 addresses: Vec::new(),
902 excess_address_data: Vec::new(),
903 excess_data: Vec::new(),
905 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
906 let valid_announcement = NodeAnnouncement {
907 signature: secp_ctx.sign(&msghash, node_1_privkey),
908 contents: unsigned_announcement.clone()
911 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
913 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
917 // Announce a channel to add a corresponding node.
918 let unsigned_announcement = UnsignedChannelAnnouncement {
919 features: ChannelFeatures::known(),
920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
924 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
925 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
926 excess_data: Vec::new(),
929 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
930 let valid_announcement = ChannelAnnouncement {
931 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
932 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
933 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
934 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
935 contents: unsigned_announcement.clone(),
937 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
938 Ok(res) => assert!(res),
943 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
944 Ok(res) => assert!(res),
948 let fake_msghash = hash_to_message!(&zero_hash);
949 match net_graph_msg_handler.handle_node_announcement(
951 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
952 contents: unsigned_announcement.clone()
955 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
958 unsigned_announcement.timestamp += 1000;
959 unsigned_announcement.excess_data.push(1);
960 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
961 let announcement_with_data = NodeAnnouncement {
962 signature: secp_ctx.sign(&msghash, node_1_privkey),
963 contents: unsigned_announcement.clone()
965 // Return false because contains excess data.
966 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
967 Ok(res) => assert!(!res),
970 unsigned_announcement.excess_data = Vec::new();
972 // Even though previous announcement was not relayed further, we still accepted it,
973 // so we now won't accept announcements before the previous one.
974 unsigned_announcement.timestamp -= 10;
975 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
976 let outdated_announcement = NodeAnnouncement {
977 signature: secp_ctx.sign(&msghash, node_1_privkey),
978 contents: unsigned_announcement.clone()
980 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
982 Err(e) => assert_eq!(e.err, "Update older than last processed update")
987 fn handling_channel_announcements() {
988 let secp_ctx = Secp256k1::new();
989 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
991 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
992 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
993 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
994 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
995 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
996 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
998 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
999 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1000 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1001 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1002 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1005 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1006 features: ChannelFeatures::known(),
1007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1008 short_channel_id: 0,
1011 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1012 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1013 excess_data: Vec::new(),
1016 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1017 let valid_announcement = ChannelAnnouncement {
1018 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1019 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1020 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1021 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1022 contents: unsigned_announcement.clone(),
1025 // Test if the UTXO lookups were not supported
1026 let mut net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
1027 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1028 Ok(res) => assert!(res),
1033 let network = net_graph_msg_handler.network_graph.read().unwrap();
1034 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1040 // If we receive announcement for the same channel (with UTXO lookups disabled),
1041 // drop new one on the floor, since we can't see any changes.
1042 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1044 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1047 // Test if an associated transaction were not on-chain (or not confirmed).
1048 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1049 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1050 net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1051 unsigned_announcement.short_channel_id += 1;
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(),
1062 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1064 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1067 // Now test if the transaction is found in the UTXO set and the script is correct.
1068 unsigned_announcement.short_channel_id += 1;
1069 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1071 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1072 let valid_announcement = ChannelAnnouncement {
1073 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1074 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1075 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1076 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1077 contents: unsigned_announcement.clone(),
1079 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1080 Ok(res) => assert!(res),
1085 let network = net_graph_msg_handler.network_graph.read().unwrap();
1086 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1092 // If we receive announcement for the same channel (but TX is not confirmed),
1093 // drop new one on the floor, since we can't see any changes.
1094 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1095 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1097 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1100 // But if it is confirmed, replace the channel
1101 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1102 unsigned_announcement.features = ChannelFeatures::empty();
1103 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1104 let valid_announcement = ChannelAnnouncement {
1105 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1106 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1107 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1108 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1109 contents: unsigned_announcement.clone(),
1111 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1112 Ok(res) => assert!(res),
1116 let network = net_graph_msg_handler.network_graph.read().unwrap();
1117 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1118 Some(channel_entry) => {
1119 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1125 // Don't relay valid channels with excess data
1126 unsigned_announcement.short_channel_id += 1;
1127 unsigned_announcement.excess_data.push(1);
1128 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1129 let valid_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_announcement) {
1137 Ok(res) => assert!(!res),
1141 unsigned_announcement.excess_data = Vec::new();
1142 let invalid_sig_announcement = ChannelAnnouncement {
1143 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1144 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1145 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1146 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1147 contents: unsigned_announcement.clone(),
1149 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1151 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1154 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1155 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1156 let channel_to_itself_announcement = ChannelAnnouncement {
1157 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1158 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1159 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1160 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1161 contents: unsigned_announcement.clone(),
1163 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1165 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1170 fn handling_channel_update() {
1171 let secp_ctx = Secp256k1::new();
1172 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1173 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1174 let net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1176 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1177 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1178 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1179 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1180 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1181 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1183 let zero_hash = Sha256dHash::hash(&[0; 32]);
1184 let short_channel_id = 0;
1185 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1186 let amount_sats = 1000_000;
1189 // Announce a channel we will update
1190 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1191 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1192 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1193 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1194 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1195 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1196 let unsigned_announcement = UnsignedChannelAnnouncement {
1197 features: ChannelFeatures::empty(),
1202 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1203 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1204 excess_data: Vec::new(),
1207 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1208 let valid_channel_announcement = ChannelAnnouncement {
1209 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1210 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1211 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1212 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1213 contents: unsigned_announcement.clone(),
1215 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1222 let mut unsigned_channel_update = UnsignedChannelUpdate {
1227 cltv_expiry_delta: 144,
1228 htlc_minimum_msat: 1000000,
1229 htlc_maximum_msat: OptionalField::Absent,
1230 fee_base_msat: 10000,
1231 fee_proportional_millionths: 20,
1232 excess_data: Vec::new()
1234 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1235 let valid_channel_update = ChannelUpdate {
1236 signature: secp_ctx.sign(&msghash, node_1_privkey),
1237 contents: unsigned_channel_update.clone()
1240 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1241 Ok(res) => assert!(res),
1246 let network = net_graph_msg_handler.network_graph.read().unwrap();
1247 match network.get_channels().get(&short_channel_id) {
1249 Some(channel_info) => {
1250 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1251 assert!(channel_info.two_to_one.is_none());
1256 unsigned_channel_update.timestamp += 100;
1257 unsigned_channel_update.excess_data.push(1);
1258 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1259 let valid_channel_update = ChannelUpdate {
1260 signature: secp_ctx.sign(&msghash, node_1_privkey),
1261 contents: unsigned_channel_update.clone()
1263 // Return false because contains excess data
1264 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1265 Ok(res) => assert!(!res),
1268 unsigned_channel_update.timestamp += 10;
1270 unsigned_channel_update.short_channel_id += 1;
1271 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1272 let valid_channel_update = ChannelUpdate {
1273 signature: secp_ctx.sign(&msghash, node_1_privkey),
1274 contents: unsigned_channel_update.clone()
1277 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1279 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1281 unsigned_channel_update.short_channel_id = short_channel_id;
1283 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1284 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1285 let valid_channel_update = ChannelUpdate {
1286 signature: secp_ctx.sign(&msghash, node_1_privkey),
1287 contents: unsigned_channel_update.clone()
1290 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1292 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1294 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1296 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1297 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1298 let valid_channel_update = ChannelUpdate {
1299 signature: secp_ctx.sign(&msghash, node_1_privkey),
1300 contents: unsigned_channel_update.clone()
1303 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1305 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1307 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1309 // Even though previous update was not relayed further, we still accepted it,
1310 // so we now won't accept update before the previous one.
1311 unsigned_channel_update.timestamp -= 10;
1312 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1313 let valid_channel_update = ChannelUpdate {
1314 signature: secp_ctx.sign(&msghash, node_1_privkey),
1315 contents: unsigned_channel_update.clone()
1318 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1320 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1322 unsigned_channel_update.timestamp += 500;
1324 let fake_msghash = hash_to_message!(&zero_hash);
1325 let invalid_sig_channel_update = ChannelUpdate {
1326 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1327 contents: unsigned_channel_update.clone()
1330 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1332 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1338 fn handling_htlc_fail_channel_update() {
1339 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1340 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1341 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1342 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1343 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1344 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1345 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1347 let short_channel_id = 0;
1348 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1351 // There is no nodes in the table at the beginning.
1352 let network = net_graph_msg_handler.network_graph.read().unwrap();
1353 assert_eq!(network.get_nodes().len(), 0);
1357 // Announce a channel we will update
1358 let unsigned_announcement = UnsignedChannelAnnouncement {
1359 features: ChannelFeatures::empty(),
1364 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1365 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1366 excess_data: Vec::new(),
1369 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1370 let valid_channel_announcement = ChannelAnnouncement {
1371 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1372 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1373 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1374 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1375 contents: unsigned_announcement.clone(),
1377 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1382 let unsigned_channel_update = UnsignedChannelUpdate {
1387 cltv_expiry_delta: 144,
1388 htlc_minimum_msat: 1000000,
1389 htlc_maximum_msat: OptionalField::Absent,
1390 fee_base_msat: 10000,
1391 fee_proportional_millionths: 20,
1392 excess_data: Vec::new()
1394 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1395 let valid_channel_update = ChannelUpdate {
1396 signature: secp_ctx.sign(&msghash, node_1_privkey),
1397 contents: unsigned_channel_update.clone()
1400 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1401 Ok(res) => assert!(res),
1406 // Non-permanent closing just disables a channel
1408 let network = net_graph_msg_handler.network_graph.read().unwrap();
1409 match network.get_channels().get(&short_channel_id) {
1411 Some(channel_info) => {
1412 assert!(channel_info.one_to_two.is_some());
1417 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1422 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1424 // Non-permanent closing just disables a channel
1426 let network = net_graph_msg_handler.network_graph.read().unwrap();
1427 match network.get_channels().get(&short_channel_id) {
1429 Some(channel_info) => {
1430 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1435 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1440 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1442 // Permanent closing deletes a channel
1444 let network = net_graph_msg_handler.network_graph.read().unwrap();
1445 assert_eq!(network.get_channels().len(), 0);
1446 // Nodes are also deleted because there are no associated channels anymore
1447 assert_eq!(network.get_nodes().len(), 0);
1449 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1453 fn getting_next_channel_announcements() {
1454 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1455 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1456 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1457 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1458 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1459 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1460 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1462 let short_channel_id = 1;
1463 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1465 // Channels were not announced yet.
1466 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1467 assert_eq!(channels_with_announcements.len(), 0);
1470 // Announce a channel we will update
1471 let unsigned_announcement = UnsignedChannelAnnouncement {
1472 features: ChannelFeatures::empty(),
1477 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1478 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1479 excess_data: Vec::new(),
1482 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1483 let valid_channel_announcement = ChannelAnnouncement {
1484 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1485 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1486 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1487 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1488 contents: unsigned_announcement.clone(),
1490 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1496 // Contains initial channel announcement now.
1497 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1498 assert_eq!(channels_with_announcements.len(), 1);
1499 if let Some(channel_announcements) = channels_with_announcements.first() {
1500 let &(_, ref update_1, ref update_2) = channel_announcements;
1501 assert_eq!(update_1, &None);
1502 assert_eq!(update_2, &None);
1509 // Valid channel update
1510 let unsigned_channel_update = UnsignedChannelUpdate {
1515 cltv_expiry_delta: 144,
1516 htlc_minimum_msat: 1000000,
1517 htlc_maximum_msat: OptionalField::Absent,
1518 fee_base_msat: 10000,
1519 fee_proportional_millionths: 20,
1520 excess_data: Vec::new()
1522 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1523 let valid_channel_update = ChannelUpdate {
1524 signature: secp_ctx.sign(&msghash, node_1_privkey),
1525 contents: unsigned_channel_update.clone()
1527 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1533 // Now contains an initial announcement and an update.
1534 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1535 assert_eq!(channels_with_announcements.len(), 1);
1536 if let Some(channel_announcements) = channels_with_announcements.first() {
1537 let &(_, ref update_1, ref update_2) = channel_announcements;
1538 assert_ne!(update_1, &None);
1539 assert_eq!(update_2, &None);
1546 // Channel update with excess data.
1547 let unsigned_channel_update = UnsignedChannelUpdate {
1552 cltv_expiry_delta: 144,
1553 htlc_minimum_msat: 1000000,
1554 htlc_maximum_msat: OptionalField::Absent,
1555 fee_base_msat: 10000,
1556 fee_proportional_millionths: 20,
1557 excess_data: [1; 3].to_vec()
1559 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1560 let valid_channel_update = ChannelUpdate {
1561 signature: secp_ctx.sign(&msghash, node_1_privkey),
1562 contents: unsigned_channel_update.clone()
1564 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1570 // Test that announcements with excess data won't be returned
1571 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1572 assert_eq!(channels_with_announcements.len(), 1);
1573 if let Some(channel_announcements) = channels_with_announcements.first() {
1574 let &(_, ref update_1, ref update_2) = channel_announcements;
1575 assert_eq!(update_1, &None);
1576 assert_eq!(update_2, &None);
1581 // Further starting point have no channels after it
1582 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1583 assert_eq!(channels_with_announcements.len(), 0);
1587 fn getting_next_node_announcements() {
1588 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1589 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1590 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1591 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1592 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1593 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1594 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1596 let short_channel_id = 1;
1597 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1600 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1601 assert_eq!(next_announcements.len(), 0);
1604 // Announce a channel to add 2 nodes
1605 let unsigned_announcement = UnsignedChannelAnnouncement {
1606 features: ChannelFeatures::empty(),
1611 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1612 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1613 excess_data: Vec::new(),
1616 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1617 let valid_channel_announcement = ChannelAnnouncement {
1618 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1619 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1620 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1621 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1622 contents: unsigned_announcement.clone(),
1624 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1631 // Nodes were never announced
1632 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1633 assert_eq!(next_announcements.len(), 0);
1636 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1637 features: NodeFeatures::known(),
1642 addresses: Vec::new(),
1643 excess_address_data: Vec::new(),
1644 excess_data: Vec::new(),
1646 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1647 let valid_announcement = NodeAnnouncement {
1648 signature: secp_ctx.sign(&msghash, node_1_privkey),
1649 contents: unsigned_announcement.clone()
1651 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1656 unsigned_announcement.node_id = node_id_2;
1657 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1658 let valid_announcement = NodeAnnouncement {
1659 signature: secp_ctx.sign(&msghash, node_2_privkey),
1660 contents: unsigned_announcement.clone()
1663 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1669 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1670 assert_eq!(next_announcements.len(), 2);
1672 // Skip the first node.
1673 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1674 assert_eq!(next_announcements.len(), 1);
1677 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1678 let unsigned_announcement = UnsignedNodeAnnouncement {
1679 features: NodeFeatures::known(),
1684 addresses: Vec::new(),
1685 excess_address_data: Vec::new(),
1686 excess_data: [1; 3].to_vec(),
1688 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1689 let valid_announcement = NodeAnnouncement {
1690 signature: secp_ctx.sign(&msghash, node_2_privkey),
1691 contents: unsigned_announcement.clone()
1693 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1694 Ok(res) => assert!(!res),
1699 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1700 assert_eq!(next_announcements.len(), 0);
1704 fn network_graph_serialization() {
1705 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1707 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1708 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1709 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1710 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1712 // Announce a channel to add a corresponding node.
1713 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1714 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1715 let unsigned_announcement = UnsignedChannelAnnouncement {
1716 features: ChannelFeatures::known(),
1717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1718 short_channel_id: 0,
1721 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1722 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1723 excess_data: Vec::new(),
1726 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1727 let valid_announcement = ChannelAnnouncement {
1728 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1729 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1730 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1731 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1732 contents: unsigned_announcement.clone(),
1734 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1735 Ok(res) => assert!(res),
1740 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1741 let unsigned_announcement = UnsignedNodeAnnouncement {
1742 features: NodeFeatures::known(),
1747 addresses: Vec::new(),
1748 excess_address_data: Vec::new(),
1749 excess_data: Vec::new(),
1751 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1752 let valid_announcement = NodeAnnouncement {
1753 signature: secp_ctx.sign(&msghash, node_1_privkey),
1754 contents: unsigned_announcement.clone()
1757 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1762 let network = net_graph_msg_handler.network_graph.write().unwrap();
1763 let mut w = test_utils::TestVecWriter(Vec::new());
1764 assert!(!network.get_nodes().is_empty());
1765 assert!(!network.get_channels().is_empty());
1766 network.write(&mut w).unwrap();
1767 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);