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