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