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