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