Disconnect duplicate node_id connections after Noise handshake
[rust-lightning] / src / ln / peer_handler.rs
1 use secp256k1::key::{SecretKey,PublicKey};
2
3 use ln::msgs;
4 use ln::msgs::{MsgEncodable,MsgDecodable};
5 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
6 use util::byte_utils;
7 use util::events::{EventsProvider,Event};
8 use util::logger::Logger;
9
10 use std::collections::{HashMap,hash_map,LinkedList};
11 use std::sync::{Arc, Mutex};
12 use std::sync::atomic::{AtomicUsize, Ordering};
13 use std::{cmp,error,mem,hash,fmt};
14
15 pub struct MessageHandler {
16         pub chan_handler: Arc<msgs::ChannelMessageHandler>,
17         pub route_handler: Arc<msgs::RoutingMessageHandler>,
18 }
19
20 /// Provides an object which can be used to send data to and which uniquely identifies a connection
21 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
22 /// implement Hash to meet the PeerManager API.
23 /// For efficiency, Clone should be relatively cheap for this type.
24 /// You probably want to just extend an int and put a file descriptor in a struct and implement
25 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
26 /// careful to ensure you don't have races whereby you might register a new connection with an fd
27 /// the same as a yet-to-be-disconnect_event()-ed.
28 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
29         /// Attempts to send some data from the given Vec starting at the given offset to the peer.
30         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
31         /// Note that in the disconnected case, a disconnect_event must still fire and further write
32         /// attempts may occur until that time.
33         /// If the returned size is smaller than data.len() - write_offset, a write_available event must
34         /// trigger the next time more data can be written. Additionally, until the a send_data event
35         /// completes fully, no further read_events should trigger on the same peer!
36         /// If a read_event on this descriptor had previously returned true (indicating that read
37         /// events should be paused to prevent DoS in the send buffer), resume_read may be set
38         /// indicating that read events on this descriptor should resume. A resume_read of false does
39         /// *not* imply that further read events should be paused.
40         fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
41         /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
42         /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
43         /// No disconnect_event should be generated as a result of this call, though obviously races
44         /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
45         /// that event completing.
46         fn disconnect_socket(&mut self);
47 }
48
49 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
50 /// generate no further read/write_events for the descriptor, only triggering a single
51 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
52 /// no such disconnect_event must be generated and the socket be silently disconencted).
53 pub struct PeerHandleError {
54         no_connection_possible: bool,
55 }
56 impl fmt::Debug for PeerHandleError {
57         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
58                 formatter.write_str("Peer Sent Invalid Data")
59         }
60 }
61 impl fmt::Display for PeerHandleError {
62         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
63                 formatter.write_str("Peer Sent Invalid Data")
64         }
65 }
66 impl error::Error for PeerHandleError {
67         fn description(&self) -> &str {
68                 "Peer Sent Invalid Data"
69         }
70 }
71
72 struct Peer {
73         channel_encryptor: PeerChannelEncryptor,
74         outbound: bool,
75         their_node_id: Option<PublicKey>,
76         their_global_features: Option<msgs::GlobalFeatures>,
77         their_local_features: Option<msgs::LocalFeatures>,
78
79         pending_outbound_buffer: LinkedList<Vec<u8>>,
80         pending_outbound_buffer_first_msg_offset: usize,
81         awaiting_write_event: bool,
82
83         pending_read_buffer: Vec<u8>,
84         pending_read_buffer_pos: usize,
85         pending_read_is_header: bool,
86 }
87
88 struct PeerHolder<Descriptor: SocketDescriptor> {
89         peers: HashMap<Descriptor, Peer>,
90         /// Only add to this set when noise completes:
91         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
92 }
93 struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
94         peers: &'a mut HashMap<Descriptor, Peer>,
95         node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
96 }
97 impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
98         fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
99                 MutPeerHolder {
100                         peers: &mut self.peers,
101                         node_id_to_descriptor: &mut self.node_id_to_descriptor,
102                 }
103         }
104 }
105
106 pub struct PeerManager<Descriptor: SocketDescriptor> {
107         message_handler: MessageHandler,
108         peers: Mutex<PeerHolder<Descriptor>>,
109         pending_events: Mutex<Vec<Event>>,
110         our_node_secret: SecretKey,
111         initial_syncs_sent: AtomicUsize,
112         logger: Arc<Logger>,
113 }
114
115 macro_rules! encode_msg {
116         ($msg: expr, $msg_code: expr) => {
117                 {
118                         let just_msg = $msg.encode();
119                         let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
120                         encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
121                         encoded_msg.extend_from_slice(&just_msg[..]);
122                         encoded_msg
123                 }
124         }
125 }
126
127 //TODO: Really should do something smarter for this
128 const INITIAL_SYNCS_TO_SEND: usize = 5;
129
130 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
131 /// PeerIds may repeat, but only after disconnect_event() has been called.
132 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
133         pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, logger: Arc<Logger>) -> PeerManager<Descriptor> {
134                 PeerManager {
135                         message_handler: message_handler,
136                         peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
137                         pending_events: Mutex::new(Vec::new()),
138                         our_node_secret: our_node_secret,
139                         initial_syncs_sent: AtomicUsize::new(0),
140                         logger,
141                 }
142         }
143
144         /// Get the list of node ids for peers which have completed the initial handshake.
145         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
146         /// new_outbound_connection, however entries will only appear once the initial handshake has
147         /// completed and we are sure the remote peer has the private key for the given node_id.
148         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
149                 let peers = self.peers.lock().unwrap();
150                 peers.peers.values().filter_map(|p| p.their_node_id).collect()
151         }
152
153         /// Indicates a new outbound connection has been established to a node with the given node_id.
154         /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
155         /// descriptor but must disconnect the connection immediately.
156         /// Returns some bytes to send to the remote node.
157         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
158         /// disconnect_event.
159         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
160                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
161                 let res = peer_encryptor.get_act_one().to_vec();
162                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
163
164                 let mut peers = self.peers.lock().unwrap();
165                 if peers.peers.insert(descriptor, Peer {
166                         channel_encryptor: peer_encryptor,
167                         outbound: true,
168                         their_node_id: Some(their_node_id),
169                         their_global_features: None,
170                         their_local_features: None,
171
172                         pending_outbound_buffer: LinkedList::new(),
173                         pending_outbound_buffer_first_msg_offset: 0,
174                         awaiting_write_event: false,
175
176                         pending_read_buffer: pending_read_buffer,
177                         pending_read_buffer_pos: 0,
178                         pending_read_is_header: false,
179                 }).is_some() {
180                         panic!("PeerManager driver duplicated descriptors!");
181                 };
182                 Ok(res)
183         }
184
185         /// Indicates a new inbound connection has been established.
186         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
187         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
188         /// call disconnect_event for the new descriptor but must disconnect the connection
189         /// immediately.
190         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
191         /// disconnect_event.
192         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
193                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
194                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
195
196                 let mut peers = self.peers.lock().unwrap();
197                 if peers.peers.insert(descriptor, Peer {
198                         channel_encryptor: peer_encryptor,
199                         outbound: false,
200                         their_node_id: None,
201                         their_global_features: None,
202                         their_local_features: None,
203
204                         pending_outbound_buffer: LinkedList::new(),
205                         pending_outbound_buffer_first_msg_offset: 0,
206                         awaiting_write_event: false,
207
208                         pending_read_buffer: pending_read_buffer,
209                         pending_read_buffer_pos: 0,
210                         pending_read_is_header: false,
211                 }).is_some() {
212                         panic!("PeerManager driver duplicated descriptors!");
213                 };
214                 Ok(())
215         }
216
217         fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
218                 while !peer.awaiting_write_event {
219                         if {
220                                 let next_buff = match peer.pending_outbound_buffer.front() {
221                                         None => return,
222                                         Some(buff) => buff,
223                                 };
224                                 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
225
226                                 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
227                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
228                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
229                         } {
230                                 peer.pending_outbound_buffer_first_msg_offset = 0;
231                                 peer.pending_outbound_buffer.pop_front();
232                         } else {
233                                 peer.awaiting_write_event = true;
234                         }
235                 }
236         }
237
238         /// Indicates that there is room to write data to the given socket descriptor.
239         /// May return an Err to indicate that the connection should be closed.
240         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
241         /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
242         /// invariants around calling write_event in case a write did not fully complete must still
243         /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
244         /// Panics if the descriptor was not previously registered in a new_*_connection event.
245         pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
246                 let mut peers = self.peers.lock().unwrap();
247                 match peers.peers.get_mut(descriptor) {
248                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
249                         Some(peer) => {
250                                 peer.awaiting_write_event = false;
251                                 Self::do_attempt_write_data(descriptor, peer);
252                         }
253                 };
254                 Ok(())
255         }
256
257         /// Indicates that data was read from the given socket descriptor.
258         /// May return an Err to indicate that the connection should be closed.
259         /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
260         /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
261         /// invariants around calling write_event in case a write did not fully complete must still
262         /// hold. Note that this function will often call send_data on many peers before returning, not
263         /// just this peer!
264         /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
265         /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
266         /// that this must be true even if a send_data call with resume_read=true was made during the
267         /// course of this function!
268         /// Panics if the descriptor was not previously registered in a new_*_connection event.
269         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
270                 match self.do_read_event(peer_descriptor, data) {
271                         Ok(res) => Ok(res),
272                         Err(e) => {
273                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
274                                 Err(e)
275                         }
276                 }
277         }
278
279         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
280                 let pause_read = {
281                         let mut peers_lock = self.peers.lock().unwrap();
282                         let peers = peers_lock.borrow_parts();
283                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
284                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
285                                 Some(peer) => {
286                                         assert!(peer.pending_read_buffer.len() > 0);
287                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
288
289                                         let mut read_pos = 0;
290                                         while read_pos < data.len() {
291                                                 {
292                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
293                                                         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]);
294                                                         read_pos += data_to_copy;
295                                                         peer.pending_read_buffer_pos += data_to_copy;
296                                                 }
297
298                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
299                                                         peer.pending_read_buffer_pos = 0;
300
301                                                         macro_rules! encode_and_send_msg {
302                                                                 ($msg: expr, $msg_code: expr) => {
303                                                                         {
304                                                                                 log_trace!(self, "Encoding and sending message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
305                                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
306                                                                         }
307                                                                 }
308                                                         }
309
310                                                         macro_rules! try_potential_handleerror {
311                                                                 ($thing: expr) => {
312                                                                         match $thing {
313                                                                                 Ok(x) => x,
314                                                                                 Err(e) => {
315                                                                                         if let Some(action) = e.action {
316                                                                                                 match action {
317                                                                                                         msgs::ErrorAction::DisconnectPeer { msg: _ } => {
318                                                                                                                 //TODO: Try to push msg
319                                                                                                                 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
320                                                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
321                                                                                                         },
322                                                                                                         msgs::ErrorAction::IgnoreError => {
323                                                                                                                 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
324                                                                                                                 continue;
325                                                                                                         },
326                                                                                                         msgs::ErrorAction::SendErrorMessage { msg } => {
327                                                                                                                 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
328                                                                                                                 encode_and_send_msg!(msg, 17);
329                                                                                                                 continue;
330                                                                                                         },
331                                                                                                 }
332                                                                                         } else {
333                                                                                                 log_debug!(self, "Got Err handling message, action not yet filled in: {}", e.err);
334                                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
335                                                                                         }
336                                                                                 }
337                                                                         };
338                                                                 }
339                                                         }
340
341                                                         macro_rules! try_potential_decodeerror {
342                                                                 ($thing: expr) => {
343                                                                         match $thing {
344                                                                                 Ok(x) => x,
345                                                                                 Err(e) => {
346                                                                                         match e {
347                                                                                                 msgs::DecodeError::UnknownRealmByte => return Err(PeerHandleError{ no_connection_possible: false }),
348                                                                                                 msgs::DecodeError::UnknownRequiredFeature => {
349                                                                                                         log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to udpate!");
350                                                                                                         continue;
351                                                                                                 },
352                                                                                                 msgs::DecodeError::BadPublicKey => return Err(PeerHandleError{ no_connection_possible: false }),
353                                                                                                 msgs::DecodeError::BadSignature => return Err(PeerHandleError{ no_connection_possible: false }),
354                                                                                                 msgs::DecodeError::BadText => return Err(PeerHandleError{ no_connection_possible: false }),
355                                                                                                 msgs::DecodeError::ShortRead => return Err(PeerHandleError{ no_connection_possible: false }),
356                                                                                                 msgs::DecodeError::ExtraAddressesPerType => {
357                                                                                                         log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
358                                                                                                         continue;
359                                                                                                 },
360                                                                                                 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
361                                                                                         }
362                                                                                 }
363                                                                         };
364                                                                 }
365                                                         }
366
367                                                         macro_rules! insert_node_id {
368                                                                 () => {
369                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
370                                                                                 hash_map::Entry::Occupied(_) => {
371                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
372                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
373                                                                                 },
374                                                                                 hash_map::Entry::Vacant(entry) => entry.insert(peer_descriptor.clone()),
375                                                                         };
376                                                                 }
377                                                         }
378
379                                                         let next_step = peer.channel_encryptor.get_noise_step();
380                                                         match next_step {
381                                                                 NextNoiseStep::ActOne => {
382                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
383                                                                         peer.pending_outbound_buffer.push_back(act_two);
384                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
385                                                                 },
386                                                                 NextNoiseStep::ActTwo => {
387                                                                         let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
388                                                                         peer.pending_outbound_buffer.push_back(act_three);
389                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
390                                                                         peer.pending_read_is_header = true;
391
392                                                                         insert_node_id!();
393                                                                         let mut local_features = msgs::LocalFeatures::new();
394                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
395                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
396                                                                                 local_features.set_initial_routing_sync();
397                                                                         }
398                                                                         encode_and_send_msg!(msgs::Init {
399                                                                                 global_features: msgs::GlobalFeatures::new(),
400                                                                                 local_features,
401                                                                         }, 16);
402                                                                 },
403                                                                 NextNoiseStep::ActThree => {
404                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
405                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
406                                                                         peer.pending_read_is_header = true;
407                                                                         peer.their_node_id = Some(their_node_id);
408                                                                         insert_node_id!();
409                                                                 },
410                                                                 NextNoiseStep::NoiseComplete => {
411                                                                         if peer.pending_read_is_header {
412                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
413                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
414                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
415                                                                                 if msg_len < 2 { // Need at least the message type tag
416                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
417                                                                                 }
418                                                                                 peer.pending_read_is_header = false;
419                                                                         } else {
420                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
421                                                                                 assert!(msg_data.len() >= 2);
422
423                                                                                 // Reset read buffer
424                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
425                                                                                 peer.pending_read_is_header = true;
426
427                                                                                 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
428                                                                                 log_trace!(self, "Received message of type {} from {}", msg_type, log_pubkey!(peer.their_node_id.unwrap()));
429                                                                                 if msg_type != 16 && peer.their_global_features.is_none() {
430                                                                                         // Need an init message as first message
431                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
432                                                                                 }
433                                                                                 match msg_type {
434                                                                                         // Connection control:
435                                                                                         16 => {
436                                                                                                 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
437                                                                                                 if msg.global_features.requires_unknown_bits() {
438                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
439                                                                                                 }
440                                                                                                 if msg.local_features.requires_unknown_bits() {
441                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
442                                                                                                 }
443                                                                                                 peer.their_global_features = Some(msg.global_features);
444                                                                                                 peer.their_local_features = Some(msg.local_features);
445
446                                                                                                 if !peer.outbound {
447                                                                                                         let mut local_features = msgs::LocalFeatures::new();
448                                                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
449                                                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
450                                                                                                                 local_features.set_initial_routing_sync();
451                                                                                                         }
452                                                                                                         encode_and_send_msg!(msgs::Init {
453                                                                                                                 global_features: msgs::GlobalFeatures::new(),
454                                                                                                                 local_features,
455                                                                                                         }, 16);
456                                                                                                 }
457                                                                                         },
458                                                                                         17 => {
459                                                                                                 let msg = try_potential_decodeerror!(msgs::ErrorMessage::decode(&msg_data[2..]));
460                                                                                                 let mut data_is_printable = true;
461                                                                                                 for b in msg.data.bytes() {
462                                                                                                         if b < 32 || b > 126 {
463                                                                                                                 data_is_printable = false;
464                                                                                                                 break;
465                                                                                                         }
466                                                                                                 }
467
468                                                                                                 if data_is_printable {
469                                                                                                         log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
470                                                                                                 } else {
471                                                                                                         log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
472                                                                                                 }
473                                                                                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
474                                                                                                 if msg.channel_id == [0; 32] {
475                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
476                                                                                                 }
477                                                                                         },
478
479                                                                                         18 => {
480                                                                                                 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
481                                                                                                 if msg.ponglen < 65532 {
482                                                                                                         let resp = msgs::Pong { byteslen: msg.ponglen };
483                                                                                                         encode_and_send_msg!(resp, 19);
484                                                                                                 }
485                                                                                         },
486                                                                                         19 => {
487                                                                                                 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
488                                                                                         },
489
490                                                                                         // Channel control:
491                                                                                         32 => {
492                                                                                                 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
493                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
494                                                                                                 encode_and_send_msg!(resp, 33);
495                                                                                         },
496                                                                                         33 => {
497                                                                                                 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
498                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
499                                                                                         },
500
501                                                                                         34 => {
502                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
503                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
504                                                                                                 encode_and_send_msg!(resp, 35);
505                                                                                         },
506                                                                                         35 => {
507                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
508                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
509                                                                                         },
510                                                                                         36 => {
511                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
512                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
513                                                                                                 match resp_option {
514                                                                                                         Some(resp) => encode_and_send_msg!(resp, 259),
515                                                                                                         None => {},
516                                                                                                 }
517                                                                                         },
518
519                                                                                         38 => {
520                                                                                                 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
521                                                                                                 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
522                                                                                                 if let Some(resp) = resp_options.0 {
523                                                                                                         encode_and_send_msg!(resp, 38);
524                                                                                                 }
525                                                                                                 if let Some(resp) = resp_options.1 {
526                                                                                                         encode_and_send_msg!(resp, 39);
527                                                                                                 }
528                                                                                         },
529                                                                                         39 => {
530                                                                                                 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
531                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
532                                                                                                 if let Some(resp) = resp_option {
533                                                                                                         encode_and_send_msg!(resp, 39);
534                                                                                                 }
535                                                                                         },
536
537                                                                                         128 => {
538                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
539                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
540                                                                                         },
541                                                                                         130 => {
542                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
543                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
544                                                                                         },
545                                                                                         131 => {
546                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
547                                                                                                 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
548                                                                                                 if let Some(update) = chan_update {
549                                                                                                         self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
550                                                                                                 }
551                                                                                         },
552                                                                                         135 => {
553                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
554                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
555                                                                                         },
556
557                                                                                         132 => {
558                                                                                                 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
559                                                                                                 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
560                                                                                                 encode_and_send_msg!(resps.0, 133);
561                                                                                                 if let Some(resp) = resps.1 {
562                                                                                                         encode_and_send_msg!(resp, 132);
563                                                                                                 }
564                                                                                         },
565                                                                                         133 => {
566                                                                                                 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
567                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
568                                                                                                 match resp_option {
569                                                                                                         Some(resps) => {
570                                                                                                                 for resp in resps.update_add_htlcs {
571                                                                                                                         encode_and_send_msg!(resp, 128);
572                                                                                                                 }
573                                                                                                                 for resp in resps.update_fulfill_htlcs {
574                                                                                                                         encode_and_send_msg!(resp, 130);
575                                                                                                                 }
576                                                                                                                 for resp in resps.update_fail_htlcs {
577                                                                                                                         encode_and_send_msg!(resp, 131);
578                                                                                                                 }
579                                                                                                                 encode_and_send_msg!(resps.commitment_signed, 132);
580                                                                                                         },
581                                                                                                         None => {},
582                                                                                                 }
583                                                                                         },
584                                                                                         134 => {
585                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
586                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
587                                                                                         },
588                                                                                         136 => { }, // TODO: channel_reestablish
589
590                                                                                         // Routing control:
591                                                                                         259 => {
592                                                                                                 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
593                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
594                                                                                         },
595                                                                                         256 => {
596                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
597                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
598
599                                                                                                 if should_forward {
600                                                                                                         // TODO: forward msg along to all our other peers!
601                                                                                                 }
602                                                                                         },
603                                                                                         257 => {
604                                                                                                 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
605                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
606
607                                                                                                 if should_forward {
608                                                                                                         // TODO: forward msg along to all our other peers!
609                                                                                                 }
610                                                                                         },
611                                                                                         258 => {
612                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
613                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
614
615                                                                                                 if should_forward {
616                                                                                                         // TODO: forward msg along to all our other peers!
617                                                                                                 }
618                                                                                         },
619                                                                                         _ => {
620                                                                                                 if (msg_type & 1) == 0 {
621                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
622                                                                                                 }
623                                                                                         },
624                                                                                 }
625                                                                         }
626                                                                 }
627                                                         }
628                                                 }
629                                         }
630
631                                         Self::do_attempt_write_data(peer_descriptor, peer);
632
633                                         peer.pending_outbound_buffer.len() > 10 // pause_read
634                                 }
635                         };
636
637                         pause_read
638                 };
639
640                 self.process_events();
641
642                 Ok(pause_read)
643         }
644
645         /// Checks for any events generated by our handlers and processes them. May be needed after eg
646         /// calls to ChannelManager::process_pending_htlc_forward.
647         pub fn process_events(&self) {
648                 let mut upstream_events = Vec::new();
649                 {
650                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
651                         // buffer by doing things like announcing channels on another node. We should be willing to
652                         // drop optional-ish messages when send buffers get full!
653
654                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
655                         let mut peers = self.peers.lock().unwrap();
656                         for event in events_generated.drain(..) {
657                                 macro_rules! get_peer_for_forwarding {
658                                         ($node_id: expr, $handle_no_such_peer: block) => {
659                                                 {
660                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
661                                                                 Some(descriptor) => descriptor.clone(),
662                                                                 None => {
663                                                                         $handle_no_such_peer;
664                                                                         continue;
665                                                                 },
666                                                         };
667                                                         match peers.peers.get_mut(&descriptor) {
668                                                                 Some(peer) => {
669                                                                         if peer.their_global_features.is_none() {
670                                                                                 $handle_no_such_peer;
671                                                                                 continue;
672                                                                         }
673                                                                         (descriptor, peer)
674                                                                 },
675                                                                 None => panic!("Inconsistent peers set state!"),
676                                                         }
677                                                 }
678                                         }
679                                 }
680                                 match event {
681                                         Event::FundingGenerationReady {..} => { /* Hand upstream */ },
682                                         Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
683                                         Event::PaymentReceived {..} => { /* Hand upstream */ },
684                                         Event::PaymentSent {..} => { /* Hand upstream */ },
685                                         Event::PaymentFailed {..} => { /* Hand upstream */ },
686                                         Event::PendingHTLCsForwardable {..} => { /* Hand upstream */ },
687
688                                         Event::SendOpenChannel { ref node_id, ref msg } => {
689                                                 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
690                                                                 log_pubkey!(node_id),
691                                                                 log_bytes!(msg.temporary_channel_id));
692                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
693                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
694                                                         });
695                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
696                                                 Self::do_attempt_write_data(&mut descriptor, peer);
697                                                 continue;
698                                         },
699                                         Event::SendFundingCreated { ref node_id, ref msg } => {
700                                                 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
701                                                                 log_pubkey!(node_id),
702                                                                 log_bytes!(msg.temporary_channel_id),
703                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
704                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
705                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
706                                                                 //they should just throw away this funding transaction
707                                                         });
708                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
709                                                 Self::do_attempt_write_data(&mut descriptor, peer);
710                                                 continue;
711                                         },
712                                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
713                                                 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {}{} for channel {}",
714                                                                 log_pubkey!(node_id),
715                                                                 if announcement_sigs.is_some() { " with announcement sigs" } else { "" },
716                                                                 log_bytes!(msg.channel_id));
717                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
718                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
719                                                         });
720                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
721                                                 match announcement_sigs {
722                                                         &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
723                                                         &None => {},
724                                                 }
725                                                 Self::do_attempt_write_data(&mut descriptor, peer);
726                                                 continue;
727                                         },
728                                         Event::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 commitment_signed } } => {
729                                                 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
730                                                                 log_pubkey!(node_id),
731                                                                 update_add_htlcs.len(),
732                                                                 update_fulfill_htlcs.len(),
733                                                                 update_fail_htlcs.len(),
734                                                                 log_bytes!(commitment_signed.channel_id));
735                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
736                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
737                                                         });
738                                                 for msg in update_add_htlcs {
739                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
740                                                 }
741                                                 for msg in update_fulfill_htlcs {
742                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
743                                                 }
744                                                 for msg in update_fail_htlcs {
745                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
746                                                 }
747                                                 for msg in update_fail_malformed_htlcs {
748                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135)));
749                                                 }
750                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed, 132)));
751                                                 Self::do_attempt_write_data(&mut descriptor, peer);
752                                                 continue;
753                                         },
754                                         Event::SendShutdown { ref node_id, ref msg } => {
755                                                 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
756                                                                 log_pubkey!(node_id),
757                                                                 log_bytes!(msg.channel_id));
758                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
759                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
760                                                         });
761                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
762                                                 Self::do_attempt_write_data(&mut descriptor, peer);
763                                                 continue;
764                                         },
765                                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
766                                                 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
767                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
768                                                         let encoded_msg = encode_msg!(msg, 256);
769                                                         let encoded_update_msg = encode_msg!(update_msg, 258);
770
771                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
772                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() {
773                                                                         continue
774                                                                 }
775                                                                 match peer.their_node_id {
776                                                                         None => continue,
777                                                                         Some(their_node_id) => {
778                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
779                                                                                         continue
780                                                                                 }
781                                                                         }
782                                                                 }
783                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
784                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
785                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
786                                                         }
787                                                 }
788                                                 continue;
789                                         },
790                                         Event::BroadcastChannelUpdate { ref msg } => {
791                                                 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
792                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
793                                                         let encoded_msg = encode_msg!(msg, 258);
794
795                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
796                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() {
797                                                                         continue
798                                                                 }
799                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
800                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
801                                                         }
802                                                 }
803                                                 continue;
804                                         },
805                                         Event::HandleError { ref node_id, ref action } => {
806                                                 if let Some(ref action) = *action {
807                                                         match *action {
808                                                                 msgs::ErrorAction::DisconnectPeer { ref msg } => {
809                                                                         if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
810                                                                                 if let Some(mut peer) = peers.peers.remove(&descriptor) {
811                                                                                         if let Some(ref msg) = *msg {
812                                                                                                 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
813                                                                                                                 log_pubkey!(node_id),
814                                                                                                                 msg.data);
815                                                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
816                                                                                                 // This isn't guaranteed to work, but if there is enough free
817                                                                                                 // room in the send buffer, put the error message there...
818                                                                                                 Self::do_attempt_write_data(&mut descriptor, &mut peer);
819                                                                                         } else {
820                                                                                                 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
821                                                                                         }
822                                                                                 }
823                                                                                 descriptor.disconnect_socket();
824                                                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
825                                                                         }
826                                                                 },
827                                                                 msgs::ErrorAction::IgnoreError => {
828                                                                         continue;
829                                                                 },
830                                                                 msgs::ErrorAction::SendErrorMessage { ref msg } => {
831                                                                         log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
832                                                                                         log_pubkey!(node_id),
833                                                                                         msg.data);
834                                                                         let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
835                                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
836                                                                         });
837                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
838                                                                         Self::do_attempt_write_data(&mut descriptor, peer);
839                                                                 },
840                                                         }
841                                                 } else {
842                                                         log_error!(self, "Got no-action HandleError Event in peer_handler for node {}, no such events should ever be generated!", log_pubkey!(node_id));
843                                                 }
844                                                 continue;
845                                         }
846                                 }
847
848                                 upstream_events.push(event);
849                         }
850                 }
851
852                 let mut pending_events = self.pending_events.lock().unwrap();
853                 for event in upstream_events.drain(..) {
854                         pending_events.push(event);
855                 }
856         }
857
858         /// Indicates that the given socket descriptor's connection is now closed.
859         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
860         /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
861         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
862         pub fn disconnect_event(&self, descriptor: &Descriptor) {
863                 self.disconnect_event_internal(descriptor, false);
864         }
865
866         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
867                 let mut peers = self.peers.lock().unwrap();
868                 let peer_option = peers.peers.remove(descriptor);
869                 match peer_option {
870                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
871                         Some(peer) => {
872                                 match peer.their_node_id {
873                                         Some(node_id) => {
874                                                 peers.node_id_to_descriptor.remove(&node_id);
875                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
876                                         },
877                                         None => {}
878                                 }
879                         }
880                 };
881         }
882 }
883
884 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
885         fn get_and_clear_pending_events(&self) -> Vec<Event> {
886                 let mut pending_events = self.pending_events.lock().unwrap();
887                 let mut ret = Vec::new();
888                 mem::swap(&mut ret, &mut *pending_events);
889                 ret
890         }
891 }
892
893 #[cfg(test)]
894 mod tests {
895         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
896         use ln::msgs;
897         use util::events;
898         use util::test_utils;
899         use util::logger::Logger;
900
901         use secp256k1::Secp256k1;
902         use secp256k1::key::{SecretKey, PublicKey};
903
904         use rand::{thread_rng, Rng};
905
906         use std::sync::{Arc};
907
908         #[derive(PartialEq, Eq, Clone, Hash)]
909         struct FileDescriptor {
910                 fd: u16,
911         }
912
913         impl SocketDescriptor for FileDescriptor {
914                 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
915                         assert!(write_offset < data.len());
916                         data.len() - write_offset
917                 }
918
919                 fn disconnect_socket(&mut self) {}
920         }
921
922         fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
923                 let secp_ctx = Secp256k1::new();
924                 let mut peers = Vec::new();
925                 let mut rng = thread_rng();
926                 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
927
928                 for _ in 0..peer_count {
929                         let chan_handler = test_utils::TestChannelMessageHandler::new();
930                         let router = test_utils::TestRoutingMessageHandler::new();
931                         let node_id = {
932                                 let mut key_slice = [0;32];
933                                 rng.fill_bytes(&mut key_slice);
934                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
935                         };
936                         let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
937                         let peer = PeerManager::new(msg_handler, node_id, Arc::clone(&logger));
938                         peers.push(peer);
939                 }
940
941                 peers
942         }
943
944         fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
945                 let secp_ctx = Secp256k1::new();
946                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
947                 let fd = FileDescriptor { fd: 1};
948                 peer_a.new_inbound_connection(fd.clone()).unwrap();
949                 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
950         }
951
952         #[test]
953         fn test_disconnect_peer() {
954                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
955                 // push an DisconnectPeer event to remove the node flagged by id
956                 let mut peers = create_network(2);
957                 establish_connection(&peers[0], &peers[1]);
958                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
959
960                 let secp_ctx = Secp256k1::new();
961                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
962
963                 let chan_handler = test_utils::TestChannelMessageHandler::new();
964                 chan_handler.pending_events.lock().unwrap().push(events::Event::HandleError {
965                         node_id: their_id,
966                         action: Some(msgs::ErrorAction::DisconnectPeer { msg: None }),
967                 });
968                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
969                 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
970
971                 peers[0].process_events();
972                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
973         }
974 }