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