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