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