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