Support responding to Ping messages in peer_handler
[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                                                                                         println!("Got error handling message: {}!", 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                                                                                                         msgs::ErrorAction::IgnoreError => {
286                                                                                                                 continue;
287                                                                                                         },
288                                                                                                 }
289                                                                                         } else {
290                                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
291                                                                                         }
292                                                                                 }
293                                                                         };
294                                                                 }
295                                                         }
296
297                                                         macro_rules! try_potential_decodeerror {
298                                                                 ($thing: expr) => {
299                                                                         match $thing {
300                                                                                 Ok(x) => x,
301                                                                                 Err(_e) => {
302                                                                                         println!("Error decoding message");
303                                                                                         //TODO: Handle e?
304                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
305                                                                                 }
306                                                                         };
307                                                                 }
308                                                         }
309
310                                                         macro_rules! try_ignore_potential_decodeerror {
311                                                                 ($thing: expr) => {
312                                                                         match $thing {
313                                                                                 Ok(x) => x,
314                                                                                 Err(_e) => {
315                                                                                         println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
316                                                                                         continue;
317                                                                                 }
318                                                                         };
319                                                                 }
320                                                         }
321
322                                                         let next_step = peer.channel_encryptor.get_noise_step();
323                                                         match next_step {
324                                                                 NextNoiseStep::ActOne => {
325                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
326                                                                         peer.pending_outbound_buffer.push_back(act_two);
327                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
328                                                                 },
329                                                                 NextNoiseStep::ActTwo => {
330                                                                         let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
331                                                                         peer.pending_outbound_buffer.push_back(act_three);
332                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
333                                                                         peer.pending_read_is_header = true;
334
335                                                                         insert_node_id = Some(peer.their_node_id.unwrap());
336                                                                         encode_and_send_msg!(msgs::Init {
337                                                                                 global_features: msgs::GlobalFeatures::new(),
338                                                                                 local_features: msgs::LocalFeatures::new(),
339                                                                         }, 16);
340                                                                 },
341                                                                 NextNoiseStep::ActThree => {
342                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
343                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
344                                                                         peer.pending_read_is_header = true;
345                                                                         peer.their_node_id = Some(their_node_id);
346                                                                         insert_node_id = Some(peer.their_node_id.unwrap());
347                                                                 },
348                                                                 NextNoiseStep::NoiseComplete => {
349                                                                         if peer.pending_read_is_header {
350                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
351                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
352                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
353                                                                                 if msg_len < 2 { // Need at least the message type tag
354                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
355                                                                                 }
356                                                                                 peer.pending_read_is_header = false;
357                                                                         } else {
358                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
359                                                                                 assert!(msg_data.len() >= 2);
360
361                                                                                 // Reset read buffer
362                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
363                                                                                 peer.pending_read_is_header = true;
364
365                                                                                 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
366                                                                                 if msg_type != 16 && peer.their_global_features.is_none() {
367                                                                                         // Need an init message as first message
368                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
369                                                                                 }
370                                                                                 match msg_type {
371                                                                                         // Connection control:
372                                                                                         16 => {
373                                                                                                 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
374                                                                                                 if msg.global_features.requires_unknown_bits() {
375                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
376                                                                                                 }
377                                                                                                 if msg.local_features.requires_unknown_bits() {
378                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
379                                                                                                 }
380                                                                                                 peer.their_global_features = Some(msg.global_features);
381                                                                                                 peer.their_local_features = Some(msg.local_features);
382
383                                                                                                 if !peer.outbound {
384                                                                                                         encode_and_send_msg!(msgs::Init {
385                                                                                                                 global_features: msgs::GlobalFeatures::new(),
386                                                                                                                 local_features: msgs::LocalFeatures::new(),
387                                                                                                         }, 16);
388                                                                                                 }
389                                                                                         },
390                                                                                         17 => {
391                                                                                                 // Error msg
392                                                                                         },
393
394                                                                                         18 => {
395                                                                                                 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
396                                                                                                 let resp = msgs::Pong { byteslen: msg.ponglen };
397                                                                                                 encode_and_send_msg!(resp, 19);
398                                                                                         },
399                                                                                         19 => {
400                                                                                                 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
401                                                                                         },
402
403                                                                                         // Channel control:
404                                                                                         32 => {
405                                                                                                 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
406                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
407                                                                                                 encode_and_send_msg!(resp, 33);
408                                                                                         },
409                                                                                         33 => {
410                                                                                                 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
411                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
412                                                                                         },
413
414                                                                                         34 => {
415                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
416                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
417                                                                                                 encode_and_send_msg!(resp, 35);
418                                                                                         },
419                                                                                         35 => {
420                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
421                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
422                                                                                         },
423                                                                                         36 => {
424                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
425                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
426                                                                                                 match resp_option {
427                                                                                                         Some(resp) => encode_and_send_msg!(resp, 259),
428                                                                                                         None => {},
429                                                                                                 }
430                                                                                         },
431
432                                                                                         38 => {
433                                                                                                 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
434                                                                                                 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
435                                                                                                 if let Some(resp) = resp_options.0 {
436                                                                                                         encode_and_send_msg!(resp, 38);
437                                                                                                 }
438                                                                                                 if let Some(resp) = resp_options.1 {
439                                                                                                         encode_and_send_msg!(resp, 39);
440                                                                                                 }
441                                                                                         },
442                                                                                         39 => {
443                                                                                                 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
444                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
445                                                                                                 if let Some(resp) = resp_option {
446                                                                                                         encode_and_send_msg!(resp, 39);
447                                                                                                 }
448                                                                                         },
449
450                                                                                         128 => {
451                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
452                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
453                                                                                         },
454                                                                                         130 => {
455                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
456                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
457                                                                                         },
458                                                                                         131 => {
459                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
460                                                                                                 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
461                                                                                                 if let Some(update) = chan_update {
462                                                                                                         self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
463                                                                                                 }
464                                                                                         },
465                                                                                         135 => {
466                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
467                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
468                                                                                         },
469
470                                                                                         132 => {
471                                                                                                 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
472                                                                                                 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
473                                                                                                 encode_and_send_msg!(resps.0, 133);
474                                                                                                 if let Some(resp) = resps.1 {
475                                                                                                         encode_and_send_msg!(resp, 132);
476                                                                                                 }
477                                                                                         },
478                                                                                         133 => {
479                                                                                                 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
480                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
481                                                                                                 match resp_option {
482                                                                                                         Some(resps) => {
483                                                                                                                 for resp in resps.update_add_htlcs {
484                                                                                                                         encode_and_send_msg!(resp, 128);
485                                                                                                                 }
486                                                                                                                 for resp in resps.update_fulfill_htlcs {
487                                                                                                                         encode_and_send_msg!(resp, 130);
488                                                                                                                 }
489                                                                                                                 for resp in resps.update_fail_htlcs {
490                                                                                                                         encode_and_send_msg!(resp, 131);
491                                                                                                                 }
492                                                                                                                 encode_and_send_msg!(resps.commitment_signed, 132);
493                                                                                                         },
494                                                                                                         None => {},
495                                                                                                 }
496                                                                                         },
497                                                                                         134 => {
498                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
499                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
500                                                                                         },
501                                                                                         136 => { }, // TODO: channel_reestablish
502
503                                                                                         // Routing control:
504                                                                                         259 => {
505                                                                                                 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
506                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
507                                                                                         },
508                                                                                         256 => {
509                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
510                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
511
512                                                                                                 if should_forward {
513                                                                                                         // TODO: forward msg along to all our other peers!
514                                                                                                 }
515                                                                                         },
516                                                                                         257 => {
517                                                                                                 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
518                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
519                                                                                         },
520                                                                                         258 => {
521                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
522                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
523                                                                                         },
524                                                                                         _ => {
525                                                                                                 if (msg_type & 1) == 0 {
526                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
527                                                                                                 }
528                                                                                         },
529                                                                                 }
530                                                                         }
531                                                                 }
532                                                         }
533                                                 }
534                                         }
535
536                                         Self::do_attempt_write_data(peer_descriptor, peer);
537
538                                         (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
539                                 }
540                         };
541
542                         match should_insert_node_id {
543                                 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
544                                 None => {}
545                         };
546
547                         pause_read
548                 };
549
550                 self.process_events();
551
552                 Ok(pause_read)
553         }
554
555         /// Checks for any events generated by our handlers and processes them. May be needed after eg
556         /// calls to ChannelManager::process_pending_htlc_forward.
557         pub fn process_events(&self) {
558                 let mut upstream_events = Vec::new();
559                 {
560                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
561                         // buffer by doing things like announcing channels on another node. We should be willing to
562                         // drop optional-ish messages when send buffers get full!
563
564                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
565                         let mut peers = self.peers.lock().unwrap();
566                         for event in events_generated.drain(..) {
567                                 macro_rules! get_peer_for_forwarding {
568                                         ($node_id: expr, $handle_no_such_peer: block) => {
569                                                 {
570                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
571                                                                 Some(descriptor) => descriptor.clone(),
572                                                                 None => {
573                                                                         $handle_no_such_peer;
574                                                                         continue;
575                                                                 },
576                                                         };
577                                                         match peers.peers.get_mut(&descriptor) {
578                                                                 Some(peer) => {
579                                                                         (descriptor, peer)
580                                                                 },
581                                                                 None => panic!("Inconsistent peers set state!"),
582                                                         }
583                                                 }
584                                         }
585                                 }
586                                 match event {
587                                         Event::FundingGenerationReady {..} => { /* Hand upstream */ },
588                                         Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
589                                         Event::PaymentReceived {..} => { /* Hand upstream */ },
590                                         Event::PaymentSent {..} => { /* Hand upstream */ },
591                                         Event::PaymentFailed {..} => { /* Hand upstream */ },
592
593                                         Event::PendingHTLCsForwardable {..} => {
594                                                 //TODO: Handle upstream in some confused form so that upstream just knows
595                                                 //to call us somehow?
596                                         },
597                                         Event::SendFundingCreated { ref node_id, ref msg } => {
598                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
599                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
600                                                                 //they should just throw away this funding transaction
601                                                         });
602                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
603                                                 Self::do_attempt_write_data(&mut descriptor, peer);
604                                                 continue;
605                                         },
606                                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
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, 36)));
611                                                 match announcement_sigs {
612                                                         &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
613                                                         &None => {},
614                                                 }
615                                                 Self::do_attempt_write_data(&mut descriptor, peer);
616                                                 continue;
617                                         },
618                                         Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
619                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
620                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
621                                                         });
622                                                 for msg in msgs {
623                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
624                                                 }
625                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
626                                                 Self::do_attempt_write_data(&mut descriptor, peer);
627                                                 continue;
628                                         },
629                                         Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
630                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
631                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
632                                                         });
633                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
634                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
635                                                 Self::do_attempt_write_data(&mut descriptor, peer);
636                                                 continue;
637                                         },
638                                         Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
639                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
640                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
641                                                         });
642                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
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::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
648                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
649                                                         let encoded_msg = encode_msg!(msg, 256);
650                                                         let encoded_update_msg = encode_msg!(update_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                                                                 match peer.their_node_id {
657                                                                         None => continue,
658                                                                         Some(their_node_id) => {
659                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
660                                                                                         continue
661                                                                                 }
662                                                                         }
663                                                                 }
664                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
665                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
666                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
667                                                         }
668                                                 }
669                                                 continue;
670                                         },
671                                         Event::BroadcastChannelUpdate { ref msg } => {
672                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
673                                                         let encoded_msg = encode_msg!(msg, 258);
674
675                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
676                                                                 if !peer.channel_encryptor.is_ready_for_encryption() {
677                                                                         continue
678                                                                 }
679                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
680                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
681                                                         }
682                                                 }
683                                                 continue;
684                                         },
685                                 }
686
687                                 upstream_events.push(event);
688                         }
689                 }
690
691                 let mut pending_events = self.pending_events.lock().unwrap();
692                 for event in upstream_events.drain(..) {
693                         pending_events.push(event);
694                 }
695         }
696
697         /// Indicates that the given socket descriptor's connection is now closed.
698         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
699         /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
700         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
701         pub fn disconnect_event(&self, descriptor: &Descriptor) {
702                 self.disconnect_event_internal(descriptor, false);
703         }
704
705         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
706                 let mut peers = self.peers.lock().unwrap();
707                 let peer_option = peers.peers.remove(descriptor);
708                 match peer_option {
709                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
710                         Some(peer) => {
711                                 match peer.their_node_id {
712                                         Some(node_id) => {
713                                                 peers.node_id_to_descriptor.remove(&node_id);
714                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
715                                         },
716                                         None => {}
717                                 }
718                         }
719                 };
720         }
721 }
722
723 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
724         fn get_and_clear_pending_events(&self) -> Vec<Event> {
725                 let mut pending_events = self.pending_events.lock().unwrap();
726                 let mut ret = Vec::new();
727                 mem::swap(&mut ret, &mut *pending_events);
728                 ret
729         }
730 }