Merge pull request #1430 from vincenzopalazzo/macros/channel_reestablish_v2
[rust-lightning] / lightning / src / ln / peer_handler.rs
index 120a7535a6ed2551ac63662c03042b36933c2d35..07300fdf62ef122fd9e8826e5ce24604ba506df0 100644 (file)
@@ -339,6 +339,7 @@ struct Peer {
        msgs_sent_since_pong: usize,
        awaiting_pong_timer_tick_intervals: i8,
        received_message_since_timer_tick: bool,
+       sent_gossip_timestamp_filter: bool,
 }
 
 impl Peer {
@@ -348,7 +349,11 @@ impl Peer {
        /// announcements/updates for the given channel_id then we will send it when we get to that
        /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
        /// sent the old versions, we should send the update, and so return true here.
-       fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
+       fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
+               if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
+                       !self.sent_gossip_timestamp_filter {
+                               return false;
+                       }
                match self.sync_status {
                        InitSyncTracker::NoSyncRequested => true,
                        InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
@@ -358,6 +363,10 @@ impl Peer {
 
        /// Similar to the above, but for node announcements indexed by node_id.
        fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
+               if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
+                       !self.sent_gossip_timestamp_filter {
+                               return false;
+                       }
                match self.sync_status {
                        InitSyncTracker::NoSyncRequested => true,
                        InitSyncTracker::ChannelsSyncing(_) => false,
@@ -377,6 +386,8 @@ struct PeerHolder<Descriptor: SocketDescriptor> {
 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
 /// issues such as overly long function definitions.
+///
+/// (C-not exported) as Arcs don't make sense in bindings
 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<NetworkGraph>, Arc<C>, Arc<L>>>, Arc<L>, Arc<IgnoringMessageHandler>>;
 
 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
@@ -385,6 +396,8 @@ pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArc
 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
 /// helps with issues such as long function definitions.
+///
+/// (C-not exported) as Arcs don't make sense in bindings
 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g NetworkGraph, &'h C, &'f L>, &'f L, IgnoringMessageHandler>;
 
 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
@@ -502,21 +515,21 @@ impl core::fmt::Display for OptionalFromDebugger<'_> {
 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
        match ip_address{
                // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
-               Some(NetAddress::IPv4{addr: [0xA, 0x00..=0xFF, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
                // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
-               Some(NetAddress::IPv4{addr: [0x0, 0x0..=0xFF, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
                // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
-               Some(NetAddress::IPv4{addr: [0x64, 0x40..=0x7F, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
                // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
-               Some(NetAddress::IPv4{addr: [0x7F, 0x0..=0xFF, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
                // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
-               Some(NetAddress::IPv4{addr: [0xA9, 0xFE, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
                // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
-               Some(NetAddress::IPv4{addr: [0xAC, 0x10..=0x1F, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
                // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
-               Some(NetAddress::IPv4{addr: [0xC0, 0xA8, _, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
                // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
-               Some(NetAddress::IPv4{addr: [0xC0, 0x58, 0x63, _], port: _}) => None,
+               Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
                // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
                Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
                // For remaining addresses
@@ -576,9 +589,10 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
 
        /// Indicates a new outbound connection has been established to a node with the given node_id
        /// and an optional remote network address.
+       ///
        /// The remote network address adds the option to report a remote IP address back to a connecting
-       /// peer using the init message. 
-       /// The user should pass the remote network address to whatever host they are connected to.
+       /// peer using the init message.
+       /// The user should pass the remote network address of the host they are connected to.
        ///
        /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
        /// descriptor but must disconnect the connection immediately.
@@ -614,6 +628,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                        msgs_sent_since_pong: 0,
                        awaiting_pong_timer_tick_intervals: 0,
                        received_message_since_timer_tick: false,
+                       sent_gossip_timestamp_filter: false,
                }).is_some() {
                        panic!("PeerManager driver duplicated descriptors!");
                };
@@ -623,6 +638,10 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
        /// Indicates a new inbound connection has been established to a node with an optional remote
        /// network address.
        ///
+       /// The remote network address adds the option to report a remote IP address back to a connecting
+       /// peer using the init message.
+       /// The user should pass the remote network address of the host they are connected to.
+       ///
        /// May refuse the connection by returning an Err, but will never write bytes to the remote end
        /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
        /// call socket_disconnected for the new descriptor but must disconnect the connection
@@ -656,6 +675,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                        msgs_sent_since_pong: 0,
                        awaiting_pong_timer_tick_intervals: 0,
                        received_message_since_timer_tick: false,
+                       sent_gossip_timestamp_filter: false,
                }).is_some() {
                        panic!("PeerManager driver duplicated descriptors!");
                };
@@ -903,7 +923,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                                                        peer.their_node_id = Some(their_node_id);
                                                                        insert_node_id!();
                                                                        let features = InitFeatures::known();
-                                                                       let resp = msgs::Init { features, remote_network_address:  filter_addresses(peer.their_net_address.clone())};
+                                                                       let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone())};
                                                                        self.enqueue_message(peer, &resp);
                                                                        peer.awaiting_pong_timer_tick_intervals = 0;
                                                                },
@@ -914,7 +934,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                                                        peer.their_node_id = Some(their_node_id);
                                                                        insert_node_id!();
                                                                        let features = InitFeatures::known();
-                                                                       let resp = msgs::Init { features, remote_network_address:  filter_addresses(peer.their_net_address.clone())};
+                                                                       let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone())};
                                                                        self.enqueue_message(peer, &resp);
                                                                        peer.awaiting_pong_timer_tick_intervals = 0;
                                                                },
@@ -1049,7 +1069,8 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
 
                                log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.features);
 
-                               if msg.features.initial_routing_sync() {
+                               // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
+                               if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
                                        peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
                                }
                                if !msg.features.supports_static_remote_key() {
@@ -1196,7 +1217,13 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
                        },
                        wire::Message::GossipTimestampFilter(_msg) => {
-                               // TODO: handle message
+                               // When supporting gossip messages, start inital gossip sync only after we receive
+                               // a GossipTimestampFilter
+                               if peer.their_features.as_ref().unwrap().supports_gossip_queries() &&
+                                       !peer.sent_gossip_timestamp_filter {
+                                       peer.sent_gossip_timestamp_filter = true;
+                                       peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
+                               }
                        },
 
                        // Unknown messages:
@@ -1698,7 +1725,11 @@ fn is_gossip_msg(type_id: u16) -> bool {
        match type_id {
                msgs::ChannelAnnouncement::TYPE |
                msgs::ChannelUpdate::TYPE |
-               msgs::NodeAnnouncement::TYPE => true,
+               msgs::NodeAnnouncement::TYPE |
+               msgs::QueryChannelRange::TYPE |
+               msgs::ReplyChannelRange::TYPE |
+               msgs::QueryShortChannelIds::TYPE |
+               msgs::ReplyShortChannelIdsEnd::TYPE => true,
                _ => false
        }
 }
@@ -1790,6 +1821,8 @@ mod tests {
                assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
                peer_b.process_events();
                assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
+               peer_a.process_events();
+               assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
                (fd_a.clone(), fd_b.clone())
        }
 
@@ -1853,21 +1886,21 @@ mod tests {
                let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
 
                // Make each peer to read the messages that the other peer just wrote to them. Note that
-               // due to the max-messagse-before-ping limits this may take a few iterations to complete.
+               // due to the max-message-before-ping limits this may take a few iterations to complete.
                for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
-                       peers[0].process_events();
-                       let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
-                       assert!(!b_read_data.is_empty());
-
-                       peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
                        peers[1].process_events();
-
                        let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
                        assert!(!a_read_data.is_empty());
+
                        peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
+                       peers[0].process_events();
 
-                       peers[1].process_events();
-                       assert_eq!(fd_b.outbound_data.lock().unwrap().len(), 0, "Until B receives data, it shouldn't send more messages");
+                       let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
+                       assert!(!b_read_data.is_empty());
+                       peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
+
+                       peers[0].process_events();
+                       assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
                }
 
                // Check that each peer has received the expected number of channel updates and channel