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