X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fpeer_handler.rs;h=040ccc655f4b93187ea52eefce46ecbe166aa8d9;hb=746f25aed06c19b3a4d4bfb25d15b3b08ed410a0;hp=d86cddb13dbc66162c52af7128f0c3c180688532;hpb=0017bc88a84fa7f253bede430fbb147f6e60c50b;p=rust-lightning diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index d86cddb1..040ccc65 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -17,24 +17,26 @@ use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey}; -use ln::features::InitFeatures; -use ln::msgs; -use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, RoutingMessageHandler}; -use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}; -use util::ser::{VecWriter, Writeable, Writer}; -use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep}; -use ln::wire; -use ln::wire::Encode; -use routing::gossip::{NetworkGraph, P2PGossipSync}; -use util::atomic_counter::AtomicCounter; -use util::events::{MessageSendEvent, MessageSendEventsProvider}; -use util::logger::Logger; - -use prelude::*; -use io; +use crate::chain::keysinterface::{KeysManager, NodeSigner, Recipient}; +use crate::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider}; +use crate::ln::features::{InitFeatures, NodeFeatures}; +use crate::ln::msgs; +use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler}; +use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}; +use crate::util::ser::{VecWriter, Writeable, Writer}; +use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep}; +use crate::ln::wire; +use crate::ln::wire::Encode; +use crate::onion_message::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger}; +use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias}; +use crate::util::atomic_counter::AtomicCounter; +use crate::util::logger::Logger; + +use crate::prelude::*; +use crate::io; use alloc::collections::LinkedList; -use sync::{Arc, Mutex, MutexGuard, FairRwLock}; -use core::sync::atomic::{AtomicBool, Ordering}; +use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock}; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use core::{cmp, hash, fmt, mem}; use core::ops::Deref; use core::convert::Infallible; @@ -44,16 +46,23 @@ use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256::HashEngine as Sha256Engine; use bitcoin::hashes::{HashEngine, Hash}; -/// Handler for BOLT1-compliant messages. +/// A handler provided to [`PeerManager`] for reading and handling custom messages. +/// +/// [BOLT 1] specifies a custom message type range for use with experimental or application-specific +/// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the +/// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler. +/// +/// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md +/// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message 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. + /// Handles the given message sent from `sender_node_id`, possibly producing messages for + /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`] + /// to send. 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 - /// correspond to the intended recipients node ids. If no connection to one of the - /// specified node does not exist, the message is simply not sent to it. + /// Returns the list of pending messages that were generated by the handler, clearing the list + /// in the process. Each message is paired with the node id of the intended recipient. If no + /// connection to the node exists, then the message is simply not sent. fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>; } @@ -67,15 +76,47 @@ impl RoutingMessageHandler for IgnoringMessageHandler { fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result { Ok(false) } fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result { Ok(false) } fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result { Ok(false) } - fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> - Vec<(msgs::ChannelAnnouncement, Option, Option)> { Vec::new() } - fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec { Vec::new() } - fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {} + fn get_next_channel_announcement(&self, _starting_point: u64) -> + Option<(msgs::ChannelAnnouncement, Option, Option)> { None } + fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option { None } + fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) } fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) } fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) } fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) } fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) } + fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } + fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { + InitFeatures::empty() + } + fn processing_queue_high(&self) -> bool { false } +} +impl OnionMessageProvider for IgnoringMessageHandler { + fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option { None } +} +impl OnionMessageHandler for IgnoringMessageHandler { + fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {} + fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) } + fn peer_disconnected(&self, _their_node_id: &PublicKey) {} + fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } + fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { + InitFeatures::empty() + } +} +impl CustomOnionMessageHandler for IgnoringMessageHandler { + type CustomMessage = Infallible; + fn handle_custom_message(&self, _msg: Infallible) { + // Since we always return `None` in the read the handle method should never be called. + unreachable!(); + } + fn read_custom_message(&self, _msg_type: u64, _buffer: &mut R) -> Result, msgs::DecodeError> where Self: Sized { + Ok(None) + } +} + +impl CustomOnionMessageContents for Infallible { + fn tlv_type(&self) -> u64 { unreachable!(); } } + impl Deref for IgnoringMessageHandler { type Target = IgnoringMessageHandler; fn deref(&self) -> &Self { self } @@ -139,10 +180,10 @@ impl MessageSendEventsProvider for ErroringMessageHandler { impl ChannelMessageHandler for ErroringMessageHandler { // Any messages which are related to a specific channel generate an error message to let the // peer know we don't care about channels. - fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) { + fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) { ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id); } - fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) { + fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) { ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id); } fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) { @@ -154,7 +195,7 @@ impl ChannelMessageHandler for ErroringMessageHandler { fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } - fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) { + fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) { ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); } fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) { @@ -189,9 +230,28 @@ impl ChannelMessageHandler for ErroringMessageHandler { } // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them. fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {} - fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {} - fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {} + fn peer_disconnected(&self, _their_node_id: &PublicKey) {} + fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) } fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {} + fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() } + fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { + // Set a number of features which various nodes may require to talk to us. It's totally + // reasonable to indicate we "support" all kinds of channel features...we just reject all + // channels. + let mut features = InitFeatures::empty(); + features.set_data_loss_protect_optional(); + features.set_upfront_shutdown_script_optional(); + features.set_variable_length_onion_optional(); + features.set_static_remote_key_optional(); + features.set_payment_secret_optional(); + features.set_basic_mpp_optional(); + features.set_wumbo_optional(); + features.set_shutdown_any_segwit_optional(); + features.set_channel_type_optional(); + features.set_scid_privacy_optional(); + features.set_zero_conf_optional(); + features + } } impl Deref for ErroringMessageHandler { type Target = ErroringMessageHandler; @@ -199,9 +259,11 @@ impl Deref for ErroringMessageHandler { } /// Provides references to trait impls which handle different types of messages. -pub struct MessageHandler where +pub struct MessageHandler where CM::Target: ChannelMessageHandler, - RM::Target: RoutingMessageHandler { + RM::Target: RoutingMessageHandler, + OM::Target: OnionMessageHandler, +{ /// A message handler which handles messages specific to channels. Usually this is just a /// [`ChannelManager`] object or an [`ErroringMessageHandler`]. /// @@ -212,13 +274,17 @@ pub struct MessageHandler where /// /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync pub route_handler: RM, + + /// A message handler which handles onion messages. For now, this can only be an + /// [`IgnoringMessageHandler`]. + pub onion_message_handler: OM, } /// Provides an object which can be used to send data to and which uniquely identifies a connection /// to a remote host. You will need to be able to generate multiple of these which meet Eq and /// implement Hash to meet the PeerManager API. /// -/// For efficiency, Clone should be relatively cheap for this type. +/// For efficiency, [`Clone`] should be relatively cheap for this type. /// /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it @@ -256,16 +322,7 @@ pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone { /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the /// descriptor. #[derive(Clone)] -pub struct PeerHandleError { - /// Used to indicate that we probably can't make any future connections to this peer (e.g. - /// because we required features that our peer was missing, or vice versa). - /// - /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close - /// any channels with this peer or check for new versions of LDK. - /// - /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager - pub no_connection_possible: bool, -} +pub struct PeerHandleError { } impl fmt::Debug for PeerHandleError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("Peer Sent Invalid Data") @@ -287,7 +344,7 @@ impl error::Error for PeerHandleError { enum InitSyncTracker{ NoSyncRequested, ChannelsSyncing(u64), - NodesSyncing(PublicKey), + NodesSyncing(NodeId), } /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop @@ -298,7 +355,7 @@ const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2; /// 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, /// refilled as we send bytes. -const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10; +const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12; /// 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 = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO; @@ -323,16 +380,33 @@ const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4; /// tick. Once we have sent this many messages since the last ping, we send a ping right away to /// ensures we don't just fill up our send buffer and leave the peer with too many messages to /// process before the next ping. +/// +/// Note that we continue responding to other messages even after we've sent this many messages, so +/// it's more of a general guideline used for gossip backfill (and gossip forwarding, times +/// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit. const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32; struct Peer { channel_encryptor: PeerChannelEncryptor, - their_node_id: Option, + /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip + /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field. + their_node_id: Option<(PublicKey, NodeId)>, + /// The features provided in the peer's [`msgs::Init`] message. + /// + /// This is set only after we've processed the [`msgs::Init`] message and called relevant + /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our + /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to + /// check this. their_features: Option, their_net_address: Option, pending_outbound_buffer: LinkedList>, pending_outbound_buffer_first_msg_offset: usize, + /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily + /// prioritize channel messages over them. + /// + /// Note that these messages are *not* encrypted/MAC'd, and are only serialized. + gossip_broadcast_buffer: LinkedList>, awaiting_write_event: bool, pending_read_buffer: Vec, @@ -342,12 +416,27 @@ struct Peer { sync_status: InitSyncTracker, msgs_sent_since_pong: usize, - awaiting_pong_timer_tick_intervals: i8, + awaiting_pong_timer_tick_intervals: i64, received_message_since_timer_tick: bool, sent_gossip_timestamp_filter: bool, + + /// Indicates we've received a `channel_announcement` since the last time we had + /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a + /// `channel_announcement` at all - we set this unconditionally but unset it every time we + /// check if we're gossip-processing-backlogged). + received_channel_announce_since_backlogged: bool, + + inbound_connection: bool, } impl Peer { + /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected` + /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer + /// normally. + fn handshake_complete(&self) -> bool { + self.their_features.is_some() + } + /// Returns true if the channel announcements/updates for the given channel should be /// forwarded to this peer. /// If we are sending our routing table to this peer and we have not yet sent channel @@ -355,6 +444,7 @@ impl Peer { /// 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 { + if !self.handshake_complete() { return false; } if self.their_features.as_ref().unwrap().supports_gossip_queries() && !self.sent_gossip_timestamp_filter { return false; @@ -367,7 +457,8 @@ impl Peer { } /// Similar to the above, but for node announcements indexed by node_id. - fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool { + fn should_forward_node_announcement(&self, node_id: NodeId) -> bool { + if !self.handshake_complete() { return false; } if self.their_features.as_ref().unwrap().supports_gossip_queries() && !self.sent_gossip_timestamp_filter { return false; @@ -375,9 +466,54 @@ impl Peer { match self.sync_status { InitSyncTracker::NoSyncRequested => true, InitSyncTracker::ChannelsSyncing(_) => false, - InitSyncTracker::NodesSyncing(pk) => pk < node_id, + InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(), } } + + /// Returns whether we should be reading bytes from this peer, based on whether its outbound + /// buffer still has space and we don't need to pause reads to get some writes out. + fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool { + if !gossip_processing_backlogged { + self.received_channel_announce_since_backlogged = false; + } + self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && + (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged) + } + + /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's + /// outbound buffer. This is checked every time the peer's buffer may have been drained. + fn should_buffer_gossip_backfill(&self) -> bool { + self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty() + && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK + && self.handshake_complete() + } + + /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked + /// every time the peer's buffer may have been drained. + fn should_buffer_onion_message(&self) -> bool { + self.pending_outbound_buffer.is_empty() && self.handshake_complete() + && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK + } + + /// Determines if we should push additional gossip broadcast messages onto a peer's outbound + /// buffer. This is checked every time the peer's buffer may have been drained. + fn should_buffer_gossip_broadcast(&self) -> bool { + self.pending_outbound_buffer.is_empty() && self.handshake_complete() + && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK + } + + /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts. + fn buffer_full_drop_gossip_broadcast(&self) -> bool { + let total_outbound_buffered = + self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len(); + + total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP || + self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO + } + + fn set_their_node_id(&mut self, node_id: PublicKey) { + self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id))); + } } /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g. @@ -386,8 +522,8 @@ impl Peer { /// 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 = PeerManager>, Arc, Arc, Arc>>, Arc, Arc>; +/// This is not exported to bindings users as `Arc`s don't make sense in bindings. +pub type SimpleArcPeerManager = PeerManager>, Arc>>, Arc, Arc>>, Arc>, Arc, IgnoringMessageHandler, Arc>; /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't @@ -396,8 +532,8 @@ pub type SimpleArcPeerManager = PeerManager = PeerManager, &'e P2PGossipSync<&'g NetworkGraph, &'h C, &'f L>, &'f L, IgnoringMessageHandler>; +/// This is not exported to bindings users as general type aliases don't make sense in bindings. +pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, SD, M, T, F, C, L> = PeerManager, &'f P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, &'i SimpleRefOnionMessenger<'j, 'k, L>, &'f L, IgnoringMessageHandler, &'c KeysManager>; /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls /// socket events into messages which it passes on to its [`MessageHandler`]. @@ -411,19 +547,21 @@ pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> /// [`PeerManager`] functions related to the same connection must occur only in serial, making new /// calls only after previous ones have returned. /// -/// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager -/// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but -/// essentially you should default to using a SimpleRefPeerManager, and use a -/// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when +/// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`] +/// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but +/// essentially you should default to using a [`SimpleRefPeerManager`], and use a +/// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when /// you're using lightning-net-tokio. /// /// [`read_event`]: PeerManager::read_event -pub struct PeerManager where +pub struct PeerManager where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, + OM::Target: OnionMessageHandler, L::Target: Logger, - CMH::Target: CustomMessageHandler { - message_handler: MessageHandler, + CMH::Target: CustomMessageHandler, + NS::Target: NodeSigner { + message_handler: MessageHandler, /// Connection state for each connected peer - we have an outer read-write lock which is taken /// as read while we're doing processing for a peer and taken write when a peer is being added /// or removed. @@ -447,12 +585,21 @@ pub struct PeerManager } @@ -482,58 +629,74 @@ macro_rules! encode_msg { }} } -impl PeerManager where +impl PeerManager where CM::Target: ChannelMessageHandler, - L::Target: Logger { - /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message - /// handler is used and network graph messages are ignored. + OM::Target: OnionMessageHandler, + L::Target: Logger, + NS::Target: NodeSigner { + /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and + /// `OnionMessageHandler`. No routing message handler is used and network graph messages are + /// ignored. /// - /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be + /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. /// - /// (C-not exported) as we can't export a PeerManager with a dummy route handler - pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { + /// `current_time` is used as an always-increasing counter that survives across restarts and is + /// incremented irregularly internally. In general it is best to simply use the current UNIX + /// timestamp, however if it is not available a persistent counter that increases once per + /// minute should suffice. + /// + /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler + pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self { Self::new(MessageHandler { chan_handler: channel_message_handler, route_handler: IgnoringMessageHandler{}, - }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{}) + onion_message_handler, + }, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{}, node_signer) } } -impl PeerManager where +impl PeerManager where RM::Target: RoutingMessageHandler, - L::Target: Logger { - /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message - /// handler is used and messages related to channels will be ignored (or generate error - /// messages). Note that some other lightning implementations time-out connections after some - /// time if no channel is built with the peer. + L::Target: Logger, + NS::Target: NodeSigner { + /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message + /// handler or onion message handler is used and onion and channel messages will be ignored (or + /// generate error messages). Note that some other lightning implementations time-out connections + /// after some time if no channel is built with the peer. + /// + /// `current_time` is used as an always-increasing counter that survives across restarts and is + /// incremented irregularly internally. In general it is best to simply use the current UNIX + /// timestamp, however if it is not available a persistent counter that increases once per + /// minute should suffice. /// - /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be + /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. /// - /// (C-not exported) as we can't export a PeerManager with a dummy channel handler - pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { + /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler + pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self { Self::new(MessageHandler { chan_handler: ErroringMessageHandler::new(), route_handler: routing_message_handler, - }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{}) + onion_message_handler: IgnoringMessageHandler{}, + }, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{}, node_signer) } } -/// A simple wrapper that optionally prints " from " for an optional pubkey. +/// A simple wrapper that optionally prints ` from ` for an optional pubkey. /// This works around `format!()` taking a reference to each argument, preventing /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling /// due to lifetime errors. -struct OptionalFromDebugger<'a>(&'a Option); +struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>); impl core::fmt::Display for OptionalFromDebugger<'_> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { - if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) } + if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) } } } /// A function used to filter out local or private addresses -/// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml -/// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml +/// +/// fn filter_addresses(ip_address: Option) -> Option { match ip_address{ // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8) @@ -561,15 +724,24 @@ fn filter_addresses(ip_address: Option) -> Option { } } -impl PeerManager where +impl PeerManager where CM::Target: ChannelMessageHandler, RM::Target: RoutingMessageHandler, + OM::Target: OnionMessageHandler, L::Target: Logger, - 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 + CMH::Target: CustomMessageHandler, + NS::Target: NodeSigner +{ + /// Constructs a new `PeerManager` with the given message handlers. + /// + /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. - pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self { + /// + /// `current_time` is used as an always-increasing counter that survives across restarts and is + /// incremented irregularly internally. In general it is best to simply use the current UNIX + /// timestamp, however if it is not available a persistent counter that increases once per + /// minute should suffice. + pub fn new(message_handler: MessageHandler, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH, node_signer: NS) -> Self { let mut ephemeral_key_midstate = Sha256::engine(); ephemeral_key_midstate.input(ephemeral_random_data); @@ -583,28 +755,36 @@ impl P node_id_to_descriptor: Mutex::new(HashMap::new()), event_processing_lock: Mutex::new(()), blocked_event_processors: AtomicBool::new(false), - our_node_secret, ephemeral_key_midstate, peer_counter: AtomicCounter::new(), + gossip_processing_backlogged: AtomicBool::new(false), + gossip_processing_backlog_lifted: AtomicBool::new(false), + last_node_announcement_serial: AtomicU32::new(current_time), logger, custom_message_handler, + node_signer, secp_ctx, } } - /// Get the list of node ids for peers which have completed the initial handshake. + /// Get a list of tuples mapping from node id to network addresses for peers which have + /// completed the initial handshake. + /// + /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter + /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial + /// handshake has completed and we are sure the remote peer has the private key for the given + /// [`PublicKey`]. /// - /// For outbound connections, this will be the same as the their_node_id parameter passed in to - /// new_outbound_connection, however entries will only appear once the initial handshake has - /// completed and we are sure the remote peer has the private key for the given node_id. - pub fn get_peer_node_ids(&self) -> Vec { + /// The returned `Option`s will only be `Some` if an address had been previously given via + /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`]. + pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option)> { let peers = self.peers.read().unwrap(); peers.values().filter_map(|peer_mutex| { let p = peer_mutex.lock().unwrap(); - if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() { + if !p.handshake_complete() { return None; } - p.their_node_id + Some((p.their_node_id.unwrap().0, p.their_net_address.clone())) }).collect() } @@ -615,52 +795,61 @@ impl P SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!") } - /// Indicates a new outbound connection has been established to a node with the given node_id + /// 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 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. + /// If an `Err` is returned here you must disconnect the connection immediately. /// /// Returns a small number of bytes to send to the remote node (currently always 50). /// /// Panics if descriptor is duplicative with some other descriptor which has not yet been - /// [`socket_disconnected()`]. + /// [`socket_disconnected`]. /// - /// [`socket_disconnected()`]: PeerManager::socket_disconnected + /// [`socket_disconnected`]: PeerManager::socket_disconnected pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option) -> Result, PeerHandleError> { let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key()); let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec(); let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes let mut peers = self.peers.write().unwrap(); - if peers.insert(descriptor, Mutex::new(Peer { - channel_encryptor: peer_encryptor, - their_node_id: None, - their_features: None, - their_net_address: remote_network_address, - - pending_outbound_buffer: LinkedList::new(), - pending_outbound_buffer_first_msg_offset: 0, - awaiting_write_event: false, - - pending_read_buffer, - pending_read_buffer_pos: 0, - pending_read_is_header: false, - - sync_status: InitSyncTracker::NoSyncRequested, - - 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!"); - }; - Ok(res) + match peers.entry(descriptor) { + hash_map::Entry::Occupied(_) => { + debug_assert!(false, "PeerManager driver duplicated descriptors!"); + Err(PeerHandleError {}) + }, + hash_map::Entry::Vacant(e) => { + e.insert(Mutex::new(Peer { + channel_encryptor: peer_encryptor, + their_node_id: None, + their_features: None, + their_net_address: remote_network_address, + + pending_outbound_buffer: LinkedList::new(), + pending_outbound_buffer_first_msg_offset: 0, + gossip_broadcast_buffer: LinkedList::new(), + awaiting_write_event: false, + + pending_read_buffer, + pending_read_buffer_pos: 0, + pending_read_is_header: false, + + sync_status: InitSyncTracker::NoSyncRequested, + + msgs_sent_since_pong: 0, + awaiting_pong_timer_tick_intervals: 0, + received_message_since_timer_tick: false, + sent_gossip_timestamp_filter: false, + + received_channel_announce_since_backlogged: false, + inbound_connection: false, + })); + Ok(res) + } + } } /// Indicates a new inbound connection has been established to a node with an optional remote @@ -671,87 +860,115 @@ impl P /// 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 - /// immediately. + /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect + /// the connection immediately. /// /// Panics if descriptor is duplicative with some other descriptor which has not yet been - /// [`socket_disconnected()`]. + /// [`socket_disconnected`]. /// - /// [`socket_disconnected()`]: PeerManager::socket_disconnected + /// [`socket_disconnected`]: PeerManager::socket_disconnected pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option) -> Result<(), PeerHandleError> { - let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx); + let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer); let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes let mut peers = self.peers.write().unwrap(); - if peers.insert(descriptor, Mutex::new(Peer { - channel_encryptor: peer_encryptor, - their_node_id: None, - their_features: None, - their_net_address: remote_network_address, - - pending_outbound_buffer: LinkedList::new(), - pending_outbound_buffer_first_msg_offset: 0, - awaiting_write_event: false, - - pending_read_buffer, - pending_read_buffer_pos: 0, - pending_read_is_header: false, - - sync_status: InitSyncTracker::NoSyncRequested, - - 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!"); - }; - Ok(()) + match peers.entry(descriptor) { + hash_map::Entry::Occupied(_) => { + debug_assert!(false, "PeerManager driver duplicated descriptors!"); + Err(PeerHandleError {}) + }, + hash_map::Entry::Vacant(e) => { + e.insert(Mutex::new(Peer { + channel_encryptor: peer_encryptor, + their_node_id: None, + their_features: None, + their_net_address: remote_network_address, + + pending_outbound_buffer: LinkedList::new(), + pending_outbound_buffer_first_msg_offset: 0, + gossip_broadcast_buffer: LinkedList::new(), + awaiting_write_event: false, + + pending_read_buffer, + pending_read_buffer_pos: 0, + pending_read_is_header: false, + + sync_status: InitSyncTracker::NoSyncRequested, + + msgs_sent_since_pong: 0, + awaiting_pong_timer_tick_intervals: 0, + received_message_since_timer_tick: false, + sent_gossip_timestamp_filter: false, + + received_channel_announce_since_backlogged: false, + inbound_connection: true, + })); + Ok(()) + } + } + } + + fn peer_should_read(&self, peer: &mut Peer) -> bool { + peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed)) + } + + fn update_gossip_backlogged(&self) { + let new_state = self.message_handler.route_handler.processing_queue_high(); + let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed); + if prev_state && !new_state { + self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed); + } } - fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) { + fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) { + let mut have_written = false; while !peer.awaiting_write_event { - if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && peer.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK { + if peer.should_buffer_onion_message() { + if let Some((peer_node_id, _)) = peer.their_node_id { + if let Some(next_onion_message) = + self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) { + self.enqueue_message(peer, &next_onion_message); + } + } + } + if peer.should_buffer_gossip_broadcast() { + if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() { + peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..])); + } + } + if peer.should_buffer_gossip_backfill() { match peer.sync_status { InitSyncTracker::NoSyncRequested => {}, InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => { - let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8; - let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps); - for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() { - self.enqueue_message(peer, announce); - if let &Some(ref update_a) = update_a_option { - self.enqueue_message(peer, update_a); + if let Some((announce, update_a_option, update_b_option)) = + self.message_handler.route_handler.get_next_channel_announcement(c) + { + self.enqueue_message(peer, &announce); + if let Some(update_a) = update_a_option { + self.enqueue_message(peer, &update_a); } - if let &Some(ref update_b) = update_b_option { - self.enqueue_message(peer, update_b); + if let Some(update_b) = update_b_option { + self.enqueue_message(peer, &update_b); } peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1); - } - if all_messages.is_empty() || all_messages.len() != steps as usize { + } else { peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff); } }, InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => { - let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8; - let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps); - for msg in all_messages.iter() { - self.enqueue_message(peer, msg); + if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) { + self.enqueue_message(peer, &msg); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); - } - if all_messages.is_empty() || all_messages.len() != steps as usize { + } else { peer.sync_status = InitSyncTracker::NoSyncRequested; } }, InitSyncTracker::ChannelsSyncing(_) => unreachable!(), - InitSyncTracker::NodesSyncing(key) => { - let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8; - let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps); - for msg in all_messages.iter() { - self.enqueue_message(peer, msg); + InitSyncTracker::NodesSyncing(sync_node_id) => { + if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) { + self.enqueue_message(peer, &msg); peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id); - } - if all_messages.is_empty() || all_messages.len() != steps as usize { + } else { peer.sync_status = InitSyncTracker::NoSyncRequested; } }, @@ -761,18 +978,25 @@ impl P self.maybe_send_extra_ping(peer); } - if { - let next_buff = match peer.pending_outbound_buffer.front() { - None => return, - Some(buff) => buff, - }; - - let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE; - let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..]; - let data_sent = descriptor.send_data(pending, should_be_reading); - peer.pending_outbound_buffer_first_msg_offset += data_sent; - if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false } - } { + let should_read = self.peer_should_read(peer); + let next_buff = match peer.pending_outbound_buffer.front() { + None => { + if force_one_write && !have_written { + if should_read { + let data_sent = descriptor.send_data(&[], should_read); + debug_assert_eq!(data_sent, 0, "Can't write more than no data"); + } + } + return + }, + Some(buff) => buff, + }; + + let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..]; + let data_sent = descriptor.send_data(pending, should_read); + have_written = true; + peer.pending_outbound_buffer_first_msg_offset += data_sent; + if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { peer.pending_outbound_buffer_first_msg_offset = 0; peer.pending_outbound_buffer.pop_front(); } else { @@ -788,7 +1012,7 @@ impl P /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before /// returning. Thus, be very careful with reentrancy issues! The invariants around calling /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be - /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't + /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't /// sufficient! /// /// [`send_data`]: SocketDescriptor::send_data @@ -800,12 +1024,12 @@ impl P // This is most likely a simple race condition where the user found that the socket // was writeable, then we told the user to `disconnect_socket()`, then they called // this method. Return an error to make sure we get disconnected. - return Err(PeerHandleError { no_connection_possible: false }); + return Err(PeerHandleError { }); }, Some(peer_mutex) => { let mut peer = peer_mutex.lock().unwrap(); peer.awaiting_write_event = false; - self.do_attempt_write_data(descriptor, &mut peer); + self.do_attempt_write_data(descriptor, &mut peer, false); } }; Ok(()) @@ -823,36 +1047,37 @@ impl P /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the /// send buffer). /// + /// In order to avoid processing too many messages at once per peer, `data` should be on the + /// order of 4KiB. + /// /// [`send_data`]: SocketDescriptor::send_data /// [`process_events`]: PeerManager::process_events pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result { match self.do_read_event(peer_descriptor, data) { Ok(res) => Ok(res), Err(e) => { - log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error"); - self.disconnect_event_internal(peer_descriptor, e.no_connection_possible); + log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection)."); + self.disconnect_event_internal(peer_descriptor); Err(e) } } } - /// Append a message to a peer's pending outbound/write buffer - fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec) { - peer.msgs_sent_since_pong += 1; - peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..])); - } - /// Append a message to a peer's pending outbound/write buffer fn enqueue_message(&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 - if is_gossip_msg(message.type_id()) { - log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap())); + log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0)); } else { - log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap())) + log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0)) } - self.enqueue_encoded_message(peer, &buffer.0); + peer.msgs_sent_since_pong += 1; + peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message)); + } + + /// Append a message to a peer's pending outbound/write gossip broadcast buffer + fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec) { + peer.msgs_sent_since_pong += 1; + peer.gossip_broadcast_buffer.push_back(encoded_message); } fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result { @@ -865,7 +1090,7 @@ impl P // This is most likely a simple race condition where the user read some bytes // from the socket, then we told the user to `disconnect_socket()`, then they // called this method. Return an error to make sure we get disconnected. - return Err(PeerHandleError { no_connection_possible: false }); + return Err(PeerHandleError { }); }, Some(peer_mutex) => { let mut read_pos = 0; @@ -879,7 +1104,7 @@ impl P msgs::ErrorAction::DisconnectPeer { msg: _ } => { //TODO: Try to push msg log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err); - return Err(PeerHandleError{ no_connection_possible: false }); + return Err(PeerHandleError { }); }, msgs::ErrorAction::IgnoreAndLog(level) => { log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err); @@ -928,14 +1153,18 @@ impl P macro_rules! insert_node_id { () => { - match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) { - hash_map::Entry::Occupied(_) => { - log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap())); + match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) { + hash_map::Entry::Occupied(e) => { + log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0)); peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event - return Err(PeerHandleError{ no_connection_possible: false }) + // Check that the peers map is consistent with the + // node_id_to_descriptor map, as this has been broken + // before. + debug_assert!(peers.get(e.get()).is_some()); + return Err(PeerHandleError { }) }, hash_map::Entry::Vacant(entry) => { - log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap())); + log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0)); entry.insert(peer_descriptor.clone()) }, }; @@ -947,21 +1176,23 @@ impl P NextNoiseStep::ActOne => { let act_two = try_potential_handleerror!(peer, peer.channel_encryptor .process_act_one_with_keys(&peer.pending_read_buffer[..], - &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec(); + &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec(); peer.pending_outbound_buffer.push_back(act_two); peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long }, NextNoiseStep::ActTwo => { let (act_three, their_node_id) = try_potential_handleerror!(peer, peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], - &self.our_node_secret, &self.secp_ctx)); + &self.node_signer)); peer.pending_outbound_buffer.push_back(act_three.to_vec()); peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes peer.pending_read_is_header = true; - peer.their_node_id = Some(their_node_id); + peer.set_their_node_id(their_node_id); insert_node_id!(); - let features = InitFeatures::known(); + let features = self.message_handler.chan_handler.provided_init_features(&their_node_id) + .or(self.message_handler.route_handler.provided_init_features(&their_node_id)) + .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id)); 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; @@ -971,9 +1202,11 @@ impl P peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..])); peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes peer.pending_read_is_header = true; - peer.their_node_id = Some(their_node_id); + peer.set_their_node_id(their_node_id); insert_node_id!(); - let features = InitFeatures::known(); + let features = self.message_handler.chan_handler.provided_init_features(&their_node_id) + .or(self.message_handler.route_handler.provided_init_features(&their_node_id)) + .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id)); 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; @@ -985,7 +1218,7 @@ impl P if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); } peer.pending_read_buffer.resize(msg_len as usize + 16, 0); if msg_len < 2 { // Need at least the message type tag - return Err(PeerHandleError{ no_connection_possible: false }); + return Err(PeerHandleError { }); } peer.pending_read_is_header = false; } else { @@ -1019,25 +1252,28 @@ impl P } (_, Some(ty)) if is_gossip_msg(ty) => { log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message"); - self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() }); + self.enqueue_message(peer, &msgs::WarningMessage { + channel_id: [0; 32], + data: format!("Unreadable/bogus gossip message of type {}", ty), + }); continue; } (msgs::DecodeError::UnknownRequiredFeature, ty) => { log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!"); self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) }); - return Err(PeerHandleError { no_connection_possible: false }); + return Err(PeerHandleError { }); } - (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }), + (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }), (msgs::DecodeError::InvalidValue, _) => { log_debug!(self.logger, "Got an invalid value while deserializing message"); - return Err(PeerHandleError { no_connection_possible: false }); + return Err(PeerHandleError { }); } (msgs::DecodeError::ShortRead, _) => { log_debug!(self.logger, "Deserialization failed due to shortness of message"); - return Err(PeerHandleError { no_connection_possible: false }); + return Err(PeerHandleError { }); } - (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }), - (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }), + (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }), + (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }), } } }; @@ -1047,7 +1283,7 @@ impl P } } } - pause_read = peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE; + pause_read = !self.peer_should_read(peer); if let Some(message) = msg_to_handle { match self.handle_message(&peer_mutex, peer_lock, message) { @@ -1068,7 +1304,7 @@ impl P } for msg in msgs_to_forward.drain(..) { - self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref()); + self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk)); } Ok(pause_read) @@ -1082,17 +1318,17 @@ impl P mut peer_lock: MutexGuard, message: wire::Message<<::Target as wire::CustomMessageReader>::CustomMessage> ) -> Result::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> { - let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages"); + let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages").0; peer_lock.received_message_since_timer_tick = true; // Need an Init as first message if let wire::Message::Init(msg) = message { if msg.features.requires_unknown_bits() { log_debug!(self.logger, "Peer features required unknown version bits"); - return Err(PeerHandleError{ no_connection_possible: true }.into()); + return Err(PeerHandleError { }.into()); } if peer_lock.their_features.is_some() { - return Err(PeerHandleError{ no_connection_possible: false }.into()); + return Err(PeerHandleError { }.into()); } log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features); @@ -1102,19 +1338,24 @@ impl P peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0); } - if !msg.features.supports_static_remote_key() { - log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id)); - return Err(PeerHandleError{ no_connection_possible: true }.into()); + if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) { + log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id)); + return Err(PeerHandleError { }.into()); + } + if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) { + log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id)); + return Err(PeerHandleError { }.into()); + } + if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) { + log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id)); + return Err(PeerHandleError { }.into()); } - self.message_handler.route_handler.peer_connected(&their_node_id, &msg); - - self.message_handler.chan_handler.peer_connected(&their_node_id, &msg); peer_lock.their_features = Some(msg.features); return Ok(None); } else if peer_lock.their_features.is_none() { log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id)); - return Err(PeerHandleError{ no_connection_possible: false }.into()); + return Err(PeerHandleError { }.into()); } if let wire::Message::GossipTimestampFilter(_msg) = message { @@ -1128,7 +1369,10 @@ impl P return Ok(None); } - let their_features = peer_lock.their_features.clone(); + if let wire::Message::ChannelAnnouncement(ref _msg) = message { + peer_lock.received_channel_announce_since_backlogged = true; + } + mem::drop(peer_lock); if is_gossip_msg(message.type_id()) { @@ -1163,7 +1407,7 @@ impl P } self.message_handler.chan_handler.handle_error(&their_node_id, &msg); if msg.channel_id == [0; 32] { - return Err(PeerHandleError{ no_connection_possible: true }.into()); + return Err(PeerHandleError { }.into()); } }, wire::Message::Warning(msg) => { @@ -1196,10 +1440,10 @@ impl P // Channel messages: wire::Message::OpenChannel(msg) => { - self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg); + self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg); }, wire::Message::AcceptChannel(msg) => { - self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg); + self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg); }, wire::Message::FundingCreated(msg) => { @@ -1213,7 +1457,7 @@ impl P }, wire::Message::Shutdown(msg) => { - self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg); + self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg); }, wire::Message::ClosingSigned(msg) => { self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg); @@ -1255,12 +1499,14 @@ impl P .map_err(|e| -> MessageHandlingError { e.into() })? { should_forward = Some(wire::Message::ChannelAnnouncement(msg)); } + self.update_gossip_backlogged(); }, wire::Message::NodeAnnouncement(msg) => { if self.message_handler.route_handler.handle_node_announcement(&msg) .map_err(|e| -> MessageHandlingError { e.into() })? { should_forward = Some(wire::Message::NodeAnnouncement(msg)); } + self.update_gossip_backlogged(); }, wire::Message::ChannelUpdate(msg) => { self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg); @@ -1268,6 +1514,7 @@ impl P .map_err(|e| -> MessageHandlingError { e.into() })? { should_forward = Some(wire::Message::ChannelUpdate(msg)); } + self.update_gossip_backlogged(); }, wire::Message::QueryShortChannelIds(msg) => { self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?; @@ -1282,11 +1529,15 @@ impl P self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?; }, + // Onion message: + wire::Message::OnionMessage(msg) => { + self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg); + }, + // Unknown messages: wire::Message::Unknown(type_id) if message.is_even() => { log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id); - // Fail the channel if message is an even, unknown type as per BOLT #1. - return Err(PeerHandleError{ no_connection_possible: true }.into()); + return Err(PeerHandleError { }.into()); }, wire::Message::Unknown(type_id) => { log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id); @@ -1306,24 +1557,25 @@ impl P for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); - if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || + if !peer.handshake_complete() || !peer.should_forward_channel_announcement(msg.contents.short_channel_id) { continue } - if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP - || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO - { + debug_assert!(peer.their_node_id.is_some()); + debug_assert!(peer.channel_encryptor.is_ready_for_encryption()); + if peer.buffer_full_drop_gossip_broadcast() { log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id); continue; } - if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) || - peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) { - continue; + if let Some((_, their_node_id)) = peer.their_node_id { + if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 { + continue; + } } - if except_node.is_some() && peer.their_node_id.as_ref() == except_node { + if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node { continue; } - self.enqueue_encoded_message(&mut *peer, &encoded_msg); + self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone()); } }, wire::Message::NodeAnnouncement(ref msg) => { @@ -1332,23 +1584,25 @@ impl P for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); - if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || + if !peer.handshake_complete() || !peer.should_forward_node_announcement(msg.contents.node_id) { continue } - if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP - || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO - { + debug_assert!(peer.their_node_id.is_some()); + debug_assert!(peer.channel_encryptor.is_ready_for_encryption()); + if peer.buffer_full_drop_gossip_broadcast() { log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id); continue; } - if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) { - continue; + if let Some((_, their_node_id)) = peer.their_node_id { + if their_node_id == msg.contents.node_id { + continue; + } } - if except_node.is_some() && peer.their_node_id.as_ref() == except_node { + if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node { continue; } - self.enqueue_encoded_message(&mut *peer, &encoded_msg); + self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone()); } }, wire::Message::ChannelUpdate(ref msg) => { @@ -1357,20 +1611,20 @@ impl P for (_, peer_mutex) in peers.iter() { let mut peer = peer_mutex.lock().unwrap(); - if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() || + if !peer.handshake_complete() || !peer.should_forward_channel_announcement(msg.contents.short_channel_id) { continue } - if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP - || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO - { + debug_assert!(peer.their_node_id.is_some()); + debug_assert!(peer.channel_encryptor.is_ready_for_encryption()); + if peer.buffer_full_drop_gossip_broadcast() { log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id); continue; } - if except_node.is_some() && peer.their_node_id.as_ref() == except_node { + if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node { continue; } - self.enqueue_encoded_message(&mut *peer, &encoded_msg); + self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone()); } }, _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"), @@ -1416,6 +1670,9 @@ impl P } } + self.update_gossip_backlogged(); + let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed); + let mut peers_to_disconnect = HashMap::new(); let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events(); events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events()); @@ -1439,7 +1696,7 @@ impl P Some(descriptor) => match peers.get(&descriptor) { Some(peer_mutex) => { let peer_lock = peer_mutex.lock().unwrap(); - if peer_lock.their_features.is_none() { + if !peer_lock.handshake_complete() { continue; } peer_lock @@ -1546,6 +1803,13 @@ impl P log_bytes!(msg.channel_id)); self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg); }, + MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => { + log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}", + log_pubkey!(node_id), + msg.contents.short_channel_id); + self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg); + self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg); + }, MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => { log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id); match self.message_handler.route_handler.handle_channel_announcement(&msg) { @@ -1553,28 +1817,30 @@ impl P self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None), _ => {}, } - match self.message_handler.route_handler.handle_channel_update(&update_msg) { + if let Some(msg) = update_msg { + match self.message_handler.route_handler.handle_channel_update(&msg) { + Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) => + self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None), + _ => {}, + } + } + }, + MessageSendEvent::BroadcastChannelUpdate { msg } => { + log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id); + match self.message_handler.route_handler.handle_channel_update(&msg) { Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) => - self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None), + self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None), _ => {}, } }, MessageSendEvent::BroadcastNodeAnnouncement { msg } => { - log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler"); + log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id); match self.message_handler.route_handler.handle_node_announcement(&msg) { Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) => self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None), _ => {}, } }, - MessageSendEvent::BroadcastChannelUpdate { msg } => { - log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id); - match self.message_handler.route_handler.handle_channel_update(&msg) { - Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) => - self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None), - _ => {}, - } - }, MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => { log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}", log_pubkey!(node_id), msg.contents.short_channel_id); @@ -1636,7 +1902,9 @@ impl P } for (descriptor, peer_mutex) in peers.iter() { - self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap()); + let mut peer = peer_mutex.lock().unwrap(); + if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; } + self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled); } } if !peers_to_disconnect.is_empty() { @@ -1648,23 +1916,21 @@ impl P // thread can be holding the peer lock if we have the global write // lock). - if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) { + let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id); + if let Some(mut descriptor) = descriptor_opt { if let Some(peer_mutex) = peers.remove(&descriptor) { + let mut peer = peer_mutex.lock().unwrap(); if let Some(msg) = msg { log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}", log_pubkey!(node_id), msg.data); - let mut peer = peer_mutex.lock().unwrap(); self.enqueue_message(&mut *peer, &msg); // This isn't guaranteed to work, but if there is enough free // room in the send buffer, put the error message there... - self.do_attempt_write_data(&mut descriptor, &mut *peer); - } else { - log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id)); + self.do_attempt_write_data(&mut descriptor, &mut *peer, false); } - } - descriptor.disconnect_socket(); - self.message_handler.chan_handler.peer_disconnected(&node_id, false); + self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError"); + } else { debug_assert!(false, "Missing connection for peer"); } } } } @@ -1672,10 +1938,26 @@ impl P /// Indicates that the given socket descriptor's connection is now closed. pub fn socket_disconnected(&self, descriptor: &Descriptor) { - self.disconnect_event_internal(descriptor, false); + self.disconnect_event_internal(descriptor); } - fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) { + fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) { + if !peer.handshake_complete() { + log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason); + descriptor.disconnect_socket(); + return; + } + + debug_assert!(peer.their_node_id.is_some()); + if let Some((node_id, _)) = peer.their_node_id { + log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason); + self.message_handler.chan_handler.peer_disconnected(&node_id); + self.message_handler.onion_message_handler.peer_disconnected(&node_id); + } + descriptor.disconnect_socket(); + } + + fn disconnect_event_internal(&self, descriptor: &Descriptor) { let mut peers = self.peers.write().unwrap(); let peer_option = peers.remove(descriptor); match peer_option { @@ -1686,12 +1968,13 @@ impl P }, Some(peer_lock) => { let peer = peer_lock.lock().unwrap(); - if let Some(node_id) = peer.their_node_id { - log_trace!(self.logger, - "Handling disconnection of peer {}, with {}future connection to the peer possible.", - log_pubkey!(node_id), if no_connection_possible { "no " } else { "" }); - self.node_id_to_descriptor.lock().unwrap().remove(&node_id); - self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible); + if let Some((node_id, _)) = peer.their_node_id { + log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id)); + let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id); + debug_assert!(removed.is_some(), "descriptor maps should be consistent"); + if !peer.handshake_complete() { return; } + self.message_handler.chan_handler.peer_disconnected(&node_id); + self.message_handler.onion_message_handler.peer_disconnected(&node_id); } } }; @@ -1699,20 +1982,17 @@ impl P /// Disconnect a peer given its node id. /// - /// Set `no_connection_possible` to true to prevent any further connection with this peer, - /// force-closing any channels we have with it. - /// /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the /// peer. Thus, be very careful about reentrancy issues. /// /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket - pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) { + pub fn disconnect_by_node_id(&self, node_id: PublicKey) { let mut peers_lock = self.peers.write().unwrap(); - if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) { - log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id); - peers_lock.remove(&descriptor); - self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible); - descriptor.disconnect_socket(); + if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) { + let peer_opt = peers_lock.remove(&descriptor); + if let Some(peer_mutex) = peer_opt { + self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request"); + } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); } } } @@ -1723,12 +2003,8 @@ impl P let mut peers_lock = self.peers.write().unwrap(); self.node_id_to_descriptor.lock().unwrap().clear(); let peers = &mut *peers_lock; - for (mut descriptor, peer) in peers.drain() { - if let Some(node_id) = peer.lock().unwrap().their_node_id { - log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id); - self.message_handler.chan_handler.peer_disconnected(&node_id, false); - } - descriptor.disconnect_socket(); + for (descriptor, peer_mutex) in peers.drain() { + self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers"); } } @@ -1762,9 +2038,14 @@ impl P { let peers_lock = self.peers.read().unwrap(); + self.update_gossip_backlogged(); + let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed); + for (descriptor, peer_mutex) in peers_lock.iter() { let mut peer = peer_mutex.lock().unwrap(); - if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() { + if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; } + + if !peer.handshake_complete() { // The peer needs to complete its handshake before we can exchange messages. We // give peers one timer tick to complete handshake, reusing // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken @@ -1776,56 +2057,126 @@ impl P } continue; } + debug_assert!(peer.channel_encryptor.is_ready_for_encryption()); + debug_assert!(peer.their_node_id.is_some()); - if peer.awaiting_pong_timer_tick_intervals == -1 { - // Magic value set in `maybe_send_extra_ping`. - peer.awaiting_pong_timer_tick_intervals = 1; + loop { // Used as a `goto` to skip writing a Ping message. + if peer.awaiting_pong_timer_tick_intervals == -1 { + // Magic value set in `maybe_send_extra_ping`. + peer.awaiting_pong_timer_tick_intervals = 1; + peer.received_message_since_timer_tick = false; + break; + } + + if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick) + || peer.awaiting_pong_timer_tick_intervals as u64 > + MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64 + { + descriptors_needing_disconnect.push(descriptor.clone()); + break; + } peer.received_message_since_timer_tick = false; - continue; - } - if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick) - || peer.awaiting_pong_timer_tick_intervals as u64 > - MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64 - { - descriptors_needing_disconnect.push(descriptor.clone()); - continue; - } - peer.received_message_since_timer_tick = false; + if peer.awaiting_pong_timer_tick_intervals > 0 { + peer.awaiting_pong_timer_tick_intervals += 1; + break; + } - if peer.awaiting_pong_timer_tick_intervals > 0 { - peer.awaiting_pong_timer_tick_intervals += 1; - continue; + peer.awaiting_pong_timer_tick_intervals = 1; + let ping = msgs::Ping { + ponglen: 0, + byteslen: 64, + }; + self.enqueue_message(&mut *peer, &ping); + break; } - - peer.awaiting_pong_timer_tick_intervals = 1; - let ping = msgs::Ping { - ponglen: 0, - byteslen: 64, - }; - self.enqueue_message(&mut *peer, &ping); - self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer); + self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled); } } if !descriptors_needing_disconnect.is_empty() { { let mut peers_lock = self.peers.write().unwrap(); - for descriptor in descriptors_needing_disconnect.iter() { - if let Some(peer) = peers_lock.remove(descriptor) { - if let Some(node_id) = peer.lock().unwrap().their_node_id { - log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id); + for descriptor in descriptors_needing_disconnect { + if let Some(peer_mutex) = peers_lock.remove(&descriptor) { + let peer = peer_mutex.lock().unwrap(); + if let Some((node_id, _)) = peer.their_node_id { self.node_id_to_descriptor.lock().unwrap().remove(&node_id); - self.message_handler.chan_handler.peer_disconnected(&node_id, false); } + self.do_disconnect(descriptor, &*peer, "ping/handshake timeout"); } } } + } + } - for mut descriptor in descriptors_needing_disconnect.drain(..) { - descriptor.disconnect_socket(); - } + #[allow(dead_code)] + // Messages of up to 64KB should never end up more than half full with addresses, as that would + // be absurd. We ensure this by checking that at least 100 (our stated public contract on when + // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB + // message... + const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2; + #[deny(const_err)] + #[allow(dead_code)] + // ...by failing to compile if the number of addresses that would be half of a message is + // smaller than 100: + const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100; + + /// Generates a signed node_announcement from the given arguments, sending it to all connected + /// peers. Note that peers will likely ignore this message unless we have at least one public + /// channel which has at least six confirmations on-chain. + /// + /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this + /// node to humans. They carry no in-protocol meaning. + /// + /// `addresses` represent the set (possibly empty) of socket addresses on which this node + /// accepts incoming connections. These will be included in the node_announcement, publicly + /// tying these addresses together and to this node. If you wish to preserve user privacy, + /// addresses should likely contain only Tor Onion addresses. + /// + /// Panics if `addresses` is absurdly large (more than 100). + /// + /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events + pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec) { + if addresses.len() > 100 { + panic!("More than half the message size was taken up by public addresses!"); } + + // While all existing nodes handle unsorted addresses just fine, the spec requires that + // addresses be sorted for future compatibility. + addresses.sort_by_key(|addr| addr.get_id()); + + let features = self.message_handler.chan_handler.provided_node_features() + .or(self.message_handler.route_handler.provided_node_features()) + .or(self.message_handler.onion_message_handler.provided_node_features()); + let announcement = msgs::UnsignedNodeAnnouncement { + features, + timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel), + node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()), + rgb, + alias: NodeAlias(alias), + addresses, + excess_address_data: Vec::new(), + excess_data: Vec::new(), + }; + let node_announce_sig = match self.node_signer.sign_gossip_message( + msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement) + ) { + Ok(sig) => sig, + Err(_) => { + log_error!(self.logger, "Failed to generate signature for node_announcement"); + return; + }, + }; + + let msg = msgs::NodeAnnouncement { + signature: node_announce_sig, + contents: announcement + }; + + log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler."); + let _ = self.message_handler.route_handler.handle_node_announcement(&msg); + self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None); } } @@ -1844,23 +2195,25 @@ fn is_gossip_msg(type_id: u16) -> bool { #[cfg(test)] mod tests { - use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses}; - use ln::{msgs, wire}; - use ln::msgs::NetAddress; - use util::events; - use util::test_utils; + use crate::chain::keysinterface::{NodeSigner, Recipient}; + use crate::events; + use crate::ln::peer_channel_encryptor::PeerChannelEncryptor; + use crate::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses}; + use crate::ln::{msgs, wire}; + use crate::ln::msgs::NetAddress; + use crate::util::test_utils; - use bitcoin::secp256k1::Secp256k1; - use bitcoin::secp256k1::{SecretKey, PublicKey}; + use bitcoin::secp256k1::SecretKey; - use prelude::*; - use sync::{Arc, Mutex}; - use core::sync::atomic::Ordering; + use crate::prelude::*; + use crate::sync::{Arc, Mutex}; + use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Clone)] struct FileDescriptor { fd: u16, outbound_data: Arc>>, + disconnect: Arc, } impl PartialEq for FileDescriptor { fn eq(&self, other: &Self) -> bool { @@ -1880,23 +2233,26 @@ mod tests { data.len() } - fn disconnect_socket(&mut self) {} + fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); } } struct PeerManagerCfg { chan_handler: test_utils::TestChannelMessageHandler, routing_handler: test_utils::TestRoutingMessageHandler, logger: test_utils::TestLogger, + node_signer: test_utils::TestNodeSigner, } fn create_peermgr_cfgs(peer_count: usize) -> Vec { let mut cfgs = Vec::new(); - for _ in 0..peer_count { + for i in 0..peer_count { + let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap(); cfgs.push( PeerManagerCfg{ chan_handler: test_utils::TestChannelMessageHandler::new(), logger: test_utils::TestLogger::new(), routing_handler: test_utils::TestRoutingMessageHandler::new(), + node_signer: test_utils::TestNodeSigner::new(node_secret), } ); } @@ -1904,55 +2260,147 @@ mod tests { cfgs } - fn create_network<'a>(peer_count: usize, cfgs: &'a Vec) -> Vec> { + fn create_network<'a>(peer_count: usize, cfgs: &'a Vec) -> Vec> { let mut peers = Vec::new(); for i in 0..peer_count { - let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap(); let ephemeral_bytes = [i as u8; 32]; - let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler }; - let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {}); + let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} }; + let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {}, &cfgs[i].node_signer); peers.push(peer); } peers } - fn establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { - let secp_ctx = Secp256k1::new(); - let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret); - let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; - let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; - let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap(); - peer_a.new_inbound_connection(fd_a.clone(), None).unwrap(); + fn establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { + let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap(); + let mut fd_a = FileDescriptor { + fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000}; + let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap(); + let mut fd_b = FileDescriptor { + fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001}; + let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap(); + peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap(); assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).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); + + let a_data = fd_a.outbound_data.lock().unwrap().split_off(0); + assert_eq!(peer_b.read_event(&mut fd_b, &a_data).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); + let b_data = fd_b.outbound_data.lock().unwrap().split_off(0); + assert_eq!(peer_a.read_event(&mut fd_a, &b_data).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); + let a_data = fd_a.outbound_data.lock().unwrap().split_off(0); + assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false); + + assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b)))); + assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a)))); + (fd_a.clone(), fd_b.clone()) } + #[test] + #[cfg(feature = "std")] + fn fuzz_threaded_connections() { + // Spawn two threads which repeatedly connect two peers together, leading to "got second + // connection with peer" disconnections and rapid reconnect. This previously found an issue + // with our internal map consistency, and is a generally good smoke test of disconnection. + let cfgs = Arc::new(create_peermgr_cfgs(2)); + // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }. + let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ })); + + let start_time = std::time::Instant::now(); + macro_rules! spawn_thread { ($id: expr) => { { + let peers = Arc::clone(&peers); + let cfgs = Arc::clone(&cfgs); + std::thread::spawn(move || { + let mut ctr = 0; + while start_time.elapsed() < std::time::Duration::from_secs(1) { + let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap(); + let mut fd_a = FileDescriptor { + fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000}; + let mut fd_b = FileDescriptor { + fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001}; + let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap(); + peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap(); + if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; } + + while start_time.elapsed() < std::time::Duration::from_secs(1) { + peers[0].process_events(); + if fd_a.disconnect.load(Ordering::Acquire) { break; } + let a_data = fd_a.outbound_data.lock().unwrap().split_off(0); + if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; } + + peers[1].process_events(); + if fd_b.disconnect.load(Ordering::Acquire) { break; } + let b_data = fd_b.outbound_data.lock().unwrap().split_off(0); + if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; } + + cfgs[0].chan_handler.pending_events.lock().unwrap() + .push(crate::events::MessageSendEvent::SendShutdown { + node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(), + msg: msgs::Shutdown { + channel_id: [0; 32], + scriptpubkey: bitcoin::Script::new(), + }, + }); + cfgs[1].chan_handler.pending_events.lock().unwrap() + .push(crate::events::MessageSendEvent::SendShutdown { + node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(), + msg: msgs::Shutdown { + channel_id: [0; 32], + scriptpubkey: bitcoin::Script::new(), + }, + }); + + if ctr % 2 == 0 { + peers[0].timer_tick_occurred(); + peers[1].timer_tick_occurred(); + } + } + + peers[0].socket_disconnected(&fd_a); + peers[1].socket_disconnected(&fd_b); + ctr += 1; + std::thread::sleep(std::time::Duration::from_micros(1)); + } + }) + } } } + let thrd_a = spawn_thread!(1); + let thrd_b = spawn_thread!(2); + + thrd_a.join().unwrap(); + thrd_b.join().unwrap(); + } + #[test] fn test_disconnect_peer() { // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and // push a DisconnectPeer event to remove the node flagged by id let cfgs = create_peermgr_cfgs(2); - let chan_handler = test_utils::TestChannelMessageHandler::new(); - let mut peers = create_network(2, &cfgs); + let peers = create_network(2, &cfgs); establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.read().unwrap().len(), 1); - let secp_ctx = Secp256k1::new(); - let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret); - - chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError { + let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap(); + cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError { node_id: their_id, action: msgs::ErrorAction::DisconnectPeer { msg: None }, }); - assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1); - peers[0].message_handler.chan_handler = &chan_handler; peers[0].process_events(); assert_eq!(peers[0].peers.read().unwrap().len(), 0); @@ -1969,8 +2417,7 @@ mod tests { let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.read().unwrap().len(), 1); - let secp_ctx = Secp256k1::new(); - let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret); + let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap(); let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() }; a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown { @@ -1987,6 +2434,38 @@ mod tests { assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false); } + #[test] + fn test_non_init_first_msg() { + // Simple test of the first message received over a connection being something other than + // Init. This results in an immediate disconnection, which previously included a spurious + // peer_disconnected event handed to event handlers (which would panic in + // `TestChannelMessageHandler` here). + let cfgs = create_peermgr_cfgs(2); + let peers = create_network(2, &cfgs); + + let mut fd_dup = FileDescriptor { + fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let addr_dup = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1003}; + let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap(); + peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap(); + + let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap()); + let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx); + assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false); + peers[0].process_events(); + + let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0); + let (act_three, _) = + dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap(); + assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false); + + let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 }; + let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg); + assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err()); + } + #[test] fn test_disconnect_all_peer() { // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and @@ -2055,10 +2534,10 @@ mod tests { // Check that each peer has received the expected number of channel updates and channel // announcements. - assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); - assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); - assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); - assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); + assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108); + assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54); + assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108); + assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54); } #[test] @@ -2070,10 +2549,15 @@ mod tests { cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release); let peers = create_network(2, &cfgs); - let secp_ctx = Secp256k1::new(); - let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret); - let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; - let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; + let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap(); + let mut fd_a = FileDescriptor { + fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; + let mut fd_b = FileDescriptor { + fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())), + disconnect: Arc::new(AtomicBool::new(false)), + }; let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap(); peers[0].new_inbound_connection(fd_a.clone(), None).unwrap(); @@ -2084,14 +2568,16 @@ mod tests { assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false); peers[0].process_events(); - assert_eq!(peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); + let a_data = fd_a.outbound_data.lock().unwrap().split_off(0); + assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false); peers[1].process_events(); // ...but if we get a second timer tick, we should disconnect the peer peers[0].timer_tick_occurred(); assert_eq!(peers[0].peers.read().unwrap().len(), 0); - assert!(peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).is_err()); + let b_data = fd_b.outbound_data.lock().unwrap().split_off(0); + assert!(peers[0].read_event(&mut fd_a, &b_data).is_err()); } #[test]