1 //! Top level peer message handling and socket handling logic lives here.
3 //! Instead of actually servicing sockets ourselves we require that you implement the
4 //! SocketDescriptor interface and use that to receive actions which you should perform on the
5 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
6 //! call into the provided message handlers (probably a ChannelManager and Router) with messages
7 //! they should handle, and encoding/sending response messages.
9 use secp256k1::key::{SecretKey,PublicKey};
12 use util::ser::{Writeable, Writer, Readable};
13 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
15 use util::events::{MessageSendEvent};
16 use util::logger::Logger;
18 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
19 use std::sync::{Arc, Mutex};
20 use std::sync::atomic::{AtomicUsize, Ordering};
21 use std::{cmp,error,hash,fmt};
23 use bitcoin_hashes::sha256::Hash as Sha256;
24 use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
25 use bitcoin_hashes::{HashEngine, Hash};
27 /// Provides references to trait impls which handle different types of messages.
28 pub struct MessageHandler {
29 /// A message handler which handles messages specific to channels. Usually this is just a
30 /// ChannelManager object.
31 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
32 /// A message handler which handles messages updating our knowledge of the network channel
33 /// graph. Usually this is just a Router object.
34 pub route_handler: Arc<msgs::RoutingMessageHandler>,
37 /// Provides an object which can be used to send data to and which uniquely identifies a connection
38 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
39 /// implement Hash to meet the PeerManager API.
41 /// For efficiency, Clone should be relatively cheap for this type.
43 /// You probably want to just extend an int and put a file descriptor in a struct and implement
44 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
45 /// careful to ensure you don't have races whereby you might register a new connection with an fd
46 /// the same as a yet-to-be-disconnect_event()-ed.
47 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
48 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
49 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
50 /// Note that in the disconnected case, a disconnect_event must still fire and further write
51 /// attempts may occur until that time.
53 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
54 /// trigger the next time more data can be written. Additionally, until the a send_data event
55 /// completes fully, no further read_events should trigger on the same peer!
57 /// If a read_event on this descriptor had previously returned true (indicating that read
58 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
59 /// indicating that read events on this descriptor should resume. A resume_read of false does
60 /// *not* imply that further read events should be paused.
61 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
62 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
63 /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
64 /// No disconnect_event should be generated as a result of this call, though obviously races
65 /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
66 /// that event completing.
67 fn disconnect_socket(&mut self);
70 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
71 /// generate no further read/write_events for the descriptor, only triggering a single
72 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
73 /// no such disconnect_event must be generated and the socket be silently disconencted).
74 pub struct PeerHandleError {
75 /// Used to indicate that we probably can't make any future connections to this peer, implying
76 /// we should go ahead and force-close any channels we have with it.
77 no_connection_possible: bool,
79 impl fmt::Debug for PeerHandleError {
80 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
81 formatter.write_str("Peer Sent Invalid Data")
84 impl fmt::Display for PeerHandleError {
85 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
86 formatter.write_str("Peer Sent Invalid Data")
89 impl error::Error for PeerHandleError {
90 fn description(&self) -> &str {
91 "Peer Sent Invalid Data"
98 NodesSyncing(PublicKey),
102 channel_encryptor: PeerChannelEncryptor,
104 their_node_id: Option<PublicKey>,
105 their_global_features: Option<msgs::GlobalFeatures>,
106 their_local_features: Option<msgs::LocalFeatures>,
108 pending_outbound_buffer: LinkedList<Vec<u8>>,
109 pending_outbound_buffer_first_msg_offset: usize,
110 awaiting_write_event: bool,
112 pending_read_buffer: Vec<u8>,
113 pending_read_buffer_pos: usize,
114 pending_read_is_header: bool,
116 sync_status: InitSyncTracker,
120 /// Returns true if the channel announcements/updates for the given channel should be
121 /// forwarded to this peer.
122 /// If we are sending our routing table to this peer and we have not yet sent channel
123 /// announcements/updates for the given channel_id then we will send it when we get to that
124 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
125 /// sent the old versions, we should send the update, and so return true here.
126 fn should_forward_channel(&self, channel_id: u64)->bool{
127 match self.sync_status {
128 InitSyncTracker::NoSyncRequested => true,
129 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
130 InitSyncTracker::NodesSyncing(_) => true,
135 struct PeerHolder<Descriptor: SocketDescriptor> {
136 peers: HashMap<Descriptor, Peer>,
137 /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
138 /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
139 peers_needing_send: HashSet<Descriptor>,
140 /// Only add to this set when noise completes:
141 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
143 struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
144 peers: &'a mut HashMap<Descriptor, Peer>,
145 peers_needing_send: &'a mut HashSet<Descriptor>,
146 node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
148 impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
149 fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
151 peers: &mut self.peers,
152 peers_needing_send: &mut self.peers_needing_send,
153 node_id_to_descriptor: &mut self.node_id_to_descriptor,
158 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
159 fn _check_usize_is_32_or_64() {
160 // See below, less than 32 bit pointers may be unsafe here!
161 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
164 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
165 /// events into messages which it passes on to its MessageHandlers.
166 pub struct PeerManager<Descriptor: SocketDescriptor> {
167 message_handler: MessageHandler,
168 peers: Mutex<PeerHolder<Descriptor>>,
169 our_node_secret: SecretKey,
170 ephemeral_key_midstate: Sha256Engine,
172 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
173 // bits we will never realistically count into high:
174 peer_counter_low: AtomicUsize,
175 peer_counter_high: AtomicUsize,
177 initial_syncs_sent: AtomicUsize,
181 struct VecWriter(Vec<u8>);
182 impl Writer for VecWriter {
183 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
184 self.0.extend_from_slice(buf);
187 fn size_hint(&mut self, size: usize) {
188 self.0.reserve_exact(size);
192 macro_rules! encode_msg {
193 ($msg: expr, $msg_code: expr) => {{
194 let mut msg = VecWriter(Vec::new());
195 ($msg_code as u16).write(&mut msg).unwrap();
196 $msg.write(&mut msg).unwrap();
201 //TODO: Really should do something smarter for this
202 const INITIAL_SYNCS_TO_SEND: usize = 5;
204 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
205 /// PeerIds may repeat, but only after disconnect_event() has been called.
206 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
207 /// Constructs a new PeerManager with the given message handlers and node_id secret key
208 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
209 /// cryptographically secure random bytes.
210 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor> {
211 let mut ephemeral_key_midstate = Sha256::engine();
212 ephemeral_key_midstate.input(ephemeral_random_data);
215 message_handler: message_handler,
216 peers: Mutex::new(PeerHolder {
217 peers: HashMap::new(),
218 peers_needing_send: HashSet::new(),
219 node_id_to_descriptor: HashMap::new()
221 our_node_secret: our_node_secret,
222 ephemeral_key_midstate,
223 peer_counter_low: AtomicUsize::new(0),
224 peer_counter_high: AtomicUsize::new(0),
225 initial_syncs_sent: AtomicUsize::new(0),
230 /// Get the list of node ids for peers which have completed the initial handshake.
232 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
233 /// new_outbound_connection, however entries will only appear once the initial handshake has
234 /// completed and we are sure the remote peer has the private key for the given node_id.
235 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
236 let peers = self.peers.lock().unwrap();
237 peers.peers.values().filter_map(|p| {
238 if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() {
245 fn get_ephemeral_key(&self) -> SecretKey {
246 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
247 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
248 let high = if low == 0 {
249 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
251 self.peer_counter_high.load(Ordering::Acquire)
253 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
254 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
255 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
258 /// Indicates a new outbound connection has been established to a node with the given node_id.
259 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
260 /// descriptor but must disconnect the connection immediately.
262 /// Returns a small number of bytes to send to the remote node (currently always 50).
264 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
265 /// disconnect_event.
266 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
267 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
268 let res = peer_encryptor.get_act_one().to_vec();
269 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
271 let mut peers = self.peers.lock().unwrap();
272 if peers.peers.insert(descriptor, Peer {
273 channel_encryptor: peer_encryptor,
276 their_global_features: None,
277 their_local_features: None,
279 pending_outbound_buffer: LinkedList::new(),
280 pending_outbound_buffer_first_msg_offset: 0,
281 awaiting_write_event: false,
283 pending_read_buffer: pending_read_buffer,
284 pending_read_buffer_pos: 0,
285 pending_read_is_header: false,
287 sync_status: InitSyncTracker::NoSyncRequested,
289 panic!("PeerManager driver duplicated descriptors!");
294 /// Indicates a new inbound connection has been established.
296 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
297 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
298 /// call disconnect_event for the new descriptor but must disconnect the connection
301 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
302 /// disconnect_event.
303 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
304 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
305 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
307 let mut peers = self.peers.lock().unwrap();
308 if peers.peers.insert(descriptor, Peer {
309 channel_encryptor: peer_encryptor,
312 their_global_features: None,
313 their_local_features: None,
315 pending_outbound_buffer: LinkedList::new(),
316 pending_outbound_buffer_first_msg_offset: 0,
317 awaiting_write_event: false,
319 pending_read_buffer: pending_read_buffer,
320 pending_read_buffer_pos: 0,
321 pending_read_is_header: false,
323 sync_status: InitSyncTracker::NoSyncRequested,
325 panic!("PeerManager driver duplicated descriptors!");
330 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
331 macro_rules! encode_and_send_msg {
332 ($msg: expr, $msg_code: expr) => {
334 log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
335 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
339 const MSG_BUFF_SIZE: usize = 10;
340 while !peer.awaiting_write_event {
341 if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
342 match peer.sync_status {
343 InitSyncTracker::NoSyncRequested => {},
344 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
345 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
346 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
347 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
348 encode_and_send_msg!(announce, 256);
349 encode_and_send_msg!(update_a, 258);
350 encode_and_send_msg!(update_b, 258);
351 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
353 if all_messages.is_empty() || all_messages.len() != steps as usize {
354 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
357 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
358 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
359 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
360 for msg in all_messages.iter() {
361 encode_and_send_msg!(msg, 256);
362 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
364 if all_messages.is_empty() || all_messages.len() != steps as usize {
365 peer.sync_status = InitSyncTracker::NoSyncRequested;
368 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
369 InitSyncTracker::NodesSyncing(key) => {
370 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
371 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
372 for msg in all_messages.iter() {
373 encode_and_send_msg!(msg, 256);
374 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
376 if all_messages.is_empty() || all_messages.len() != steps as usize {
377 peer.sync_status = InitSyncTracker::NoSyncRequested;
384 let next_buff = match peer.pending_outbound_buffer.front() {
389 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
390 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
391 peer.pending_outbound_buffer_first_msg_offset += data_sent;
392 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
394 peer.pending_outbound_buffer_first_msg_offset = 0;
395 peer.pending_outbound_buffer.pop_front();
397 peer.awaiting_write_event = true;
402 /// Indicates that there is room to write data to the given socket descriptor.
404 /// May return an Err to indicate that the connection should be closed.
406 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
407 /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
408 /// invariants around calling write_event in case a write did not fully complete must still
409 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
410 /// Panics if the descriptor was not previously registered in a new_\*_connection event.
411 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
412 let mut peers = self.peers.lock().unwrap();
413 match peers.peers.get_mut(descriptor) {
414 None => panic!("Descriptor for write_event is not already known to PeerManager"),
416 peer.awaiting_write_event = false;
417 self.do_attempt_write_data(descriptor, peer);
423 /// Indicates that data was read from the given socket descriptor.
425 /// May return an Err to indicate that the connection should be closed.
427 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
428 /// Thus, however, you almost certainly want to call process_events() after any read_event to
429 /// generate send_data calls to handle responses.
431 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
432 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer).
434 /// Panics if the descriptor was not previously registered in a new_*_connection event.
435 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
436 match self.do_read_event(peer_descriptor, data) {
439 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
445 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
447 let mut peers_lock = self.peers.lock().unwrap();
448 let peers = peers_lock.borrow_parts();
449 let pause_read = match peers.peers.get_mut(peer_descriptor) {
450 None => panic!("Descriptor for read_event is not already known to PeerManager"),
452 assert!(peer.pending_read_buffer.len() > 0);
453 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
455 let mut read_pos = 0;
456 while read_pos < data.len() {
458 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
459 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]);
460 read_pos += data_to_copy;
461 peer.pending_read_buffer_pos += data_to_copy;
464 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
465 peer.pending_read_buffer_pos = 0;
467 macro_rules! encode_and_send_msg {
468 ($msg: expr, $msg_code: expr) => {
470 log_trace!(self, "Encoding and sending message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
471 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
472 peers.peers_needing_send.insert(peer_descriptor.clone());
477 macro_rules! try_potential_handleerror {
482 if let Some(action) = e.action {
484 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
485 //TODO: Try to push msg
486 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
487 return Err(PeerHandleError{ no_connection_possible: false });
489 msgs::ErrorAction::IgnoreError => {
490 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
493 msgs::ErrorAction::SendErrorMessage { msg } => {
494 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
495 encode_and_send_msg!(msg, 17);
500 log_debug!(self, "Got Err handling message, action not yet filled in: {}", e.err);
501 return Err(PeerHandleError{ no_connection_possible: false });
508 macro_rules! try_potential_decodeerror {
514 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError{ no_connection_possible: false }),
515 msgs::DecodeError::UnknownRequiredFeature => {
516 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
519 msgs::DecodeError::InvalidValue => {
520 log_debug!(self, "Got an invalid value while deserializing message");
521 return Err(PeerHandleError{ no_connection_possible: false });
523 msgs::DecodeError::ShortRead => {
524 log_debug!(self, "Deserialization failed due to shortness of message");
525 return Err(PeerHandleError{ no_connection_possible: false });
527 msgs::DecodeError::ExtraAddressesPerType => {
528 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
531 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
532 msgs::DecodeError::Io(_) => return Err(PeerHandleError{ no_connection_possible: false }),
539 macro_rules! insert_node_id {
541 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
542 hash_map::Entry::Occupied(_) => {
543 log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
544 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
545 return Err(PeerHandleError{ no_connection_possible: false })
547 hash_map::Entry::Vacant(entry) => {
548 log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
549 entry.insert(peer_descriptor.clone())
555 let next_step = peer.channel_encryptor.get_noise_step();
557 NextNoiseStep::ActOne => {
558 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();
559 peer.pending_outbound_buffer.push_back(act_two);
560 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
562 NextNoiseStep::ActTwo => {
563 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
564 peer.pending_outbound_buffer.push_back(act_three.to_vec());
565 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
566 peer.pending_read_is_header = true;
568 peer.their_node_id = Some(their_node_id);
570 let mut local_features = msgs::LocalFeatures::new();
571 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
572 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
573 local_features.set_initial_routing_sync();
575 encode_and_send_msg!(msgs::Init {
576 global_features: msgs::GlobalFeatures::new(),
580 NextNoiseStep::ActThree => {
581 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
582 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
583 peer.pending_read_is_header = true;
584 peer.their_node_id = Some(their_node_id);
587 NextNoiseStep::NoiseComplete => {
588 if peer.pending_read_is_header {
589 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
590 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
591 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
592 if msg_len < 2 { // Need at least the message type tag
593 return Err(PeerHandleError{ no_connection_possible: false });
595 peer.pending_read_is_header = false;
597 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
598 assert!(msg_data.len() >= 2);
601 peer.pending_read_buffer = [0; 18].to_vec();
602 peer.pending_read_is_header = true;
604 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
605 log_trace!(self, "Received message of type {} from {}", msg_type, log_pubkey!(peer.their_node_id.unwrap()));
606 if msg_type != 16 && peer.their_global_features.is_none() {
607 // Need an init message as first message
608 log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
609 return Err(PeerHandleError{ no_connection_possible: false });
611 let mut reader = ::std::io::Cursor::new(&msg_data[2..]);
613 // Connection control:
615 let msg = try_potential_decodeerror!(msgs::Init::read(&mut reader));
616 if msg.global_features.requires_unknown_bits() {
617 log_info!(self, "Peer global features required unknown version bits");
618 return Err(PeerHandleError{ no_connection_possible: true });
620 if msg.local_features.requires_unknown_bits() {
621 log_info!(self, "Peer local features required unknown version bits");
622 return Err(PeerHandleError{ no_connection_possible: true });
624 if msg.local_features.requires_data_loss_protect() {
625 log_info!(self, "Peer local features required data_loss_protect");
626 return Err(PeerHandleError{ no_connection_possible: true });
628 if peer.their_global_features.is_some() {
629 return Err(PeerHandleError{ no_connection_possible: false });
632 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
633 if msg.local_features.supports_data_loss_protect() { "supported" } else { "not supported"},
634 if msg.local_features.initial_routing_sync() { "requested" } else { "not requested" },
635 if msg.local_features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
636 if msg.local_features.supports_unknown_bits() { "present" } else { "none" },
637 if msg.global_features.supports_unknown_bits() { "present" } else { "none" });
639 if msg.local_features.initial_routing_sync() {
640 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
641 peers.peers_needing_send.insert(peer_descriptor.clone());
643 peer.their_global_features = Some(msg.global_features);
644 peer.their_local_features = Some(msg.local_features);
647 let mut local_features = msgs::LocalFeatures::new();
648 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
649 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
650 local_features.set_initial_routing_sync();
653 encode_and_send_msg!(msgs::Init {
654 global_features: msgs::GlobalFeatures::new(),
659 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap());
662 let msg = try_potential_decodeerror!(msgs::ErrorMessage::read(&mut reader));
663 let mut data_is_printable = true;
664 for b in msg.data.bytes() {
665 if b < 32 || b > 126 {
666 data_is_printable = false;
671 if data_is_printable {
672 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
674 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
676 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
677 if msg.channel_id == [0; 32] {
678 return Err(PeerHandleError{ no_connection_possible: true });
683 let msg = try_potential_decodeerror!(msgs::Ping::read(&mut reader));
684 if msg.ponglen < 65532 {
685 let resp = msgs::Pong { byteslen: msg.ponglen };
686 encode_and_send_msg!(resp, 19);
690 try_potential_decodeerror!(msgs::Pong::read(&mut reader));
695 let msg = try_potential_decodeerror!(msgs::OpenChannel::read(&mut reader));
696 try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
699 let msg = try_potential_decodeerror!(msgs::AcceptChannel::read(&mut reader));
700 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
704 let msg = try_potential_decodeerror!(msgs::FundingCreated::read(&mut reader));
705 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
708 let msg = try_potential_decodeerror!(msgs::FundingSigned::read(&mut reader));
709 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
712 let msg = try_potential_decodeerror!(msgs::FundingLocked::read(&mut reader));
713 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
717 let msg = try_potential_decodeerror!(msgs::Shutdown::read(&mut reader));
718 try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
721 let msg = try_potential_decodeerror!(msgs::ClosingSigned::read(&mut reader));
722 try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
726 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::read(&mut reader));
727 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
730 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::read(&mut reader));
731 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
734 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::read(&mut reader));
735 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
738 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::read(&mut reader));
739 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
743 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::read(&mut reader));
744 try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
747 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::read(&mut reader));
748 try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
751 let msg = try_potential_decodeerror!(msgs::UpdateFee::read(&mut reader));
752 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
755 let msg = try_potential_decodeerror!(msgs::ChannelReestablish::read(&mut reader));
756 try_potential_handleerror!(self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg));
761 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::read(&mut reader));
762 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
765 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::read(&mut reader));
766 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
769 // TODO: forward msg along to all our other peers!
773 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::read(&mut reader));
774 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
777 // TODO: forward msg along to all our other peers!
781 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::read(&mut reader));
782 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
785 // TODO: forward msg along to all our other peers!
789 if (msg_type & 1) == 0 {
790 return Err(PeerHandleError{ no_connection_possible: true });
800 self.do_attempt_write_data(peer_descriptor, peer);
802 peer.pending_outbound_buffer.len() > 10 // pause_read
812 /// Checks for any events generated by our handlers and processes them. Includes sending most
813 /// response messages as well as messages generated by calls to handler functions directly (eg
814 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
815 pub fn process_events(&self) {
817 // TODO: There are some DoS attacks here where you can flood someone's outbound send
818 // buffer by doing things like announcing channels on another node. We should be willing to
819 // drop optional-ish messages when send buffers get full!
821 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
822 let mut peers_lock = self.peers.lock().unwrap();
823 let peers = peers_lock.borrow_parts();
824 for event in events_generated.drain(..) {
825 macro_rules! get_peer_for_forwarding {
826 ($node_id: expr, $handle_no_such_peer: block) => {
828 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
829 Some(descriptor) => descriptor.clone(),
831 $handle_no_such_peer;
835 match peers.peers.get_mut(&descriptor) {
837 if peer.their_global_features.is_none() {
838 $handle_no_such_peer;
843 None => panic!("Inconsistent peers set state!"),
849 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
850 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
851 log_pubkey!(node_id),
852 log_bytes!(msg.temporary_channel_id));
853 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
854 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
856 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 33)));
857 self.do_attempt_write_data(&mut descriptor, peer);
859 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
860 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
861 log_pubkey!(node_id),
862 log_bytes!(msg.temporary_channel_id));
863 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
864 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
866 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
867 self.do_attempt_write_data(&mut descriptor, peer);
869 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
870 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
871 log_pubkey!(node_id),
872 log_bytes!(msg.temporary_channel_id),
873 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
874 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
875 //TODO: generate a DiscardFunding event indicating to the wallet that
876 //they should just throw away this funding transaction
878 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
879 self.do_attempt_write_data(&mut descriptor, peer);
881 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
882 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
883 log_pubkey!(node_id),
884 log_bytes!(msg.channel_id));
885 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
886 //TODO: generate a DiscardFunding event indicating to the wallet that
887 //they should just throw away this funding transaction
889 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 35)));
890 self.do_attempt_write_data(&mut descriptor, peer);
892 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
893 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
894 log_pubkey!(node_id),
895 log_bytes!(msg.channel_id));
896 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
897 //TODO: Do whatever we're gonna do for handling dropped messages
899 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
900 self.do_attempt_write_data(&mut descriptor, peer);
902 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
903 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
904 log_pubkey!(node_id),
905 log_bytes!(msg.channel_id));
906 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
907 //TODO: generate a DiscardFunding event indicating to the wallet that
908 //they should just throw away this funding transaction
910 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 259)));
911 self.do_attempt_write_data(&mut descriptor, peer);
913 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 } } => {
914 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
915 log_pubkey!(node_id),
916 update_add_htlcs.len(),
917 update_fulfill_htlcs.len(),
918 update_fail_htlcs.len(),
919 log_bytes!(commitment_signed.channel_id));
920 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
921 //TODO: Do whatever we're gonna do for handling dropped messages
923 for msg in update_add_htlcs {
924 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
926 for msg in update_fulfill_htlcs {
927 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
929 for msg in update_fail_htlcs {
930 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
932 for msg in update_fail_malformed_htlcs {
933 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135)));
935 if let &Some(ref msg) = update_fee {
936 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 134)));
938 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed, 132)));
939 self.do_attempt_write_data(&mut descriptor, peer);
941 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
942 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
943 log_pubkey!(node_id),
944 log_bytes!(msg.channel_id));
945 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
946 //TODO: Do whatever we're gonna do for handling dropped messages
948 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 133)));
949 self.do_attempt_write_data(&mut descriptor, peer);
951 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
952 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
953 log_pubkey!(node_id),
954 log_bytes!(msg.channel_id));
955 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
956 //TODO: Do whatever we're gonna do for handling dropped messages
958 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 39)));
959 self.do_attempt_write_data(&mut descriptor, peer);
961 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
962 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
963 log_pubkey!(node_id),
964 log_bytes!(msg.channel_id));
965 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
966 //TODO: Do whatever we're gonna do for handling dropped messages
968 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
969 self.do_attempt_write_data(&mut descriptor, peer);
971 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
972 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
973 log_pubkey!(node_id),
974 log_bytes!(msg.channel_id));
975 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
976 //TODO: Do whatever we're gonna do for handling dropped messages
978 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 136)));
979 self.do_attempt_write_data(&mut descriptor, peer);
981 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
982 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
983 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
984 let encoded_msg = encode_msg!(msg, 256);
985 let encoded_update_msg = encode_msg!(update_msg, 258);
987 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
988 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
989 !peer.should_forward_channel(msg.contents.short_channel_id) {
992 match peer.their_node_id {
994 Some(their_node_id) => {
995 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1000 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1001 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
1002 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1006 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1007 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1008 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
1009 let encoded_msg = encode_msg!(msg, 258);
1011 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
1012 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
1013 !peer.should_forward_channel(msg.contents.short_channel_id) {
1016 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1017 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1021 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1022 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1024 MessageSendEvent::HandleError { ref node_id, ref action } => {
1025 if let Some(ref action) = *action {
1027 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1028 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1029 peers.peers_needing_send.remove(&descriptor);
1030 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1031 if let Some(ref msg) = *msg {
1032 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1033 log_pubkey!(node_id),
1035 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1036 // This isn't guaranteed to work, but if there is enough free
1037 // room in the send buffer, put the error message there...
1038 self.do_attempt_write_data(&mut descriptor, &mut peer);
1040 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1043 descriptor.disconnect_socket();
1044 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1047 msgs::ErrorAction::IgnoreError => {},
1048 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1049 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1050 log_pubkey!(node_id),
1052 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1053 //TODO: Do whatever we're gonna do for handling dropped messages
1055 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1056 self.do_attempt_write_data(&mut descriptor, peer);
1060 log_error!(self, "Got no-action HandleError Event in peer_handler for node {}, no such events should ever be generated!", log_pubkey!(node_id));
1066 for mut descriptor in peers.peers_needing_send.drain() {
1067 match peers.peers.get_mut(&descriptor) {
1068 Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1069 None => panic!("Inconsistent peers set state!"),
1075 /// Indicates that the given socket descriptor's connection is now closed.
1077 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
1078 /// but must NOT be called if a PeerHandleError was provided out of a new_\*\_connection event!
1080 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1081 pub fn disconnect_event(&self, descriptor: &Descriptor) {
1082 self.disconnect_event_internal(descriptor, false);
1085 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1086 let mut peers = self.peers.lock().unwrap();
1087 peers.peers_needing_send.remove(descriptor);
1088 let peer_option = peers.peers.remove(descriptor);
1090 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1092 match peer.their_node_id {
1094 peers.node_id_to_descriptor.remove(&node_id);
1095 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1106 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1109 use util::test_utils;
1110 use util::logger::Logger;
1112 use secp256k1::Secp256k1;
1113 use secp256k1::key::{SecretKey, PublicKey};
1115 use rand::{thread_rng, Rng};
1117 use std::sync::{Arc};
1119 #[derive(PartialEq, Eq, Clone, Hash)]
1120 struct FileDescriptor {
1124 impl SocketDescriptor for FileDescriptor {
1125 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
1126 assert!(write_offset < data.len());
1127 data.len() - write_offset
1130 fn disconnect_socket(&mut self) {}
1133 fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
1134 let mut peers = Vec::new();
1135 let mut rng = thread_rng();
1136 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1137 let mut ephemeral_bytes = [0; 32];
1138 rng.fill_bytes(&mut ephemeral_bytes);
1140 for _ in 0..peer_count {
1141 let chan_handler = test_utils::TestChannelMessageHandler::new();
1142 let router = test_utils::TestRoutingMessageHandler::new();
1144 let mut key_slice = [0;32];
1145 rng.fill_bytes(&mut key_slice);
1146 SecretKey::from_slice(&key_slice).unwrap()
1148 let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
1149 let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1156 fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
1157 let secp_ctx = Secp256k1::new();
1158 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
1159 let fd = FileDescriptor { fd: 1};
1160 peer_a.new_inbound_connection(fd.clone()).unwrap();
1161 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
1165 fn test_disconnect_peer() {
1166 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1167 // push a DisconnectPeer event to remove the node flagged by id
1168 let mut peers = create_network(2);
1169 establish_connection(&peers[0], &peers[1]);
1170 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1172 let secp_ctx = Secp256k1::new();
1173 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1175 let chan_handler = test_utils::TestChannelMessageHandler::new();
1176 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1178 action: Some(msgs::ErrorAction::DisconnectPeer { msg: None }),
1180 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1181 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
1183 peers[0].process_events();
1184 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);