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