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