3c4196519c5cca1700e8c008e2af97f5d76cb81d
[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                                                                                         18 => { }, // ping
394                                                                                         19 => { }, // pong
395
396                                                                                         // Channel control:
397                                                                                         32 => {
398                                                                                                 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
399                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
400                                                                                                 encode_and_send_msg!(resp, 33);
401                                                                                         },
402                                                                                         33 => {
403                                                                                                 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
404                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
405                                                                                         },
406
407                                                                                         34 => {
408                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
409                                                                                                 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
410                                                                                                 encode_and_send_msg!(resp, 35);
411                                                                                         },
412                                                                                         35 => {
413                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
414                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
415                                                                                         },
416                                                                                         36 => {
417                                                                                                 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
418                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
419                                                                                                 match resp_option {
420                                                                                                         Some(resp) => encode_and_send_msg!(resp, 259),
421                                                                                                         None => {},
422                                                                                                 }
423                                                                                         },
424
425                                                                                         38 => {
426                                                                                                 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
427                                                                                                 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
428                                                                                                 if let Some(resp) = resp_options.0 {
429                                                                                                         encode_and_send_msg!(resp, 38);
430                                                                                                 }
431                                                                                                 if let Some(resp) = resp_options.1 {
432                                                                                                         encode_and_send_msg!(resp, 39);
433                                                                                                 }
434                                                                                         },
435                                                                                         39 => {
436                                                                                                 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
437                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
438                                                                                                 if let Some(resp) = resp_option {
439                                                                                                         encode_and_send_msg!(resp, 39);
440                                                                                                 }
441                                                                                         },
442
443                                                                                         128 => {
444                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
445                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
446                                                                                         },
447                                                                                         130 => {
448                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
449                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
450                                                                                         },
451                                                                                         131 => {
452                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
453                                                                                                 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
454                                                                                                 if let Some(update) = chan_update {
455                                                                                                         self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
456                                                                                                 }
457                                                                                         },
458                                                                                         135 => {
459                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
460                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
461                                                                                         },
462
463                                                                                         132 => {
464                                                                                                 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
465                                                                                                 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
466                                                                                                 encode_and_send_msg!(resps.0, 133);
467                                                                                                 if let Some(resp) = resps.1 {
468                                                                                                         encode_and_send_msg!(resp, 132);
469                                                                                                 }
470                                                                                         },
471                                                                                         133 => {
472                                                                                                 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
473                                                                                                 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
474                                                                                                 match resp_option {
475                                                                                                         Some(resps) => {
476                                                                                                                 for resp in resps.update_add_htlcs {
477                                                                                                                         encode_and_send_msg!(resp, 128);
478                                                                                                                 }
479                                                                                                                 for resp in resps.update_fulfill_htlcs {
480                                                                                                                         encode_and_send_msg!(resp, 130);
481                                                                                                                 }
482                                                                                                                 for resp in resps.update_fail_htlcs {
483                                                                                                                         encode_and_send_msg!(resp, 131);
484                                                                                                                 }
485                                                                                                                 encode_and_send_msg!(resps.commitment_signed, 132);
486                                                                                                         },
487                                                                                                         None => {},
488                                                                                                 }
489                                                                                         },
490                                                                                         134 => {
491                                                                                                 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
492                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
493                                                                                         },
494                                                                                         136 => { }, // TODO: channel_reestablish
495
496                                                                                         // Routing control:
497                                                                                         259 => {
498                                                                                                 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
499                                                                                                 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
500                                                                                         },
501                                                                                         256 => {
502                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
503                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
504
505                                                                                                 if should_forward {
506                                                                                                         // TODO: forward msg along to all our other peers!
507                                                                                                 }
508                                                                                         },
509                                                                                         257 => {
510                                                                                                 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
511                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
512                                                                                         },
513                                                                                         258 => {
514                                                                                                 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
515                                                                                                 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
516                                                                                         },
517                                                                                         _ => {
518                                                                                                 if (msg_type & 1) == 0 {
519                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
520                                                                                                 }
521                                                                                         },
522                                                                                 }
523                                                                         }
524                                                                 }
525                                                         }
526                                                 }
527                                         }
528
529                                         Self::do_attempt_write_data(peer_descriptor, peer);
530
531                                         (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
532                                 }
533                         };
534
535                         match should_insert_node_id {
536                                 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
537                                 None => {}
538                         };
539
540                         pause_read
541                 };
542
543                 self.process_events();
544
545                 Ok(pause_read)
546         }
547
548         /// Checks for any events generated by our handlers and processes them. May be needed after eg
549         /// calls to ChannelManager::process_pending_htlc_forward.
550         pub fn process_events(&self) {
551                 let mut upstream_events = Vec::new();
552                 {
553                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
554                         // buffer by doing things like announcing channels on another node. We should be willing to
555                         // drop optional-ish messages when send buffers get full!
556
557                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
558                         let mut peers = self.peers.lock().unwrap();
559                         for event in events_generated.drain(..) {
560                                 macro_rules! get_peer_for_forwarding {
561                                         ($node_id: expr, $handle_no_such_peer: block) => {
562                                                 {
563                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
564                                                                 Some(descriptor) => descriptor.clone(),
565                                                                 None => {
566                                                                         $handle_no_such_peer;
567                                                                         continue;
568                                                                 },
569                                                         };
570                                                         match peers.peers.get_mut(&descriptor) {
571                                                                 Some(peer) => {
572                                                                         (descriptor, peer)
573                                                                 },
574                                                                 None => panic!("Inconsistent peers set state!"),
575                                                         }
576                                                 }
577                                         }
578                                 }
579                                 match event {
580                                         Event::FundingGenerationReady {..} => { /* Hand upstream */ },
581                                         Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
582                                         Event::PaymentReceived {..} => { /* Hand upstream */ },
583                                         Event::PaymentSent {..} => { /* Hand upstream */ },
584                                         Event::PaymentFailed {..} => { /* Hand upstream */ },
585
586                                         Event::PendingHTLCsForwardable {..} => {
587                                                 //TODO: Handle upstream in some confused form so that upstream just knows
588                                                 //to call us somehow?
589                                         },
590                                         Event::SendFundingCreated { ref node_id, ref msg } => {
591                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
592                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
593                                                                 //they should just throw away this funding transaction
594                                                         });
595                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
596                                                 Self::do_attempt_write_data(&mut descriptor, peer);
597                                                 continue;
598                                         },
599                                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
600                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
601                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
602                                                         });
603                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
604                                                 match announcement_sigs {
605                                                         &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
606                                                         &None => {},
607                                                 }
608                                                 Self::do_attempt_write_data(&mut descriptor, peer);
609                                                 continue;
610                                         },
611                                         Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
612                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
613                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
614                                                         });
615                                                 for msg in msgs {
616                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
617                                                 }
618                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
619                                                 Self::do_attempt_write_data(&mut descriptor, peer);
620                                                 continue;
621                                         },
622                                         Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
623                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
624                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
625                                                         });
626                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
627                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
628                                                 Self::do_attempt_write_data(&mut descriptor, peer);
629                                                 continue;
630                                         },
631                                         Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
632                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
633                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
634                                                         });
635                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
636                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
637                                                 Self::do_attempt_write_data(&mut descriptor, peer);
638                                                 continue;
639                                         },
640                                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
641                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
642                                                         let encoded_msg = encode_msg!(msg, 256);
643                                                         let encoded_update_msg = encode_msg!(update_msg, 258);
644
645                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
646                                                                 if !peer.channel_encryptor.is_ready_for_encryption() {
647                                                                         continue
648                                                                 }
649                                                                 match peer.their_node_id {
650                                                                         None => continue,
651                                                                         Some(their_node_id) => {
652                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
653                                                                                         continue
654                                                                                 }
655                                                                         }
656                                                                 }
657                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
658                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
659                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
660                                                         }
661                                                 }
662                                                 continue;
663                                         },
664                                         Event::BroadcastChannelUpdate { ref msg } => {
665                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
666                                                         let encoded_msg = encode_msg!(msg, 258);
667
668                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
669                                                                 if !peer.channel_encryptor.is_ready_for_encryption() {
670                                                                         continue
671                                                                 }
672                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
673                                                                 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
674                                                         }
675                                                 }
676                                                 continue;
677                                         },
678                                 }
679
680                                 upstream_events.push(event);
681                         }
682                 }
683
684                 let mut pending_events = self.pending_events.lock().unwrap();
685                 for event in upstream_events.drain(..) {
686                         pending_events.push(event);
687                 }
688         }
689
690         /// Indicates that the given socket descriptor's connection is now closed.
691         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
692         /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
693         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
694         pub fn disconnect_event(&self, descriptor: &Descriptor) {
695                 self.disconnect_event_internal(descriptor, false);
696         }
697
698         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
699                 let mut peers = self.peers.lock().unwrap();
700                 let peer_option = peers.peers.remove(descriptor);
701                 match peer_option {
702                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
703                         Some(peer) => {
704                                 match peer.their_node_id {
705                                         Some(node_id) => {
706                                                 peers.node_id_to_descriptor.remove(&node_id);
707                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
708                                         },
709                                         None => {}
710                                 }
711                         }
712                 };
713         }
714 }
715
716 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
717         fn get_and_clear_pending_events(&self) -> Vec<Event> {
718                 let mut pending_events = self.pending_events.lock().unwrap();
719                 let mut ret = Vec::new();
720                 mem::swap(&mut ret, &mut *pending_events);
721                 ret
722         }
723 }