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