Drop peers_needing_send tracking and try to write for each peer
[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. Once this function returns, no
198         /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
199         /// this descriptor. No socket_disconnected call should be generated as a result of this call,
200         /// though races may occur whereby disconnect_socket is called after a call to
201         /// socket_disconnected but prior to socket_disconnected returning.
202         fn disconnect_socket(&mut self);
203 }
204
205 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
206 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
207 /// descriptor.
208 #[derive(Clone)]
209 pub struct PeerHandleError {
210         /// Used to indicate that we probably can't make any future connections to this peer, implying
211         /// we should go ahead and force-close any channels we have with it.
212         pub no_connection_possible: bool,
213 }
214 impl fmt::Debug for PeerHandleError {
215         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
216                 formatter.write_str("Peer Sent Invalid Data")
217         }
218 }
219 impl fmt::Display for PeerHandleError {
220         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
221                 formatter.write_str("Peer Sent Invalid Data")
222         }
223 }
224 impl error::Error for PeerHandleError {
225         fn description(&self) -> &str {
226                 "Peer Sent Invalid Data"
227         }
228 }
229
230 enum InitSyncTracker{
231         NoSyncRequested,
232         ChannelsSyncing(u64),
233         NodesSyncing(PublicKey),
234 }
235
236 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
237 /// we have fewer than this many messages in the outbound buffer again.
238 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
239 /// refilled as we send bytes.
240 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
241 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
242 /// the peer.
243 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = 20;
244
245 struct Peer {
246         channel_encryptor: PeerChannelEncryptor,
247         their_node_id: Option<PublicKey>,
248         their_features: Option<InitFeatures>,
249
250         pending_outbound_buffer: LinkedList<Vec<u8>>,
251         pending_outbound_buffer_first_msg_offset: usize,
252         awaiting_write_event: bool,
253
254         pending_read_buffer: Vec<u8>,
255         pending_read_buffer_pos: usize,
256         pending_read_is_header: bool,
257
258         sync_status: InitSyncTracker,
259
260         awaiting_pong: bool,
261 }
262
263 impl Peer {
264         /// Returns true if the channel announcements/updates for the given channel should be
265         /// forwarded to this peer.
266         /// If we are sending our routing table to this peer and we have not yet sent channel
267         /// announcements/updates for the given channel_id then we will send it when we get to that
268         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
269         /// sent the old versions, we should send the update, and so return true here.
270         fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
271                 match self.sync_status {
272                         InitSyncTracker::NoSyncRequested => true,
273                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
274                         InitSyncTracker::NodesSyncing(_) => true,
275                 }
276         }
277
278         /// Similar to the above, but for node announcements indexed by node_id.
279         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
280                 match self.sync_status {
281                         InitSyncTracker::NoSyncRequested => true,
282                         InitSyncTracker::ChannelsSyncing(_) => false,
283                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
284                 }
285         }
286 }
287
288 struct PeerHolder<Descriptor: SocketDescriptor> {
289         peers: HashMap<Descriptor, Peer>,
290         /// Only add to this set when noise completes:
291         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
292 }
293
294 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
295 fn _check_usize_is_32_or_64() {
296         // See below, less than 32 bit pointers may be unsafe here!
297         unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
298 }
299
300 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
301 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
302 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
303 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
304 /// issues such as overly long function definitions.
305 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>>;
306
307 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
308 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
309 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
310 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
311 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
312 /// helps with issues such as long function definitions.
313 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>;
314
315 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
316 /// events into messages which it passes on to its MessageHandlers.
317 ///
318 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
319 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
320 /// essentially you should default to using a SimpleRefPeerManager, and use a
321 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
322 /// you're using lightning-net-tokio.
323 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> where
324                 CM::Target: ChannelMessageHandler,
325                 RM::Target: RoutingMessageHandler,
326                 L::Target: Logger {
327         message_handler: MessageHandler<CM, RM>,
328         peers: Mutex<PeerHolder<Descriptor>>,
329         our_node_secret: SecretKey,
330         ephemeral_key_midstate: Sha256Engine,
331
332         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
333         // bits we will never realistically count into high:
334         peer_counter_low: AtomicUsize,
335         peer_counter_high: AtomicUsize,
336
337         logger: L,
338 }
339
340 enum MessageHandlingError {
341         PeerHandleError(PeerHandleError),
342         LightningError(LightningError),
343 }
344
345 impl From<PeerHandleError> for MessageHandlingError {
346         fn from(error: PeerHandleError) -> Self {
347                 MessageHandlingError::PeerHandleError(error)
348         }
349 }
350
351 impl From<LightningError> for MessageHandlingError {
352         fn from(error: LightningError) -> Self {
353                 MessageHandlingError::LightningError(error)
354         }
355 }
356
357 macro_rules! encode_msg {
358         ($msg: expr) => {{
359                 let mut buffer = VecWriter(Vec::new());
360                 wire::write($msg, &mut buffer).unwrap();
361                 buffer.0
362         }}
363 }
364
365 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L> where
366                 CM::Target: ChannelMessageHandler,
367                 L::Target: Logger {
368         /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
369         /// handler is used and network graph messages are ignored.
370         ///
371         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
372         /// cryptographically secure random bytes.
373         ///
374         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
375         pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
376                 Self::new(MessageHandler {
377                         chan_handler: channel_message_handler,
378                         route_handler: IgnoringMessageHandler{},
379                 }, our_node_secret, ephemeral_random_data, logger)
380         }
381 }
382
383 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L> where
384                 RM::Target: RoutingMessageHandler,
385                 L::Target: Logger {
386         /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
387         /// handler is used and messages related to channels will be ignored (or generate error
388         /// messages). Note that some other lightning implementations time-out connections after some
389         /// time if no channel is built with the peer.
390         ///
391         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
392         /// cryptographically secure random bytes.
393         ///
394         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
395         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
396                 Self::new(MessageHandler {
397                         chan_handler: ErroringMessageHandler::new(),
398                         route_handler: routing_message_handler,
399                 }, our_node_secret, ephemeral_random_data, logger)
400         }
401 }
402
403 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
404 /// PeerIds may repeat, but only after socket_disconnected() has been called.
405 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<Descriptor, CM, RM, L> where
406                 CM::Target: ChannelMessageHandler,
407                 RM::Target: RoutingMessageHandler,
408                 L::Target: Logger {
409         /// Constructs a new PeerManager with the given message handlers and node_id secret key
410         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
411         /// cryptographically secure random bytes.
412         pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
413                 let mut ephemeral_key_midstate = Sha256::engine();
414                 ephemeral_key_midstate.input(ephemeral_random_data);
415
416                 PeerManager {
417                         message_handler,
418                         peers: Mutex::new(PeerHolder {
419                                 peers: HashMap::new(),
420                                 node_id_to_descriptor: HashMap::new()
421                         }),
422                         our_node_secret,
423                         ephemeral_key_midstate,
424                         peer_counter_low: AtomicUsize::new(0),
425                         peer_counter_high: AtomicUsize::new(0),
426                         logger,
427                 }
428         }
429
430         /// Get the list of node ids for peers which have completed the initial handshake.
431         ///
432         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
433         /// new_outbound_connection, however entries will only appear once the initial handshake has
434         /// completed and we are sure the remote peer has the private key for the given node_id.
435         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
436                 let peers = self.peers.lock().unwrap();
437                 peers.peers.values().filter_map(|p| {
438                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
439                                 return None;
440                         }
441                         p.their_node_id
442                 }).collect()
443         }
444
445         fn get_ephemeral_key(&self) -> SecretKey {
446                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
447                 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
448                 let high = if low == 0 {
449                         self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
450                 } else {
451                         self.peer_counter_high.load(Ordering::Acquire)
452                 };
453                 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
454                 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
455                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
456         }
457
458         /// Indicates a new outbound connection has been established to a node with the given node_id.
459         /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
460         /// descriptor but must disconnect the connection immediately.
461         ///
462         /// Returns a small number of bytes to send to the remote node (currently always 50).
463         ///
464         /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
465         /// socket_disconnected().
466         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
467                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
468                 let res = peer_encryptor.get_act_one().to_vec();
469                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
470
471                 let mut peers = self.peers.lock().unwrap();
472                 if peers.peers.insert(descriptor, Peer {
473                         channel_encryptor: peer_encryptor,
474                         their_node_id: None,
475                         their_features: None,
476
477                         pending_outbound_buffer: LinkedList::new(),
478                         pending_outbound_buffer_first_msg_offset: 0,
479                         awaiting_write_event: false,
480
481                         pending_read_buffer,
482                         pending_read_buffer_pos: 0,
483                         pending_read_is_header: false,
484
485                         sync_status: InitSyncTracker::NoSyncRequested,
486
487                         awaiting_pong: false,
488                 }).is_some() {
489                         panic!("PeerManager driver duplicated descriptors!");
490                 };
491                 Ok(res)
492         }
493
494         /// Indicates a new inbound connection has been established.
495         ///
496         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
497         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
498         /// call socket_disconnected for the new descriptor but must disconnect the connection
499         /// immediately.
500         ///
501         /// Panics if descriptor is duplicative with some other descriptor which has not yet had
502         /// socket_disconnected called.
503         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
504                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
505                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
506
507                 let mut peers = self.peers.lock().unwrap();
508                 if peers.peers.insert(descriptor, Peer {
509                         channel_encryptor: peer_encryptor,
510                         their_node_id: None,
511                         their_features: None,
512
513                         pending_outbound_buffer: LinkedList::new(),
514                         pending_outbound_buffer_first_msg_offset: 0,
515                         awaiting_write_event: false,
516
517                         pending_read_buffer,
518                         pending_read_buffer_pos: 0,
519                         pending_read_is_header: false,
520
521                         sync_status: InitSyncTracker::NoSyncRequested,
522
523                         awaiting_pong: false,
524                 }).is_some() {
525                         panic!("PeerManager driver duplicated descriptors!");
526                 };
527                 Ok(())
528         }
529
530         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
531                 macro_rules! encode_and_send_msg {
532                         ($msg: expr) => {
533                                 {
534                                         log_trace!(self.logger, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
535                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..]));
536                                 }
537                         }
538                 }
539                 while !peer.awaiting_write_event {
540                         if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE {
541                                 match peer.sync_status {
542                                         InitSyncTracker::NoSyncRequested => {},
543                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
544                                                 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
545                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
546                                                 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
547                                                         encode_and_send_msg!(announce);
548                                                         if let &Some(ref update_a) = update_a_option {
549                                                                 encode_and_send_msg!(update_a);
550                                                         }
551                                                         if let &Some(ref update_b) = update_b_option {
552                                                                 encode_and_send_msg!(update_b);
553                                                         }
554                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
555                                                 }
556                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
557                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
558                                                 }
559                                         },
560                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
561                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
562                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
563                                                 for msg in all_messages.iter() {
564                                                         encode_and_send_msg!(msg);
565                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
566                                                 }
567                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
568                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
569                                                 }
570                                         },
571                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
572                                         InitSyncTracker::NodesSyncing(key) => {
573                                                 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
574                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
575                                                 for msg in all_messages.iter() {
576                                                         encode_and_send_msg!(msg);
577                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
578                                                 }
579                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
580                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
581                                                 }
582                                         },
583                                 }
584                         }
585
586                         if {
587                                 let next_buff = match peer.pending_outbound_buffer.front() {
588                                         None => return,
589                                         Some(buff) => buff,
590                                 };
591
592                                 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
593                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
594                                 let data_sent = descriptor.send_data(pending, should_be_reading);
595                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
596                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
597                         } {
598                                 peer.pending_outbound_buffer_first_msg_offset = 0;
599                                 peer.pending_outbound_buffer.pop_front();
600                         } else {
601                                 peer.awaiting_write_event = true;
602                         }
603                 }
604         }
605
606         /// Indicates that there is room to write data to the given socket descriptor.
607         ///
608         /// May return an Err to indicate that the connection should be closed.
609         ///
610         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
611         /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
612         /// invariants around calling write_buffer_space_avail in case a write did not fully complete
613         /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
614         /// here isn't sufficient! Panics if the descriptor was not previously registered in a
615         /// new_\*_connection event.
616         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
617                 let mut peers = self.peers.lock().unwrap();
618                 match peers.peers.get_mut(descriptor) {
619                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
620                         Some(peer) => {
621                                 peer.awaiting_write_event = false;
622                                 self.do_attempt_write_data(descriptor, peer);
623                         }
624                 };
625                 Ok(())
626         }
627
628         /// Indicates that data was read from the given socket descriptor.
629         ///
630         /// May return an Err to indicate that the connection should be closed.
631         ///
632         /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
633         /// Thus, however, you almost certainly want to call process_events() after any read_event to
634         /// generate send_data calls to handle responses.
635         ///
636         /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
637         /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
638         ///
639         /// Panics if the descriptor was not previously registered in a new_*_connection event.
640         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
641                 match self.do_read_event(peer_descriptor, data) {
642                         Ok(res) => Ok(res),
643                         Err(e) => {
644                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
645                                 Err(e)
646                         }
647                 }
648         }
649
650         /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
651         fn enqueue_message<M: Encode + Writeable>(&self, peer: &mut Peer, message: &M) {
652                 let mut buffer = VecWriter(Vec::new());
653                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
654                 let encoded_message = buffer.0;
655
656                 log_trace!(self.logger, "Enqueueing message of type {} to {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
657                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
658         }
659
660         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
661                 let pause_read = {
662                         let mut peers_lock = self.peers.lock().unwrap();
663                         let peers = &mut *peers_lock;
664                         let mut msgs_to_forward = Vec::new();
665                         let mut peer_node_id = None;
666                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
667                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
668                                 Some(peer) => {
669                                         assert!(peer.pending_read_buffer.len() > 0);
670                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
671
672                                         let mut read_pos = 0;
673                                         while read_pos < data.len() {
674                                                 {
675                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
676                                                         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]);
677                                                         read_pos += data_to_copy;
678                                                         peer.pending_read_buffer_pos += data_to_copy;
679                                                 }
680
681                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
682                                                         peer.pending_read_buffer_pos = 0;
683
684                                                         macro_rules! try_potential_handleerror {
685                                                                 ($thing: expr) => {
686                                                                         match $thing {
687                                                                                 Ok(x) => x,
688                                                                                 Err(e) => {
689                                                                                         match e.action {
690                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
691                                                                                                         //TODO: Try to push msg
692                                                                                                         log_trace!(self.logger, "Got Err handling message, disconnecting peer because {}", e.err);
693                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
694                                                                                                 },
695                                                                                                 msgs::ErrorAction::IgnoreError => {
696                                                                                                         log_trace!(self.logger, "Got Err handling message, ignoring because {}", e.err);
697                                                                                                         continue;
698                                                                                                 },
699                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
700                                                                                                         log_trace!(self.logger, "Got Err handling message, sending Error message because {}", e.err);
701                                                                                                         self.enqueue_message(peer, &msg);
702                                                                                                         continue;
703                                                                                                 },
704                                                                                         }
705                                                                                 }
706                                                                         };
707                                                                 }
708                                                         }
709
710                                                         macro_rules! insert_node_id {
711                                                                 () => {
712                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
713                                                                                 hash_map::Entry::Occupied(_) => {
714                                                                                         log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
715                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
716                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
717                                                                                 },
718                                                                                 hash_map::Entry::Vacant(entry) => {
719                                                                                         log_trace!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
720                                                                                         entry.insert(peer_descriptor.clone())
721                                                                                 },
722                                                                         };
723                                                                 }
724                                                         }
725
726                                                         let next_step = peer.channel_encryptor.get_noise_step();
727                                                         match next_step {
728                                                                 NextNoiseStep::ActOne => {
729                                                                         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();
730                                                                         peer.pending_outbound_buffer.push_back(act_two);
731                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
732                                                                 },
733                                                                 NextNoiseStep::ActTwo => {
734                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
735                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
736                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
737                                                                         peer.pending_read_is_header = true;
738
739                                                                         peer.their_node_id = Some(their_node_id);
740                                                                         insert_node_id!();
741                                                                         let features = InitFeatures::known();
742                                                                         let resp = msgs::Init { features };
743                                                                         self.enqueue_message(peer, &resp);
744                                                                 },
745                                                                 NextNoiseStep::ActThree => {
746                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
747                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
748                                                                         peer.pending_read_is_header = true;
749                                                                         peer.their_node_id = Some(their_node_id);
750                                                                         insert_node_id!();
751                                                                         let features = InitFeatures::known();
752                                                                         let resp = msgs::Init { features };
753                                                                         self.enqueue_message(peer, &resp);
754                                                                 },
755                                                                 NextNoiseStep::NoiseComplete => {
756                                                                         if peer.pending_read_is_header {
757                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
758                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
759                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
760                                                                                 if msg_len < 2 { // Need at least the message type tag
761                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
762                                                                                 }
763                                                                                 peer.pending_read_is_header = false;
764                                                                         } else {
765                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
766                                                                                 assert!(msg_data.len() >= 2);
767
768                                                                                 // Reset read buffer
769                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
770                                                                                 peer.pending_read_is_header = true;
771
772                                                                                 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
773                                                                                 let message_result = wire::read(&mut reader);
774                                                                                 let message = match message_result {
775                                                                                         Ok(x) => x,
776                                                                                         Err(e) => {
777                                                                                                 match e {
778                                                                                                         msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
779                                                                                                         msgs::DecodeError::UnknownRequiredFeature => {
780                                                                                                                 log_debug!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!");
781                                                                                                                 continue;
782                                                                                                         }
783                                                                                                         msgs::DecodeError::InvalidValue => {
784                                                                                                                 log_debug!(self.logger, "Got an invalid value while deserializing message");
785                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
786                                                                                                         }
787                                                                                                         msgs::DecodeError::ShortRead => {
788                                                                                                                 log_debug!(self.logger, "Deserialization failed due to shortness of message");
789                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
790                                                                                                         }
791                                                                                                         msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
792                                                                                                         msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
793                                                                                                         msgs::DecodeError::UnsupportedCompression => {
794                                                                                                                 log_debug!(self.logger, "We don't support zlib-compressed message fields, ignoring message");
795                                                                                                                 continue;
796                                                                                                         }
797                                                                                                 }
798                                                                                         }
799                                                                                 };
800
801                                                                                 match self.handle_message(peer, message) {
802                                                                                         Err(handling_error) => match handling_error {
803                                                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
804                                                                                                 MessageHandlingError::LightningError(e) => {
805                                                                                                         try_potential_handleerror!(Err(e));
806                                                                                                 },
807                                                                                         },
808                                                                                         Ok(Some(msg)) => {
809                                                                                                 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
810                                                                                                 msgs_to_forward.push(msg);
811                                                                                         },
812                                                                                         Ok(None) => {},
813                                                                                 }
814                                                                         }
815                                                                 }
816                                                         }
817                                                 }
818                                         }
819
820                                         peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
821                                 }
822                         };
823
824                         for msg in msgs_to_forward.drain(..) {
825                                 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
826                         }
827
828                         pause_read
829                 };
830
831                 Ok(pause_read)
832         }
833
834         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
835         /// Returns the message back if it needs to be broadcasted to all other peers.
836         fn handle_message(&self, peer: &mut Peer, message: wire::Message) -> Result<Option<wire::Message>, MessageHandlingError> {
837                 log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
838
839                 // Need an Init as first message
840                 if let wire::Message::Init(_) = message {
841                 } else if peer.their_features.is_none() {
842                         log_trace!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
843                         return Err(PeerHandleError{ no_connection_possible: false }.into());
844                 }
845
846                 let mut should_forward = None;
847
848                 match message {
849                         // Setup and Control messages:
850                         wire::Message::Init(msg) => {
851                                 if msg.features.requires_unknown_bits() {
852                                         log_info!(self.logger, "Peer features required unknown version bits");
853                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
854                                 }
855                                 if peer.their_features.is_some() {
856                                         return Err(PeerHandleError{ no_connection_possible: false }.into());
857                                 }
858
859                                 log_info!(
860                                         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): {}",
861                                         if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
862                                         if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
863                                         if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
864                                         if msg.features.supports_gossip_queries() { "supported" } else { "not supported" },
865                                         if msg.features.supports_static_remote_key() { "supported" } else { "not supported"},
866                                         if msg.features.supports_unknown_bits() { "present" } else { "none" }
867                                 );
868
869                                 if msg.features.initial_routing_sync() {
870                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
871                                 }
872                                 if !msg.features.supports_static_remote_key() {
873                                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
874                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
875                                 }
876
877                                 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
878
879                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
880                                 peer.their_features = Some(msg.features);
881                         },
882                         wire::Message::Error(msg) => {
883                                 let mut data_is_printable = true;
884                                 for b in msg.data.bytes() {
885                                         if b < 32 || b > 126 {
886                                                 data_is_printable = false;
887                                                 break;
888                                         }
889                                 }
890
891                                 if data_is_printable {
892                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
893                                 } else {
894                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
895                                 }
896                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
897                                 if msg.channel_id == [0; 32] {
898                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
899                                 }
900                         },
901
902                         wire::Message::Ping(msg) => {
903                                 if msg.ponglen < 65532 {
904                                         let resp = msgs::Pong { byteslen: msg.ponglen };
905                                         self.enqueue_message(peer, &resp);
906                                 }
907                         },
908                         wire::Message::Pong(_msg) => {
909                                 peer.awaiting_pong = false;
910                         },
911
912                         // Channel messages:
913                         wire::Message::OpenChannel(msg) => {
914                                 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
915                         },
916                         wire::Message::AcceptChannel(msg) => {
917                                 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
918                         },
919
920                         wire::Message::FundingCreated(msg) => {
921                                 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
922                         },
923                         wire::Message::FundingSigned(msg) => {
924                                 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
925                         },
926                         wire::Message::FundingLocked(msg) => {
927                                 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
928                         },
929
930                         wire::Message::Shutdown(msg) => {
931                                 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
932                         },
933                         wire::Message::ClosingSigned(msg) => {
934                                 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
935                         },
936
937                         // Commitment messages:
938                         wire::Message::UpdateAddHTLC(msg) => {
939                                 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
940                         },
941                         wire::Message::UpdateFulfillHTLC(msg) => {
942                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
943                         },
944                         wire::Message::UpdateFailHTLC(msg) => {
945                                 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
946                         },
947                         wire::Message::UpdateFailMalformedHTLC(msg) => {
948                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
949                         },
950
951                         wire::Message::CommitmentSigned(msg) => {
952                                 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
953                         },
954                         wire::Message::RevokeAndACK(msg) => {
955                                 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
956                         },
957                         wire::Message::UpdateFee(msg) => {
958                                 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
959                         },
960                         wire::Message::ChannelReestablish(msg) => {
961                                 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
962                         },
963
964                         // Routing messages:
965                         wire::Message::AnnouncementSignatures(msg) => {
966                                 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
967                         },
968                         wire::Message::ChannelAnnouncement(msg) => {
969                                 if match self.message_handler.route_handler.handle_channel_announcement(&msg) {
970                                         Ok(v) => v,
971                                         Err(e) => { return Err(e.into()); },
972                                 } {
973                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
974                                 }
975                         },
976                         wire::Message::NodeAnnouncement(msg) => {
977                                 if match self.message_handler.route_handler.handle_node_announcement(&msg) {
978                                         Ok(v) => v,
979                                         Err(e) => { return Err(e.into()); },
980                                 } {
981                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
982                                 }
983                         },
984                         wire::Message::ChannelUpdate(msg) => {
985                                 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
986                                 if match self.message_handler.route_handler.handle_channel_update(&msg) {
987                                         Ok(v) => v,
988                                         Err(e) => { return Err(e.into()); },
989                                 } {
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                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
1104                                                                 Some(descriptor) => descriptor.clone(),
1105                                                                 None => {
1106                                                                         continue;
1107                                                                 },
1108                                                         };
1109                                                         match peers.peers.get_mut(&descriptor) {
1110                                                                 Some(peer) => {
1111                                                                         if peer.their_features.is_none() {
1112                                                                                 continue;
1113                                                                         }
1114                                                                         (descriptor, peer)
1115                                                                 },
1116                                                                 None => panic!("Inconsistent peers set state!"),
1117                                                         }
1118                                                 }
1119                                         }
1120                                 }
1121                                 match event {
1122                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1123                                                 log_trace!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1124                                                                 log_pubkey!(node_id),
1125                                                                 log_bytes!(msg.temporary_channel_id));
1126                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1127                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1128                                         },
1129                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1130                                                 log_trace!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1131                                                                 log_pubkey!(node_id),
1132                                                                 log_bytes!(msg.temporary_channel_id));
1133                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1134                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1135                                         },
1136                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1137                                                 log_trace!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1138                                                                 log_pubkey!(node_id),
1139                                                                 log_bytes!(msg.temporary_channel_id),
1140                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1141                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1142                                                 // indicating to the wallet that they should just throw away this funding transaction
1143                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1144                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1145                                         },
1146                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1147                                                 log_trace!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1148                                                                 log_pubkey!(node_id),
1149                                                                 log_bytes!(msg.channel_id));
1150                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1151                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1152                                         },
1153                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1154                                                 log_trace!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1155                                                                 log_pubkey!(node_id),
1156                                                                 log_bytes!(msg.channel_id));
1157                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1158                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1159                                         },
1160                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1161                                                 log_trace!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1162                                                                 log_pubkey!(node_id),
1163                                                                 log_bytes!(msg.channel_id));
1164                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1165                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1166                                         },
1167                                         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 } } => {
1168                                                 log_trace!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1169                                                                 log_pubkey!(node_id),
1170                                                                 update_add_htlcs.len(),
1171                                                                 update_fulfill_htlcs.len(),
1172                                                                 update_fail_htlcs.len(),
1173                                                                 log_bytes!(commitment_signed.channel_id));
1174                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1175                                                 for msg in update_add_htlcs {
1176                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1177                                                 }
1178                                                 for msg in update_fulfill_htlcs {
1179                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1180                                                 }
1181                                                 for msg in update_fail_htlcs {
1182                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1183                                                 }
1184                                                 for msg in update_fail_malformed_htlcs {
1185                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1186                                                 }
1187                                                 if let &Some(ref msg) = update_fee {
1188                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1189                                                 }
1190                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
1191                                         },
1192                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1193                                                 log_trace!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1194                                                                 log_pubkey!(node_id),
1195                                                                 log_bytes!(msg.channel_id));
1196                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1197                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1198                                         },
1199                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1200                                                 log_trace!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1201                                                                 log_pubkey!(node_id),
1202                                                                 log_bytes!(msg.channel_id));
1203                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1204                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1205                                         },
1206                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1207                                                 log_trace!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1208                                                                 log_pubkey!(node_id),
1209                                                                 log_bytes!(msg.channel_id));
1210                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1211                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1212                                         },
1213                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1214                                                 log_trace!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1215                                                                 log_pubkey!(node_id),
1216                                                                 log_bytes!(msg.channel_id));
1217                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1218                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1219                                         },
1220                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1221                                                 log_trace!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1222                                                 if self.message_handler.route_handler.handle_channel_announcement(&msg).is_ok() && self.message_handler.route_handler.handle_channel_update(&update_msg).is_ok() {
1223                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None);
1224                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None);
1225                                                 }
1226                                         },
1227                                         MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1228                                                 log_trace!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1229                                                 if self.message_handler.route_handler.handle_node_announcement(&msg).is_ok() {
1230                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None);
1231                                                 }
1232                                         },
1233                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1234                                                 log_trace!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1235                                                 if self.message_handler.route_handler.handle_channel_update(&msg).is_ok() {
1236                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None);
1237                                                 }
1238                                         },
1239                                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1240                                                 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1241                                         },
1242                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1243                                                 match *action {
1244                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1245                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1246                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
1247                                                                                 if let Some(ref msg) = *msg {
1248                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1249                                                                                                         log_pubkey!(node_id),
1250                                                                                                         msg.data);
1251                                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1252                                                                                         // This isn't guaranteed to work, but if there is enough free
1253                                                                                         // room in the send buffer, put the error message there...
1254                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1255                                                                                 } else {
1256                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1257                                                                                 }
1258                                                                         }
1259                                                                         descriptor.disconnect_socket();
1260                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1261                                                                 }
1262                                                         },
1263                                                         msgs::ErrorAction::IgnoreError => {},
1264                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1265                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1266                                                                                 log_pubkey!(node_id),
1267                                                                                 msg.data);
1268                                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1269                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1270                                                         },
1271                                                 }
1272                                         },
1273                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1274                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1275                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1276                                         },
1277                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1278                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1279                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1280                                         }
1281                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1282                                                 log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1283                                                         log_pubkey!(node_id),
1284                                                         msg.short_channel_ids.len(),
1285                                                         msg.first_blocknum,
1286                                                         msg.number_of_blocks,
1287                                                         msg.sync_complete);
1288                                                 let (_, peer) = get_peer_for_forwarding!(node_id);
1289                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1290                                         }
1291                                 }
1292                         }
1293
1294                         for (descriptor, peer) in peers.peers.iter_mut() {
1295                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1296                         }
1297                 }
1298         }
1299
1300         /// Indicates that the given socket descriptor's connection is now closed.
1301         ///
1302         /// This must only be called if the socket has been disconnected by the peer or your own
1303         /// decision to disconnect it and must NOT be called in any case where other parts of this
1304         /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
1305         /// the peer.
1306         ///
1307         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1308         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1309                 self.disconnect_event_internal(descriptor, false);
1310         }
1311
1312         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1313                 let mut peers = self.peers.lock().unwrap();
1314                 let peer_option = peers.peers.remove(descriptor);
1315                 match peer_option {
1316                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
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 }