Merge pull request #34 from TheBlueMatt/master
[rust-lightning] / src / ln / peer_handler.rs
1 use secp256k1::key::{SecretKey,PublicKey};
2
3 use ln::msgs;
4 use ln::msgs::{MsgEncodable,MsgDecodable};
5 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
6 use util::byte_utils;
7 use util::events::{EventsProvider,Event};
8
9 use std::collections::{HashMap,LinkedList};
10 use std::sync::{Arc, Mutex};
11 use std::sync::atomic::{AtomicUsize, Ordering};
12 use std::{cmp,error,mem,hash,fmt};
13
14 pub struct MessageHandler {
15         pub chan_handler: Arc<msgs::ChannelMessageHandler>,
16         pub route_handler: Arc<msgs::RoutingMessageHandler>,
17 }
18
19 /// Provides an object which can be used to send data to and which uniquely identifies a connection
20 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
21 /// implement Hash to meet the PeerManager API.
22 /// For efficiency, Clone should be relatively cheap for this type.
23 /// You probably want to just extend an int and put a file descriptor in a struct and implement
24 /// send_data.
25 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
26         /// Attempts to send some data from the given Vec starting at the given offset to the peer.
27         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
28         /// Note that in the disconnected case, a disconnect_event must still fire and further write
29         /// attempts may occur until that time.
30         /// If the returned size is smaller than data.len() - write_offset, a write_available event must
31         /// trigger the next time more data can be written. Additionally, until the a send_data event
32         /// completes fully, no further read_events should trigger on the same peer!
33         /// If a read_event on this descriptor had previously returned true (indicating that read
34         /// events should be paused to prevent DoS in the send buffer), resume_read may be set
35         /// indicating that read events on this descriptor should resume. A resume_read of false does
36         /// *not* imply that further read events should be paused.
37         fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
38 }
39
40 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
41 /// generate no further read/write_events for the descriptor, only triggering a single
42 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
43 /// no such disconnect_event must be generated and the socket be silently disconencted).
44 pub struct PeerHandleError {
45         no_connection_possible: bool,
46 }
47 impl fmt::Debug for PeerHandleError {
48         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
49                 formatter.write_str("Peer Sent Invalid Data")
50         }
51 }
52 impl fmt::Display for PeerHandleError {
53         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
54                 formatter.write_str("Peer Sent Invalid Data")
55         }
56 }
57 impl error::Error for PeerHandleError {
58         fn description(&self) -> &str {
59                 "Peer Sent Invalid Data"
60         }
61 }
62
63 struct Peer {
64         channel_encryptor: PeerChannelEncryptor,
65         outbound: bool,
66         their_node_id: Option<PublicKey>,
67         their_global_features: Option<msgs::GlobalFeatures>,
68         their_local_features: Option<msgs::LocalFeatures>,
69
70         pending_outbound_buffer: LinkedList<Vec<u8>>,
71         pending_outbound_buffer_first_msg_offset: usize,
72         awaiting_write_event: bool,
73
74         pending_read_buffer: Vec<u8>,
75         pending_read_buffer_pos: usize,
76         pending_read_is_header: bool,
77 }
78
79 struct PeerHolder<Descriptor: SocketDescriptor> {
80         peers: HashMap<Descriptor, Peer>,
81         /// Only add to this set when noise completes:
82         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
83 }
84
85 pub struct PeerManager<Descriptor: SocketDescriptor> {
86         message_handler: MessageHandler,
87         peers: Mutex<PeerHolder<Descriptor>>,
88         pending_events: Mutex<Vec<Event>>,
89         our_node_secret: SecretKey,
90         initial_syncs_sent: AtomicUsize,
91 }
92
93
94 macro_rules! encode_msg {
95         ($msg: expr, $msg_code: expr) => {
96                 {
97                         let just_msg = $msg.encode();
98                         let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
99                         encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
100                         encoded_msg.extend_from_slice(&just_msg[..]);
101                         encoded_msg
102                 }
103         }
104 }
105
106 //TODO: Really should do something smarter for this
107 const INITIAL_SYNCS_TO_SEND: usize = 5;
108
109 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
110 /// PeerIds may repeat, but only after disconnect_event() has been called.
111 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
112         pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
113                 PeerManager {
114                         message_handler: message_handler,
115                         peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
116                         pending_events: Mutex::new(Vec::new()),
117                         our_node_secret: our_node_secret,
118                         initial_syncs_sent: AtomicUsize::new(0),
119                 }
120         }
121
122         /// Indicates a new outbound connection has been established to a node with the given node_id.
123         /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
124         /// descriptor but must disconnect the connection immediately.
125         /// Returns some bytes to send to the remote node.
126         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
127         /// disconnect_event.
128         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
129                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
130                 let res = peer_encryptor.get_act_one().to_vec();
131                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
132
133                 let mut peers = self.peers.lock().unwrap();
134                 if peers.peers.insert(descriptor, Peer {
135                         channel_encryptor: peer_encryptor,
136                         outbound: true,
137                         their_node_id: Some(their_node_id),
138                         their_global_features: None,
139                         their_local_features: None,
140
141                         pending_outbound_buffer: LinkedList::new(),
142                         pending_outbound_buffer_first_msg_offset: 0,
143                         awaiting_write_event: false,
144
145                         pending_read_buffer: pending_read_buffer,
146                         pending_read_buffer_pos: 0,
147                         pending_read_is_header: false,
148                 }).is_some() {
149                         panic!("PeerManager driver duplicated descriptors!");
150                 };
151                 Ok(res)
152         }
153
154         /// Indicates a new inbound connection has been established.
155         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
156         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
157         /// call disconnect_event for the new descriptor but must disconnect the connection
158         /// immediately.
159         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
160         /// disconnect_event.
161         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
162                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
163                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
164
165                 let mut peers = self.peers.lock().unwrap();
166                 if peers.peers.insert(descriptor, Peer {
167                         channel_encryptor: peer_encryptor,
168                         outbound: false,
169                         their_node_id: None,
170                         their_global_features: None,
171                         their_local_features: None,
172
173                         pending_outbound_buffer: LinkedList::new(),
174                         pending_outbound_buffer_first_msg_offset: 0,
175                         awaiting_write_event: false,
176
177                         pending_read_buffer: pending_read_buffer,
178                         pending_read_buffer_pos: 0,
179                         pending_read_is_header: false,
180                 }).is_some() {
181                         panic!("PeerManager driver duplicated descriptors!");
182                 };
183                 Ok(())
184         }
185
186         fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
187                 while !peer.awaiting_write_event {
188                         if {
189                                 let next_buff = match peer.pending_outbound_buffer.front() {
190                                         None => return,
191                                         Some(buff) => buff,
192                                 };
193                                 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
194
195                                 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
196                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
197                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
198                         } {
199                                 peer.pending_outbound_buffer_first_msg_offset = 0;
200                                 peer.pending_outbound_buffer.pop_front();
201                         } else {
202                                 peer.awaiting_write_event = true;
203                         }
204                 }
205         }
206
207         /// Indicates that there is room to write data to the given socket descriptor.
208         /// May return an Err to indicate that the connection should be closed.
209         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
210         /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
211         /// invariants around calling write_event in case a write did not fully complete must still
212         /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
213         /// Panics if the descriptor was not previously registered in a new_*_connection event.
214         pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
215                 let mut peers = self.peers.lock().unwrap();
216                 match peers.peers.get_mut(descriptor) {
217                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
218                         Some(peer) => {
219                                 peer.awaiting_write_event = false;
220                                 Self::do_attempt_write_data(descriptor, peer);
221                         }
222                 };
223                 Ok(())
224         }
225
226         /// Indicates that data was read from the given socket descriptor.
227         /// May return an Err to indicate that the connection should be closed.
228         /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
229         /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
230         /// invariants around calling write_event in case a write did not fully complete must still
231         /// hold. Note that this function will often call send_data on many peers before returning, not
232         /// just this peer!
233         /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
234         /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
235         /// that this must be true even if a send_data call with resume_read=true was made during the
236         /// course of this function!
237         /// Panics if the descriptor was not previously registered in a new_*_connection event.
238         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
239                 match self.do_read_event(peer_descriptor, data) {
240                         Ok(res) => Ok(res),
241                         Err(e) => {
242                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
243                                 Err(e)
244                         }
245                 }
246         }
247
248         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
249                 let pause_read = {
250                         let mut peers = self.peers.lock().unwrap();
251                         let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
252                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
253                                 Some(peer) => {
254                                         assert!(peer.pending_read_buffer.len() > 0);
255                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
256
257                                         let mut insert_node_id = None;
258                                         let mut read_pos = 0;
259                                         while read_pos < data.len() {
260                                                 {
261                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
262                                                         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]);
263                                                         read_pos += data_to_copy;
264                                                         peer.pending_read_buffer_pos += data_to_copy;
265                                                 }
266
267                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
268                                                         peer.pending_read_buffer_pos = 0;
269
270                                                         macro_rules! encode_and_send_msg {
271                                                                 ($msg: expr, $msg_code: expr) => {
272                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
273                                                                 }
274                                                         }
275
276                                                         macro_rules! try_potential_handleerror {
277                                                                 ($thing: expr) => {
278                                                                         match $thing {
279                                                                                 Ok(x) => x,
280                                                                                 Err(e) => {
281                                                                                         println!("Got error handling message: {}!", e.err);
282                                                                                         if let Some(action) = e.msg {
283                                                                                                 match action {
284                                                                                                         msgs::ErrorAction::UpdateFailHTLC { msg } => {
285                                                                                                                 encode_and_send_msg!(msg, 131);
286                                                                                                                 continue;
287                                                                                                         },
288                                                                                                         msgs::ErrorAction::DisconnectPeer => {
289                                                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
290                                                                                                         },
291                                                                                                         msgs::ErrorAction::IgnoreError => {
292                                                                                                                 continue;
293                                                                                                         },
294                                                                                                 }
295                                                                                         } else {
296                                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
297                                                                                         }
298                                                                                 }
299                                                                         };
300                                                                 }
301                                                         }
302
303                                                         macro_rules! try_potential_decodeerror {
304                                                                 ($thing: expr) => {
305                                                                         match $thing {
306                                                                                 Ok(x) => x,
307                                                                                 Err(_e) => {
308                                                                                         println!("Error decoding message");
309                                                                                         //TODO: Handle e?
310                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
311                                                                                 }
312                                                                         };
313                                                                 }
314                                                         }
315
316                                                         macro_rules! try_ignore_potential_decodeerror {
317                                                                 ($thing: expr) => {
318                                                                         match $thing {
319                                                                                 Ok(x) => x,
320                                                                                 Err(_e) => {
321                                                                                         println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
322                                                                                         continue;
323                                                                                 }
324                                                                         };
325                                                                 }
326                                                         }
327
328                                                         let next_step = peer.channel_encryptor.get_noise_step();
329                                                         match next_step {
330                                                                 NextNoiseStep::ActOne => {
331                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
332                                                                         peer.pending_outbound_buffer.push_back(act_two);
333                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
334                                                                 },
335                                                                 NextNoiseStep::ActTwo => {
336                                                                         let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
337                                                                         peer.pending_outbound_buffer.push_back(act_three);
338                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
339                                                                         peer.pending_read_is_header = true;
340
341                                                                         insert_node_id = Some(peer.their_node_id.unwrap());
342                                                                         let mut local_features = msgs::LocalFeatures::new();
343                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
344                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
345                                                                                 local_features.set_initial_routing_sync();
346                                                                         }
347                                                                         encode_and_send_msg!(msgs::Init {
348                                                                                 global_features: msgs::GlobalFeatures::new(),
349                                                                                 local_features,
350                                                                         }, 16);
351                                                                 },
352                                                                 NextNoiseStep::ActThree => {
353                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
354                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
355                                                                         peer.pending_read_is_header = true;
356                                                                         peer.their_node_id = Some(their_node_id);
357                                                                         insert_node_id = Some(peer.their_node_id.unwrap());
358                                                                 },
359                                                                 NextNoiseStep::NoiseComplete => {
360                                                                         if peer.pending_read_is_header {
361                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
362                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
363                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
364                                                                                 if msg_len < 2 { // Need at least the message type tag
365                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
366                                                                                 }
367                                                                                 peer.pending_read_is_header = false;
368                                                                         } else {
369                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
370                                                                                 assert!(msg_data.len() >= 2);
371
372                                                                                 // Reset read buffer
373                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
374                                                                                 peer.pending_read_is_header = true;
375
376                                                                                 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
377                                                                                 if msg_type != 16 && peer.their_global_features.is_none() {
378                                                                                         // Need an init message as first message
379                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
380                                                                                 }
381                                                                                 match msg_type {
382                                                                                         // Connection control:
383                                                                                         16 => {
384                                                                                                 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
385                                                                                                 if msg.global_features.requires_unknown_bits() {
386                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
387                                                                                                 }
388                                                                                                 if msg.local_features.requires_unknown_bits() {
389                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
390                                                                                                 }
391                                                                                                 peer.their_global_features = Some(msg.global_features);
392                                                                                                 peer.their_local_features = Some(msg.local_features);
393
394                                                                                                 if !peer.outbound {
395                                                                                                         let mut local_features = msgs::LocalFeatures::new();
396                                                                                                         if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
397                                                                                                                 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
398                                                                                                                 local_features.set_initial_routing_sync();
399                                                                                                         }
400                                                                                                         encode_and_send_msg!(msgs::Init {
401                                                                                                                 global_features: msgs::GlobalFeatures::new(),
402                                                                                                                 local_features,
403                                                                                                         }, 16);
404                                                                                                 }
405                                                                                         },
406                                                                                         17 => {
407                                                                                                 // Error msg
408                                                                                         },
409
410                                                                                         18 => {
411                                                                                                 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
412                                                                                                 if msg.ponglen < 65532 {
413                                                                                                         let resp = msgs::Pong { byteslen: msg.ponglen };
414                                                                                                         encode_and_send_msg!(resp, 19);
415                                                                                                 }
416                                                                                         },
417                                                                                         19 => {
418                                                                                                 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
419                                                                                         },
420
421                                                                                         // Channel control:
422                                                                                         32 => {
423                                                                                                 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
424                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
425                                                                                                 encode_and_send_msg!(resp, 33);
426                                                                                         },
427                                                                                         33 => {
428                                                                                                 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
429                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
430                                                                                         },
431
432                                                                                         34 => {
433                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
434                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
435                                                                                                 encode_and_send_msg!(resp, 35);
436                                                                                         },
437                                                                                         35 => {
438                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
439                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
440                                                                                         },
441                                                                                         36 => {
442                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
443                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
444                                                                                                 match resp_option {
445                                                                                                         Some(resp) => encode_and_send_msg!(resp, 259),
446                                                                                                         None => {},
447                                                                                                 }
448                                                                                         },
449
450                                                                                         38 => {
451                                                                                                 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
452                                                                                                 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
453                                                                                                 if let Some(resp) = resp_options.0 {
454                                                                                                         encode_and_send_msg!(resp, 38);
455                                                                                                 }
456                                                                                                 if let Some(resp) = resp_options.1 {
457                                                                                                         encode_and_send_msg!(resp, 39);
458                                                                                                 }
459                                                                                         },
460                                                                                         39 => {
461                                                                                                 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
462                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
463                                                                                                 if let Some(resp) = resp_option {
464                                                                                                         encode_and_send_msg!(resp, 39);
465                                                                                                 }
466                                                                                         },
467
468                                                                                         128 => {
469                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
470                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
471                                                                                         },
472                                                                                         130 => {
473                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
474                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
475                                                                                         },
476                                                                                         131 => {
477                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
478                                                                                                 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
479                                                                                                 if let Some(update) = chan_update {
480                                                                                                         self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
481                                                                                                 }
482                                                                                         },
483                                                                                         135 => {
484                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
485                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
486                                                                                         },
487
488                                                                                         132 => {
489                                                                                                 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
490                                                                                                 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
491                                                                                                 encode_and_send_msg!(resps.0, 133);
492                                                                                                 if let Some(resp) = resps.1 {
493                                                                                                         encode_and_send_msg!(resp, 132);
494                                                                                                 }
495                                                                                         },
496                                                                                         133 => {
497                                                                                                 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
498                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
499                                                                                                 match resp_option {
500                                                                                                         Some(resps) => {
501                                                                                                                 for resp in resps.update_add_htlcs {
502                                                                                                                         encode_and_send_msg!(resp, 128);
503                                                                                                                 }
504                                                                                                                 for resp in resps.update_fulfill_htlcs {
505                                                                                                                         encode_and_send_msg!(resp, 130);
506                                                                                                                 }
507                                                                                                                 for resp in resps.update_fail_htlcs {
508                                                                                                                         encode_and_send_msg!(resp, 131);
509                                                                                                                 }
510                                                                                                                 encode_and_send_msg!(resps.commitment_signed, 132);
511                                                                                                         },
512                                                                                                         None => {},
513                                                                                                 }
514                                                                                         },
515                                                                                         134 => {
516                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
517                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
518                                                                                         },
519                                                                                         136 => { }, // TODO: channel_reestablish
520
521                                                                                         // Routing control:
522                                                                                         259 => {
523                                                                                                 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
524                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
525                                                                                         },
526                                                                                         256 => {
527                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
528                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
529
530                                                                                                 if should_forward {
531                                                                                                         // TODO: forward msg along to all our other peers!
532                                                                                                 }
533                                                                                         },
534                                                                                         257 => {
535                                                                                                 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
536                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
537                                                                                         },
538                                                                                         258 => {
539                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
540                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
541                                                                                         },
542                                                                                         _ => {
543                                                                                                 if (msg_type & 1) == 0 {
544                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
545                                                                                                 }
546                                                                                         },
547                                                                                 }
548                                                                         }
549                                                                 }
550                                                         }
551                                                 }
552                                         }
553
554                                         Self::do_attempt_write_data(peer_descriptor, peer);
555
556                                         (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
557                                 }
558                         };
559
560                         match should_insert_node_id {
561                                 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
562                                 None => {}
563                         };
564
565                         pause_read
566                 };
567
568                 self.process_events();
569
570                 Ok(pause_read)
571         }
572
573         /// Checks for any events generated by our handlers and processes them. May be needed after eg
574         /// calls to ChannelManager::process_pending_htlc_forward.
575         pub fn process_events(&self) {
576                 let mut upstream_events = Vec::new();
577                 {
578                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
579                         // buffer by doing things like announcing channels on another node. We should be willing to
580                         // drop optional-ish messages when send buffers get full!
581
582                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
583                         let mut peers = self.peers.lock().unwrap();
584                         for event in events_generated.drain(..) {
585                                 macro_rules! get_peer_for_forwarding {
586                                         ($node_id: expr, $handle_no_such_peer: block) => {
587                                                 {
588                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
589                                                                 Some(descriptor) => descriptor.clone(),
590                                                                 None => {
591                                                                         $handle_no_such_peer;
592                                                                         continue;
593                                                                 },
594                                                         };
595                                                         match peers.peers.get_mut(&descriptor) {
596                                                                 Some(peer) => {
597                                                                         (descriptor, peer)
598                                                                 },
599                                                                 None => panic!("Inconsistent peers set state!"),
600                                                         }
601                                                 }
602                                         }
603                                 }
604                                 match event {
605                                         Event::FundingGenerationReady {..} => { /* Hand upstream */ },
606                                         Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
607                                         Event::PaymentReceived {..} => { /* Hand upstream */ },
608                                         Event::PaymentSent {..} => { /* Hand upstream */ },
609                                         Event::PaymentFailed {..} => { /* Hand upstream */ },
610
611                                         Event::PendingHTLCsForwardable {..} => {
612                                                 //TODO: Handle upstream in some confused form so that upstream just knows
613                                                 //to call us somehow?
614                                         },
615                                         Event::SendFundingCreated { ref node_id, ref msg } => {
616                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
617                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
618                                                                 //they should just throw away this funding transaction
619                                                         });
620                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
621                                                 Self::do_attempt_write_data(&mut descriptor, peer);
622                                                 continue;
623                                         },
624                                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
625                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
626                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
627                                                         });
628                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
629                                                 match announcement_sigs {
630                                                         &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
631                                                         &None => {},
632                                                 }
633                                                 Self::do_attempt_write_data(&mut descriptor, peer);
634                                                 continue;
635                                         },
636                                         Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
637                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
638                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
639                                                         });
640                                                 for msg in msgs {
641                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
642                                                 }
643                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
644                                                 Self::do_attempt_write_data(&mut descriptor, peer);
645                                                 continue;
646                                         },
647                                         Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
648                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
649                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
650                                                         });
651                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
652                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
653                                                 Self::do_attempt_write_data(&mut descriptor, peer);
654                                                 continue;
655                                         },
656                                         Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
657                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
658                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
659                                                         });
660                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
661                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
662                                                 Self::do_attempt_write_data(&mut descriptor, peer);
663                                                 continue;
664                                         },
665                                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
666                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
667                                                         let encoded_msg = encode_msg!(msg, 256);
668                                                         let encoded_update_msg = encode_msg!(update_msg, 258);
669
670                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
671                                                                 if !peer.channel_encryptor.is_ready_for_encryption() {
672                                                                         continue
673                                                                 }
674                                                                 match peer.their_node_id {
675                                                                         None => continue,
676                                                                         Some(their_node_id) => {
677                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
678                                                                                         continue
679                                                                                 }
680                                                                         }
681                                                                 }
682                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
683                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
684                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
685                                                         }
686                                                 }
687                                                 continue;
688                                         },
689                                         Event::BroadcastChannelUpdate { ref msg } => {
690                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
691                                                         let encoded_msg = encode_msg!(msg, 258);
692
693                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
694                                                                 if !peer.channel_encryptor.is_ready_for_encryption() {
695                                                                         continue
696                                                                 }
697                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
698                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
699                                                         }
700                                                 }
701                                                 continue;
702                                         },
703                                 }
704
705                                 upstream_events.push(event);
706                         }
707                 }
708
709                 let mut pending_events = self.pending_events.lock().unwrap();
710                 for event in upstream_events.drain(..) {
711                         pending_events.push(event);
712                 }
713         }
714
715         /// Indicates that the given socket descriptor's connection is now closed.
716         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
717         /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
718         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
719         pub fn disconnect_event(&self, descriptor: &Descriptor) {
720                 self.disconnect_event_internal(descriptor, false);
721         }
722
723         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
724                 let mut peers = self.peers.lock().unwrap();
725                 let peer_option = peers.peers.remove(descriptor);
726                 match peer_option {
727                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
728                         Some(peer) => {
729                                 match peer.their_node_id {
730                                         Some(node_id) => {
731                                                 peers.node_id_to_descriptor.remove(&node_id);
732                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
733                                         },
734                                         None => {}
735                                 }
736                         }
737                 };
738         }
739 }
740
741 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
742         fn get_and_clear_pending_events(&self) -> Vec<Event> {
743                 let mut pending_events = self.pending_events.lock().unwrap();
744                 let mut ret = Vec::new();
745                 mem::swap(&mut ret, &mut *pending_events);
746                 ret
747         }
748 }