f tweak const names somewhat
[rust-lightning] / lightning / src / ln / peer_handler.rs
index e6a06b56e9598b25958729a2bd974583ffef6cee..38308bb8c434ff2259779dec267d41c7839e1b81 100644 (file)
@@ -32,11 +32,11 @@ use routing::network_graph::NetGraphMsgHandler;
 use prelude::*;
 use io;
 use alloc::collections::LinkedList;
-use alloc::fmt::Debug;
 use sync::{Arc, Mutex};
 use core::sync::atomic::{AtomicUsize, Ordering};
 use core::{cmp, hash, fmt, mem};
 use core::ops::Deref;
+use core::convert::Infallible;
 #[cfg(feature = "std")] use std::error;
 
 use bitcoin::hashes::sha256::Hash as Sha256;
@@ -47,7 +47,7 @@ use bitcoin::hashes::{HashEngine, Hash};
 pub trait CustomMessageHandler: wire::CustomMessageReader {
        /// Called with the message type that was received and the buffer to be read.
        /// Can return a `MessageHandlingError` if the message could not be handled.
-       fn handle_custom_message(&self, msg: Self::CustomMessage) -> Result<(), LightningError>;
+       fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
 
        /// Gets the list of pending messages which were generated by the custom message
        /// handler, clearing the list in the process. The first tuple element must
@@ -66,7 +66,6 @@ impl RoutingMessageHandler for IgnoringMessageHandler {
        fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
        fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
        fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
-       fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
        fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
                Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
        fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
@@ -81,28 +80,28 @@ impl Deref for IgnoringMessageHandler {
        fn deref(&self) -> &Self { self }
 }
 
-impl wire::Type for () {
+// Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
+// method that takes self for it.
+impl wire::Type for Infallible {
        fn type_id(&self) -> u16 {
-               // We should never call this for `DummyCustomType`
                unreachable!();
        }
 }
-
-impl Writeable for () {
+impl Writeable for Infallible {
        fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
                unreachable!();
        }
 }
 
 impl wire::CustomMessageReader for IgnoringMessageHandler {
-       type CustomMessage = ();
+       type CustomMessage = Infallible;
        fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
                Ok(None)
        }
 }
 
 impl CustomMessageHandler for IgnoringMessageHandler {
-       fn handle_custom_message(&self, _msg: Self::CustomMessage) -> Result<(), LightningError> {
+       fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
                // Since we always return `None` in the read the handle method should never be called.
                unreachable!();
        }
@@ -286,6 +285,10 @@ enum InitSyncTracker{
        NodesSyncing(PublicKey),
 }
 
+/// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
+/// forwarding gossip messages to peers altogether.
+const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
+
 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
 /// we have fewer than this many messages in the outbound buffer again.
 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
@@ -293,7 +296,7 @@ enum InitSyncTracker{
 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
 /// the peer.
-const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = 20;
+const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
 
 struct Peer {
        channel_encryptor: PeerChannelEncryptor,
@@ -470,7 +473,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                CM::Target: ChannelMessageHandler,
                RM::Target: RoutingMessageHandler,
                L::Target: Logger,
-               CMH::Target: CustomMessageHandler + wire::CustomMessageReader {
+               CMH::Target: CustomMessageHandler {
        /// Constructs a new PeerManager with the given message handlers and node_id secret key
        /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
        /// cryptographically secure random bytes.
@@ -720,7 +723,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
        }
 
        /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
-       fn enqueue_message<M: wire::Type + Writeable + Debug>(&self, peer: &mut Peer, message: &M) {
+       fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
                let mut buffer = VecWriter(Vec::with_capacity(2048));
                wire::write(message, &mut buffer).unwrap(); // crash if the write failed
                let encoded_message = buffer.0;
@@ -1087,7 +1090,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
                        },
                        wire::Message::Custom(custom) => {
-                               self.custom_message_handler.handle_custom_message(custom)?;
+                               self.custom_message_handler.handle_custom_message(custom, &peer.their_node_id.unwrap())?;
                        },
                };
                Ok(should_forward)
@@ -1170,6 +1173,9 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
        /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
        /// issues!
        ///
+       /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
+       /// or one of the other clients provided in our language bindings.
+       ///
        /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
        /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
        /// [`send_data`]: SocketDescriptor::send_data
@@ -1318,9 +1324,6 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                                                let peer = get_peer_for_forwarding!(node_id);
                                                peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
                                        },
-                                       MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
-                                               self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
-                                       },
                                        MessageSendEvent::HandleError { ref node_id, ref action } => {
                                                match *action {
                                                        msgs::ErrorAction::DisconnectPeer { ref msg } => {
@@ -1432,6 +1435,23 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> P
                }
        }
 
+       /// Disconnects all currently-connected peers. This is useful on platforms where there may be
+       /// an indication that TCP sockets have stalled even if we weren't around to time them out
+       /// using regular ping/pongs.
+       pub fn disconnect_all_peers(&self) {
+               let mut peers_lock = self.peers.lock().unwrap();
+               let peers = &mut *peers_lock;
+               for (mut descriptor, peer) in peers.peers.drain() {
+                       if let Some(node_id) = peer.their_node_id {
+                               log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
+                               peers.node_id_to_descriptor.remove(&node_id);
+                               self.message_handler.chan_handler.peer_disconnected(&node_id, false);
+                       }
+                       descriptor.disconnect_socket();
+               }
+               debug_assert!(peers.node_id_to_descriptor.is_empty());
+       }
+
        /// Send pings to each peer and disconnect those which did not respond to the last round of
        /// pings.
        ///