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