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