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