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