Merge pull request #1054 from ariard/2021-08-check-outbound-feerate
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Top level peer message handling and socket handling logic lives here.
11 //!
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages
16 //! they should handle, and encoding/sending response messages.
17
18 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
19
20 use ln::features::InitFeatures;
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
26 use ln::wire;
27 use ln::wire::Encode;
28 use util::atomic_counter::AtomicCounter;
29 use util::events::{MessageSendEvent, MessageSendEventsProvider};
30 use util::logger::Logger;
31 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
32
33 use prelude::*;
34 use io;
35 use alloc::collections::LinkedList;
36 use sync::{Arc, Mutex};
37 use core::{cmp, hash, fmt, mem};
38 use core::ops::Deref;
39 use core::convert::Infallible;
40 #[cfg(feature = "std")] use std::error;
41
42 use bitcoin::hashes::sha256::Hash as Sha256;
43 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
44 use bitcoin::hashes::{HashEngine, Hash};
45
46 /// Handler for BOLT1-compliant messages.
47 pub trait CustomMessageHandler: wire::CustomMessageReader {
48         /// Called with the message type that was received and the buffer to be read.
49         /// Can return a `MessageHandlingError` if the message could not be handled.
50         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
51
52         /// Gets the list of pending messages which were generated by the custom message
53         /// handler, clearing the list in the process. The first tuple element must
54         /// correspond to the intended recipients node ids. If no connection to one of the
55         /// specified node does not exist, the message is simply not sent to it.
56         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
57 }
58
59 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
60 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
61 pub struct IgnoringMessageHandler{}
62 impl MessageSendEventsProvider for IgnoringMessageHandler {
63         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
64 }
65 impl RoutingMessageHandler for IgnoringMessageHandler {
66         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
67         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
68         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
69         fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
70                 Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
71         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
72         fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
73         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
74         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
75         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
76         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
77 }
78 impl Deref for IgnoringMessageHandler {
79         type Target = IgnoringMessageHandler;
80         fn deref(&self) -> &Self { self }
81 }
82
83 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
84 // method that takes self for it.
85 impl wire::Type for Infallible {
86         fn type_id(&self) -> u16 {
87                 unreachable!();
88         }
89 }
90 impl Writeable for Infallible {
91         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
92                 unreachable!();
93         }
94 }
95
96 impl wire::CustomMessageReader for IgnoringMessageHandler {
97         type CustomMessage = Infallible;
98         fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
99                 Ok(None)
100         }
101 }
102
103 impl CustomMessageHandler for IgnoringMessageHandler {
104         fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
105                 // Since we always return `None` in the read the handle method should never be called.
106                 unreachable!();
107         }
108
109         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
110 }
111
112 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
113 /// You can provide one of these as the route_handler in a MessageHandler.
114 pub struct ErroringMessageHandler {
115         message_queue: Mutex<Vec<MessageSendEvent>>
116 }
117 impl ErroringMessageHandler {
118         /// Constructs a new ErroringMessageHandler
119         pub fn new() -> Self {
120                 Self { message_queue: Mutex::new(Vec::new()) }
121         }
122         fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
123                 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
124                         action: msgs::ErrorAction::SendErrorMessage {
125                                 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
126                         },
127                         node_id: node_id.clone(),
128                 });
129         }
130 }
131 impl MessageSendEventsProvider for ErroringMessageHandler {
132         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
133                 let mut res = Vec::new();
134                 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
135                 res
136         }
137 }
138 impl ChannelMessageHandler for ErroringMessageHandler {
139         // Any messages which are related to a specific channel generate an error message to let the
140         // peer know we don't care about channels.
141         fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
142                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
143         }
144         fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
145                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
146         }
147         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
148                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
149         }
150         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
151                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
152         }
153         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
154                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
155         }
156         fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
157                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
158         }
159         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
160                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
161         }
162         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
163                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
164         }
165         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
166                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
167         }
168         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
169                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
170         }
171         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
172                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
173         }
174         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
175                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
176         }
177         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
178                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
179         }
180         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
181                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
182         }
183         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
184                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
185         }
186         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
187                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
188         }
189         // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
190         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
191         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
192         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
193         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
194 }
195 impl Deref for ErroringMessageHandler {
196         type Target = ErroringMessageHandler;
197         fn deref(&self) -> &Self { self }
198 }
199
200 /// Provides references to trait impls which handle different types of messages.
201 pub struct MessageHandler<CM: Deref, RM: Deref> where
202                 CM::Target: ChannelMessageHandler,
203                 RM::Target: RoutingMessageHandler {
204         /// A message handler which handles messages specific to channels. Usually this is just a
205         /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
206         ///
207         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
208         pub chan_handler: CM,
209         /// A message handler which handles messages updating our knowledge of the network channel
210         /// graph. Usually this is just a [`NetGraphMsgHandler`] object or an
211         /// [`IgnoringMessageHandler`].
212         ///
213         /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
214         pub route_handler: RM,
215 }
216
217 /// Provides an object which can be used to send data to and which uniquely identifies a connection
218 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
219 /// implement Hash to meet the PeerManager API.
220 ///
221 /// For efficiency, Clone should be relatively cheap for this type.
222 ///
223 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
224 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
225 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
226 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
227 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
228 /// to simply use another value which is guaranteed to be globally unique instead.
229 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
230         /// Attempts to send some data from the given slice to the peer.
231         ///
232         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
233         /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
234         /// called and further write attempts may occur until that time.
235         ///
236         /// If the returned size is smaller than `data.len()`, a
237         /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
238         /// written. Additionally, until a `send_data` event completes fully, no further
239         /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
240         /// prevent denial-of-service issues, you should not read or buffer any data from the socket
241         /// until then.
242         ///
243         /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
244         /// (indicating that read events should be paused to prevent DoS in the send buffer),
245         /// `resume_read` may be set indicating that read events on this descriptor should resume. A
246         /// `resume_read` of false carries no meaning, and should not cause any action.
247         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
248         /// Disconnect the socket pointed to by this SocketDescriptor.
249         ///
250         /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
251         /// call (doing so is a noop).
252         fn disconnect_socket(&mut self);
253 }
254
255 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
256 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
257 /// descriptor.
258 #[derive(Clone)]
259 pub struct PeerHandleError {
260         /// Used to indicate that we probably can't make any future connections to this peer, implying
261         /// we should go ahead and force-close any channels we have with it.
262         pub no_connection_possible: bool,
263 }
264 impl fmt::Debug for PeerHandleError {
265         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
266                 formatter.write_str("Peer Sent Invalid Data")
267         }
268 }
269 impl fmt::Display for PeerHandleError {
270         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
271                 formatter.write_str("Peer Sent Invalid Data")
272         }
273 }
274
275 #[cfg(feature = "std")]
276 impl error::Error for PeerHandleError {
277         fn description(&self) -> &str {
278                 "Peer Sent Invalid Data"
279         }
280 }
281
282 enum InitSyncTracker{
283         NoSyncRequested,
284         ChannelsSyncing(u64),
285         NodesSyncing(PublicKey),
286 }
287
288 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
289 /// forwarding gossip messages to peers altogether.
290 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
291
292 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
293 /// we have fewer than this many messages in the outbound buffer again.
294 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
295 /// refilled as we send bytes.
296 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
297 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
298 /// the peer.
299 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
300
301 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
302 /// the socket receive buffer before receiving the ping.
303 ///
304 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
305 /// including any network delays, outbound traffic, or the same for messages from other peers.
306 ///
307 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
308 /// per connected peer to respond to a ping, as long as they send us at least one message during
309 /// each tick, ensuring we aren't actually just disconnected.
310 /// With a timer tick interval of five seconds, this translates to about 30 seconds per connected
311 /// peer.
312 ///
313 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
314 /// two connected peers, assuming most LDK-running systems have at least two cores.
315 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 6;
316
317 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
318 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
319 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
320 /// process before the next ping.
321 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
322
323 struct Peer {
324         channel_encryptor: PeerChannelEncryptor,
325         their_node_id: Option<PublicKey>,
326         their_features: Option<InitFeatures>,
327
328         pending_outbound_buffer: LinkedList<Vec<u8>>,
329         pending_outbound_buffer_first_msg_offset: usize,
330         awaiting_write_event: bool,
331
332         pending_read_buffer: Vec<u8>,
333         pending_read_buffer_pos: usize,
334         pending_read_is_header: bool,
335
336         sync_status: InitSyncTracker,
337
338         msgs_sent_since_pong: usize,
339         awaiting_pong_timer_tick_intervals: i8,
340         received_message_since_timer_tick: bool,
341 }
342
343 impl Peer {
344         /// Returns true if the channel announcements/updates for the given channel should be
345         /// forwarded to this peer.
346         /// If we are sending our routing table to this peer and we have not yet sent channel
347         /// announcements/updates for the given channel_id then we will send it when we get to that
348         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
349         /// sent the old versions, we should send the update, and so return true here.
350         fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
351                 match self.sync_status {
352                         InitSyncTracker::NoSyncRequested => true,
353                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
354                         InitSyncTracker::NodesSyncing(_) => true,
355                 }
356         }
357
358         /// Similar to the above, but for node announcements indexed by node_id.
359         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
360                 match self.sync_status {
361                         InitSyncTracker::NoSyncRequested => true,
362                         InitSyncTracker::ChannelsSyncing(_) => false,
363                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
364                 }
365         }
366 }
367
368 struct PeerHolder<Descriptor: SocketDescriptor> {
369         peers: HashMap<Descriptor, Peer>,
370         /// Only add to this set when noise completes:
371         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
372 }
373
374 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
375 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
376 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
377 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
378 /// issues such as overly long function definitions.
379 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<NetworkGraph>, Arc<C>, Arc<L>>>, Arc<L>, Arc<IgnoringMessageHandler>>;
380
381 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
382 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
383 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
384 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
385 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
386 /// helps with issues such as long function definitions.
387 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g NetworkGraph, &'h C, &'f L>, &'f L, IgnoringMessageHandler>;
388
389 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
390 /// socket events into messages which it passes on to its [`MessageHandler`].
391 ///
392 /// Locks are taken internally, so you must never assume that reentrancy from a
393 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
394 ///
395 /// Calls to [`read_event`] will decode relevant messages and pass them to the
396 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
397 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
398 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
399 /// calls only after previous ones have returned.
400 ///
401 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
402 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
403 /// essentially you should default to using a SimpleRefPeerManager, and use a
404 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
405 /// you're using lightning-net-tokio.
406 ///
407 /// [`read_event`]: PeerManager::read_event
408 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> where
409                 CM::Target: ChannelMessageHandler,
410                 RM::Target: RoutingMessageHandler,
411                 L::Target: Logger,
412                 CMH::Target: CustomMessageHandler {
413         message_handler: MessageHandler<CM, RM>,
414         peers: Mutex<PeerHolder<Descriptor>>,
415         our_node_secret: SecretKey,
416         ephemeral_key_midstate: Sha256Engine,
417         custom_message_handler: CMH,
418
419         peer_counter: AtomicCounter,
420
421         logger: L,
422 }
423
424 enum MessageHandlingError {
425         PeerHandleError(PeerHandleError),
426         LightningError(LightningError),
427 }
428
429 impl From<PeerHandleError> for MessageHandlingError {
430         fn from(error: PeerHandleError) -> Self {
431                 MessageHandlingError::PeerHandleError(error)
432         }
433 }
434
435 impl From<LightningError> for MessageHandlingError {
436         fn from(error: LightningError) -> Self {
437                 MessageHandlingError::LightningError(error)
438         }
439 }
440
441 macro_rules! encode_msg {
442         ($msg: expr) => {{
443                 let mut buffer = VecWriter(Vec::new());
444                 wire::write($msg, &mut buffer).unwrap();
445                 buffer.0
446         }}
447 }
448
449 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
450                 CM::Target: ChannelMessageHandler,
451                 L::Target: Logger {
452         /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
453         /// handler is used and network graph messages are ignored.
454         ///
455         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
456         /// cryptographically secure random bytes.
457         ///
458         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
459         pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
460                 Self::new(MessageHandler {
461                         chan_handler: channel_message_handler,
462                         route_handler: IgnoringMessageHandler{},
463                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
464         }
465 }
466
467 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringMessageHandler> where
468                 RM::Target: RoutingMessageHandler,
469                 L::Target: Logger {
470         /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
471         /// handler is used and messages related to channels will be ignored (or generate error
472         /// messages). Note that some other lightning implementations time-out connections after some
473         /// time if no channel is built with the peer.
474         ///
475         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
476         /// cryptographically secure random bytes.
477         ///
478         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
479         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
480                 Self::new(MessageHandler {
481                         chan_handler: ErroringMessageHandler::new(),
482                         route_handler: routing_message_handler,
483                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
484         }
485 }
486
487 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
488 /// This works around `format!()` taking a reference to each argument, preventing
489 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
490 /// due to lifetime errors.
491 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
492 impl core::fmt::Display for OptionalFromDebugger<'_> {
493         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
494                 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
495         }
496 }
497
498 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, L, CMH> where
499                 CM::Target: ChannelMessageHandler,
500                 RM::Target: RoutingMessageHandler,
501                 L::Target: Logger,
502                 CMH::Target: CustomMessageHandler {
503         /// Constructs a new PeerManager with the given message handlers and node_id secret key
504         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
505         /// cryptographically secure random bytes.
506         pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
507                 let mut ephemeral_key_midstate = Sha256::engine();
508                 ephemeral_key_midstate.input(ephemeral_random_data);
509
510                 PeerManager {
511                         message_handler,
512                         peers: Mutex::new(PeerHolder {
513                                 peers: HashMap::new(),
514                                 node_id_to_descriptor: HashMap::new()
515                         }),
516                         our_node_secret,
517                         ephemeral_key_midstate,
518                         peer_counter: AtomicCounter::new(),
519                         logger,
520                         custom_message_handler,
521                 }
522         }
523
524         /// Get the list of node ids for peers which have completed the initial handshake.
525         ///
526         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
527         /// new_outbound_connection, however entries will only appear once the initial handshake has
528         /// completed and we are sure the remote peer has the private key for the given node_id.
529         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
530                 let peers = self.peers.lock().unwrap();
531                 peers.peers.values().filter_map(|p| {
532                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
533                                 return None;
534                         }
535                         p.their_node_id
536                 }).collect()
537         }
538
539         fn get_ephemeral_key(&self) -> SecretKey {
540                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
541                 let counter = self.peer_counter.get_increment();
542                 ephemeral_hash.input(&counter.to_le_bytes());
543                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
544         }
545
546         /// Indicates a new outbound connection has been established to a node with the given node_id.
547         /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
548         /// descriptor but must disconnect the connection immediately.
549         ///
550         /// Returns a small number of bytes to send to the remote node (currently always 50).
551         ///
552         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
553         /// [`socket_disconnected()`].
554         ///
555         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
556         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
557                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
558                 let res = peer_encryptor.get_act_one().to_vec();
559                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
560
561                 let mut peers = self.peers.lock().unwrap();
562                 if peers.peers.insert(descriptor, Peer {
563                         channel_encryptor: peer_encryptor,
564                         their_node_id: None,
565                         their_features: None,
566
567                         pending_outbound_buffer: LinkedList::new(),
568                         pending_outbound_buffer_first_msg_offset: 0,
569                         awaiting_write_event: false,
570
571                         pending_read_buffer,
572                         pending_read_buffer_pos: 0,
573                         pending_read_is_header: false,
574
575                         sync_status: InitSyncTracker::NoSyncRequested,
576
577                         msgs_sent_since_pong: 0,
578                         awaiting_pong_timer_tick_intervals: 0,
579                         received_message_since_timer_tick: false,
580                 }).is_some() {
581                         panic!("PeerManager driver duplicated descriptors!");
582                 };
583                 Ok(res)
584         }
585
586         /// Indicates a new inbound connection has been established.
587         ///
588         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
589         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
590         /// call socket_disconnected for the new descriptor but must disconnect the connection
591         /// immediately.
592         ///
593         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
594         /// [`socket_disconnected()`].
595         ///
596         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
597         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
598                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
599                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
600
601                 let mut peers = self.peers.lock().unwrap();
602                 if peers.peers.insert(descriptor, Peer {
603                         channel_encryptor: peer_encryptor,
604                         their_node_id: None,
605                         their_features: None,
606
607                         pending_outbound_buffer: LinkedList::new(),
608                         pending_outbound_buffer_first_msg_offset: 0,
609                         awaiting_write_event: false,
610
611                         pending_read_buffer,
612                         pending_read_buffer_pos: 0,
613                         pending_read_is_header: false,
614
615                         sync_status: InitSyncTracker::NoSyncRequested,
616
617                         msgs_sent_since_pong: 0,
618                         awaiting_pong_timer_tick_intervals: 0,
619                         received_message_since_timer_tick: false,
620                 }).is_some() {
621                         panic!("PeerManager driver duplicated descriptors!");
622                 };
623                 Ok(())
624         }
625
626         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
627                 while !peer.awaiting_write_event {
628                         if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && peer.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK {
629                                 match peer.sync_status {
630                                         InitSyncTracker::NoSyncRequested => {},
631                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
632                                                 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
633                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
634                                                 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
635                                                         self.enqueue_message(peer, announce);
636                                                         if let &Some(ref update_a) = update_a_option {
637                                                                 self.enqueue_message(peer, update_a);
638                                                         }
639                                                         if let &Some(ref update_b) = update_b_option {
640                                                                 self.enqueue_message(peer, update_b);
641                                                         }
642                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
643                                                 }
644                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
645                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
646                                                 }
647                                         },
648                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
649                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
650                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
651                                                 for msg in all_messages.iter() {
652                                                         self.enqueue_message(peer, msg);
653                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
654                                                 }
655                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
656                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
657                                                 }
658                                         },
659                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
660                                         InitSyncTracker::NodesSyncing(key) => {
661                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
662                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
663                                                 for msg in all_messages.iter() {
664                                                         self.enqueue_message(peer, msg);
665                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
666                                                 }
667                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
668                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
669                                                 }
670                                         },
671                                 }
672                         }
673                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
674                                 self.maybe_send_extra_ping(peer);
675                         }
676
677                         if {
678                                 let next_buff = match peer.pending_outbound_buffer.front() {
679                                         None => return,
680                                         Some(buff) => buff,
681                                 };
682
683                                 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
684                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
685                                 let data_sent = descriptor.send_data(pending, should_be_reading);
686                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
687                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
688                         } {
689                                 peer.pending_outbound_buffer_first_msg_offset = 0;
690                                 peer.pending_outbound_buffer.pop_front();
691                         } else {
692                                 peer.awaiting_write_event = true;
693                         }
694                 }
695         }
696
697         /// Indicates that there is room to write data to the given socket descriptor.
698         ///
699         /// May return an Err to indicate that the connection should be closed.
700         ///
701         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
702         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
703         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
704         /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
705         /// sufficient!
706         ///
707         /// [`send_data`]: SocketDescriptor::send_data
708         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
709         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
710                 let mut peers = self.peers.lock().unwrap();
711                 match peers.peers.get_mut(descriptor) {
712                         None => {
713                                 // This is most likely a simple race condition where the user found that the socket
714                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
715                                 // this method. Return an error to make sure we get disconnected.
716                                 return Err(PeerHandleError { no_connection_possible: false });
717                         },
718                         Some(peer) => {
719                                 peer.awaiting_write_event = false;
720                                 self.do_attempt_write_data(descriptor, peer);
721                         }
722                 };
723                 Ok(())
724         }
725
726         /// Indicates that data was read from the given socket descriptor.
727         ///
728         /// May return an Err to indicate that the connection should be closed.
729         ///
730         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
731         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
732         /// [`send_data`] calls to handle responses.
733         ///
734         /// If `Ok(true)` is returned, further read_events should not be triggered until a
735         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
736         /// send buffer).
737         ///
738         /// [`send_data`]: SocketDescriptor::send_data
739         /// [`process_events`]: PeerManager::process_events
740         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
741                 match self.do_read_event(peer_descriptor, data) {
742                         Ok(res) => Ok(res),
743                         Err(e) => {
744                                 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
745                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
746                                 Err(e)
747                         }
748                 }
749         }
750
751         /// Append a message to a peer's pending outbound/write buffer
752         fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
753                 peer.msgs_sent_since_pong += 1;
754                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
755         }
756
757         /// Append a message to a peer's pending outbound/write buffer
758         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
759                 let mut buffer = VecWriter(Vec::with_capacity(2048));
760                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
761
762                 if is_gossip_msg(message.type_id()) {
763                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
764                 } else {
765                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
766                 }
767                 self.enqueue_encoded_message(peer, &buffer.0);
768         }
769
770         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
771                 let pause_read = {
772                         let mut peers_lock = self.peers.lock().unwrap();
773                         let peers = &mut *peers_lock;
774                         let mut msgs_to_forward = Vec::new();
775                         let mut peer_node_id = None;
776                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
777                                 None => {
778                                         // This is most likely a simple race condition where the user read some bytes
779                                         // from the socket, then we told the user to `disconnect_socket()`, then they
780                                         // called this method. Return an error to make sure we get disconnected.
781                                         return Err(PeerHandleError { no_connection_possible: false });
782                                 },
783                                 Some(peer) => {
784                                         assert!(peer.pending_read_buffer.len() > 0);
785                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
786
787                                         let mut read_pos = 0;
788                                         while read_pos < data.len() {
789                                                 {
790                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
791                                                         peer.pending_read_buffer[peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy].copy_from_slice(&data[read_pos..read_pos + data_to_copy]);
792                                                         read_pos += data_to_copy;
793                                                         peer.pending_read_buffer_pos += data_to_copy;
794                                                 }
795
796                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
797                                                         peer.pending_read_buffer_pos = 0;
798
799                                                         macro_rules! try_potential_handleerror {
800                                                                 ($thing: expr) => {
801                                                                         match $thing {
802                                                                                 Ok(x) => x,
803                                                                                 Err(e) => {
804                                                                                         match e.action {
805                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
806                                                                                                         //TODO: Try to push msg
807                                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
808                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
809                                                                                                 },
810                                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
811                                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
812                                                                                                         continue
813                                                                                                 },
814                                                                                                 msgs::ErrorAction::IgnoreError => {
815                                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
816                                                                                                         continue;
817                                                                                                 },
818                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
819                                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
820                                                                                                         self.enqueue_message(peer, &msg);
821                                                                                                         continue;
822                                                                                                 },
823                                                                                         }
824                                                                                 }
825                                                                         }
826                                                                 }
827                                                         }
828
829                                                         macro_rules! insert_node_id {
830                                                                 () => {
831                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
832                                                                                 hash_map::Entry::Occupied(_) => {
833                                                                                         log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
834                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
835                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
836                                                                                 },
837                                                                                 hash_map::Entry::Vacant(entry) => {
838                                                                                         log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
839                                                                                         entry.insert(peer_descriptor.clone())
840                                                                                 },
841                                                                         };
842                                                                 }
843                                                         }
844
845                                                         let next_step = peer.channel_encryptor.get_noise_step();
846                                                         match next_step {
847                                                                 NextNoiseStep::ActOne => {
848                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
849                                                                         peer.pending_outbound_buffer.push_back(act_two);
850                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
851                                                                 },
852                                                                 NextNoiseStep::ActTwo => {
853                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
854                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
855                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
856                                                                         peer.pending_read_is_header = true;
857
858                                                                         peer.their_node_id = Some(their_node_id);
859                                                                         insert_node_id!();
860                                                                         let features = InitFeatures::known();
861                                                                         let resp = msgs::Init { features };
862                                                                         self.enqueue_message(peer, &resp);
863                                                                         peer.awaiting_pong_timer_tick_intervals = 0;
864                                                                 },
865                                                                 NextNoiseStep::ActThree => {
866                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
867                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
868                                                                         peer.pending_read_is_header = true;
869                                                                         peer.their_node_id = Some(their_node_id);
870                                                                         insert_node_id!();
871                                                                         let features = InitFeatures::known();
872                                                                         let resp = msgs::Init { features };
873                                                                         self.enqueue_message(peer, &resp);
874                                                                         peer.awaiting_pong_timer_tick_intervals = 0;
875                                                                 },
876                                                                 NextNoiseStep::NoiseComplete => {
877                                                                         if peer.pending_read_is_header {
878                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
879                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
880                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
881                                                                                 if msg_len < 2 { // Need at least the message type tag
882                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
883                                                                                 }
884                                                                                 peer.pending_read_is_header = false;
885                                                                         } else {
886                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
887                                                                                 assert!(msg_data.len() >= 2);
888
889                                                                                 // Reset read buffer
890                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
891                                                                                 peer.pending_read_is_header = true;
892
893                                                                                 let mut reader = io::Cursor::new(&msg_data[..]);
894                                                                                 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
895                                                                                 let message = match message_result {
896                                                                                         Ok(x) => x,
897                                                                                         Err(e) => {
898                                                                                                 match e {
899                                                                                                         msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
900                                                                                                         msgs::DecodeError::UnknownRequiredFeature => {
901                                                                                                                 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
902                                                                                                                 continue;
903                                                                                                         }
904                                                                                                         msgs::DecodeError::InvalidValue => {
905                                                                                                                 log_debug!(self.logger, "Got an invalid value while deserializing message");
906                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
907                                                                                                         }
908                                                                                                         msgs::DecodeError::ShortRead => {
909                                                                                                                 log_debug!(self.logger, "Deserialization failed due to shortness of message");
910                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
911                                                                                                         }
912                                                                                                         msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
913                                                                                                         msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
914                                                                                                         msgs::DecodeError::UnsupportedCompression => {
915                                                                                                                 log_gossip!(self.logger, "We don't support zlib-compressed message fields, ignoring message");
916                                                                                                                 continue;
917                                                                                                         }
918                                                                                                 }
919                                                                                         }
920                                                                                 };
921
922                                                                                 match self.handle_message(peer, message) {
923                                                                                         Err(handling_error) => match handling_error {
924                                                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
925                                                                                                 MessageHandlingError::LightningError(e) => {
926                                                                                                         try_potential_handleerror!(Err(e));
927                                                                                                 },
928                                                                                         },
929                                                                                         Ok(Some(msg)) => {
930                                                                                                 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
931                                                                                                 msgs_to_forward.push(msg);
932                                                                                         },
933                                                                                         Ok(None) => {},
934                                                                                 }
935                                                                         }
936                                                                 }
937                                                         }
938                                                 }
939                                         }
940
941                                         peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
942                                 }
943                         };
944
945                         for msg in msgs_to_forward.drain(..) {
946                                 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
947                         }
948
949                         pause_read
950                 };
951
952                 Ok(pause_read)
953         }
954
955         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
956         /// Returns the message back if it needs to be broadcasted to all other peers.
957         fn handle_message(
958                 &self,
959                 peer: &mut Peer,
960                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
961         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
962                 if is_gossip_msg(message.type_id()) {
963                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
964                 } else {
965                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
966                 }
967
968                 peer.received_message_since_timer_tick = true;
969
970                 // Need an Init as first message
971                 if let wire::Message::Init(_) = message {
972                 } else if peer.their_features.is_none() {
973                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
974                         return Err(PeerHandleError{ no_connection_possible: false }.into());
975                 }
976
977                 let mut should_forward = None;
978
979                 match message {
980                         // Setup and Control messages:
981                         wire::Message::Init(msg) => {
982                                 if msg.features.requires_unknown_bits() {
983                                         log_debug!(self.logger, "Peer features required unknown version bits");
984                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
985                                 }
986                                 if peer.their_features.is_some() {
987                                         return Err(PeerHandleError{ no_connection_possible: false }.into());
988                                 }
989
990                                 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.features);
991
992                                 if msg.features.initial_routing_sync() {
993                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
994                                 }
995                                 if !msg.features.supports_static_remote_key() {
996                                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
997                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
998                                 }
999
1000                                 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
1001
1002                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1003                                 peer.their_features = Some(msg.features);
1004                         },
1005                         wire::Message::Error(msg) => {
1006                                 let mut data_is_printable = true;
1007                                 for b in msg.data.bytes() {
1008                                         if b < 32 || b > 126 {
1009                                                 data_is_printable = false;
1010                                                 break;
1011                                         }
1012                                 }
1013
1014                                 if data_is_printable {
1015                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1016                                 } else {
1017                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1018                                 }
1019                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
1020                                 if msg.channel_id == [0; 32] {
1021                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1022                                 }
1023                         },
1024
1025                         wire::Message::Ping(msg) => {
1026                                 if msg.ponglen < 65532 {
1027                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1028                                         self.enqueue_message(peer, &resp);
1029                                 }
1030                         },
1031                         wire::Message::Pong(_msg) => {
1032                                 peer.awaiting_pong_timer_tick_intervals = 0;
1033                                 peer.msgs_sent_since_pong = 0;
1034                         },
1035
1036                         // Channel messages:
1037                         wire::Message::OpenChannel(msg) => {
1038                                 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1039                         },
1040                         wire::Message::AcceptChannel(msg) => {
1041                                 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1042                         },
1043
1044                         wire::Message::FundingCreated(msg) => {
1045                                 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
1046                         },
1047                         wire::Message::FundingSigned(msg) => {
1048                                 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
1049                         },
1050                         wire::Message::FundingLocked(msg) => {
1051                                 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
1052                         },
1053
1054                         wire::Message::Shutdown(msg) => {
1055                                 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
1056                         },
1057                         wire::Message::ClosingSigned(msg) => {
1058                                 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
1059                         },
1060
1061                         // Commitment messages:
1062                         wire::Message::UpdateAddHTLC(msg) => {
1063                                 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
1064                         },
1065                         wire::Message::UpdateFulfillHTLC(msg) => {
1066                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
1067                         },
1068                         wire::Message::UpdateFailHTLC(msg) => {
1069                                 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
1070                         },
1071                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1072                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
1073                         },
1074
1075                         wire::Message::CommitmentSigned(msg) => {
1076                                 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
1077                         },
1078                         wire::Message::RevokeAndACK(msg) => {
1079                                 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
1080                         },
1081                         wire::Message::UpdateFee(msg) => {
1082                                 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
1083                         },
1084                         wire::Message::ChannelReestablish(msg) => {
1085                                 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
1086                         },
1087
1088                         // Routing messages:
1089                         wire::Message::AnnouncementSignatures(msg) => {
1090                                 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
1091                         },
1092                         wire::Message::ChannelAnnouncement(msg) => {
1093                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1094                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1095                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1096                                 }
1097                         },
1098                         wire::Message::NodeAnnouncement(msg) => {
1099                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1100                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1101                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1102                                 }
1103                         },
1104                         wire::Message::ChannelUpdate(msg) => {
1105                                 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1106                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1107                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1108                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1109                                 }
1110                         },
1111                         wire::Message::QueryShortChannelIds(msg) => {
1112                                 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1113                         },
1114                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1115                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1116                         },
1117                         wire::Message::QueryChannelRange(msg) => {
1118                                 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1119                         },
1120                         wire::Message::ReplyChannelRange(msg) => {
1121                                 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1122                         },
1123                         wire::Message::GossipTimestampFilter(_msg) => {
1124                                 // TODO: handle message
1125                         },
1126
1127                         // Unknown messages:
1128                         wire::Message::Unknown(type_id) if message.is_even() => {
1129                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1130                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
1131                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1132                         },
1133                         wire::Message::Unknown(type_id) => {
1134                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1135                         },
1136                         wire::Message::Custom(custom) => {
1137                                 self.custom_message_handler.handle_custom_message(custom, &peer.their_node_id.unwrap())?;
1138                         },
1139                 };
1140                 Ok(should_forward)
1141         }
1142
1143         fn forward_broadcast_msg(&self, peers: &mut PeerHolder<Descriptor>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1144                 match msg {
1145                         wire::Message::ChannelAnnouncement(ref msg) => {
1146                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1147                                 let encoded_msg = encode_msg!(msg);
1148
1149                                 for (_, peer) in peers.peers.iter_mut() {
1150                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1151                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1152                                                 continue
1153                                         }
1154                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1155                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1156                                         {
1157                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1158                                                 continue;
1159                                         }
1160                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1161                                            peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1162                                                 continue;
1163                                         }
1164                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1165                                                 continue;
1166                                         }
1167                                         self.enqueue_encoded_message(peer, &encoded_msg);
1168                                 }
1169                         },
1170                         wire::Message::NodeAnnouncement(ref msg) => {
1171                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1172                                 let encoded_msg = encode_msg!(msg);
1173
1174                                 for (_, peer) in peers.peers.iter_mut() {
1175                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1176                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1177                                                 continue
1178                                         }
1179                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1180                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1181                                         {
1182                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1183                                                 continue;
1184                                         }
1185                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1186                                                 continue;
1187                                         }
1188                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1189                                                 continue;
1190                                         }
1191                                         self.enqueue_encoded_message(peer, &encoded_msg);
1192                                 }
1193                         },
1194                         wire::Message::ChannelUpdate(ref msg) => {
1195                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1196                                 let encoded_msg = encode_msg!(msg);
1197
1198                                 for (_, peer) in peers.peers.iter_mut() {
1199                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1200                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1201                                                 continue
1202                                         }
1203                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1204                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1205                                         {
1206                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1207                                                 continue;
1208                                         }
1209                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1210                                                 continue;
1211                                         }
1212                                         self.enqueue_encoded_message(peer, &encoded_msg);
1213                                 }
1214                         },
1215                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1216                 }
1217         }
1218
1219         /// Checks for any events generated by our handlers and processes them. Includes sending most
1220         /// response messages as well as messages generated by calls to handler functions directly (eg
1221         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1222         ///
1223         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1224         /// issues!
1225         ///
1226         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1227         /// or one of the other clients provided in our language bindings.
1228         ///
1229         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1230         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1231         /// [`send_data`]: SocketDescriptor::send_data
1232         pub fn process_events(&self) {
1233                 {
1234                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
1235                         // buffer by doing things like announcing channels on another node. We should be willing to
1236                         // drop optional-ish messages when send buffers get full!
1237
1238                         let mut peers_lock = self.peers.lock().unwrap();
1239                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1240                         events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1241                         let peers = &mut *peers_lock;
1242                         macro_rules! get_peer_for_forwarding {
1243                                 ($node_id: expr) => {
1244                                         {
1245                                                 match peers.node_id_to_descriptor.get($node_id) {
1246                                                         Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1247                                                                 Some(peer) => {
1248                                                                         if peer.their_features.is_none() {
1249                                                                                 continue;
1250                                                                         }
1251                                                                         peer
1252                                                                 },
1253                                                                 None => panic!("Inconsistent peers set state!"),
1254                                                         },
1255                                                         None => {
1256                                                                 continue;
1257                                                         },
1258                                                 }
1259                                         }
1260                                 }
1261                         }
1262                         for event in events_generated.drain(..) {
1263                                 match event {
1264                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1265                                                 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1266                                                                 log_pubkey!(node_id),
1267                                                                 log_bytes!(msg.temporary_channel_id));
1268                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1269                                         },
1270                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1271                                                 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1272                                                                 log_pubkey!(node_id),
1273                                                                 log_bytes!(msg.temporary_channel_id));
1274                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1275                                         },
1276                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1277                                                 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1278                                                                 log_pubkey!(node_id),
1279                                                                 log_bytes!(msg.temporary_channel_id),
1280                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1281                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1282                                                 // indicating to the wallet that they should just throw away this funding transaction
1283                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1284                                         },
1285                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1286                                                 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1287                                                                 log_pubkey!(node_id),
1288                                                                 log_bytes!(msg.channel_id));
1289                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1290                                         },
1291                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1292                                                 log_debug!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1293                                                                 log_pubkey!(node_id),
1294                                                                 log_bytes!(msg.channel_id));
1295                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1296                                         },
1297                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1298                                                 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1299                                                                 log_pubkey!(node_id),
1300                                                                 log_bytes!(msg.channel_id));
1301                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1302                                         },
1303                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1304                                                 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1305                                                                 log_pubkey!(node_id),
1306                                                                 update_add_htlcs.len(),
1307                                                                 update_fulfill_htlcs.len(),
1308                                                                 update_fail_htlcs.len(),
1309                                                                 log_bytes!(commitment_signed.channel_id));
1310                                                 let peer = get_peer_for_forwarding!(node_id);
1311                                                 for msg in update_add_htlcs {
1312                                                         self.enqueue_message(peer, msg);
1313                                                 }
1314                                                 for msg in update_fulfill_htlcs {
1315                                                         self.enqueue_message(peer, msg);
1316                                                 }
1317                                                 for msg in update_fail_htlcs {
1318                                                         self.enqueue_message(peer, msg);
1319                                                 }
1320                                                 for msg in update_fail_malformed_htlcs {
1321                                                         self.enqueue_message(peer, msg);
1322                                                 }
1323                                                 if let &Some(ref msg) = update_fee {
1324                                                         self.enqueue_message(peer, msg);
1325                                                 }
1326                                                 self.enqueue_message(peer, commitment_signed);
1327                                         },
1328                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1329                                                 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1330                                                                 log_pubkey!(node_id),
1331                                                                 log_bytes!(msg.channel_id));
1332                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1333                                         },
1334                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1335                                                 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1336                                                                 log_pubkey!(node_id),
1337                                                                 log_bytes!(msg.channel_id));
1338                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1339                                         },
1340                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1341                                                 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1342                                                                 log_pubkey!(node_id),
1343                                                                 log_bytes!(msg.channel_id));
1344                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1345                                         },
1346                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1347                                                 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1348                                                                 log_pubkey!(node_id),
1349                                                                 log_bytes!(msg.channel_id));
1350                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1351                                         },
1352                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1353                                                 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1354                                                 if self.message_handler.route_handler.handle_channel_announcement(&msg).is_ok() && self.message_handler.route_handler.handle_channel_update(&update_msg).is_ok() {
1355                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None);
1356                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None);
1357                                                 }
1358                                         },
1359                                         MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1360                                                 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1361                                                 if self.message_handler.route_handler.handle_node_announcement(&msg).is_ok() {
1362                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None);
1363                                                 }
1364                                         },
1365                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1366                                                 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1367                                                 if self.message_handler.route_handler.handle_channel_update(&msg).is_ok() {
1368                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None);
1369                                                 }
1370                                         },
1371                                         MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1372                                                 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1373                                                                 log_pubkey!(node_id), msg.contents.short_channel_id);
1374                                                 let peer = get_peer_for_forwarding!(node_id);
1375                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1376                                         },
1377                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1378                                                 match *action {
1379                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1380                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1381                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
1382                                                                                 if let Some(ref msg) = *msg {
1383                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1384                                                                                                         log_pubkey!(node_id),
1385                                                                                                         msg.data);
1386                                                                                         self.enqueue_message(&mut peer, msg);
1387                                                                                         // This isn't guaranteed to work, but if there is enough free
1388                                                                                         // room in the send buffer, put the error message there...
1389                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1390                                                                                 } else {
1391                                                                                         log_gossip!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1392                                                                                 }
1393                                                                         }
1394                                                                         descriptor.disconnect_socket();
1395                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1396                                                                 }
1397                                                         },
1398                                                         msgs::ErrorAction::IgnoreAndLog(level) => {
1399                                                                 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1400                                                         },
1401                                                         msgs::ErrorAction::IgnoreError => {
1402                                                                 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1403                                                         },
1404                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1405                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1406                                                                                 log_pubkey!(node_id),
1407                                                                                 msg.data);
1408                                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1409                                                         },
1410                                                 }
1411                                         },
1412                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1413                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1414                                         },
1415                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1416                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1417                                         }
1418                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1419                                                 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1420                                                         log_pubkey!(node_id),
1421                                                         msg.short_channel_ids.len(),
1422                                                         msg.first_blocknum,
1423                                                         msg.number_of_blocks,
1424                                                         msg.sync_complete);
1425                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1426                                         }
1427                                 }
1428                         }
1429
1430                         for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1431                                 self.enqueue_message(get_peer_for_forwarding!(&node_id), &msg);
1432                         }
1433
1434                         for (descriptor, peer) in peers.peers.iter_mut() {
1435                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1436                         }
1437                 }
1438         }
1439
1440         /// Indicates that the given socket descriptor's connection is now closed.
1441         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1442                 self.disconnect_event_internal(descriptor, false);
1443         }
1444
1445         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1446                 let mut peers = self.peers.lock().unwrap();
1447                 let peer_option = peers.peers.remove(descriptor);
1448                 match peer_option {
1449                         None => {
1450                                 // This is most likely a simple race condition where the user found that the socket
1451                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
1452                                 // called this method. Either way we're disconnected, return.
1453                         },
1454                         Some(peer) => {
1455                                 match peer.their_node_id {
1456                                         Some(node_id) => {
1457                                                 log_trace!(self.logger,
1458                                                         "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1459                                                         log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1460                                                 peers.node_id_to_descriptor.remove(&node_id);
1461                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1462                                         },
1463                                         None => {}
1464                                 }
1465                         }
1466                 };
1467         }
1468
1469         /// Disconnect a peer given its node id.
1470         ///
1471         /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1472         /// force-closing any channels we have with it.
1473         ///
1474         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1475         /// peer. Thus, be very careful about reentrancy issues.
1476         ///
1477         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1478         pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1479                 let mut peers_lock = self.peers.lock().unwrap();
1480                 if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
1481                         log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1482                         peers_lock.peers.remove(&descriptor);
1483                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1484                         descriptor.disconnect_socket();
1485                 }
1486         }
1487
1488         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1489         /// an indication that TCP sockets have stalled even if we weren't around to time them out
1490         /// using regular ping/pongs.
1491         pub fn disconnect_all_peers(&self) {
1492                 let mut peers_lock = self.peers.lock().unwrap();
1493                 let peers = &mut *peers_lock;
1494                 for (mut descriptor, peer) in peers.peers.drain() {
1495                         if let Some(node_id) = peer.their_node_id {
1496                                 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1497                                 peers.node_id_to_descriptor.remove(&node_id);
1498                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1499                         }
1500                         descriptor.disconnect_socket();
1501                 }
1502                 debug_assert!(peers.node_id_to_descriptor.is_empty());
1503         }
1504
1505         /// This is called when we're blocked on sending additional gossip messages until we receive a
1506         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1507         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1508         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1509                 if peer.awaiting_pong_timer_tick_intervals == 0 {
1510                         peer.awaiting_pong_timer_tick_intervals = -1;
1511                         let ping = msgs::Ping {
1512                                 ponglen: 0,
1513                                 byteslen: 64,
1514                         };
1515                         self.enqueue_message(peer, &ping);
1516                 }
1517         }
1518
1519         /// Send pings to each peer and disconnect those which did not respond to the last round of
1520         /// pings.
1521         ///
1522         /// This may be called on any timescale you want, however, roughly once every five to ten
1523         /// seconds is preferred. The call rate determines both how often we send a ping to our peers
1524         /// and how much time they have to respond before we disconnect them.
1525         ///
1526         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1527         /// issues!
1528         ///
1529         /// [`send_data`]: SocketDescriptor::send_data
1530         pub fn timer_tick_occurred(&self) {
1531                 let mut peers_lock = self.peers.lock().unwrap();
1532                 {
1533                         let peers = &mut *peers_lock;
1534                         let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1535                         let peers = &mut peers.peers;
1536                         let mut descriptors_needing_disconnect = Vec::new();
1537                         let peer_count = peers.len();
1538
1539                         peers.retain(|descriptor, peer| {
1540                                 let mut do_disconnect_peer = false;
1541                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1542                                         // The peer needs to complete its handshake before we can exchange messages. We
1543                                         // give peers one timer tick to complete handshake, reusing
1544                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1545                                         // for handshake completion.
1546                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
1547                                                 do_disconnect_peer = true;
1548                                         } else {
1549                                                 peer.awaiting_pong_timer_tick_intervals = 1;
1550                                                 return true;
1551                                         }
1552                                 }
1553
1554                                 if peer.awaiting_pong_timer_tick_intervals == -1 {
1555                                         // Magic value set in `maybe_send_extra_ping`.
1556                                         peer.awaiting_pong_timer_tick_intervals = 1;
1557                                         peer.received_message_since_timer_tick = false;
1558                                         return true;
1559                                 }
1560
1561                                 if do_disconnect_peer
1562                                         || (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1563                                         || peer.awaiting_pong_timer_tick_intervals as u64 >
1564                                                 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peer_count as u64
1565                                 {
1566                                         descriptors_needing_disconnect.push(descriptor.clone());
1567                                         match peer.their_node_id {
1568                                                 Some(node_id) => {
1569                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1570                                                         node_id_to_descriptor.remove(&node_id);
1571                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1572                                                 }
1573                                                 None => {},
1574                                         }
1575                                         return false;
1576                                 }
1577                                 peer.received_message_since_timer_tick = false;
1578
1579                                 if peer.awaiting_pong_timer_tick_intervals > 0 {
1580                                         peer.awaiting_pong_timer_tick_intervals += 1;
1581                                         return true;
1582                                 }
1583
1584                                 peer.awaiting_pong_timer_tick_intervals = 1;
1585                                 let ping = msgs::Ping {
1586                                         ponglen: 0,
1587                                         byteslen: 64,
1588                                 };
1589                                 self.enqueue_message(peer, &ping);
1590                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1591
1592                                 true
1593                         });
1594
1595                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1596                                 descriptor.disconnect_socket();
1597                         }
1598                 }
1599         }
1600 }
1601
1602 fn is_gossip_msg(type_id: u16) -> bool {
1603         match type_id {
1604                 msgs::ChannelAnnouncement::TYPE |
1605                 msgs::ChannelUpdate::TYPE |
1606                 msgs::NodeAnnouncement::TYPE => true,
1607                 _ => false
1608         }
1609 }
1610
1611 #[cfg(test)]
1612 mod tests {
1613         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
1614         use ln::msgs;
1615         use util::events;
1616         use util::test_utils;
1617
1618         use bitcoin::secp256k1::Secp256k1;
1619         use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1620
1621         use prelude::*;
1622         use sync::{Arc, Mutex};
1623         use core::sync::atomic::Ordering;
1624
1625         #[derive(Clone)]
1626         struct FileDescriptor {
1627                 fd: u16,
1628                 outbound_data: Arc<Mutex<Vec<u8>>>,
1629         }
1630         impl PartialEq for FileDescriptor {
1631                 fn eq(&self, other: &Self) -> bool {
1632                         self.fd == other.fd
1633                 }
1634         }
1635         impl Eq for FileDescriptor { }
1636         impl core::hash::Hash for FileDescriptor {
1637                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1638                         self.fd.hash(hasher)
1639                 }
1640         }
1641
1642         impl SocketDescriptor for FileDescriptor {
1643                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1644                         self.outbound_data.lock().unwrap().extend_from_slice(data);
1645                         data.len()
1646                 }
1647
1648                 fn disconnect_socket(&mut self) {}
1649         }
1650
1651         struct PeerManagerCfg {
1652                 chan_handler: test_utils::TestChannelMessageHandler,
1653                 routing_handler: test_utils::TestRoutingMessageHandler,
1654                 logger: test_utils::TestLogger,
1655         }
1656
1657         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1658                 let mut cfgs = Vec::new();
1659                 for _ in 0..peer_count {
1660                         cfgs.push(
1661                                 PeerManagerCfg{
1662                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
1663                                         logger: test_utils::TestLogger::new(),
1664                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
1665                                 }
1666                         );
1667                 }
1668
1669                 cfgs
1670         }
1671
1672         fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>> {
1673                 let mut peers = Vec::new();
1674                 for i in 0..peer_count {
1675                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1676                         let ephemeral_bytes = [i as u8; 32];
1677                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1678                         let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1679                         peers.push(peer);
1680                 }
1681
1682                 peers
1683         }
1684
1685         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
1686                 let secp_ctx = Secp256k1::new();
1687                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1688                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1689                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1690                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1691                 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1692                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1693                 peer_a.process_events();
1694                 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1695                 peer_b.process_events();
1696                 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1697                 (fd_a.clone(), fd_b.clone())
1698         }
1699
1700         #[test]
1701         fn test_disconnect_peer() {
1702                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1703                 // push a DisconnectPeer event to remove the node flagged by id
1704                 let cfgs = create_peermgr_cfgs(2);
1705                 let chan_handler = test_utils::TestChannelMessageHandler::new();
1706                 let mut peers = create_network(2, &cfgs);
1707                 establish_connection(&peers[0], &peers[1]);
1708                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1709
1710                 let secp_ctx = Secp256k1::new();
1711                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1712
1713                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1714                         node_id: their_id,
1715                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
1716                 });
1717                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1718                 peers[0].message_handler.chan_handler = &chan_handler;
1719
1720                 peers[0].process_events();
1721                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1722         }
1723
1724         #[test]
1725         fn test_timer_tick_occurred() {
1726                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1727                 let cfgs = create_peermgr_cfgs(2);
1728                 let peers = create_network(2, &cfgs);
1729                 establish_connection(&peers[0], &peers[1]);
1730                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1731
1732                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1733                 peers[0].timer_tick_occurred();
1734                 peers[0].process_events();
1735                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1736
1737                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1738                 peers[0].timer_tick_occurred();
1739                 peers[0].process_events();
1740                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1741         }
1742
1743         #[test]
1744         fn test_do_attempt_write_data() {
1745                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1746                 let cfgs = create_peermgr_cfgs(2);
1747                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1748                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1749                 let peers = create_network(2, &cfgs);
1750
1751                 // By calling establish_connect, we trigger do_attempt_write_data between
1752                 // the peers. Previously this function would mistakenly enter an infinite loop
1753                 // when there were more channel messages available than could fit into a peer's
1754                 // buffer. This issue would now be detected by this test (because we use custom
1755                 // RoutingMessageHandlers that intentionally return more channel messages
1756                 // than can fit into a peer's buffer).
1757                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1758
1759                 // Make each peer to read the messages that the other peer just wrote to them. Note that
1760                 // due to the max-messagse-before-ping limits this may take a few iterations to complete.
1761                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
1762                         peers[0].process_events();
1763                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1764                         assert!(!b_read_data.is_empty());
1765
1766                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
1767                         peers[1].process_events();
1768
1769                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1770                         assert!(!a_read_data.is_empty());
1771                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
1772
1773                         peers[1].process_events();
1774                         assert_eq!(fd_b.outbound_data.lock().unwrap().len(), 0, "Until B receives data, it shouldn't send more messages");
1775                 }
1776
1777                 // Check that each peer has received the expected number of channel updates and channel
1778                 // announcements.
1779                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1780                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1781                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1782                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1783         }
1784
1785         #[test]
1786         fn test_handshake_timeout() {
1787                 // Tests that we time out a peer still waiting on handshake completion after a full timer
1788                 // tick.
1789                 let cfgs = create_peermgr_cfgs(2);
1790                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1791                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1792                 let peers = create_network(2, &cfgs);
1793
1794                 let secp_ctx = Secp256k1::new();
1795                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
1796                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1797                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1798                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone()).unwrap();
1799                 peers[0].new_inbound_connection(fd_a.clone()).unwrap();
1800
1801                 // If we get a single timer tick before completion, that's fine
1802                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1803                 peers[0].timer_tick_occurred();
1804                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1805
1806                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
1807                 peers[0].process_events();
1808                 assert_eq!(peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1809                 peers[1].process_events();
1810
1811                 // ...but if we get a second timer tick, we should disconnect the peer
1812                 peers[0].timer_tick_occurred();
1813                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1814
1815                 assert!(peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).is_err());
1816         }
1817 }