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