Tag some type aliases with `(C-not exported)`
[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 ten seconds, this translates to about 40 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 = 4;
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 ///
380 /// (C-not exported) as Arcs don't make sense in bindings
381 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>>;
382
383 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
384 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
385 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
386 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
387 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
388 /// helps with issues such as long function definitions.
389 ///
390 /// (C-not exported) as Arcs don't make sense in bindings
391 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>;
392
393 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
394 /// socket events into messages which it passes on to its [`MessageHandler`].
395 ///
396 /// Locks are taken internally, so you must never assume that reentrancy from a
397 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
398 ///
399 /// Calls to [`read_event`] will decode relevant messages and pass them to the
400 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
401 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
402 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
403 /// calls only after previous ones have returned.
404 ///
405 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
406 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
407 /// essentially you should default to using a SimpleRefPeerManager, and use a
408 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
409 /// you're using lightning-net-tokio.
410 ///
411 /// [`read_event`]: PeerManager::read_event
412 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> where
413                 CM::Target: ChannelMessageHandler,
414                 RM::Target: RoutingMessageHandler,
415                 L::Target: Logger,
416                 CMH::Target: CustomMessageHandler {
417         message_handler: MessageHandler<CM, RM>,
418         peers: Mutex<PeerHolder<Descriptor>>,
419         our_node_secret: SecretKey,
420         ephemeral_key_midstate: Sha256Engine,
421         custom_message_handler: CMH,
422
423         peer_counter: AtomicCounter,
424
425         logger: L,
426 }
427
428 enum MessageHandlingError {
429         PeerHandleError(PeerHandleError),
430         LightningError(LightningError),
431 }
432
433 impl From<PeerHandleError> for MessageHandlingError {
434         fn from(error: PeerHandleError) -> Self {
435                 MessageHandlingError::PeerHandleError(error)
436         }
437 }
438
439 impl From<LightningError> for MessageHandlingError {
440         fn from(error: LightningError) -> Self {
441                 MessageHandlingError::LightningError(error)
442         }
443 }
444
445 macro_rules! encode_msg {
446         ($msg: expr) => {{
447                 let mut buffer = VecWriter(Vec::new());
448                 wire::write($msg, &mut buffer).unwrap();
449                 buffer.0
450         }}
451 }
452
453 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
454                 CM::Target: ChannelMessageHandler,
455                 L::Target: Logger {
456         /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
457         /// handler is used and network graph messages are ignored.
458         ///
459         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
460         /// cryptographically secure random bytes.
461         ///
462         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
463         pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
464                 Self::new(MessageHandler {
465                         chan_handler: channel_message_handler,
466                         route_handler: IgnoringMessageHandler{},
467                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
468         }
469 }
470
471 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringMessageHandler> where
472                 RM::Target: RoutingMessageHandler,
473                 L::Target: Logger {
474         /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
475         /// handler is used and messages related to channels will be ignored (or generate error
476         /// messages). Note that some other lightning implementations time-out connections after some
477         /// time if no channel is built with the peer.
478         ///
479         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
480         /// cryptographically secure random bytes.
481         ///
482         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
483         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
484                 Self::new(MessageHandler {
485                         chan_handler: ErroringMessageHandler::new(),
486                         route_handler: routing_message_handler,
487                 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
488         }
489 }
490
491 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
492 /// This works around `format!()` taking a reference to each argument, preventing
493 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
494 /// due to lifetime errors.
495 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
496 impl core::fmt::Display for OptionalFromDebugger<'_> {
497         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
498                 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
499         }
500 }
501
502 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, L, CMH> where
503                 CM::Target: ChannelMessageHandler,
504                 RM::Target: RoutingMessageHandler,
505                 L::Target: Logger,
506                 CMH::Target: CustomMessageHandler {
507         /// Constructs a new PeerManager with the given message handlers and node_id secret key
508         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
509         /// cryptographically secure random bytes.
510         pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
511                 let mut ephemeral_key_midstate = Sha256::engine();
512                 ephemeral_key_midstate.input(ephemeral_random_data);
513
514                 PeerManager {
515                         message_handler,
516                         peers: Mutex::new(PeerHolder {
517                                 peers: HashMap::new(),
518                                 node_id_to_descriptor: HashMap::new()
519                         }),
520                         our_node_secret,
521                         ephemeral_key_midstate,
522                         peer_counter: AtomicCounter::new(),
523                         logger,
524                         custom_message_handler,
525                 }
526         }
527
528         /// Get the list of node ids for peers which have completed the initial handshake.
529         ///
530         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
531         /// new_outbound_connection, however entries will only appear once the initial handshake has
532         /// completed and we are sure the remote peer has the private key for the given node_id.
533         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
534                 let peers = self.peers.lock().unwrap();
535                 peers.peers.values().filter_map(|p| {
536                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
537                                 return None;
538                         }
539                         p.their_node_id
540                 }).collect()
541         }
542
543         fn get_ephemeral_key(&self) -> SecretKey {
544                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
545                 let counter = self.peer_counter.get_increment();
546                 ephemeral_hash.input(&counter.to_le_bytes());
547                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
548         }
549
550         /// Indicates a new outbound connection has been established to a node with the given node_id.
551         /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
552         /// descriptor but must disconnect the connection immediately.
553         ///
554         /// Returns a small number of bytes to send to the remote node (currently always 50).
555         ///
556         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
557         /// [`socket_disconnected()`].
558         ///
559         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
560         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
561                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
562                 let res = peer_encryptor.get_act_one().to_vec();
563                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
564
565                 let mut peers = self.peers.lock().unwrap();
566                 if peers.peers.insert(descriptor, Peer {
567                         channel_encryptor: peer_encryptor,
568                         their_node_id: None,
569                         their_features: None,
570
571                         pending_outbound_buffer: LinkedList::new(),
572                         pending_outbound_buffer_first_msg_offset: 0,
573                         awaiting_write_event: false,
574
575                         pending_read_buffer,
576                         pending_read_buffer_pos: 0,
577                         pending_read_is_header: false,
578
579                         sync_status: InitSyncTracker::NoSyncRequested,
580
581                         msgs_sent_since_pong: 0,
582                         awaiting_pong_timer_tick_intervals: 0,
583                         received_message_since_timer_tick: false,
584                 }).is_some() {
585                         panic!("PeerManager driver duplicated descriptors!");
586                 };
587                 Ok(res)
588         }
589
590         /// Indicates a new inbound connection has been established.
591         ///
592         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
593         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
594         /// call socket_disconnected for the new descriptor but must disconnect the connection
595         /// immediately.
596         ///
597         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
598         /// [`socket_disconnected()`].
599         ///
600         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
601         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
602                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
603                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
604
605                 let mut peers = self.peers.lock().unwrap();
606                 if peers.peers.insert(descriptor, Peer {
607                         channel_encryptor: peer_encryptor,
608                         their_node_id: None,
609                         their_features: None,
610
611                         pending_outbound_buffer: LinkedList::new(),
612                         pending_outbound_buffer_first_msg_offset: 0,
613                         awaiting_write_event: false,
614
615                         pending_read_buffer,
616                         pending_read_buffer_pos: 0,
617                         pending_read_is_header: false,
618
619                         sync_status: InitSyncTracker::NoSyncRequested,
620
621                         msgs_sent_since_pong: 0,
622                         awaiting_pong_timer_tick_intervals: 0,
623                         received_message_since_timer_tick: false,
624                 }).is_some() {
625                         panic!("PeerManager driver duplicated descriptors!");
626                 };
627                 Ok(())
628         }
629
630         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
631                 while !peer.awaiting_write_event {
632                         if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && peer.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK {
633                                 match peer.sync_status {
634                                         InitSyncTracker::NoSyncRequested => {},
635                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
636                                                 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
637                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
638                                                 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
639                                                         self.enqueue_message(peer, announce);
640                                                         if let &Some(ref update_a) = update_a_option {
641                                                                 self.enqueue_message(peer, update_a);
642                                                         }
643                                                         if let &Some(ref update_b) = update_b_option {
644                                                                 self.enqueue_message(peer, update_b);
645                                                         }
646                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
647                                                 }
648                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
649                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
650                                                 }
651                                         },
652                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
653                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
654                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
655                                                 for msg in all_messages.iter() {
656                                                         self.enqueue_message(peer, msg);
657                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
658                                                 }
659                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
660                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
661                                                 }
662                                         },
663                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
664                                         InitSyncTracker::NodesSyncing(key) => {
665                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
666                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
667                                                 for msg in all_messages.iter() {
668                                                         self.enqueue_message(peer, msg);
669                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
670                                                 }
671                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
672                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
673                                                 }
674                                         },
675                                 }
676                         }
677                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
678                                 self.maybe_send_extra_ping(peer);
679                         }
680
681                         if {
682                                 let next_buff = match peer.pending_outbound_buffer.front() {
683                                         None => return,
684                                         Some(buff) => buff,
685                                 };
686
687                                 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
688                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
689                                 let data_sent = descriptor.send_data(pending, should_be_reading);
690                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
691                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
692                         } {
693                                 peer.pending_outbound_buffer_first_msg_offset = 0;
694                                 peer.pending_outbound_buffer.pop_front();
695                         } else {
696                                 peer.awaiting_write_event = true;
697                         }
698                 }
699         }
700
701         /// Indicates that there is room to write data to the given socket descriptor.
702         ///
703         /// May return an Err to indicate that the connection should be closed.
704         ///
705         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
706         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
707         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
708         /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
709         /// sufficient!
710         ///
711         /// [`send_data`]: SocketDescriptor::send_data
712         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
713         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
714                 let mut peers = self.peers.lock().unwrap();
715                 match peers.peers.get_mut(descriptor) {
716                         None => {
717                                 // This is most likely a simple race condition where the user found that the socket
718                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
719                                 // this method. Return an error to make sure we get disconnected.
720                                 return Err(PeerHandleError { no_connection_possible: false });
721                         },
722                         Some(peer) => {
723                                 peer.awaiting_write_event = false;
724                                 self.do_attempt_write_data(descriptor, peer);
725                         }
726                 };
727                 Ok(())
728         }
729
730         /// Indicates that data was read from the given socket descriptor.
731         ///
732         /// May return an Err to indicate that the connection should be closed.
733         ///
734         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
735         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
736         /// [`send_data`] calls to handle responses.
737         ///
738         /// If `Ok(true)` is returned, further read_events should not be triggered until a
739         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
740         /// send buffer).
741         ///
742         /// [`send_data`]: SocketDescriptor::send_data
743         /// [`process_events`]: PeerManager::process_events
744         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
745                 match self.do_read_event(peer_descriptor, data) {
746                         Ok(res) => Ok(res),
747                         Err(e) => {
748                                 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
749                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
750                                 Err(e)
751                         }
752                 }
753         }
754
755         /// Append a message to a peer's pending outbound/write buffer
756         fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
757                 peer.msgs_sent_since_pong += 1;
758                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
759         }
760
761         /// Append a message to a peer's pending outbound/write buffer
762         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
763                 let mut buffer = VecWriter(Vec::with_capacity(2048));
764                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
765
766                 if is_gossip_msg(message.type_id()) {
767                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
768                 } else {
769                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
770                 }
771                 self.enqueue_encoded_message(peer, &buffer.0);
772         }
773
774         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
775                 let pause_read = {
776                         let mut peers_lock = self.peers.lock().unwrap();
777                         let peers = &mut *peers_lock;
778                         let mut msgs_to_forward = Vec::new();
779                         let mut peer_node_id = None;
780                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
781                                 None => {
782                                         // This is most likely a simple race condition where the user read some bytes
783                                         // from the socket, then we told the user to `disconnect_socket()`, then they
784                                         // called this method. Return an error to make sure we get disconnected.
785                                         return Err(PeerHandleError { no_connection_possible: false });
786                                 },
787                                 Some(peer) => {
788                                         assert!(peer.pending_read_buffer.len() > 0);
789                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
790
791                                         let mut read_pos = 0;
792                                         while read_pos < data.len() {
793                                                 {
794                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
795                                                         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]);
796                                                         read_pos += data_to_copy;
797                                                         peer.pending_read_buffer_pos += data_to_copy;
798                                                 }
799
800                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
801                                                         peer.pending_read_buffer_pos = 0;
802
803                                                         macro_rules! try_potential_handleerror {
804                                                                 ($thing: expr) => {
805                                                                         match $thing {
806                                                                                 Ok(x) => x,
807                                                                                 Err(e) => {
808                                                                                         match e.action {
809                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
810                                                                                                         //TODO: Try to push msg
811                                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
812                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
813                                                                                                 },
814                                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
815                                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
816                                                                                                         continue
817                                                                                                 },
818                                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
819                                                                                                 msgs::ErrorAction::IgnoreError => {
820                                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
821                                                                                                         continue;
822                                                                                                 },
823                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
824                                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
825                                                                                                         self.enqueue_message(peer, &msg);
826                                                                                                         continue;
827                                                                                                 },
828                                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
829                                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
830                                                                                                         self.enqueue_message(peer, &msg);
831                                                                                                         continue;
832                                                                                                 },
833                                                                                         }
834                                                                                 }
835                                                                         }
836                                                                 }
837                                                         }
838
839                                                         macro_rules! insert_node_id {
840                                                                 () => {
841                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
842                                                                                 hash_map::Entry::Occupied(_) => {
843                                                                                         log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
844                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
845                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
846                                                                                 },
847                                                                                 hash_map::Entry::Vacant(entry) => {
848                                                                                         log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
849                                                                                         entry.insert(peer_descriptor.clone())
850                                                                                 },
851                                                                         };
852                                                                 }
853                                                         }
854
855                                                         let next_step = peer.channel_encryptor.get_noise_step();
856                                                         match next_step {
857                                                                 NextNoiseStep::ActOne => {
858                                                                         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();
859                                                                         peer.pending_outbound_buffer.push_back(act_two);
860                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
861                                                                 },
862                                                                 NextNoiseStep::ActTwo => {
863                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
864                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
865                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
866                                                                         peer.pending_read_is_header = true;
867
868                                                                         peer.their_node_id = Some(their_node_id);
869                                                                         insert_node_id!();
870                                                                         let features = InitFeatures::known();
871                                                                         let resp = msgs::Init { features };
872                                                                         self.enqueue_message(peer, &resp);
873                                                                         peer.awaiting_pong_timer_tick_intervals = 0;
874                                                                 },
875                                                                 NextNoiseStep::ActThree => {
876                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
877                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
878                                                                         peer.pending_read_is_header = true;
879                                                                         peer.their_node_id = Some(their_node_id);
880                                                                         insert_node_id!();
881                                                                         let features = InitFeatures::known();
882                                                                         let resp = msgs::Init { features };
883                                                                         self.enqueue_message(peer, &resp);
884                                                                         peer.awaiting_pong_timer_tick_intervals = 0;
885                                                                 },
886                                                                 NextNoiseStep::NoiseComplete => {
887                                                                         if peer.pending_read_is_header {
888                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
889                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
890                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
891                                                                                 if msg_len < 2 { // Need at least the message type tag
892                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
893                                                                                 }
894                                                                                 peer.pending_read_is_header = false;
895                                                                         } else {
896                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
897                                                                                 assert!(msg_data.len() >= 2);
898
899                                                                                 // Reset read buffer
900                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
901                                                                                 peer.pending_read_is_header = true;
902
903                                                                                 let mut reader = io::Cursor::new(&msg_data[..]);
904                                                                                 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
905                                                                                 let message = match message_result {
906                                                                                         Ok(x) => x,
907                                                                                         Err(e) => {
908                                                                                                 match e {
909                                                                                                         // Note that to avoid recursion we never call
910                                                                                                         // `do_attempt_write_data` from here, causing
911                                                                                                         // the messages enqueued here to not actually
912                                                                                                         // be sent before the peer is disconnected.
913                                                                                                         (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
914                                                                                                                 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
915                                                                                                                 continue;
916                                                                                                         }
917                                                                                                         (msgs::DecodeError::UnsupportedCompression, _) => {
918                                                                                                                 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
919                                                                                                                 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
920                                                                                                                 continue;
921                                                                                                         }
922                                                                                                         (_, Some(ty)) if is_gossip_msg(ty) => {
923                                                                                                                 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
924                                                                                                                 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
925                                                                                                                 continue;
926                                                                                                         }
927                                                                                                         (msgs::DecodeError::UnknownRequiredFeature, ty) => {
928                                                                                                                 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
929                                                                                                                 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
930                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
931                                                                                                         }
932                                                                                                         (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
933                                                                                                         (msgs::DecodeError::InvalidValue, _) => {
934                                                                                                                 log_debug!(self.logger, "Got an invalid value while deserializing message");
935                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
936                                                                                                         }
937                                                                                                         (msgs::DecodeError::ShortRead, _) => {
938                                                                                                                 log_debug!(self.logger, "Deserialization failed due to shortness of message");
939                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
940                                                                                                         }
941                                                                                                         (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
942                                                                                                         (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
943                                                                                                 }
944                                                                                         }
945                                                                                 };
946
947                                                                                 match self.handle_message(peer, message) {
948                                                                                         Err(handling_error) => match handling_error {
949                                                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
950                                                                                                 MessageHandlingError::LightningError(e) => {
951                                                                                                         try_potential_handleerror!(Err(e));
952                                                                                                 },
953                                                                                         },
954                                                                                         Ok(Some(msg)) => {
955                                                                                                 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
956                                                                                                 msgs_to_forward.push(msg);
957                                                                                         },
958                                                                                         Ok(None) => {},
959                                                                                 }
960                                                                         }
961                                                                 }
962                                                         }
963                                                 }
964                                         }
965
966                                         peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
967                                 }
968                         };
969
970                         for msg in msgs_to_forward.drain(..) {
971                                 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
972                         }
973
974                         pause_read
975                 };
976
977                 Ok(pause_read)
978         }
979
980         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
981         /// Returns the message back if it needs to be broadcasted to all other peers.
982         fn handle_message(
983                 &self,
984                 peer: &mut Peer,
985                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
986         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
987                 if is_gossip_msg(message.type_id()) {
988                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
989                 } else {
990                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
991                 }
992
993                 peer.received_message_since_timer_tick = true;
994
995                 // Need an Init as first message
996                 if let wire::Message::Init(_) = message {
997                 } else if peer.their_features.is_none() {
998                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
999                         return Err(PeerHandleError{ no_connection_possible: false }.into());
1000                 }
1001
1002                 let mut should_forward = None;
1003
1004                 match message {
1005                         // Setup and Control messages:
1006                         wire::Message::Init(msg) => {
1007                                 if msg.features.requires_unknown_bits() {
1008                                         log_debug!(self.logger, "Peer features required unknown version bits");
1009                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1010                                 }
1011                                 if peer.their_features.is_some() {
1012                                         return Err(PeerHandleError{ no_connection_possible: false }.into());
1013                                 }
1014
1015                                 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.features);
1016
1017                                 if msg.features.initial_routing_sync() {
1018                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
1019                                 }
1020                                 if !msg.features.supports_static_remote_key() {
1021                                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
1022                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1023                                 }
1024
1025                                 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
1026
1027                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1028                                 peer.their_features = Some(msg.features);
1029                         },
1030                         wire::Message::Error(msg) => {
1031                                 let mut data_is_printable = true;
1032                                 for b in msg.data.bytes() {
1033                                         if b < 32 || b > 126 {
1034                                                 data_is_printable = false;
1035                                                 break;
1036                                         }
1037                                 }
1038
1039                                 if data_is_printable {
1040                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1041                                 } else {
1042                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1043                                 }
1044                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
1045                                 if msg.channel_id == [0; 32] {
1046                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1047                                 }
1048                         },
1049                         wire::Message::Warning(msg) => {
1050                                 let mut data_is_printable = true;
1051                                 for b in msg.data.bytes() {
1052                                         if b < 32 || b > 126 {
1053                                                 data_is_printable = false;
1054                                                 break;
1055                                         }
1056                                 }
1057
1058                                 if data_is_printable {
1059                                         log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1060                                 } else {
1061                                         log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1062                                 }
1063                         },
1064
1065                         wire::Message::Ping(msg) => {
1066                                 if msg.ponglen < 65532 {
1067                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1068                                         self.enqueue_message(peer, &resp);
1069                                 }
1070                         },
1071                         wire::Message::Pong(_msg) => {
1072                                 peer.awaiting_pong_timer_tick_intervals = 0;
1073                                 peer.msgs_sent_since_pong = 0;
1074                         },
1075
1076                         // Channel messages:
1077                         wire::Message::OpenChannel(msg) => {
1078                                 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1079                         },
1080                         wire::Message::AcceptChannel(msg) => {
1081                                 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1082                         },
1083
1084                         wire::Message::FundingCreated(msg) => {
1085                                 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
1086                         },
1087                         wire::Message::FundingSigned(msg) => {
1088                                 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
1089                         },
1090                         wire::Message::FundingLocked(msg) => {
1091                                 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
1092                         },
1093
1094                         wire::Message::Shutdown(msg) => {
1095                                 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
1096                         },
1097                         wire::Message::ClosingSigned(msg) => {
1098                                 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
1099                         },
1100
1101                         // Commitment messages:
1102                         wire::Message::UpdateAddHTLC(msg) => {
1103                                 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
1104                         },
1105                         wire::Message::UpdateFulfillHTLC(msg) => {
1106                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
1107                         },
1108                         wire::Message::UpdateFailHTLC(msg) => {
1109                                 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
1110                         },
1111                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1112                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
1113                         },
1114
1115                         wire::Message::CommitmentSigned(msg) => {
1116                                 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
1117                         },
1118                         wire::Message::RevokeAndACK(msg) => {
1119                                 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
1120                         },
1121                         wire::Message::UpdateFee(msg) => {
1122                                 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
1123                         },
1124                         wire::Message::ChannelReestablish(msg) => {
1125                                 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
1126                         },
1127
1128                         // Routing messages:
1129                         wire::Message::AnnouncementSignatures(msg) => {
1130                                 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
1131                         },
1132                         wire::Message::ChannelAnnouncement(msg) => {
1133                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1134                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1135                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1136                                 }
1137                         },
1138                         wire::Message::NodeAnnouncement(msg) => {
1139                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1140                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1141                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1142                                 }
1143                         },
1144                         wire::Message::ChannelUpdate(msg) => {
1145                                 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1146                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1147                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1148                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1149                                 }
1150                         },
1151                         wire::Message::QueryShortChannelIds(msg) => {
1152                                 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1153                         },
1154                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1155                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1156                         },
1157                         wire::Message::QueryChannelRange(msg) => {
1158                                 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1159                         },
1160                         wire::Message::ReplyChannelRange(msg) => {
1161                                 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1162                         },
1163                         wire::Message::GossipTimestampFilter(_msg) => {
1164                                 // TODO: handle message
1165                         },
1166
1167                         // Unknown messages:
1168                         wire::Message::Unknown(type_id) if message.is_even() => {
1169                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1170                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
1171                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1172                         },
1173                         wire::Message::Unknown(type_id) => {
1174                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1175                         },
1176                         wire::Message::Custom(custom) => {
1177                                 self.custom_message_handler.handle_custom_message(custom, &peer.their_node_id.unwrap())?;
1178                         },
1179                 };
1180                 Ok(should_forward)
1181         }
1182
1183         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>) {
1184                 match msg {
1185                         wire::Message::ChannelAnnouncement(ref msg) => {
1186                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1187                                 let encoded_msg = encode_msg!(msg);
1188
1189                                 for (_, peer) in peers.peers.iter_mut() {
1190                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1191                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1192                                                 continue
1193                                         }
1194                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1195                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1196                                         {
1197                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1198                                                 continue;
1199                                         }
1200                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1201                                            peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1202                                                 continue;
1203                                         }
1204                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1205                                                 continue;
1206                                         }
1207                                         self.enqueue_encoded_message(peer, &encoded_msg);
1208                                 }
1209                         },
1210                         wire::Message::NodeAnnouncement(ref msg) => {
1211                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1212                                 let encoded_msg = encode_msg!(msg);
1213
1214                                 for (_, peer) in peers.peers.iter_mut() {
1215                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1216                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1217                                                 continue
1218                                         }
1219                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1220                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1221                                         {
1222                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1223                                                 continue;
1224                                         }
1225                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1226                                                 continue;
1227                                         }
1228                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1229                                                 continue;
1230                                         }
1231                                         self.enqueue_encoded_message(peer, &encoded_msg);
1232                                 }
1233                         },
1234                         wire::Message::ChannelUpdate(ref msg) => {
1235                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1236                                 let encoded_msg = encode_msg!(msg);
1237
1238                                 for (_, peer) in peers.peers.iter_mut() {
1239                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1240                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1241                                                 continue
1242                                         }
1243                                         if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1244                                                 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1245                                         {
1246                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1247                                                 continue;
1248                                         }
1249                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1250                                                 continue;
1251                                         }
1252                                         self.enqueue_encoded_message(peer, &encoded_msg);
1253                                 }
1254                         },
1255                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1256                 }
1257         }
1258
1259         /// Checks for any events generated by our handlers and processes them. Includes sending most
1260         /// response messages as well as messages generated by calls to handler functions directly (eg
1261         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1262         ///
1263         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1264         /// issues!
1265         ///
1266         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1267         /// or one of the other clients provided in our language bindings.
1268         ///
1269         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1270         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1271         /// [`send_data`]: SocketDescriptor::send_data
1272         pub fn process_events(&self) {
1273                 {
1274                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
1275                         // buffer by doing things like announcing channels on another node. We should be willing to
1276                         // drop optional-ish messages when send buffers get full!
1277
1278                         let mut peers_lock = self.peers.lock().unwrap();
1279                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1280                         events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1281                         let peers = &mut *peers_lock;
1282                         macro_rules! get_peer_for_forwarding {
1283                                 ($node_id: expr) => {
1284                                         {
1285                                                 match peers.node_id_to_descriptor.get($node_id) {
1286                                                         Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1287                                                                 Some(peer) => {
1288                                                                         if peer.their_features.is_none() {
1289                                                                                 continue;
1290                                                                         }
1291                                                                         peer
1292                                                                 },
1293                                                                 None => panic!("Inconsistent peers set state!"),
1294                                                         },
1295                                                         None => {
1296                                                                 continue;
1297                                                         },
1298                                                 }
1299                                         }
1300                                 }
1301                         }
1302                         for event in events_generated.drain(..) {
1303                                 match event {
1304                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1305                                                 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1306                                                                 log_pubkey!(node_id),
1307                                                                 log_bytes!(msg.temporary_channel_id));
1308                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1309                                         },
1310                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1311                                                 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1312                                                                 log_pubkey!(node_id),
1313                                                                 log_bytes!(msg.temporary_channel_id));
1314                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1315                                         },
1316                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1317                                                 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1318                                                                 log_pubkey!(node_id),
1319                                                                 log_bytes!(msg.temporary_channel_id),
1320                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1321                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1322                                                 // indicating to the wallet that they should just throw away this funding transaction
1323                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1324                                         },
1325                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1326                                                 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1327                                                                 log_pubkey!(node_id),
1328                                                                 log_bytes!(msg.channel_id));
1329                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1330                                         },
1331                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1332                                                 log_debug!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1333                                                                 log_pubkey!(node_id),
1334                                                                 log_bytes!(msg.channel_id));
1335                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1336                                         },
1337                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1338                                                 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1339                                                                 log_pubkey!(node_id),
1340                                                                 log_bytes!(msg.channel_id));
1341                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1342                                         },
1343                                         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 } } => {
1344                                                 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1345                                                                 log_pubkey!(node_id),
1346                                                                 update_add_htlcs.len(),
1347                                                                 update_fulfill_htlcs.len(),
1348                                                                 update_fail_htlcs.len(),
1349                                                                 log_bytes!(commitment_signed.channel_id));
1350                                                 let peer = get_peer_for_forwarding!(node_id);
1351                                                 for msg in update_add_htlcs {
1352                                                         self.enqueue_message(peer, msg);
1353                                                 }
1354                                                 for msg in update_fulfill_htlcs {
1355                                                         self.enqueue_message(peer, msg);
1356                                                 }
1357                                                 for msg in update_fail_htlcs {
1358                                                         self.enqueue_message(peer, msg);
1359                                                 }
1360                                                 for msg in update_fail_malformed_htlcs {
1361                                                         self.enqueue_message(peer, msg);
1362                                                 }
1363                                                 if let &Some(ref msg) = update_fee {
1364                                                         self.enqueue_message(peer, msg);
1365                                                 }
1366                                                 self.enqueue_message(peer, commitment_signed);
1367                                         },
1368                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1369                                                 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1370                                                                 log_pubkey!(node_id),
1371                                                                 log_bytes!(msg.channel_id));
1372                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1373                                         },
1374                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1375                                                 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1376                                                                 log_pubkey!(node_id),
1377                                                                 log_bytes!(msg.channel_id));
1378                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1379                                         },
1380                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1381                                                 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1382                                                                 log_pubkey!(node_id),
1383                                                                 log_bytes!(msg.channel_id));
1384                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1385                                         },
1386                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1387                                                 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1388                                                                 log_pubkey!(node_id),
1389                                                                 log_bytes!(msg.channel_id));
1390                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1391                                         },
1392                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1393                                                 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1394                                                 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1395                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1396                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1397                                                         _ => {},
1398                                                 }
1399                                                 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1400                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1401                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1402                                                         _ => {},
1403                                                 }
1404                                         },
1405                                         MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1406                                                 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1407                                                 match self.message_handler.route_handler.handle_node_announcement(&msg) {
1408                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1409                                                                 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
1410                                                         _ => {},
1411                                                 }
1412                                         },
1413                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1414                                                 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1415                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
1416                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1417                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1418                                                         _ => {},
1419                                                 }
1420                                         },
1421                                         MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1422                                                 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1423                                                                 log_pubkey!(node_id), msg.contents.short_channel_id);
1424                                                 let peer = get_peer_for_forwarding!(node_id);
1425                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1426                                         },
1427                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1428                                                 match *action {
1429                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1430                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1431                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
1432                                                                                 if let Some(ref msg) = *msg {
1433                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1434                                                                                                         log_pubkey!(node_id),
1435                                                                                                         msg.data);
1436                                                                                         self.enqueue_message(&mut peer, msg);
1437                                                                                         // This isn't guaranteed to work, but if there is enough free
1438                                                                                         // room in the send buffer, put the error message there...
1439                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1440                                                                                 } else {
1441                                                                                         log_gossip!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1442                                                                                 }
1443                                                                         }
1444                                                                         descriptor.disconnect_socket();
1445                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1446                                                                 }
1447                                                         },
1448                                                         msgs::ErrorAction::IgnoreAndLog(level) => {
1449                                                                 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1450                                                         },
1451                                                         msgs::ErrorAction::IgnoreDuplicateGossip => {},
1452                                                         msgs::ErrorAction::IgnoreError => {
1453                                                                 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1454                                                         },
1455                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1456                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1457                                                                                 log_pubkey!(node_id),
1458                                                                                 msg.data);
1459                                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1460                                                         },
1461                                                         msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1462                                                                 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1463                                                                                 log_pubkey!(node_id),
1464                                                                                 msg.data);
1465                                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1466                                                         },
1467                                                 }
1468                                         },
1469                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1470                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1471                                         },
1472                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1473                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1474                                         }
1475                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1476                                                 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1477                                                         log_pubkey!(node_id),
1478                                                         msg.short_channel_ids.len(),
1479                                                         msg.first_blocknum,
1480                                                         msg.number_of_blocks,
1481                                                         msg.sync_complete);
1482                                                 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1483                                         }
1484                                 }
1485                         }
1486
1487                         for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1488                                 self.enqueue_message(get_peer_for_forwarding!(&node_id), &msg);
1489                         }
1490
1491                         for (descriptor, peer) in peers.peers.iter_mut() {
1492                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1493                         }
1494                 }
1495         }
1496
1497         /// Indicates that the given socket descriptor's connection is now closed.
1498         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1499                 self.disconnect_event_internal(descriptor, false);
1500         }
1501
1502         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1503                 let mut peers = self.peers.lock().unwrap();
1504                 let peer_option = peers.peers.remove(descriptor);
1505                 match peer_option {
1506                         None => {
1507                                 // This is most likely a simple race condition where the user found that the socket
1508                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
1509                                 // called this method. Either way we're disconnected, return.
1510                         },
1511                         Some(peer) => {
1512                                 match peer.their_node_id {
1513                                         Some(node_id) => {
1514                                                 log_trace!(self.logger,
1515                                                         "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1516                                                         log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1517                                                 peers.node_id_to_descriptor.remove(&node_id);
1518                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1519                                         },
1520                                         None => {}
1521                                 }
1522                         }
1523                 };
1524         }
1525
1526         /// Disconnect a peer given its node id.
1527         ///
1528         /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1529         /// force-closing any channels we have with it.
1530         ///
1531         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1532         /// peer. Thus, be very careful about reentrancy issues.
1533         ///
1534         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1535         pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1536                 let mut peers_lock = self.peers.lock().unwrap();
1537                 if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
1538                         log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1539                         peers_lock.peers.remove(&descriptor);
1540                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1541                         descriptor.disconnect_socket();
1542                 }
1543         }
1544
1545         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1546         /// an indication that TCP sockets have stalled even if we weren't around to time them out
1547         /// using regular ping/pongs.
1548         pub fn disconnect_all_peers(&self) {
1549                 let mut peers_lock = self.peers.lock().unwrap();
1550                 let peers = &mut *peers_lock;
1551                 for (mut descriptor, peer) in peers.peers.drain() {
1552                         if let Some(node_id) = peer.their_node_id {
1553                                 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1554                                 peers.node_id_to_descriptor.remove(&node_id);
1555                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1556                         }
1557                         descriptor.disconnect_socket();
1558                 }
1559                 debug_assert!(peers.node_id_to_descriptor.is_empty());
1560         }
1561
1562         /// This is called when we're blocked on sending additional gossip messages until we receive a
1563         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1564         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1565         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1566                 if peer.awaiting_pong_timer_tick_intervals == 0 {
1567                         peer.awaiting_pong_timer_tick_intervals = -1;
1568                         let ping = msgs::Ping {
1569                                 ponglen: 0,
1570                                 byteslen: 64,
1571                         };
1572                         self.enqueue_message(peer, &ping);
1573                 }
1574         }
1575
1576         /// Send pings to each peer and disconnect those which did not respond to the last round of
1577         /// pings.
1578         ///
1579         /// This may be called on any timescale you want, however, roughly once every ten seconds is
1580         /// preferred. The call rate determines both how often we send a ping to our peers and how much
1581         /// time they have to respond before we disconnect them.
1582         ///
1583         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1584         /// issues!
1585         ///
1586         /// [`send_data`]: SocketDescriptor::send_data
1587         pub fn timer_tick_occurred(&self) {
1588                 let mut peers_lock = self.peers.lock().unwrap();
1589                 {
1590                         let peers = &mut *peers_lock;
1591                         let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1592                         let peers = &mut peers.peers;
1593                         let mut descriptors_needing_disconnect = Vec::new();
1594                         let peer_count = peers.len();
1595
1596                         peers.retain(|descriptor, peer| {
1597                                 let mut do_disconnect_peer = false;
1598                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1599                                         // The peer needs to complete its handshake before we can exchange messages. We
1600                                         // give peers one timer tick to complete handshake, reusing
1601                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1602                                         // for handshake completion.
1603                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
1604                                                 do_disconnect_peer = true;
1605                                         } else {
1606                                                 peer.awaiting_pong_timer_tick_intervals = 1;
1607                                                 return true;
1608                                         }
1609                                 }
1610
1611                                 if peer.awaiting_pong_timer_tick_intervals == -1 {
1612                                         // Magic value set in `maybe_send_extra_ping`.
1613                                         peer.awaiting_pong_timer_tick_intervals = 1;
1614                                         peer.received_message_since_timer_tick = false;
1615                                         return true;
1616                                 }
1617
1618                                 if do_disconnect_peer
1619                                         || (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1620                                         || peer.awaiting_pong_timer_tick_intervals as u64 >
1621                                                 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peer_count as u64
1622                                 {
1623                                         descriptors_needing_disconnect.push(descriptor.clone());
1624                                         match peer.their_node_id {
1625                                                 Some(node_id) => {
1626                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1627                                                         node_id_to_descriptor.remove(&node_id);
1628                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1629                                                 }
1630                                                 None => {},
1631                                         }
1632                                         return false;
1633                                 }
1634                                 peer.received_message_since_timer_tick = false;
1635
1636                                 if peer.awaiting_pong_timer_tick_intervals > 0 {
1637                                         peer.awaiting_pong_timer_tick_intervals += 1;
1638                                         return true;
1639                                 }
1640
1641                                 peer.awaiting_pong_timer_tick_intervals = 1;
1642                                 let ping = msgs::Ping {
1643                                         ponglen: 0,
1644                                         byteslen: 64,
1645                                 };
1646                                 self.enqueue_message(peer, &ping);
1647                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1648
1649                                 true
1650                         });
1651
1652                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1653                                 descriptor.disconnect_socket();
1654                         }
1655                 }
1656         }
1657 }
1658
1659 fn is_gossip_msg(type_id: u16) -> bool {
1660         match type_id {
1661                 msgs::ChannelAnnouncement::TYPE |
1662                 msgs::ChannelUpdate::TYPE |
1663                 msgs::NodeAnnouncement::TYPE => true,
1664                 _ => false
1665         }
1666 }
1667
1668 #[cfg(test)]
1669 mod tests {
1670         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
1671         use ln::msgs;
1672         use util::events;
1673         use util::test_utils;
1674
1675         use bitcoin::secp256k1::Secp256k1;
1676         use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1677
1678         use prelude::*;
1679         use sync::{Arc, Mutex};
1680         use core::sync::atomic::Ordering;
1681
1682         #[derive(Clone)]
1683         struct FileDescriptor {
1684                 fd: u16,
1685                 outbound_data: Arc<Mutex<Vec<u8>>>,
1686         }
1687         impl PartialEq for FileDescriptor {
1688                 fn eq(&self, other: &Self) -> bool {
1689                         self.fd == other.fd
1690                 }
1691         }
1692         impl Eq for FileDescriptor { }
1693         impl core::hash::Hash for FileDescriptor {
1694                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1695                         self.fd.hash(hasher)
1696                 }
1697         }
1698
1699         impl SocketDescriptor for FileDescriptor {
1700                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1701                         self.outbound_data.lock().unwrap().extend_from_slice(data);
1702                         data.len()
1703                 }
1704
1705                 fn disconnect_socket(&mut self) {}
1706         }
1707
1708         struct PeerManagerCfg {
1709                 chan_handler: test_utils::TestChannelMessageHandler,
1710                 routing_handler: test_utils::TestRoutingMessageHandler,
1711                 logger: test_utils::TestLogger,
1712         }
1713
1714         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1715                 let mut cfgs = Vec::new();
1716                 for _ in 0..peer_count {
1717                         cfgs.push(
1718                                 PeerManagerCfg{
1719                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
1720                                         logger: test_utils::TestLogger::new(),
1721                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
1722                                 }
1723                         );
1724                 }
1725
1726                 cfgs
1727         }
1728
1729         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>> {
1730                 let mut peers = Vec::new();
1731                 for i in 0..peer_count {
1732                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1733                         let ephemeral_bytes = [i as u8; 32];
1734                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1735                         let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1736                         peers.push(peer);
1737                 }
1738
1739                 peers
1740         }
1741
1742         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) {
1743                 let secp_ctx = Secp256k1::new();
1744                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1745                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1746                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1747                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1748                 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1749                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1750                 peer_a.process_events();
1751                 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1752                 peer_b.process_events();
1753                 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1754                 (fd_a.clone(), fd_b.clone())
1755         }
1756
1757         #[test]
1758         fn test_disconnect_peer() {
1759                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1760                 // push a DisconnectPeer event to remove the node flagged by id
1761                 let cfgs = create_peermgr_cfgs(2);
1762                 let chan_handler = test_utils::TestChannelMessageHandler::new();
1763                 let mut peers = create_network(2, &cfgs);
1764                 establish_connection(&peers[0], &peers[1]);
1765                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1766
1767                 let secp_ctx = Secp256k1::new();
1768                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1769
1770                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1771                         node_id: their_id,
1772                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
1773                 });
1774                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1775                 peers[0].message_handler.chan_handler = &chan_handler;
1776
1777                 peers[0].process_events();
1778                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1779         }
1780
1781         #[test]
1782         fn test_timer_tick_occurred() {
1783                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1784                 let cfgs = create_peermgr_cfgs(2);
1785                 let peers = create_network(2, &cfgs);
1786                 establish_connection(&peers[0], &peers[1]);
1787                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1788
1789                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1790                 peers[0].timer_tick_occurred();
1791                 peers[0].process_events();
1792                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1793
1794                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1795                 peers[0].timer_tick_occurred();
1796                 peers[0].process_events();
1797                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1798         }
1799
1800         #[test]
1801         fn test_do_attempt_write_data() {
1802                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1803                 let cfgs = create_peermgr_cfgs(2);
1804                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1805                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1806                 let peers = create_network(2, &cfgs);
1807
1808                 // By calling establish_connect, we trigger do_attempt_write_data between
1809                 // the peers. Previously this function would mistakenly enter an infinite loop
1810                 // when there were more channel messages available than could fit into a peer's
1811                 // buffer. This issue would now be detected by this test (because we use custom
1812                 // RoutingMessageHandlers that intentionally return more channel messages
1813                 // than can fit into a peer's buffer).
1814                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1815
1816                 // Make each peer to read the messages that the other peer just wrote to them. Note that
1817                 // due to the max-messagse-before-ping limits this may take a few iterations to complete.
1818                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
1819                         peers[0].process_events();
1820                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1821                         assert!(!b_read_data.is_empty());
1822
1823                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
1824                         peers[1].process_events();
1825
1826                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1827                         assert!(!a_read_data.is_empty());
1828                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
1829
1830                         peers[1].process_events();
1831                         assert_eq!(fd_b.outbound_data.lock().unwrap().len(), 0, "Until B receives data, it shouldn't send more messages");
1832                 }
1833
1834                 // Check that each peer has received the expected number of channel updates and channel
1835                 // announcements.
1836                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1837                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1838                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1839                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1840         }
1841
1842         #[test]
1843         fn test_handshake_timeout() {
1844                 // Tests that we time out a peer still waiting on handshake completion after a full timer
1845                 // tick.
1846                 let cfgs = create_peermgr_cfgs(2);
1847                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1848                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1849                 let peers = create_network(2, &cfgs);
1850
1851                 let secp_ctx = Secp256k1::new();
1852                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
1853                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1854                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1855                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone()).unwrap();
1856                 peers[0].new_inbound_connection(fd_a.clone()).unwrap();
1857
1858                 // If we get a single timer tick before completion, that's fine
1859                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1860                 peers[0].timer_tick_occurred();
1861                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1862
1863                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
1864                 peers[0].process_events();
1865                 assert_eq!(peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1866                 peers[1].process_events();
1867
1868                 // ...but if we get a second timer tick, we should disconnect the peer
1869                 peers[0].timer_tick_occurred();
1870                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1871
1872                 assert!(peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).is_err());
1873         }
1874 }