]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/peer_handler.rs
Bump versions to 0.0.10
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 //! Top level peer message handling and socket handling logic lives here.
2 //!
3 //! Instead of actually servicing sockets ourselves we require that you implement the
4 //! SocketDescriptor interface and use that to receive actions which you should perform on the
5 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
6 //! call into the provided message handlers (probably a ChannelManager and Router) with messages
7 //! they should handle, and encoding/sending response messages.
8
9 use secp256k1::key::{SecretKey,PublicKey};
10
11 use ln::msgs;
12 use util::ser::{Writeable, Writer, Readable};
13 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
14 use util::byte_utils;
15 use util::events::{MessageSendEvent};
16 use util::logger::Logger;
17
18 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
19 use std::sync::{Arc, Mutex};
20 use std::sync::atomic::{AtomicUsize, Ordering};
21 use std::{cmp,error,hash,fmt};
22
23 use bitcoin_hashes::sha256::Hash as Sha256;
24 use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
25 use bitcoin_hashes::{HashEngine, Hash};
26
27 /// Provides references to trait impls which handle different types of messages.
28 pub struct MessageHandler {
29         /// A message handler which handles messages specific to channels. Usually this is just a
30         /// ChannelManager object.
31         pub chan_handler: Arc<msgs::ChannelMessageHandler>,
32         /// A message handler which handles messages updating our knowledge of the network channel
33         /// graph. Usually this is just a Router object.
34         pub route_handler: Arc<msgs::RoutingMessageHandler>,
35 }
36
37 /// Provides an object which can be used to send data to and which uniquely identifies a connection
38 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
39 /// implement Hash to meet the PeerManager API.
40 ///
41 /// For efficiency, Clone should be relatively cheap for this type.
42 ///
43 /// You probably want to just extend an int and put a file descriptor in a struct and implement
44 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
45 /// careful to ensure you don't have races whereby you might register a new connection with an fd
46 /// the same as a yet-to-be-disconnect_event()-ed.
47 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
48         /// Attempts to send some data from the given slice to the peer.
49         ///
50         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
51         /// Note that in the disconnected case, a disconnect_event must still fire and further write
52         /// attempts may occur until that time.
53         ///
54         /// If the returned size is smaller than data.len(), a write_available event must
55         /// trigger the next time more data can be written. Additionally, until the a send_data event
56         /// completes fully, no further read_events should trigger on the same peer!
57         ///
58         /// If a read_event on this descriptor had previously returned true (indicating that read
59         /// events should be paused to prevent DoS in the send buffer), resume_read may be set
60         /// indicating that read events on this descriptor should resume. A resume_read of false does
61         /// *not* imply that further read events should be paused.
62         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
63         /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
64         /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
65         /// No disconnect_event should be generated as a result of this call, though obviously races
66         /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
67         /// that event completing.
68         fn disconnect_socket(&mut self);
69 }
70
71 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
72 /// generate no further read/write_events for the descriptor, only triggering a single
73 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
74 /// no such disconnect_event must be generated and the socket be silently disconencted).
75 pub struct PeerHandleError {
76         /// Used to indicate that we probably can't make any future connections to this peer, implying
77         /// we should go ahead and force-close any channels we have with it.
78         no_connection_possible: bool,
79 }
80 impl fmt::Debug for PeerHandleError {
81         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
82                 formatter.write_str("Peer Sent Invalid Data")
83         }
84 }
85 impl fmt::Display for PeerHandleError {
86         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
87                 formatter.write_str("Peer Sent Invalid Data")
88         }
89 }
90 impl error::Error for PeerHandleError {
91         fn description(&self) -> &str {
92                 "Peer Sent Invalid Data"
93         }
94 }
95
96 enum InitSyncTracker{
97         NoSyncRequested,
98         ChannelsSyncing(u64),
99         NodesSyncing(PublicKey),
100 }
101
102 struct Peer {
103         channel_encryptor: PeerChannelEncryptor,
104         outbound: bool,
105         their_node_id: Option<PublicKey>,
106         their_global_features: Option<msgs::GlobalFeatures>,
107         their_local_features: Option<msgs::LocalFeatures>,
108
109         pending_outbound_buffer: LinkedList<Vec<u8>>,
110         pending_outbound_buffer_first_msg_offset: usize,
111         awaiting_write_event: bool,
112
113         pending_read_buffer: Vec<u8>,
114         pending_read_buffer_pos: usize,
115         pending_read_is_header: bool,
116
117         sync_status: InitSyncTracker,
118 }
119
120 impl Peer {
121         /// Returns true if the channel announcements/updates for the given channel should be
122         /// forwarded to this peer.
123         /// If we are sending our routing table to this peer and we have not yet sent channel
124         /// announcements/updates for the given channel_id then we will send it when we get to that
125         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
126         /// sent the old versions, we should send the update, and so return true here.
127         fn should_forward_channel(&self, channel_id: u64)->bool{
128                 match self.sync_status {
129                         InitSyncTracker::NoSyncRequested => true,
130                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
131                         InitSyncTracker::NodesSyncing(_) => true,
132                 }
133         }
134 }
135
136 struct PeerHolder<Descriptor: SocketDescriptor> {
137         peers: HashMap<Descriptor, Peer>,
138         /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
139         /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
140         peers_needing_send: HashSet<Descriptor>,
141         /// Only add to this set when noise completes:
142         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
143 }
144 struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
145         peers: &'a mut HashMap<Descriptor, Peer>,
146         peers_needing_send: &'a mut HashSet<Descriptor>,
147         node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
148 }
149 impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
150         fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
151                 MutPeerHolder {
152                         peers: &mut self.peers,
153                         peers_needing_send: &mut self.peers_needing_send,
154                         node_id_to_descriptor: &mut self.node_id_to_descriptor,
155                 }
156         }
157 }
158
159 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
160 fn _check_usize_is_32_or_64() {
161         // See below, less than 32 bit pointers may be unsafe here!
162         unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
163 }
164
165 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
166 /// events into messages which it passes on to its MessageHandlers.
167 pub struct PeerManager<Descriptor: SocketDescriptor> {
168         message_handler: MessageHandler,
169         peers: Mutex<PeerHolder<Descriptor>>,
170         our_node_secret: SecretKey,
171         ephemeral_key_midstate: Sha256Engine,
172
173         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
174         // bits we will never realistically count into high:
175         peer_counter_low: AtomicUsize,
176         peer_counter_high: AtomicUsize,
177
178         initial_syncs_sent: AtomicUsize,
179         logger: Arc<Logger>,
180 }
181
182 struct VecWriter(Vec<u8>);
183 impl Writer for VecWriter {
184         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
185                 self.0.extend_from_slice(buf);
186                 Ok(())
187         }
188         fn size_hint(&mut self, size: usize) {
189                 self.0.reserve_exact(size);
190         }
191 }
192
193 macro_rules! encode_msg {
194         ($msg: expr, $msg_code: expr) => {{
195                 let mut msg = VecWriter(Vec::new());
196                 ($msg_code as u16).write(&mut msg).unwrap();
197                 $msg.write(&mut msg).unwrap();
198                 msg.0
199         }}
200 }
201
202 //TODO: Really should do something smarter for this
203 const INITIAL_SYNCS_TO_SEND: usize = 5;
204
205 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
206 /// PeerIds may repeat, but only after disconnect_event() has been called.
207 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
208         /// Constructs a new PeerManager with the given message handlers and node_id secret key
209         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
210         /// cryptographically secure random bytes.
211         pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor> {
212                 let mut ephemeral_key_midstate = Sha256::engine();
213                 ephemeral_key_midstate.input(ephemeral_random_data);
214
215                 PeerManager {
216                         message_handler: message_handler,
217                         peers: Mutex::new(PeerHolder {
218                                 peers: HashMap::new(),
219                                 peers_needing_send: HashSet::new(),
220                                 node_id_to_descriptor: HashMap::new()
221                         }),
222                         our_node_secret: our_node_secret,
223                         ephemeral_key_midstate,
224                         peer_counter_low: AtomicUsize::new(0),
225                         peer_counter_high: AtomicUsize::new(0),
226                         initial_syncs_sent: AtomicUsize::new(0),
227                         logger,
228                 }
229         }
230
231         /// Get the list of node ids for peers which have completed the initial handshake.
232         ///
233         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
234         /// new_outbound_connection, however entries will only appear once the initial handshake has
235         /// completed and we are sure the remote peer has the private key for the given node_id.
236         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
237                 let peers = self.peers.lock().unwrap();
238                 peers.peers.values().filter_map(|p| {
239                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() {
240                                 return None;
241                         }
242                         p.their_node_id
243                 }).collect()
244         }
245
246         fn get_ephemeral_key(&self) -> SecretKey {
247                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
248                 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
249                 let high = if low == 0 {
250                         self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
251                 } else {
252                         self.peer_counter_high.load(Ordering::Acquire)
253                 };
254                 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
255                 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
256                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
257         }
258
259         /// Indicates a new outbound connection has been established to a node with the given node_id.
260         /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
261         /// descriptor but must disconnect the connection immediately.
262         ///
263         /// Returns a small number of bytes to send to the remote node (currently always 50).
264         ///
265         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
266         /// disconnect_event.
267         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
268                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
269                 let res = peer_encryptor.get_act_one().to_vec();
270                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
271
272                 let mut peers = self.peers.lock().unwrap();
273                 if peers.peers.insert(descriptor, Peer {
274                         channel_encryptor: peer_encryptor,
275                         outbound: true,
276                         their_node_id: None,
277                         their_global_features: None,
278                         their_local_features: None,
279
280                         pending_outbound_buffer: LinkedList::new(),
281                         pending_outbound_buffer_first_msg_offset: 0,
282                         awaiting_write_event: false,
283
284                         pending_read_buffer: pending_read_buffer,
285                         pending_read_buffer_pos: 0,
286                         pending_read_is_header: false,
287
288                         sync_status: InitSyncTracker::NoSyncRequested,
289                 }).is_some() {
290                         panic!("PeerManager driver duplicated descriptors!");
291                 };
292                 Ok(res)
293         }
294
295         /// Indicates a new inbound connection has been established.
296         ///
297         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
298         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
299         /// call disconnect_event for the new descriptor but must disconnect the connection
300         /// immediately.
301         ///
302         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
303         /// disconnect_event.
304         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
305                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
306                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
307
308                 let mut peers = self.peers.lock().unwrap();
309                 if peers.peers.insert(descriptor, Peer {
310                         channel_encryptor: peer_encryptor,
311                         outbound: false,
312                         their_node_id: None,
313                         their_global_features: None,
314                         their_local_features: None,
315
316                         pending_outbound_buffer: LinkedList::new(),
317                         pending_outbound_buffer_first_msg_offset: 0,
318                         awaiting_write_event: false,
319
320                         pending_read_buffer: pending_read_buffer,
321                         pending_read_buffer_pos: 0,
322                         pending_read_is_header: false,
323
324                         sync_status: InitSyncTracker::NoSyncRequested,
325                 }).is_some() {
326                         panic!("PeerManager driver duplicated descriptors!");
327                 };
328                 Ok(())
329         }
330
331         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
332                 macro_rules! encode_and_send_msg {
333                         ($msg: expr, $msg_code: expr) => {
334                                 {
335                                         log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
336                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
337                                 }
338                         }
339                 }
340                 const MSG_BUFF_SIZE: usize = 10;
341                 while !peer.awaiting_write_event {
342                         if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
343                                 match peer.sync_status {
344                                         InitSyncTracker::NoSyncRequested => {},
345                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
346                                                 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
347                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
348                                                 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
349                                                         encode_and_send_msg!(announce, 256);
350                                                         encode_and_send_msg!(update_a, 258);
351                                                         encode_and_send_msg!(update_b, 258);
352                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
353                                                 }
354                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
355                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
356                                                 }
357                                         },
358                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
359                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
360                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
361                                                 for msg in all_messages.iter() {
362                                                         encode_and_send_msg!(msg, 256);
363                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
364                                                 }
365                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
366                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
367                                                 }
368                                         },
369                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
370                                         InitSyncTracker::NodesSyncing(key) => {
371                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
372                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
373                                                 for msg in all_messages.iter() {
374                                                         encode_and_send_msg!(msg, 256);
375                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
376                                                 }
377                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
378                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
379                                                 }
380                                         },
381                                 }
382                         }
383
384                         if {
385                                 let next_buff = match peer.pending_outbound_buffer.front() {
386                                         None => return,
387                                         Some(buff) => buff,
388                                 };
389
390                                 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
391                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
392                                 let data_sent = descriptor.send_data(pending, should_be_reading);
393                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
394                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
395                         } {
396                                 peer.pending_outbound_buffer_first_msg_offset = 0;
397                                 peer.pending_outbound_buffer.pop_front();
398                         } else {
399                                 peer.awaiting_write_event = true;
400                         }
401                 }
402         }
403
404         /// Indicates that there is room to write data to the given socket descriptor.
405         ///
406         /// May return an Err to indicate that the connection should be closed.
407         ///
408         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
409         /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
410         /// invariants around calling write_event in case a write did not fully complete must still
411         /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
412         /// Panics if the descriptor was not previously registered in a new_\*_connection event.
413         pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
414                 let mut peers = self.peers.lock().unwrap();
415                 match peers.peers.get_mut(descriptor) {
416                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
417                         Some(peer) => {
418                                 peer.awaiting_write_event = false;
419                                 self.do_attempt_write_data(descriptor, peer);
420                         }
421                 };
422                 Ok(())
423         }
424
425         /// Indicates that data was read from the given socket descriptor.
426         ///
427         /// May return an Err to indicate that the connection should be closed.
428         ///
429         /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
430         /// Thus, however, you almost certainly want to call process_events() after any read_event to
431         /// generate send_data calls to handle responses.
432         ///
433         /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
434         /// this file descriptor has resume_read set (preventing DoS issues in the send buffer).
435         ///
436         /// Panics if the descriptor was not previously registered in a new_*_connection event.
437         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
438                 match self.do_read_event(peer_descriptor, data) {
439                         Ok(res) => Ok(res),
440                         Err(e) => {
441                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
442                                 Err(e)
443                         }
444                 }
445         }
446
447         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
448                 let pause_read = {
449                         let mut peers_lock = self.peers.lock().unwrap();
450                         let peers = peers_lock.borrow_parts();
451                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
452                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
453                                 Some(peer) => {
454                                         assert!(peer.pending_read_buffer.len() > 0);
455                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
456
457                                         let mut read_pos = 0;
458                                         while read_pos < data.len() {
459                                                 {
460                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
461                                                         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]);
462                                                         read_pos += data_to_copy;
463                                                         peer.pending_read_buffer_pos += data_to_copy;
464                                                 }
465
466                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
467                                                         peer.pending_read_buffer_pos = 0;
468
469                                                         macro_rules! encode_and_send_msg {
470                                                                 ($msg: expr, $msg_code: expr) => {
471                                                                         {
472                                                                                 log_trace!(self, "Encoding and sending message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
473                                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
474                                                                                 peers.peers_needing_send.insert(peer_descriptor.clone());
475                                                                         }
476                                                                 }
477                                                         }
478
479                                                         macro_rules! try_potential_handleerror {
480                                                                 ($thing: expr) => {
481                                                                         match $thing {
482                                                                                 Ok(x) => x,
483                                                                                 Err(e) => {
484                                                                                         match e.action {
485                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
486                                                                                                         //TODO: Try to push msg
487                                                                                                         log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
488                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
489                                                                                                 },
490                                                                                                 msgs::ErrorAction::IgnoreError => {
491                                                                                                         log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
492                                                                                                         continue;
493                                                                                                 },
494                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
495                                                                                                         log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
496                                                                                                         encode_and_send_msg!(msg, 17);
497                                                                                                         continue;
498                                                                                                 },
499                                                                                         }
500                                                                                 }
501                                                                         };
502                                                                 }
503                                                         }
504
505                                                         macro_rules! try_potential_decodeerror {
506                                                                 ($thing: expr) => {
507                                                                         match $thing {
508                                                                                 Ok(x) => x,
509                                                                                 Err(e) => {
510                                                                                         match e {
511                                                                                                 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError{ no_connection_possible: false }),
512                                                                                                 msgs::DecodeError::UnknownRequiredFeature => {
513                                                                                                         log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
514                                                                                                         continue;
515                                                                                                 },
516                                                                                                 msgs::DecodeError::InvalidValue => {
517                                                                                                         log_debug!(self, "Got an invalid value while deserializing message");
518                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
519                                                                                                 },
520                                                                                                 msgs::DecodeError::ShortRead => {
521                                                                                                         log_debug!(self, "Deserialization failed due to shortness of message");
522                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
523                                                                                                 },
524                                                                                                 msgs::DecodeError::ExtraAddressesPerType => {
525                                                                                                         log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
526                                                                                                         continue;
527                                                                                                 },
528                                                                                                 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
529                                                                                                 msgs::DecodeError::Io(_) => return Err(PeerHandleError{ no_connection_possible: false }),
530                                                                                         }
531                                                                                 }
532                                                                         };
533                                                                 }
534                                                         }
535
536                                                         macro_rules! insert_node_id {
537                                                                 () => {
538                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
539                                                                                 hash_map::Entry::Occupied(_) => {
540                                                                                         log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
541                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
542                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
543                                                                                 },
544                                                                                 hash_map::Entry::Vacant(entry) => {
545                                                                                         log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
546                                                                                         entry.insert(peer_descriptor.clone())
547                                                                                 },
548                                                                         };
549                                                                 }
550                                                         }
551
552                                                         let next_step = peer.channel_encryptor.get_noise_step();
553                                                         match next_step {
554                                                                 NextNoiseStep::ActOne => {
555                                                                         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();
556                                                                         peer.pending_outbound_buffer.push_back(act_two);
557                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
558                                                                 },
559                                                                 NextNoiseStep::ActTwo => {
560                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
561                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
562                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
563                                                                         peer.pending_read_is_header = true;
564
565                                                                         peer.their_node_id = Some(their_node_id);
566                                                                         insert_node_id!();
567                                                                         let mut local_features = msgs::LocalFeatures::new();
568                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
569                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
570                                                                                 local_features.set_initial_routing_sync();
571                                                                         }
572                                                                         encode_and_send_msg!(msgs::Init {
573                                                                                 global_features: msgs::GlobalFeatures::new(),
574                                                                                 local_features,
575                                                                         }, 16);
576                                                                 },
577                                                                 NextNoiseStep::ActThree => {
578                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
579                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
580                                                                         peer.pending_read_is_header = true;
581                                                                         peer.their_node_id = Some(their_node_id);
582                                                                         insert_node_id!();
583                                                                 },
584                                                                 NextNoiseStep::NoiseComplete => {
585                                                                         if peer.pending_read_is_header {
586                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
587                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
588                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
589                                                                                 if msg_len < 2 { // Need at least the message type tag
590                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
591                                                                                 }
592                                                                                 peer.pending_read_is_header = false;
593                                                                         } else {
594                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
595                                                                                 assert!(msg_data.len() >= 2);
596
597                                                                                 // Reset read buffer
598                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
599                                                                                 peer.pending_read_is_header = true;
600
601                                                                                 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
602                                                                                 log_trace!(self, "Received message of type {} from {}", msg_type, log_pubkey!(peer.their_node_id.unwrap()));
603                                                                                 if msg_type != 16 && peer.their_global_features.is_none() {
604                                                                                         // Need an init message as first message
605                                                                                         log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
606                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
607                                                                                 }
608                                                                                 let mut reader = ::std::io::Cursor::new(&msg_data[2..]);
609                                                                                 match msg_type {
610                                                                                         // Connection control:
611                                                                                         16 => {
612                                                                                                 let msg = try_potential_decodeerror!(msgs::Init::read(&mut reader));
613                                                                                                 if msg.global_features.requires_unknown_bits() {
614                                                                                                         log_info!(self, "Peer global features required unknown version bits");
615                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
616                                                                                                 }
617                                                                                                 if msg.local_features.requires_unknown_bits() {
618                                                                                                         log_info!(self, "Peer local features required unknown version bits");
619                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
620                                                                                                 }
621                                                                                                 if peer.their_global_features.is_some() {
622                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
623                                                                                                 }
624
625                                                                                                 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
626                                                                                                         if msg.local_features.supports_data_loss_protect() { "supported" } else { "not supported"},
627                                                                                                         if msg.local_features.initial_routing_sync() { "requested" } else { "not requested" },
628                                                                                                         if msg.local_features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
629                                                                                                         if msg.local_features.supports_unknown_bits() { "present" } else { "none" },
630                                                                                                         if msg.global_features.supports_unknown_bits() { "present" } else { "none" });
631
632                                                                                                 if msg.local_features.initial_routing_sync() {
633                                                                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
634                                                                                                         peers.peers_needing_send.insert(peer_descriptor.clone());
635                                                                                                 }
636                                                                                                 peer.their_global_features = Some(msg.global_features);
637                                                                                                 peer.their_local_features = Some(msg.local_features);
638
639                                                                                                 if !peer.outbound {
640                                                                                                         let mut local_features = msgs::LocalFeatures::new();
641                                                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
642                                                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
643                                                                                                                 local_features.set_initial_routing_sync();
644                                                                                                         }
645
646                                                                                                         encode_and_send_msg!(msgs::Init {
647                                                                                                                 global_features: msgs::GlobalFeatures::new(),
648                                                                                                                 local_features,
649                                                                                                         }, 16);
650                                                                                                 }
651
652                                                                                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap());
653                                                                                         },
654                                                                                         17 => {
655                                                                                                 let msg = try_potential_decodeerror!(msgs::ErrorMessage::read(&mut reader));
656                                                                                                 let mut data_is_printable = true;
657                                                                                                 for b in msg.data.bytes() {
658                                                                                                         if b < 32 || b > 126 {
659                                                                                                                 data_is_printable = false;
660                                                                                                                 break;
661                                                                                                         }
662                                                                                                 }
663
664                                                                                                 if data_is_printable {
665                                                                                                         log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
666                                                                                                 } else {
667                                                                                                         log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
668                                                                                                 }
669                                                                                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
670                                                                                                 if msg.channel_id == [0; 32] {
671                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
672                                                                                                 }
673                                                                                         },
674
675                                                                                         18 => {
676                                                                                                 let msg = try_potential_decodeerror!(msgs::Ping::read(&mut reader));
677                                                                                                 if msg.ponglen < 65532 {
678                                                                                                         let resp = msgs::Pong { byteslen: msg.ponglen };
679                                                                                                         encode_and_send_msg!(resp, 19);
680                                                                                                 }
681                                                                                         },
682                                                                                         19 => {
683                                                                                                 try_potential_decodeerror!(msgs::Pong::read(&mut reader));
684                                                                                         },
685
686                                                                                         // Channel control:
687                                                                                         32 => {
688                                                                                                 let msg = try_potential_decodeerror!(msgs::OpenChannel::read(&mut reader));
689                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
690                                                                                         },
691                                                                                         33 => {
692                                                                                                 let msg = try_potential_decodeerror!(msgs::AcceptChannel::read(&mut reader));
693                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
694                                                                                         },
695
696                                                                                         34 => {
697                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingCreated::read(&mut reader));
698                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
699                                                                                         },
700                                                                                         35 => {
701                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingSigned::read(&mut reader));
702                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
703                                                                                         },
704                                                                                         36 => {
705                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingLocked::read(&mut reader));
706                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
707                                                                                         },
708
709                                                                                         38 => {
710                                                                                                 let msg = try_potential_decodeerror!(msgs::Shutdown::read(&mut reader));
711                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
712                                                                                         },
713                                                                                         39 => {
714                                                                                                 let msg = try_potential_decodeerror!(msgs::ClosingSigned::read(&mut reader));
715                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
716                                                                                         },
717
718                                                                                         128 => {
719                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::read(&mut reader));
720                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
721                                                                                         },
722                                                                                         130 => {
723                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::read(&mut reader));
724                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
725                                                                                         },
726                                                                                         131 => {
727                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::read(&mut reader));
728                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
729                                                                                         },
730                                                                                         135 => {
731                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::read(&mut reader));
732                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
733                                                                                         },
734
735                                                                                         132 => {
736                                                                                                 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::read(&mut reader));
737                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
738                                                                                         },
739                                                                                         133 => {
740                                                                                                 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::read(&mut reader));
741                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
742                                                                                         },
743                                                                                         134 => {
744                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFee::read(&mut reader));
745                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
746                                                                                         },
747                                                                                         136 => {
748                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelReestablish::read(&mut reader));
749                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg));
750                                                                                         },
751
752                                                                                         // Routing control:
753                                                                                         259 => {
754                                                                                                 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::read(&mut reader));
755                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
756                                                                                         },
757                                                                                         256 => {
758                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::read(&mut reader));
759                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
760
761                                                                                                 if should_forward {
762                                                                                                         // TODO: forward msg along to all our other peers!
763                                                                                                 }
764                                                                                         },
765                                                                                         257 => {
766                                                                                                 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::read(&mut reader));
767                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
768
769                                                                                                 if should_forward {
770                                                                                                         // TODO: forward msg along to all our other peers!
771                                                                                                 }
772                                                                                         },
773                                                                                         258 => {
774                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::read(&mut reader));
775                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
776
777                                                                                                 if should_forward {
778                                                                                                         // TODO: forward msg along to all our other peers!
779                                                                                                 }
780                                                                                         },
781                                                                                         _ => {
782                                                                                                 if (msg_type & 1) == 0 {
783                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
784                                                                                                 }
785                                                                                         },
786                                                                                 }
787                                                                         }
788                                                                 }
789                                                         }
790                                                 }
791                                         }
792
793                                         self.do_attempt_write_data(peer_descriptor, peer);
794
795                                         peer.pending_outbound_buffer.len() > 10 // pause_read
796                                 }
797                         };
798
799                         pause_read
800                 };
801
802                 Ok(pause_read)
803         }
804
805         /// Checks for any events generated by our handlers and processes them. Includes sending most
806         /// response messages as well as messages generated by calls to handler functions directly (eg
807         /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
808         pub fn process_events(&self) {
809                 {
810                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
811                         // buffer by doing things like announcing channels on another node. We should be willing to
812                         // drop optional-ish messages when send buffers get full!
813
814                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
815                         let mut peers_lock = self.peers.lock().unwrap();
816                         let peers = peers_lock.borrow_parts();
817                         for event in events_generated.drain(..) {
818                                 macro_rules! get_peer_for_forwarding {
819                                         ($node_id: expr, $handle_no_such_peer: block) => {
820                                                 {
821                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
822                                                                 Some(descriptor) => descriptor.clone(),
823                                                                 None => {
824                                                                         $handle_no_such_peer;
825                                                                         continue;
826                                                                 },
827                                                         };
828                                                         match peers.peers.get_mut(&descriptor) {
829                                                                 Some(peer) => {
830                                                                         if peer.their_global_features.is_none() {
831                                                                                 $handle_no_such_peer;
832                                                                                 continue;
833                                                                         }
834                                                                         (descriptor, peer)
835                                                                 },
836                                                                 None => panic!("Inconsistent peers set state!"),
837                                                         }
838                                                 }
839                                         }
840                                 }
841                                 match event {
842                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
843                                                 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
844                                                                 log_pubkey!(node_id),
845                                                                 log_bytes!(msg.temporary_channel_id));
846                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
847                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
848                                                         });
849                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 33)));
850                                                 self.do_attempt_write_data(&mut descriptor, peer);
851                                         },
852                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
853                                                 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
854                                                                 log_pubkey!(node_id),
855                                                                 log_bytes!(msg.temporary_channel_id));
856                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
857                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
858                                                         });
859                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
860                                                 self.do_attempt_write_data(&mut descriptor, peer);
861                                         },
862                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
863                                                 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
864                                                                 log_pubkey!(node_id),
865                                                                 log_bytes!(msg.temporary_channel_id),
866                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
867                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
868                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
869                                                                 //they should just throw away this funding transaction
870                                                         });
871                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
872                                                 self.do_attempt_write_data(&mut descriptor, peer);
873                                         },
874                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
875                                                 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
876                                                                 log_pubkey!(node_id),
877                                                                 log_bytes!(msg.channel_id));
878                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
879                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
880                                                                 //they should just throw away this funding transaction
881                                                         });
882                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 35)));
883                                                 self.do_attempt_write_data(&mut descriptor, peer);
884                                         },
885                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
886                                                 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
887                                                                 log_pubkey!(node_id),
888                                                                 log_bytes!(msg.channel_id));
889                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
890                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
891                                                         });
892                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
893                                                 self.do_attempt_write_data(&mut descriptor, peer);
894                                         },
895                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
896                                                 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
897                                                                 log_pubkey!(node_id),
898                                                                 log_bytes!(msg.channel_id));
899                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
900                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
901                                                                 //they should just throw away this funding transaction
902                                                         });
903                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 259)));
904                                                 self.do_attempt_write_data(&mut descriptor, peer);
905                                         },
906                                         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 } } => {
907                                                 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
908                                                                 log_pubkey!(node_id),
909                                                                 update_add_htlcs.len(),
910                                                                 update_fulfill_htlcs.len(),
911                                                                 update_fail_htlcs.len(),
912                                                                 log_bytes!(commitment_signed.channel_id));
913                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
914                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
915                                                         });
916                                                 for msg in update_add_htlcs {
917                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
918                                                 }
919                                                 for msg in update_fulfill_htlcs {
920                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
921                                                 }
922                                                 for msg in update_fail_htlcs {
923                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
924                                                 }
925                                                 for msg in update_fail_malformed_htlcs {
926                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135)));
927                                                 }
928                                                 if let &Some(ref msg) = update_fee {
929                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 134)));
930                                                 }
931                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed, 132)));
932                                                 self.do_attempt_write_data(&mut descriptor, peer);
933                                         },
934                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
935                                                 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
936                                                                 log_pubkey!(node_id),
937                                                                 log_bytes!(msg.channel_id));
938                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
939                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
940                                                         });
941                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 133)));
942                                                 self.do_attempt_write_data(&mut descriptor, peer);
943                                         },
944                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
945                                                 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
946                                                                 log_pubkey!(node_id),
947                                                                 log_bytes!(msg.channel_id));
948                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
949                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
950                                                         });
951                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 39)));
952                                                 self.do_attempt_write_data(&mut descriptor, peer);
953                                         },
954                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
955                                                 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
956                                                                 log_pubkey!(node_id),
957                                                                 log_bytes!(msg.channel_id));
958                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
959                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
960                                                         });
961                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
962                                                 self.do_attempt_write_data(&mut descriptor, peer);
963                                         },
964                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
965                                                 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
966                                                                 log_pubkey!(node_id),
967                                                                 log_bytes!(msg.channel_id));
968                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
969                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
970                                                         });
971                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 136)));
972                                                 self.do_attempt_write_data(&mut descriptor, peer);
973                                         },
974                                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
975                                                 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
976                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
977                                                         let encoded_msg = encode_msg!(msg, 256);
978                                                         let encoded_update_msg = encode_msg!(update_msg, 258);
979
980                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
981                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
982                                                                                 !peer.should_forward_channel(msg.contents.short_channel_id) {
983                                                                         continue
984                                                                 }
985                                                                 match peer.their_node_id {
986                                                                         None => continue,
987                                                                         Some(their_node_id) => {
988                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
989                                                                                         continue
990                                                                                 }
991                                                                         }
992                                                                 }
993                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
994                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
995                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
996                                                         }
997                                                 }
998                                         },
999                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1000                                                 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1001                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
1002                                                         let encoded_msg = encode_msg!(msg, 258);
1003
1004                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
1005                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
1006                                                                                 !peer.should_forward_channel(msg.contents.short_channel_id)  {
1007                                                                         continue
1008                                                                 }
1009                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1010                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1011                                                         }
1012                                                 }
1013                                         },
1014                                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1015                                                 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1016                                         },
1017                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1018                                                 match *action {
1019                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1020                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1021                                                                         peers.peers_needing_send.remove(&descriptor);
1022                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
1023                                                                                 if let Some(ref msg) = *msg {
1024                                                                                         log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1025                                                                                                         log_pubkey!(node_id),
1026                                                                                                         msg.data);
1027                                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1028                                                                                         // This isn't guaranteed to work, but if there is enough free
1029                                                                                         // room in the send buffer, put the error message there...
1030                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1031                                                                                 } else {
1032                                                                                         log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1033                                                                                 }
1034                                                                         }
1035                                                                         descriptor.disconnect_socket();
1036                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1037                                                                 }
1038                                                         },
1039                                                         msgs::ErrorAction::IgnoreError => {},
1040                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1041                                                                 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1042                                                                                 log_pubkey!(node_id),
1043                                                                                 msg.data);
1044                                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1045                                                                         //TODO: Do whatever we're gonna do for handling dropped messages
1046                                                                 });
1047                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1048                                                                 self.do_attempt_write_data(&mut descriptor, peer);
1049                                                         },
1050                                                 }
1051                                         }
1052                                 }
1053                         }
1054
1055                         for mut descriptor in peers.peers_needing_send.drain() {
1056                                 match peers.peers.get_mut(&descriptor) {
1057                                         Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1058                                         None => panic!("Inconsistent peers set state!"),
1059                                 }
1060                         }
1061                 }
1062         }
1063
1064         /// Indicates that the given socket descriptor's connection is now closed.
1065         ///
1066         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
1067         /// but must NOT be called if a PeerHandleError was provided out of a new_\*\_connection event!
1068         ///
1069         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1070         pub fn disconnect_event(&self, descriptor: &Descriptor) {
1071                 self.disconnect_event_internal(descriptor, false);
1072         }
1073
1074         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1075                 let mut peers = self.peers.lock().unwrap();
1076                 peers.peers_needing_send.remove(descriptor);
1077                 let peer_option = peers.peers.remove(descriptor);
1078                 match peer_option {
1079                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1080                         Some(peer) => {
1081                                 match peer.their_node_id {
1082                                         Some(node_id) => {
1083                                                 peers.node_id_to_descriptor.remove(&node_id);
1084                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1085                                         },
1086                                         None => {}
1087                                 }
1088                         }
1089                 };
1090         }
1091 }
1092
1093 #[cfg(test)]
1094 mod tests {
1095         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1096         use ln::msgs;
1097         use util::events;
1098         use util::test_utils;
1099         use util::logger::Logger;
1100
1101         use secp256k1::Secp256k1;
1102         use secp256k1::key::{SecretKey, PublicKey};
1103
1104         use rand::{thread_rng, Rng};
1105
1106         use std::sync::{Arc};
1107
1108         #[derive(PartialEq, Eq, Clone, Hash)]
1109         struct FileDescriptor {
1110                 fd: u16,
1111         }
1112
1113         impl SocketDescriptor for FileDescriptor {
1114                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1115                         data.len()
1116                 }
1117
1118                 fn disconnect_socket(&mut self) {}
1119         }
1120
1121         fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
1122                 let mut peers = Vec::new();
1123                 let mut rng = thread_rng();
1124                 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1125                 let mut ephemeral_bytes = [0; 32];
1126                 rng.fill_bytes(&mut ephemeral_bytes);
1127
1128                 for _ in 0..peer_count {
1129                         let chan_handler = test_utils::TestChannelMessageHandler::new();
1130                         let router = test_utils::TestRoutingMessageHandler::new();
1131                         let node_id = {
1132                                 let mut key_slice = [0;32];
1133                                 rng.fill_bytes(&mut key_slice);
1134                                 SecretKey::from_slice(&key_slice).unwrap()
1135                         };
1136                         let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
1137                         let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1138                         peers.push(peer);
1139                 }
1140
1141                 peers
1142         }
1143
1144         fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
1145                 let secp_ctx = Secp256k1::new();
1146                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
1147                 let fd = FileDescriptor { fd: 1};
1148                 peer_a.new_inbound_connection(fd.clone()).unwrap();
1149                 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
1150         }
1151
1152         #[test]
1153         fn test_disconnect_peer() {
1154                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1155                 // push a DisconnectPeer event to remove the node flagged by id
1156                 let mut peers = create_network(2);
1157                 establish_connection(&peers[0], &peers[1]);
1158                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1159
1160                 let secp_ctx = Secp256k1::new();
1161                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1162
1163                 let chan_handler = test_utils::TestChannelMessageHandler::new();
1164                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1165                         node_id: their_id,
1166                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
1167                 });
1168                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1169                 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
1170
1171                 peers[0].process_events();
1172                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1173         }
1174 }