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