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