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