Merge pull request #470 from ariard/2020-01-contributing-draft
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 //! Top level peer message handling and socket handling logic lives here.
2 //!
3 //! Instead of actually servicing sockets ourselves we require that you implement the
4 //! SocketDescriptor interface and use that to receive actions which you should perform on the
5 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
6 //! call into the provided message handlers (probably a ChannelManager and Router) with messages
7 //! they should handle, and encoding/sending response messages.
8
9 use secp256k1::key::{SecretKey,PublicKey};
10
11 use ln::features::InitFeatures;
12 use ln::msgs;
13 use ln::msgs::ChannelMessageHandler;
14 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
15 use util::ser::VecWriter;
16 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
17 use ln::wire;
18 use ln::wire::Encode;
19 use util::byte_utils;
20 use util::events::{MessageSendEvent, MessageSendEventsProvider};
21 use util::logger::Logger;
22
23 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
24 use std::sync::{Arc, Mutex};
25 use std::sync::atomic::{AtomicUsize, Ordering};
26 use std::{cmp,error,hash,fmt};
27 use std::ops::Deref;
28
29 use bitcoin_hashes::sha256::Hash as Sha256;
30 use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
31 use bitcoin_hashes::{HashEngine, Hash};
32
33 /// Provides references to trait impls which handle different types of messages.
34 pub struct MessageHandler<CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
35         /// A message handler which handles messages specific to channels. Usually this is just a
36         /// ChannelManager object.
37         pub chan_handler: CM,
38         /// A message handler which handles messages updating our knowledge of the network channel
39         /// graph. Usually this is just a Router object.
40         pub route_handler: Arc<msgs::RoutingMessageHandler>,
41 }
42
43 /// Provides an object which can be used to send data to and which uniquely identifies a connection
44 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
45 /// implement Hash to meet the PeerManager API.
46 ///
47 /// For efficiency, Clone should be relatively cheap for this type.
48 ///
49 /// You probably want to just extend an int and put a file descriptor in a struct and implement
50 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
51 /// careful to ensure you don't have races whereby you might register a new connection with an fd
52 /// the same as a yet-to-be-disconnect_event()-ed.
53 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
54         /// Attempts to send some data from the given slice to the peer.
55         ///
56         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
57         /// Note that in the disconnected case, a disconnect_event must still fire and further write
58         /// attempts may occur until that time.
59         ///
60         /// If the returned size is smaller than data.len(), a write_available event must
61         /// trigger the next time more data can be written. Additionally, until the a send_data event
62         /// completes fully, no further read_events should trigger on the same peer!
63         ///
64         /// If a read_event on this descriptor had previously returned true (indicating that read
65         /// events should be paused to prevent DoS in the send buffer), resume_read may be set
66         /// indicating that read events on this descriptor should resume. A resume_read of false does
67         /// *not* imply that further read events should be paused.
68         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
69         /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
70         /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
71         /// No disconnect_event should be generated as a result of this call, though obviously races
72         /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
73         /// that event completing.
74         fn disconnect_socket(&mut self);
75 }
76
77 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
78 /// generate no further read/write_events for the descriptor, only triggering a single
79 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
80 /// no such disconnect_event must be generated and the socket be silently disconencted).
81 pub struct PeerHandleError {
82         /// Used to indicate that we probably can't make any future connections to this peer, implying
83         /// we should go ahead and force-close any channels we have with it.
84         no_connection_possible: bool,
85 }
86 impl fmt::Debug for PeerHandleError {
87         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
88                 formatter.write_str("Peer Sent Invalid Data")
89         }
90 }
91 impl fmt::Display for PeerHandleError {
92         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
93                 formatter.write_str("Peer Sent Invalid Data")
94         }
95 }
96 impl error::Error for PeerHandleError {
97         fn description(&self) -> &str {
98                 "Peer Sent Invalid Data"
99         }
100 }
101
102 enum InitSyncTracker{
103         NoSyncRequested,
104         ChannelsSyncing(u64),
105         NodesSyncing(PublicKey),
106 }
107
108 struct Peer {
109         channel_encryptor: PeerChannelEncryptor,
110         outbound: bool,
111         their_node_id: Option<PublicKey>,
112         their_features: Option<InitFeatures>,
113
114         pending_outbound_buffer: LinkedList<Vec<u8>>,
115         pending_outbound_buffer_first_msg_offset: usize,
116         awaiting_write_event: bool,
117
118         pending_read_buffer: Vec<u8>,
119         pending_read_buffer_pos: usize,
120         pending_read_is_header: bool,
121
122         sync_status: InitSyncTracker,
123
124         awaiting_pong: bool,
125 }
126
127 impl Peer {
128         /// Returns true if the channel announcements/updates for the given channel should be
129         /// forwarded to this peer.
130         /// If we are sending our routing table to this peer and we have not yet sent channel
131         /// announcements/updates for the given channel_id then we will send it when we get to that
132         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
133         /// sent the old versions, we should send the update, and so return true here.
134         fn should_forward_channel(&self, channel_id: u64)->bool{
135                 match self.sync_status {
136                         InitSyncTracker::NoSyncRequested => true,
137                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
138                         InitSyncTracker::NodesSyncing(_) => true,
139                 }
140         }
141 }
142
143 struct PeerHolder<Descriptor: SocketDescriptor> {
144         peers: HashMap<Descriptor, Peer>,
145         /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
146         /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
147         peers_needing_send: HashSet<Descriptor>,
148         /// Only add to this set when noise completes:
149         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
150 }
151
152 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
153 fn _check_usize_is_32_or_64() {
154         // See below, less than 32 bit pointers may be unsafe here!
155         unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
156 }
157
158 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
159 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
160 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
161 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
162 /// issues such as overly long function definitions.
163 pub type SimpleArcPeerManager<SD, M> = Arc<PeerManager<SD, SimpleArcChannelManager<M>>>;
164
165 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
166 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
167 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
168 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
169 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
170 /// helps with issues such as long function definitions.
171 pub type SimpleRefPeerManager<'a, SD, M> = PeerManager<SD, SimpleRefChannelManager<'a, M>>;
172
173 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
174 /// events into messages which it passes on to its MessageHandlers.
175 ///
176 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
177 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
178 /// essentially you should default to using a SimpleRefPeerManager, and use a
179 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
180 /// you're using lightning-net-tokio.
181 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
182         message_handler: MessageHandler<CM>,
183         peers: Mutex<PeerHolder<Descriptor>>,
184         our_node_secret: SecretKey,
185         ephemeral_key_midstate: Sha256Engine,
186
187         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
188         // bits we will never realistically count into high:
189         peer_counter_low: AtomicUsize,
190         peer_counter_high: AtomicUsize,
191
192         logger: Arc<Logger>,
193 }
194
195 macro_rules! encode_msg {
196         ($msg: expr) => {{
197                 let mut buffer = VecWriter(Vec::new());
198                 wire::write($msg, &mut buffer).unwrap();
199                 buffer.0
200         }}
201 }
202
203 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
204 /// PeerIds may repeat, but only after disconnect_event() has been called.
205 impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where CM::Target: msgs::ChannelMessageHandler {
206         /// Constructs a new PeerManager with the given message handlers and node_id secret key
207         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
208         /// cryptographically secure random bytes.
209         pub fn new(message_handler: MessageHandler<CM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor, CM> {
210                 let mut ephemeral_key_midstate = Sha256::engine();
211                 ephemeral_key_midstate.input(ephemeral_random_data);
212
213                 PeerManager {
214                         message_handler: message_handler,
215                         peers: Mutex::new(PeerHolder {
216                                 peers: HashMap::new(),
217                                 peers_needing_send: HashSet::new(),
218                                 node_id_to_descriptor: HashMap::new()
219                         }),
220                         our_node_secret: our_node_secret,
221                         ephemeral_key_midstate,
222                         peer_counter_low: AtomicUsize::new(0),
223                         peer_counter_high: AtomicUsize::new(0),
224                         logger,
225                 }
226         }
227
228         /// Get the list of node ids for peers which have completed the initial handshake.
229         ///
230         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
231         /// new_outbound_connection, however entries will only appear once the initial handshake has
232         /// completed and we are sure the remote peer has the private key for the given node_id.
233         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
234                 let peers = self.peers.lock().unwrap();
235                 peers.peers.values().filter_map(|p| {
236                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
237                                 return None;
238                         }
239                         p.their_node_id
240                 }).collect()
241         }
242
243         fn get_ephemeral_key(&self) -> SecretKey {
244                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
245                 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
246                 let high = if low == 0 {
247                         self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
248                 } else {
249                         self.peer_counter_high.load(Ordering::Acquire)
250                 };
251                 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
252                 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
253                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
254         }
255
256         /// Indicates a new outbound connection has been established to a node with the given node_id.
257         /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
258         /// descriptor but must disconnect the connection immediately.
259         ///
260         /// Returns a small number of bytes to send to the remote node (currently always 50).
261         ///
262         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
263         /// disconnect_event.
264         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
265                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
266                 let res = peer_encryptor.get_act_one().to_vec();
267                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
268
269                 let mut peers = self.peers.lock().unwrap();
270                 if peers.peers.insert(descriptor, Peer {
271                         channel_encryptor: peer_encryptor,
272                         outbound: true,
273                         their_node_id: None,
274                         their_features: None,
275
276                         pending_outbound_buffer: LinkedList::new(),
277                         pending_outbound_buffer_first_msg_offset: 0,
278                         awaiting_write_event: false,
279
280                         pending_read_buffer: pending_read_buffer,
281                         pending_read_buffer_pos: 0,
282                         pending_read_is_header: false,
283
284                         sync_status: InitSyncTracker::NoSyncRequested,
285
286                         awaiting_pong: false,
287                 }).is_some() {
288                         panic!("PeerManager driver duplicated descriptors!");
289                 };
290                 Ok(res)
291         }
292
293         /// Indicates a new inbound connection has been established.
294         ///
295         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
296         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
297         /// call disconnect_event for the new descriptor but must disconnect the connection
298         /// immediately.
299         ///
300         /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
301         /// disconnect_event.
302         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
303                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
304                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
305
306                 let mut peers = self.peers.lock().unwrap();
307                 if peers.peers.insert(descriptor, Peer {
308                         channel_encryptor: peer_encryptor,
309                         outbound: false,
310                         their_node_id: None,
311                         their_features: None,
312
313                         pending_outbound_buffer: LinkedList::new(),
314                         pending_outbound_buffer_first_msg_offset: 0,
315                         awaiting_write_event: false,
316
317                         pending_read_buffer: pending_read_buffer,
318                         pending_read_buffer_pos: 0,
319                         pending_read_is_header: false,
320
321                         sync_status: InitSyncTracker::NoSyncRequested,
322
323                         awaiting_pong: false,
324                 }).is_some() {
325                         panic!("PeerManager driver duplicated descriptors!");
326                 };
327                 Ok(())
328         }
329
330         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
331                 macro_rules! encode_and_send_msg {
332                         ($msg: expr) => {
333                                 {
334                                         log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
335                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..]));
336                                 }
337                         }
338                 }
339                 const MSG_BUFF_SIZE: usize = 10;
340                 while !peer.awaiting_write_event {
341                         if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
342                                 match peer.sync_status {
343                                         InitSyncTracker::NoSyncRequested => {},
344                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
345                                                 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
346                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
347                                                 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
348                                                         encode_and_send_msg!(announce);
349                                                         encode_and_send_msg!(update_a);
350                                                         encode_and_send_msg!(update_b);
351                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
352                                                 }
353                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
354                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
355                                                 }
356                                         },
357                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
358                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
359                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
360                                                 for msg in all_messages.iter() {
361                                                         encode_and_send_msg!(msg);
362                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
363                                                 }
364                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
365                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
366                                                 }
367                                         },
368                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
369                                         InitSyncTracker::NodesSyncing(key) => {
370                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
371                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
372                                                 for msg in all_messages.iter() {
373                                                         encode_and_send_msg!(msg);
374                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
375                                                 }
376                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
377                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
378                                                 }
379                                         },
380                                 }
381                         }
382
383                         if {
384                                 let next_buff = match peer.pending_outbound_buffer.front() {
385                                         None => return,
386                                         Some(buff) => buff,
387                                 };
388
389                                 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
390                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
391                                 let data_sent = descriptor.send_data(pending, should_be_reading);
392                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
393                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
394                         } {
395                                 peer.pending_outbound_buffer_first_msg_offset = 0;
396                                 peer.pending_outbound_buffer.pop_front();
397                         } else {
398                                 peer.awaiting_write_event = true;
399                         }
400                 }
401         }
402
403         /// Indicates that there is room to write data to the given socket descriptor.
404         ///
405         /// May return an Err to indicate that the connection should be closed.
406         ///
407         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
408         /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
409         /// invariants around calling write_event in case a write did not fully complete must still
410         /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
411         /// Panics if the descriptor was not previously registered in a new_\*_connection event.
412         pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
413                 let mut peers = self.peers.lock().unwrap();
414                 match peers.peers.get_mut(descriptor) {
415                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
416                         Some(peer) => {
417                                 peer.awaiting_write_event = false;
418                                 self.do_attempt_write_data(descriptor, peer);
419                         }
420                 };
421                 Ok(())
422         }
423
424         /// Indicates that data was read from the given socket descriptor.
425         ///
426         /// May return an Err to indicate that the connection should be closed.
427         ///
428         /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
429         /// Thus, however, you almost certainly want to call process_events() after any read_event to
430         /// generate send_data calls to handle responses.
431         ///
432         /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
433         /// this file descriptor has resume_read set (preventing DoS issues in the send buffer).
434         ///
435         /// Panics if the descriptor was not previously registered in a new_*_connection event.
436         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
437                 match self.do_read_event(peer_descriptor, data) {
438                         Ok(res) => Ok(res),
439                         Err(e) => {
440                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
441                                 Err(e)
442                         }
443                 }
444         }
445
446         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
447                 let pause_read = {
448                         let mut peers_lock = self.peers.lock().unwrap();
449                         let peers = &mut *peers_lock;
450                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
451                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
452                                 Some(peer) => {
453                                         assert!(peer.pending_read_buffer.len() > 0);
454                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
455
456                                         let mut read_pos = 0;
457                                         while read_pos < data.len() {
458                                                 {
459                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
460                                                         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]);
461                                                         read_pos += data_to_copy;
462                                                         peer.pending_read_buffer_pos += data_to_copy;
463                                                 }
464
465                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
466                                                         peer.pending_read_buffer_pos = 0;
467
468                                                         macro_rules! encode_and_send_msg {
469                                                                 ($msg: expr) => {
470                                                                         {
471                                                                                 log_trace!(self, "Encoding and sending message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
472                                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&$msg)[..]));
473                                                                                 peers.peers_needing_send.insert(peer_descriptor.clone());
474                                                                         }
475                                                                 }
476                                                         }
477
478                                                         macro_rules! try_potential_handleerror {
479                                                                 ($thing: expr) => {
480                                                                         match $thing {
481                                                                                 Ok(x) => x,
482                                                                                 Err(e) => {
483                                                                                         match e.action {
484                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
485                                                                                                         //TODO: Try to push msg
486                                                                                                         log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
487                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
488                                                                                                 },
489                                                                                                 msgs::ErrorAction::IgnoreError => {
490                                                                                                         log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
491                                                                                                         continue;
492                                                                                                 },
493                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
494                                                                                                         log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
495                                                                                                         encode_and_send_msg!(msg);
496                                                                                                         continue;
497                                                                                                 },
498                                                                                         }
499                                                                                 }
500                                                                         };
501                                                                 }
502                                                         }
503
504                                                         macro_rules! insert_node_id {
505                                                                 () => {
506                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
507                                                                                 hash_map::Entry::Occupied(_) => {
508                                                                                         log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
509                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
510                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
511                                                                                 },
512                                                                                 hash_map::Entry::Vacant(entry) => {
513                                                                                         log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
514                                                                                         entry.insert(peer_descriptor.clone())
515                                                                                 },
516                                                                         };
517                                                                 }
518                                                         }
519
520                                                         let next_step = peer.channel_encryptor.get_noise_step();
521                                                         match next_step {
522                                                                 NextNoiseStep::ActOne => {
523                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
524                                                                         peer.pending_outbound_buffer.push_back(act_two);
525                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
526                                                                 },
527                                                                 NextNoiseStep::ActTwo => {
528                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
529                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
530                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
531                                                                         peer.pending_read_is_header = true;
532
533                                                                         peer.their_node_id = Some(their_node_id);
534                                                                         insert_node_id!();
535                                                                         let mut features = InitFeatures::supported();
536                                                                         if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
537                                                                                 features.set_initial_routing_sync();
538                                                                         }
539
540                                                                         let resp = msgs::Init { features };
541                                                                         encode_and_send_msg!(resp);
542                                                                 },
543                                                                 NextNoiseStep::ActThree => {
544                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
545                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
546                                                                         peer.pending_read_is_header = true;
547                                                                         peer.their_node_id = Some(their_node_id);
548                                                                         insert_node_id!();
549                                                                 },
550                                                                 NextNoiseStep::NoiseComplete => {
551                                                                         if peer.pending_read_is_header {
552                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
553                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
554                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
555                                                                                 if msg_len < 2 { // Need at least the message type tag
556                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
557                                                                                 }
558                                                                                 peer.pending_read_is_header = false;
559                                                                         } else {
560                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
561                                                                                 assert!(msg_data.len() >= 2);
562
563                                                                                 // Reset read buffer
564                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
565                                                                                 peer.pending_read_is_header = true;
566
567                                                                                 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
568                                                                                 let message_result = wire::read(&mut reader);
569                                                                                 let message = match message_result {
570                                                                                         Ok(x) => x,
571                                                                                         Err(e) => {
572                                                                                                 match e {
573                                                                                                         msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
574                                                                                                         msgs::DecodeError::UnknownRequiredFeature => {
575                                                                                                                 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
576                                                                                                                 continue;
577                                                                                                         }
578                                                                                                         msgs::DecodeError::InvalidValue => {
579                                                                                                                 log_debug!(self, "Got an invalid value while deserializing message");
580                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
581                                                                                                         }
582                                                                                                         msgs::DecodeError::ShortRead => {
583                                                                                                                 log_debug!(self, "Deserialization failed due to shortness of message");
584                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
585                                                                                                         }
586                                                                                                         msgs::DecodeError::ExtraAddressesPerType => {
587                                                                                                                 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
588                                                                                                                 continue;
589                                                                                                         }
590                                                                                                         msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
591                                                                                                         msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
592                                                                                                 }
593                                                                                         }
594                                                                                 };
595
596                                                                                 log_trace!(self, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
597
598                                                                                 // Need an Init as first message
599                                                                                 if let wire::Message::Init(_) = message {
600                                                                                 } else if peer.their_features.is_none() {
601                                                                                         log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
602                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
603                                                                                 }
604
605                                                                                 match message {
606                                                                                         // Setup and Control messages:
607                                                                                         wire::Message::Init(msg) => {
608                                                                                                 if msg.features.requires_unknown_bits() {
609                                                                                                         log_info!(self, "Peer global features required unknown version bits");
610                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
611                                                                                                 }
612                                                                                                 if msg.features.requires_unknown_bits() {
613                                                                                                         log_info!(self, "Peer local features required unknown version bits");
614                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
615                                                                                                 }
616                                                                                                 if peer.their_features.is_some() {
617                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
618                                                                                                 }
619
620                                                                                                 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
621                                                                                                         if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
622                                                                                                         if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
623                                                                                                         if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
624                                                                                                         if msg.features.supports_unknown_bits() { "present" } else { "none" },
625                                                                                                         if msg.features.supports_unknown_bits() { "present" } else { "none" });
626
627                                                                                                 if msg.features.initial_routing_sync() {
628                                                                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
629                                                                                                         peers.peers_needing_send.insert(peer_descriptor.clone());
630                                                                                                 }
631
632                                                                                                 if !peer.outbound {
633                                                                                                         let mut features = InitFeatures::supported();
634                                                                                                         if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
635                                                                                                                 features.set_initial_routing_sync();
636                                                                                                         }
637
638                                                                                                         let resp = msgs::Init { features };
639                                                                                                         encode_and_send_msg!(resp);
640                                                                                                 }
641
642                                                                                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
643                                                                                                 peer.their_features = Some(msg.features);
644                                                                                         },
645                                                                                         wire::Message::Error(msg) => {
646                                                                                                 let mut data_is_printable = true;
647                                                                                                 for b in msg.data.bytes() {
648                                                                                                         if b < 32 || b > 126 {
649                                                                                                                 data_is_printable = false;
650                                                                                                                 break;
651                                                                                                         }
652                                                                                                 }
653
654                                                                                                 if data_is_printable {
655                                                                                                         log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
656                                                                                                 } else {
657                                                                                                         log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
658                                                                                                 }
659                                                                                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
660                                                                                                 if msg.channel_id == [0; 32] {
661                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
662                                                                                                 }
663                                                                                         },
664
665                                                                                         wire::Message::Ping(msg) => {
666                                                                                                 if msg.ponglen < 65532 {
667                                                                                                         let resp = msgs::Pong { byteslen: msg.ponglen };
668                                                                                                         encode_and_send_msg!(resp);
669                                                                                                 }
670                                                                                         },
671                                                                                         wire::Message::Pong(_msg) => {
672                                                                                                 peer.awaiting_pong = false;
673                                                                                         },
674
675                                                                                         // Channel messages:
676                                                                                         wire::Message::OpenChannel(msg) => {
677                                                                                                 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
678                                                                                         },
679                                                                                         wire::Message::AcceptChannel(msg) => {
680                                                                                                 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
681                                                                                         },
682
683                                                                                         wire::Message::FundingCreated(msg) => {
684                                                                                                 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
685                                                                                         },
686                                                                                         wire::Message::FundingSigned(msg) => {
687                                                                                                 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
688                                                                                         },
689                                                                                         wire::Message::FundingLocked(msg) => {
690                                                                                                 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
691                                                                                         },
692
693                                                                                         wire::Message::Shutdown(msg) => {
694                                                                                                 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
695                                                                                         },
696                                                                                         wire::Message::ClosingSigned(msg) => {
697                                                                                                 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
698                                                                                         },
699
700                                                                                         // Commitment messages:
701                                                                                         wire::Message::UpdateAddHTLC(msg) => {
702                                                                                                 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
703                                                                                         },
704                                                                                         wire::Message::UpdateFulfillHTLC(msg) => {
705                                                                                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
706                                                                                         },
707                                                                                         wire::Message::UpdateFailHTLC(msg) => {
708                                                                                                 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
709                                                                                         },
710                                                                                         wire::Message::UpdateFailMalformedHTLC(msg) => {
711                                                                                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
712                                                                                         },
713
714                                                                                         wire::Message::CommitmentSigned(msg) => {
715                                                                                                 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
716                                                                                         },
717                                                                                         wire::Message::RevokeAndACK(msg) => {
718                                                                                                 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
719                                                                                         },
720                                                                                         wire::Message::UpdateFee(msg) => {
721                                                                                                 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
722                                                                                         },
723                                                                                         wire::Message::ChannelReestablish(msg) => {
724                                                                                                 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
725                                                                                         },
726
727                                                                                         // Routing messages:
728                                                                                         wire::Message::AnnouncementSignatures(msg) => {
729                                                                                                 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
730                                                                                         },
731                                                                                         wire::Message::ChannelAnnouncement(msg) => {
732                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
733
734                                                                                                 if should_forward {
735                                                                                                         // TODO: forward msg along to all our other peers!
736                                                                                                 }
737                                                                                         },
738                                                                                         wire::Message::NodeAnnouncement(msg) => {
739                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
740
741                                                                                                 if should_forward {
742                                                                                                         // TODO: forward msg along to all our other peers!
743                                                                                                 }
744                                                                                         },
745                                                                                         wire::Message::ChannelUpdate(msg) => {
746                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
747
748                                                                                                 if should_forward {
749                                                                                                         // TODO: forward msg along to all our other peers!
750                                                                                                 }
751                                                                                         },
752
753                                                                                         // Unknown messages:
754                                                                                         wire::Message::Unknown(msg_type) if msg_type.is_even() => {
755                                                                                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
756                                                                                                 return Err(PeerHandleError{ no_connection_possible: true });
757                                                                                         },
758                                                                                         wire::Message::Unknown(_) => {},
759                                                                                 }
760                                                                         }
761                                                                 }
762                                                         }
763                                                 }
764                                         }
765
766                                         self.do_attempt_write_data(peer_descriptor, peer);
767
768                                         peer.pending_outbound_buffer.len() > 10 // pause_read
769                                 }
770                         };
771
772                         pause_read
773                 };
774
775                 Ok(pause_read)
776         }
777
778         /// Checks for any events generated by our handlers and processes them. Includes sending most
779         /// response messages as well as messages generated by calls to handler functions directly (eg
780         /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
781         pub fn process_events(&self) {
782                 {
783                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
784                         // buffer by doing things like announcing channels on another node. We should be willing to
785                         // drop optional-ish messages when send buffers get full!
786
787                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
788                         let mut peers_lock = self.peers.lock().unwrap();
789                         let peers = &mut *peers_lock;
790                         for event in events_generated.drain(..) {
791                                 macro_rules! get_peer_for_forwarding {
792                                         ($node_id: expr, $handle_no_such_peer: block) => {
793                                                 {
794                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
795                                                                 Some(descriptor) => descriptor.clone(),
796                                                                 None => {
797                                                                         $handle_no_such_peer;
798                                                                         continue;
799                                                                 },
800                                                         };
801                                                         match peers.peers.get_mut(&descriptor) {
802                                                                 Some(peer) => {
803                                                                         if peer.their_features.is_none() {
804                                                                                 $handle_no_such_peer;
805                                                                                 continue;
806                                                                         }
807                                                                         (descriptor, peer)
808                                                                 },
809                                                                 None => panic!("Inconsistent peers set state!"),
810                                                         }
811                                                 }
812                                         }
813                                 }
814                                 match event {
815                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
816                                                 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
817                                                                 log_pubkey!(node_id),
818                                                                 log_bytes!(msg.temporary_channel_id));
819                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
820                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
821                                                         });
822                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
823                                                 self.do_attempt_write_data(&mut descriptor, peer);
824                                         },
825                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
826                                                 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
827                                                                 log_pubkey!(node_id),
828                                                                 log_bytes!(msg.temporary_channel_id));
829                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
830                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
831                                                         });
832                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
833                                                 self.do_attempt_write_data(&mut descriptor, peer);
834                                         },
835                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
836                                                 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
837                                                                 log_pubkey!(node_id),
838                                                                 log_bytes!(msg.temporary_channel_id),
839                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
840                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
841                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
842                                                                 //they should just throw away this funding transaction
843                                                         });
844                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
845                                                 self.do_attempt_write_data(&mut descriptor, peer);
846                                         },
847                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
848                                                 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
849                                                                 log_pubkey!(node_id),
850                                                                 log_bytes!(msg.channel_id));
851                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
852                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
853                                                                 //they should just throw away this funding transaction
854                                                         });
855                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
856                                                 self.do_attempt_write_data(&mut descriptor, peer);
857                                         },
858                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
859                                                 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
860                                                                 log_pubkey!(node_id),
861                                                                 log_bytes!(msg.channel_id));
862                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
863                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
864                                                         });
865                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
866                                                 self.do_attempt_write_data(&mut descriptor, peer);
867                                         },
868                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
869                                                 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
870                                                                 log_pubkey!(node_id),
871                                                                 log_bytes!(msg.channel_id));
872                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
873                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
874                                                                 //they should just throw away this funding transaction
875                                                         });
876                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
877                                                 self.do_attempt_write_data(&mut descriptor, peer);
878                                         },
879                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
880                                                 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
881                                                                 log_pubkey!(node_id),
882                                                                 update_add_htlcs.len(),
883                                                                 update_fulfill_htlcs.len(),
884                                                                 update_fail_htlcs.len(),
885                                                                 log_bytes!(commitment_signed.channel_id));
886                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
887                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
888                                                         });
889                                                 for msg in update_add_htlcs {
890                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
891                                                 }
892                                                 for msg in update_fulfill_htlcs {
893                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
894                                                 }
895                                                 for msg in update_fail_htlcs {
896                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
897                                                 }
898                                                 for msg in update_fail_malformed_htlcs {
899                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
900                                                 }
901                                                 if let &Some(ref msg) = update_fee {
902                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
903                                                 }
904                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
905                                                 self.do_attempt_write_data(&mut descriptor, peer);
906                                         },
907                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
908                                                 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
909                                                                 log_pubkey!(node_id),
910                                                                 log_bytes!(msg.channel_id));
911                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
912                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
913                                                         });
914                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
915                                                 self.do_attempt_write_data(&mut descriptor, peer);
916                                         },
917                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
918                                                 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
919                                                                 log_pubkey!(node_id),
920                                                                 log_bytes!(msg.channel_id));
921                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
922                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
923                                                         });
924                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
925                                                 self.do_attempt_write_data(&mut descriptor, peer);
926                                         },
927                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
928                                                 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
929                                                                 log_pubkey!(node_id),
930                                                                 log_bytes!(msg.channel_id));
931                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
932                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
933                                                         });
934                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
935                                                 self.do_attempt_write_data(&mut descriptor, peer);
936                                         },
937                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
938                                                 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
939                                                                 log_pubkey!(node_id),
940                                                                 log_bytes!(msg.channel_id));
941                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
942                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
943                                                         });
944                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
945                                                 self.do_attempt_write_data(&mut descriptor, peer);
946                                         },
947                                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
948                                                 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
949                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
950                                                         let encoded_msg = encode_msg!(msg);
951                                                         let encoded_update_msg = encode_msg!(update_msg);
952
953                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
954                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
955                                                                                 !peer.should_forward_channel(msg.contents.short_channel_id) {
956                                                                         continue
957                                                                 }
958                                                                 match peer.their_node_id {
959                                                                         None => continue,
960                                                                         Some(their_node_id) => {
961                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
962                                                                                         continue
963                                                                                 }
964                                                                         }
965                                                                 }
966                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
967                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
968                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
969                                                         }
970                                                 }
971                                         },
972                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
973                                                 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
974                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
975                                                         let encoded_msg = encode_msg!(msg);
976
977                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
978                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
979                                                                                 !peer.should_forward_channel(msg.contents.short_channel_id)  {
980                                                                         continue
981                                                                 }
982                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
983                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
984                                                         }
985                                                 }
986                                         },
987                                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
988                                                 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
989                                         },
990                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
991                                                 match *action {
992                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
993                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
994                                                                         peers.peers_needing_send.remove(&descriptor);
995                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
996                                                                                 if let Some(ref msg) = *msg {
997                                                                                         log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
998                                                                                                         log_pubkey!(node_id),
999                                                                                                         msg.data);
1000                                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1001                                                                                         // This isn't guaranteed to work, but if there is enough free
1002                                                                                         // room in the send buffer, put the error message there...
1003                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1004                                                                                 } else {
1005                                                                                         log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1006                                                                                 }
1007                                                                         }
1008                                                                         descriptor.disconnect_socket();
1009                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1010                                                                 }
1011                                                         },
1012                                                         msgs::ErrorAction::IgnoreError => {},
1013                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1014                                                                 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1015                                                                                 log_pubkey!(node_id),
1016                                                                                 msg.data);
1017                                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1018                                                                         //TODO: Do whatever we're gonna do for handling dropped messages
1019                                                                 });
1020                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1021                                                                 self.do_attempt_write_data(&mut descriptor, peer);
1022                                                         },
1023                                                 }
1024                                         }
1025                                 }
1026                         }
1027
1028                         for mut descriptor in peers.peers_needing_send.drain() {
1029                                 match peers.peers.get_mut(&descriptor) {
1030                                         Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1031                                         None => panic!("Inconsistent peers set state!"),
1032                                 }
1033                         }
1034                 }
1035         }
1036
1037         /// Indicates that the given socket descriptor's connection is now closed.
1038         ///
1039         /// This must be called even if a PeerHandleError was given for a read_event or write_event,
1040         /// but must NOT be called if a PeerHandleError was provided out of a new_\*\_connection event!
1041         ///
1042         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1043         pub fn disconnect_event(&self, descriptor: &Descriptor) {
1044                 self.disconnect_event_internal(descriptor, false);
1045         }
1046
1047         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1048                 let mut peers = self.peers.lock().unwrap();
1049                 peers.peers_needing_send.remove(descriptor);
1050                 let peer_option = peers.peers.remove(descriptor);
1051                 match peer_option {
1052                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1053                         Some(peer) => {
1054                                 match peer.their_node_id {
1055                                         Some(node_id) => {
1056                                                 peers.node_id_to_descriptor.remove(&node_id);
1057                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1058                                         },
1059                                         None => {}
1060                                 }
1061                         }
1062                 };
1063         }
1064
1065         /// This function should be called roughly once every 30 seconds.
1066         /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
1067
1068         /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
1069         pub fn timer_tick_occured(&self) {
1070                 let mut peers_lock = self.peers.lock().unwrap();
1071                 {
1072                         let peers = &mut *peers_lock;
1073                         let peers_needing_send = &mut peers.peers_needing_send;
1074                         let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1075                         let peers = &mut peers.peers;
1076
1077                         peers.retain(|descriptor, peer| {
1078                                 if peer.awaiting_pong == true {
1079                                         peers_needing_send.remove(descriptor);
1080                                         match peer.their_node_id {
1081                                                 Some(node_id) => {
1082                                                         node_id_to_descriptor.remove(&node_id);
1083                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, true);
1084                                                 },
1085                                                 None => {}
1086                                         }
1087                                 }
1088
1089                                 let ping = msgs::Ping {
1090                                         ponglen: 0,
1091                                         byteslen: 64,
1092                                 };
1093                                 peer.pending_outbound_buffer.push_back(encode_msg!(&ping));
1094                                 let mut descriptor_clone = descriptor.clone();
1095                                 self.do_attempt_write_data(&mut descriptor_clone, peer);
1096
1097                                 if peer.awaiting_pong {
1098                                         false // Drop the peer
1099                                 } else {
1100                                         peer.awaiting_pong = true;
1101                                         true
1102                                 }
1103                         });
1104                 }
1105         }
1106 }
1107
1108 #[cfg(test)]
1109 mod tests {
1110         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1111         use ln::msgs;
1112         use util::events;
1113         use util::test_utils;
1114         use util::logger::Logger;
1115
1116         use secp256k1::Secp256k1;
1117         use secp256k1::key::{SecretKey, PublicKey};
1118
1119         use rand::{thread_rng, Rng};
1120
1121         use std::sync::{Arc};
1122
1123         #[derive(PartialEq, Eq, Clone, Hash)]
1124         struct FileDescriptor {
1125                 fd: u16,
1126         }
1127
1128         impl SocketDescriptor for FileDescriptor {
1129                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1130                         data.len()
1131                 }
1132
1133                 fn disconnect_socket(&mut self) {}
1134         }
1135
1136         fn create_chan_handlers(peer_count: usize) -> Vec<test_utils::TestChannelMessageHandler> {
1137                 let mut chan_handlers = Vec::new();
1138                 for _ in 0..peer_count {
1139                         let chan_handler = test_utils::TestChannelMessageHandler::new();
1140                         chan_handlers.push(chan_handler);
1141                 }
1142
1143                 chan_handlers
1144         }
1145
1146         fn create_network<'a>(peer_count: usize, chan_handlers: &'a Vec<test_utils::TestChannelMessageHandler>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>> {
1147                 let mut peers = Vec::new();
1148                 let mut rng = thread_rng();
1149                 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1150                 let mut ephemeral_bytes = [0; 32];
1151                 rng.fill_bytes(&mut ephemeral_bytes);
1152
1153                 for i in 0..peer_count {
1154                         let router = test_utils::TestRoutingMessageHandler::new();
1155                         let node_id = {
1156                                 let mut key_slice = [0;32];
1157                                 rng.fill_bytes(&mut key_slice);
1158                                 SecretKey::from_slice(&key_slice).unwrap()
1159                         };
1160                         let msg_handler = MessageHandler { chan_handler: &chan_handlers[i], route_handler: Arc::new(router) };
1161                         let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1162                         peers.push(peer);
1163                 }
1164
1165                 peers
1166         }
1167
1168         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>) {
1169                 let secp_ctx = Secp256k1::new();
1170                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
1171                 let fd = FileDescriptor { fd: 1};
1172                 peer_a.new_inbound_connection(fd.clone()).unwrap();
1173                 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
1174         }
1175
1176         #[test]
1177         fn test_disconnect_peer() {
1178                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1179                 // push a DisconnectPeer event to remove the node flagged by id
1180                 let chan_handlers = create_chan_handlers(2);
1181                 let chan_handler = test_utils::TestChannelMessageHandler::new();
1182                 let mut peers = create_network(2, &chan_handlers);
1183                 establish_connection(&peers[0], &peers[1]);
1184                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1185
1186                 let secp_ctx = Secp256k1::new();
1187                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1188
1189                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1190                         node_id: their_id,
1191                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
1192                 });
1193                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1194                 peers[0].message_handler.chan_handler = &chan_handler;
1195
1196                 peers[0].process_events();
1197                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1198         }
1199         #[test]
1200         fn test_timer_tick_occured(){
1201                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1202                 let chan_handlers = create_chan_handlers(2);
1203                 let peers = create_network(2, &chan_handlers);
1204                 establish_connection(&peers[0], &peers[1]);
1205                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1206
1207                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1208                 peers[0].timer_tick_occured();
1209                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1210
1211                 // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected
1212                 peers[0].timer_tick_occured();
1213                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1214         }
1215 }