Merge pull request #646 from naumenkogs/2020-06-router-mpp
[rust-lightning] / lightning / src / routing / network_graph.rs
index bba99244b4a98624a1725c2d57a7eb2be15b6712..13dc662642c62ccd8aabc9affd520a9ad927bb2a 100644 (file)
@@ -40,8 +40,12 @@ use std::collections::btree_map::Entry as BtreeEntry;
 use std::ops::Deref;
 use bitcoin::hashes::hex::ToHex;
 
+/// The maximum number of extra bytes which we do not understand in a gossip message before we will
+/// refuse to relay the message.
+const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
+
 /// Represents the network as nodes and channels between them
-#[derive(PartialEq)]
+#[derive(Clone, PartialEq)]
 pub struct NetworkGraph {
        genesis_hash: BlockHash,
        channels: BTreeMap<u64, ChannelInfo>,
@@ -98,6 +102,13 @@ impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access
                }
        }
 
+       /// Adds a provider used to check new announcements. Does not affect
+       /// existing announcements unless they are updated.
+       /// Add, update or remove the provider would replace the current one.
+       pub fn add_chain_access(&mut self, chain_access: Option<C>) {
+               self.chain_access = chain_access;
+       }
+
        /// Take a read lock on the network_graph and return it in the C-bindings
        /// newtype helper. This is likely only useful when called via the C
        /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
@@ -139,13 +150,15 @@ macro_rules! secp_verify_sig {
 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
        fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
-               Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
+               Ok(msg.contents.excess_data.len() <=  MAX_EXCESS_BYTES_FOR_RELAY &&
+                  msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                  msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
                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 { "" });
-               Ok(msg.contents.excess_data.is_empty())
+               Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
@@ -164,7 +177,7 @@ impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for N
 
        fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
                self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
-               Ok(msg.contents.excess_data.is_empty())
+               Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
        }
 
        fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
@@ -329,7 +342,7 @@ where
        }
 }
 
-#[derive(PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about one direction of a channel. Received
 /// within a channel update.
 pub struct DirectionalChannelInfo {
@@ -370,7 +383,7 @@ impl_writeable!(DirectionalChannelInfo, 0, {
        last_update_message
 });
 
-#[derive(PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about a channel (both directions).
 /// Received within a channel announcement.
 pub struct ChannelInfo {
@@ -441,7 +454,7 @@ impl Writeable for RoutingFees {
        }
 }
 
-#[derive(PartialEq, Debug)]
+#[derive(Clone, Debug, PartialEq)]
 /// Information received in the latest node_announcement from this node.
 pub struct NodeAnnouncementInfo {
        /// Protocol features the node announced support for
@@ -507,7 +520,7 @@ impl Readable for NodeAnnouncementInfo {
        }
 }
 
-#[derive(PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
 /// Details about a node in the network, known from the network announcement.
 pub struct NodeInfo {
        /// All valid channels a node has announced
@@ -680,7 +693,10 @@ impl NetworkGraph {
                                        }
                                }
 
-                               let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
+                               let should_relay =
+                                       msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                                       msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
+                                       msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
                                node.announcement_info = Some(NodeAnnouncementInfo {
                                        features: msg.features.clone(),
                                        last_update: msg.timestamp,
@@ -773,7 +789,8 @@ impl NetworkGraph {
                                node_two: msg.node_id_2.clone(),
                                two_to_one: None,
                                capacity_sats: utxo_value,
-                               announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
+                               announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
+                                       { full_msg.cloned() } else { None },
                        };
 
                match self.channels.entry(msg.short_channel_id) {
@@ -902,7 +919,8 @@ impl NetworkGraph {
                                                        chan_was_enabled = false;
                                                }
 
-                                               let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
+                                               let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
+                                                       { full_msg.cloned() } else { None };
 
                                                let updated_channel_dir_info = DirectionalChannelInfo {
                                                        enabled: chan_enabled,
@@ -1002,7 +1020,7 @@ impl NetworkGraph {
 mod tests {
        use chain;
        use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
-       use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
+       use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
        use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
                UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
                ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
@@ -1124,7 +1142,7 @@ mod tests {
                };
 
                unsigned_announcement.timestamp += 1000;
-               unsigned_announcement.excess_data.push(1);
+               unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                let announcement_with_data = NodeAnnouncement {
                        signature: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1292,7 +1310,7 @@ mod tests {
 
                // Don't relay valid channels with excess data
                unsigned_announcement.short_channel_id += 1;
-               unsigned_announcement.excess_data.push(1);
+               unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                let valid_announcement = ChannelAnnouncement {
                        node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1422,7 +1440,7 @@ mod tests {
                }
 
                unsigned_channel_update.timestamp += 100;
-               unsigned_channel_update.excess_data.push(1);
+               unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
                let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
                let valid_channel_update = ChannelUpdate {
                        signature: secp_ctx.sign(&msghash, node_1_privkey),
@@ -1722,7 +1740,7 @@ mod tests {
                                htlc_maximum_msat: OptionalField::Absent,
                                fee_base_msat: 10000,
                                fee_proportional_millionths: 20,
-                               excess_data: [1; 3].to_vec()
+                               excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
                        };
                        let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
                        let valid_channel_update = ChannelUpdate {
@@ -1851,7 +1869,7 @@ mod tests {
                                alias: [0; 32],
                                addresses: Vec::new(),
                                excess_address_data: Vec::new(),
-                               excess_data: [1; 3].to_vec(),
+                               excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
                        };
                        let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
                        let valid_announcement = NodeAnnouncement {