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