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