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 slice to the peer.
50 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
51 /// Note that in the disconnected case, a disconnect_event must still fire and further write
52 /// attempts may occur until that time.
54 /// If the returned size is smaller than data.len(), a write_available event must
55 /// trigger the next time more data can be written. Additionally, until the a send_data event
56 /// completes fully, no further read_events should trigger on the same peer!
58 /// If a read_event on this descriptor had previously returned true (indicating that read
59 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
60 /// indicating that read events on this descriptor should resume. A resume_read of false does
61 /// *not* imply that further read events should be paused.
62 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
63 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
64 /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
65 /// No disconnect_event should be generated as a result of this call, though obviously races
66 /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
67 /// that event completing.
68 fn disconnect_socket(&mut self);
71 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
72 /// generate no further read/write_events for the descriptor, only triggering a single
73 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
74 /// no such disconnect_event must be generated and the socket be silently disconencted).
75 pub struct PeerHandleError {
76 /// Used to indicate that we probably can't make any future connections to this peer, implying
77 /// we should go ahead and force-close any channels we have with it.
78 no_connection_possible: bool,
80 impl fmt::Debug for PeerHandleError {
81 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
82 formatter.write_str("Peer Sent Invalid Data")
85 impl fmt::Display for PeerHandleError {
86 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
87 formatter.write_str("Peer Sent Invalid Data")
90 impl error::Error for PeerHandleError {
91 fn description(&self) -> &str {
92 "Peer Sent Invalid Data"
99 NodesSyncing(PublicKey),
103 channel_encryptor: PeerChannelEncryptor,
105 their_node_id: Option<PublicKey>,
106 their_global_features: Option<msgs::GlobalFeatures>,
107 their_local_features: Option<msgs::LocalFeatures>,
109 pending_outbound_buffer: LinkedList<Vec<u8>>,
110 pending_outbound_buffer_first_msg_offset: usize,
111 awaiting_write_event: bool,
113 pending_read_buffer: Vec<u8>,
114 pending_read_buffer_pos: usize,
115 pending_read_is_header: bool,
117 sync_status: InitSyncTracker,
121 /// Returns true if the channel announcements/updates for the given channel should be
122 /// forwarded to this peer.
123 /// If we are sending our routing table to this peer and we have not yet sent channel
124 /// announcements/updates for the given channel_id then we will send it when we get to that
125 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
126 /// sent the old versions, we should send the update, and so return true here.
127 fn should_forward_channel(&self, channel_id: u64)->bool{
128 match self.sync_status {
129 InitSyncTracker::NoSyncRequested => true,
130 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
131 InitSyncTracker::NodesSyncing(_) => true,
136 struct PeerHolder<Descriptor: SocketDescriptor> {
137 peers: HashMap<Descriptor, Peer>,
138 /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
139 /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
140 peers_needing_send: HashSet<Descriptor>,
141 /// Only add to this set when noise completes:
142 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
144 struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
145 peers: &'a mut HashMap<Descriptor, Peer>,
146 peers_needing_send: &'a mut HashSet<Descriptor>,
147 node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
149 impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
150 fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
152 peers: &mut self.peers,
153 peers_needing_send: &mut self.peers_needing_send,
154 node_id_to_descriptor: &mut self.node_id_to_descriptor,
159 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
160 fn _check_usize_is_32_or_64() {
161 // See below, less than 32 bit pointers may be unsafe here!
162 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
165 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
166 /// events into messages which it passes on to its MessageHandlers.
167 pub struct PeerManager<Descriptor: SocketDescriptor> {
168 message_handler: MessageHandler,
169 peers: Mutex<PeerHolder<Descriptor>>,
170 our_node_secret: SecretKey,
171 ephemeral_key_midstate: Sha256Engine,
173 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
174 // bits we will never realistically count into high:
175 peer_counter_low: AtomicUsize,
176 peer_counter_high: AtomicUsize,
178 initial_syncs_sent: AtomicUsize,
182 struct VecWriter(Vec<u8>);
183 impl Writer for VecWriter {
184 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
185 self.0.extend_from_slice(buf);
188 fn size_hint(&mut self, size: usize) {
189 self.0.reserve_exact(size);
193 macro_rules! encode_msg {
194 ($msg: expr, $msg_code: expr) => {{
195 let mut msg = VecWriter(Vec::new());
196 ($msg_code as u16).write(&mut msg).unwrap();
197 $msg.write(&mut msg).unwrap();
202 //TODO: Really should do something smarter for this
203 const INITIAL_SYNCS_TO_SEND: usize = 5;
205 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
206 /// PeerIds may repeat, but only after disconnect_event() has been called.
207 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
208 /// Constructs a new PeerManager with the given message handlers and node_id secret key
209 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
210 /// cryptographically secure random bytes.
211 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor> {
212 let mut ephemeral_key_midstate = Sha256::engine();
213 ephemeral_key_midstate.input(ephemeral_random_data);
216 message_handler: message_handler,
217 peers: Mutex::new(PeerHolder {
218 peers: HashMap::new(),
219 peers_needing_send: HashSet::new(),
220 node_id_to_descriptor: HashMap::new()
222 our_node_secret: our_node_secret,
223 ephemeral_key_midstate,
224 peer_counter_low: AtomicUsize::new(0),
225 peer_counter_high: AtomicUsize::new(0),
226 initial_syncs_sent: AtomicUsize::new(0),
231 /// Get the list of node ids for peers which have completed the initial handshake.
233 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
234 /// new_outbound_connection, however entries will only appear once the initial handshake has
235 /// completed and we are sure the remote peer has the private key for the given node_id.
236 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
237 let peers = self.peers.lock().unwrap();
238 peers.peers.values().filter_map(|p| {
239 if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() {
246 fn get_ephemeral_key(&self) -> SecretKey {
247 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
248 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
249 let high = if low == 0 {
250 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
252 self.peer_counter_high.load(Ordering::Acquire)
254 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
255 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
256 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
259 /// Indicates a new outbound connection has been established to a node with the given node_id.
260 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
261 /// descriptor but must disconnect the connection immediately.
263 /// Returns a small number of bytes to send to the remote node (currently always 50).
265 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
266 /// disconnect_event.
267 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
268 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
269 let res = peer_encryptor.get_act_one().to_vec();
270 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
272 let mut peers = self.peers.lock().unwrap();
273 if peers.peers.insert(descriptor, Peer {
274 channel_encryptor: peer_encryptor,
277 their_global_features: None,
278 their_local_features: None,
280 pending_outbound_buffer: LinkedList::new(),
281 pending_outbound_buffer_first_msg_offset: 0,
282 awaiting_write_event: false,
284 pending_read_buffer: pending_read_buffer,
285 pending_read_buffer_pos: 0,
286 pending_read_is_header: false,
288 sync_status: InitSyncTracker::NoSyncRequested,
290 panic!("PeerManager driver duplicated descriptors!");
295 /// Indicates a new inbound connection has been established.
297 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
298 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
299 /// call disconnect_event for the new descriptor but must disconnect the connection
302 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
303 /// disconnect_event.
304 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
305 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
306 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
308 let mut peers = self.peers.lock().unwrap();
309 if peers.peers.insert(descriptor, Peer {
310 channel_encryptor: peer_encryptor,
313 their_global_features: None,
314 their_local_features: None,
316 pending_outbound_buffer: LinkedList::new(),
317 pending_outbound_buffer_first_msg_offset: 0,
318 awaiting_write_event: false,
320 pending_read_buffer: pending_read_buffer,
321 pending_read_buffer_pos: 0,
322 pending_read_is_header: false,
324 sync_status: InitSyncTracker::NoSyncRequested,
326 panic!("PeerManager driver duplicated descriptors!");
331 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
332 macro_rules! encode_and_send_msg {
333 ($msg: expr, $msg_code: expr) => {
335 log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
336 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
340 const MSG_BUFF_SIZE: usize = 10;
341 while !peer.awaiting_write_event {
342 if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
343 match peer.sync_status {
344 InitSyncTracker::NoSyncRequested => {},
345 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
346 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
347 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
348 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
349 encode_and_send_msg!(announce, 256);
350 encode_and_send_msg!(update_a, 258);
351 encode_and_send_msg!(update_b, 258);
352 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
354 if all_messages.is_empty() || all_messages.len() != steps as usize {
355 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
358 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
359 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
360 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
361 for msg in all_messages.iter() {
362 encode_and_send_msg!(msg, 256);
363 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
365 if all_messages.is_empty() || all_messages.len() != steps as usize {
366 peer.sync_status = InitSyncTracker::NoSyncRequested;
369 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
370 InitSyncTracker::NodesSyncing(key) => {
371 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
372 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
373 for msg in all_messages.iter() {
374 encode_and_send_msg!(msg, 256);
375 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
377 if all_messages.is_empty() || all_messages.len() != steps as usize {
378 peer.sync_status = InitSyncTracker::NoSyncRequested;
385 let next_buff = match peer.pending_outbound_buffer.front() {
390 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
391 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
392 let data_sent = descriptor.send_data(pending, should_be_reading);
393 peer.pending_outbound_buffer_first_msg_offset += data_sent;
394 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
396 peer.pending_outbound_buffer_first_msg_offset = 0;
397 peer.pending_outbound_buffer.pop_front();
399 peer.awaiting_write_event = true;
404 /// Indicates that there is room to write data to the given socket descriptor.
406 /// May return an Err to indicate that the connection should be closed.
408 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
409 /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
410 /// invariants around calling write_event in case a write did not fully complete must still
411 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
412 /// Panics if the descriptor was not previously registered in a new_\*_connection event.
413 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
414 let mut peers = self.peers.lock().unwrap();
415 match peers.peers.get_mut(descriptor) {
416 None => panic!("Descriptor for write_event is not already known to PeerManager"),
418 peer.awaiting_write_event = false;
419 self.do_attempt_write_data(descriptor, peer);
425 /// Indicates that data was read from the given socket descriptor.
427 /// May return an Err to indicate that the connection should be closed.
429 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
430 /// Thus, however, you almost certainly want to call process_events() after any read_event to
431 /// generate send_data calls to handle responses.
433 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
434 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer).
436 /// Panics if the descriptor was not previously registered in a new_*_connection event.
437 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
438 match self.do_read_event(peer_descriptor, data) {
441 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
447 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
449 let mut peers_lock = self.peers.lock().unwrap();
450 let peers = peers_lock.borrow_parts();
451 let pause_read = match peers.peers.get_mut(peer_descriptor) {
452 None => panic!("Descriptor for read_event is not already known to PeerManager"),
454 assert!(peer.pending_read_buffer.len() > 0);
455 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
457 let mut read_pos = 0;
458 while read_pos < data.len() {
460 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
461 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]);
462 read_pos += data_to_copy;
463 peer.pending_read_buffer_pos += data_to_copy;
466 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
467 peer.pending_read_buffer_pos = 0;
469 macro_rules! encode_and_send_msg {
470 ($msg: expr, $msg_code: expr) => {
472 log_trace!(self, "Encoding and sending message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
473 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
474 peers.peers_needing_send.insert(peer_descriptor.clone());
479 macro_rules! try_potential_handleerror {
485 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
486 //TODO: Try to push msg
487 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
488 return Err(PeerHandleError{ no_connection_possible: false });
490 msgs::ErrorAction::IgnoreError => {
491 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
494 msgs::ErrorAction::SendErrorMessage { msg } => {
495 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
496 encode_and_send_msg!(msg, 17);
505 macro_rules! try_potential_decodeerror {
511 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError{ no_connection_possible: false }),
512 msgs::DecodeError::UnknownRequiredFeature => {
513 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
516 msgs::DecodeError::InvalidValue => {
517 log_debug!(self, "Got an invalid value while deserializing message");
518 return Err(PeerHandleError{ no_connection_possible: false });
520 msgs::DecodeError::ShortRead => {
521 log_debug!(self, "Deserialization failed due to shortness of message");
522 return Err(PeerHandleError{ no_connection_possible: false });
524 msgs::DecodeError::ExtraAddressesPerType => {
525 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
528 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
529 msgs::DecodeError::Io(_) => return Err(PeerHandleError{ no_connection_possible: false }),
536 macro_rules! insert_node_id {
538 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
539 hash_map::Entry::Occupied(_) => {
540 log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
541 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
542 return Err(PeerHandleError{ no_connection_possible: false })
544 hash_map::Entry::Vacant(entry) => {
545 log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
546 entry.insert(peer_descriptor.clone())
552 let next_step = peer.channel_encryptor.get_noise_step();
554 NextNoiseStep::ActOne => {
555 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();
556 peer.pending_outbound_buffer.push_back(act_two);
557 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
559 NextNoiseStep::ActTwo => {
560 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
561 peer.pending_outbound_buffer.push_back(act_three.to_vec());
562 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
563 peer.pending_read_is_header = true;
565 peer.their_node_id = Some(their_node_id);
567 let mut local_features = msgs::LocalFeatures::new();
568 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
569 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
570 local_features.set_initial_routing_sync();
572 encode_and_send_msg!(msgs::Init {
573 global_features: msgs::GlobalFeatures::new(),
577 NextNoiseStep::ActThree => {
578 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
579 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
580 peer.pending_read_is_header = true;
581 peer.their_node_id = Some(their_node_id);
584 NextNoiseStep::NoiseComplete => {
585 if peer.pending_read_is_header {
586 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
587 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
588 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
589 if msg_len < 2 { // Need at least the message type tag
590 return Err(PeerHandleError{ no_connection_possible: false });
592 peer.pending_read_is_header = false;
594 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
595 assert!(msg_data.len() >= 2);
598 peer.pending_read_buffer = [0; 18].to_vec();
599 peer.pending_read_is_header = true;
601 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
602 log_trace!(self, "Received message of type {} from {}", msg_type, log_pubkey!(peer.their_node_id.unwrap()));
603 if msg_type != 16 && peer.their_global_features.is_none() {
604 // Need an init message as first message
605 log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
606 return Err(PeerHandleError{ no_connection_possible: false });
608 let mut reader = ::std::io::Cursor::new(&msg_data[2..]);
610 // Connection control:
612 let msg = try_potential_decodeerror!(msgs::Init::read(&mut reader));
613 if msg.global_features.requires_unknown_bits() {
614 log_info!(self, "Peer global features required unknown version bits");
615 return Err(PeerHandleError{ no_connection_possible: true });
617 if msg.local_features.requires_unknown_bits() {
618 log_info!(self, "Peer local features required unknown version bits");
619 return Err(PeerHandleError{ no_connection_possible: true });
621 if peer.their_global_features.is_some() {
622 return Err(PeerHandleError{ no_connection_possible: false });
625 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
626 if msg.local_features.supports_data_loss_protect() { "supported" } else { "not supported"},
627 if msg.local_features.initial_routing_sync() { "requested" } else { "not requested" },
628 if msg.local_features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
629 if msg.local_features.supports_unknown_bits() { "present" } else { "none" },
630 if msg.global_features.supports_unknown_bits() { "present" } else { "none" });
632 if msg.local_features.initial_routing_sync() {
633 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
634 peers.peers_needing_send.insert(peer_descriptor.clone());
636 peer.their_global_features = Some(msg.global_features);
637 peer.their_local_features = Some(msg.local_features);
640 let mut local_features = msgs::LocalFeatures::new();
641 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
642 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
643 local_features.set_initial_routing_sync();
646 encode_and_send_msg!(msgs::Init {
647 global_features: msgs::GlobalFeatures::new(),
652 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap());
655 let msg = try_potential_decodeerror!(msgs::ErrorMessage::read(&mut reader));
656 let mut data_is_printable = true;
657 for b in msg.data.bytes() {
658 if b < 32 || b > 126 {
659 data_is_printable = false;
664 if data_is_printable {
665 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
667 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
669 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
670 if msg.channel_id == [0; 32] {
671 return Err(PeerHandleError{ no_connection_possible: true });
676 let msg = try_potential_decodeerror!(msgs::Ping::read(&mut reader));
677 if msg.ponglen < 65532 {
678 let resp = msgs::Pong { byteslen: msg.ponglen };
679 encode_and_send_msg!(resp, 19);
683 try_potential_decodeerror!(msgs::Pong::read(&mut reader));
688 let msg = try_potential_decodeerror!(msgs::OpenChannel::read(&mut reader));
689 try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
692 let msg = try_potential_decodeerror!(msgs::AcceptChannel::read(&mut reader));
693 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_local_features.clone().unwrap(), &msg));
697 let msg = try_potential_decodeerror!(msgs::FundingCreated::read(&mut reader));
698 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
701 let msg = try_potential_decodeerror!(msgs::FundingSigned::read(&mut reader));
702 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
705 let msg = try_potential_decodeerror!(msgs::FundingLocked::read(&mut reader));
706 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
710 let msg = try_potential_decodeerror!(msgs::Shutdown::read(&mut reader));
711 try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
714 let msg = try_potential_decodeerror!(msgs::ClosingSigned::read(&mut reader));
715 try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
719 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::read(&mut reader));
720 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
723 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::read(&mut reader));
724 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
727 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::read(&mut reader));
728 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
731 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::read(&mut reader));
732 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
736 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::read(&mut reader));
737 try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
740 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::read(&mut reader));
741 try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
744 let msg = try_potential_decodeerror!(msgs::UpdateFee::read(&mut reader));
745 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
748 let msg = try_potential_decodeerror!(msgs::ChannelReestablish::read(&mut reader));
749 try_potential_handleerror!(self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg));
754 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::read(&mut reader));
755 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
758 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::read(&mut reader));
759 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
762 // TODO: forward msg along to all our other peers!
766 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::read(&mut reader));
767 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
770 // TODO: forward msg along to all our other peers!
774 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::read(&mut reader));
775 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
778 // TODO: forward msg along to all our other peers!
782 if (msg_type & 1) == 0 {
783 return Err(PeerHandleError{ no_connection_possible: true });
793 self.do_attempt_write_data(peer_descriptor, peer);
795 peer.pending_outbound_buffer.len() > 10 // pause_read
805 /// Checks for any events generated by our handlers and processes them. Includes sending most
806 /// response messages as well as messages generated by calls to handler functions directly (eg
807 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
808 pub fn process_events(&self) {
810 // TODO: There are some DoS attacks here where you can flood someone's outbound send
811 // buffer by doing things like announcing channels on another node. We should be willing to
812 // drop optional-ish messages when send buffers get full!
814 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
815 let mut peers_lock = self.peers.lock().unwrap();
816 let peers = peers_lock.borrow_parts();
817 for event in events_generated.drain(..) {
818 macro_rules! get_peer_for_forwarding {
819 ($node_id: expr, $handle_no_such_peer: block) => {
821 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
822 Some(descriptor) => descriptor.clone(),
824 $handle_no_such_peer;
828 match peers.peers.get_mut(&descriptor) {
830 if peer.their_global_features.is_none() {
831 $handle_no_such_peer;
836 None => panic!("Inconsistent peers set state!"),
842 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
843 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
844 log_pubkey!(node_id),
845 log_bytes!(msg.temporary_channel_id));
846 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
847 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
849 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 33)));
850 self.do_attempt_write_data(&mut descriptor, peer);
852 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
853 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
854 log_pubkey!(node_id),
855 log_bytes!(msg.temporary_channel_id));
856 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
857 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
859 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
860 self.do_attempt_write_data(&mut descriptor, peer);
862 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
863 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
864 log_pubkey!(node_id),
865 log_bytes!(msg.temporary_channel_id),
866 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
867 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
868 //TODO: generate a DiscardFunding event indicating to the wallet that
869 //they should just throw away this funding transaction
871 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
872 self.do_attempt_write_data(&mut descriptor, peer);
874 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
875 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
876 log_pubkey!(node_id),
877 log_bytes!(msg.channel_id));
878 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
879 //TODO: generate a DiscardFunding event indicating to the wallet that
880 //they should just throw away this funding transaction
882 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 35)));
883 self.do_attempt_write_data(&mut descriptor, peer);
885 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
886 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
887 log_pubkey!(node_id),
888 log_bytes!(msg.channel_id));
889 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
890 //TODO: Do whatever we're gonna do for handling dropped messages
892 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
893 self.do_attempt_write_data(&mut descriptor, peer);
895 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
896 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
897 log_pubkey!(node_id),
898 log_bytes!(msg.channel_id));
899 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
900 //TODO: generate a DiscardFunding event indicating to the wallet that
901 //they should just throw away this funding transaction
903 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 259)));
904 self.do_attempt_write_data(&mut descriptor, peer);
906 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 } } => {
907 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
908 log_pubkey!(node_id),
909 update_add_htlcs.len(),
910 update_fulfill_htlcs.len(),
911 update_fail_htlcs.len(),
912 log_bytes!(commitment_signed.channel_id));
913 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
914 //TODO: Do whatever we're gonna do for handling dropped messages
916 for msg in update_add_htlcs {
917 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
919 for msg in update_fulfill_htlcs {
920 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
922 for msg in update_fail_htlcs {
923 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
925 for msg in update_fail_malformed_htlcs {
926 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135)));
928 if let &Some(ref msg) = update_fee {
929 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 134)));
931 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed, 132)));
932 self.do_attempt_write_data(&mut descriptor, peer);
934 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
935 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
936 log_pubkey!(node_id),
937 log_bytes!(msg.channel_id));
938 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
939 //TODO: Do whatever we're gonna do for handling dropped messages
941 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 133)));
942 self.do_attempt_write_data(&mut descriptor, peer);
944 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
945 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
946 log_pubkey!(node_id),
947 log_bytes!(msg.channel_id));
948 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
949 //TODO: Do whatever we're gonna do for handling dropped messages
951 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 39)));
952 self.do_attempt_write_data(&mut descriptor, peer);
954 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
955 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
956 log_pubkey!(node_id),
957 log_bytes!(msg.channel_id));
958 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
959 //TODO: Do whatever we're gonna do for handling dropped messages
961 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
962 self.do_attempt_write_data(&mut descriptor, peer);
964 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
965 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
966 log_pubkey!(node_id),
967 log_bytes!(msg.channel_id));
968 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
969 //TODO: Do whatever we're gonna do for handling dropped messages
971 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 136)));
972 self.do_attempt_write_data(&mut descriptor, peer);
974 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
975 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
976 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
977 let encoded_msg = encode_msg!(msg, 256);
978 let encoded_update_msg = encode_msg!(update_msg, 258);
980 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
981 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
982 !peer.should_forward_channel(msg.contents.short_channel_id) {
985 match peer.their_node_id {
987 Some(their_node_id) => {
988 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
993 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
994 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
995 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
999 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1000 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1001 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
1002 let encoded_msg = encode_msg!(msg, 258);
1004 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
1005 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() ||
1006 !peer.should_forward_channel(msg.contents.short_channel_id) {
1009 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1010 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1014 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1015 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1017 MessageSendEvent::HandleError { ref node_id, ref action } => {
1019 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1020 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1021 peers.peers_needing_send.remove(&descriptor);
1022 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1023 if let Some(ref msg) = *msg {
1024 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1025 log_pubkey!(node_id),
1027 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1028 // This isn't guaranteed to work, but if there is enough free
1029 // room in the send buffer, put the error message there...
1030 self.do_attempt_write_data(&mut descriptor, &mut peer);
1032 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1035 descriptor.disconnect_socket();
1036 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1039 msgs::ErrorAction::IgnoreError => {},
1040 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1041 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1042 log_pubkey!(node_id),
1044 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1045 //TODO: Do whatever we're gonna do for handling dropped messages
1047 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
1048 self.do_attempt_write_data(&mut descriptor, peer);
1055 for mut descriptor in peers.peers_needing_send.drain() {
1056 match peers.peers.get_mut(&descriptor) {
1057 Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1058 None => panic!("Inconsistent peers set state!"),
1064 /// Indicates that the given socket descriptor's connection is now closed.
1066 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
1067 /// but must NOT be called if a PeerHandleError was provided out of a new_\*\_connection event!
1069 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1070 pub fn disconnect_event(&self, descriptor: &Descriptor) {
1071 self.disconnect_event_internal(descriptor, false);
1074 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1075 let mut peers = self.peers.lock().unwrap();
1076 peers.peers_needing_send.remove(descriptor);
1077 let peer_option = peers.peers.remove(descriptor);
1079 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1081 match peer.their_node_id {
1083 peers.node_id_to_descriptor.remove(&node_id);
1084 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1095 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1098 use util::test_utils;
1099 use util::logger::Logger;
1101 use secp256k1::Secp256k1;
1102 use secp256k1::key::{SecretKey, PublicKey};
1104 use rand::{thread_rng, Rng};
1106 use std::sync::{Arc};
1108 #[derive(PartialEq, Eq, Clone, Hash)]
1109 struct FileDescriptor {
1113 impl SocketDescriptor for FileDescriptor {
1114 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1118 fn disconnect_socket(&mut self) {}
1121 fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
1122 let mut peers = Vec::new();
1123 let mut rng = thread_rng();
1124 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1125 let mut ephemeral_bytes = [0; 32];
1126 rng.fill_bytes(&mut ephemeral_bytes);
1128 for _ in 0..peer_count {
1129 let chan_handler = test_utils::TestChannelMessageHandler::new();
1130 let router = test_utils::TestRoutingMessageHandler::new();
1132 let mut key_slice = [0;32];
1133 rng.fill_bytes(&mut key_slice);
1134 SecretKey::from_slice(&key_slice).unwrap()
1136 let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
1137 let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1144 fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
1145 let secp_ctx = Secp256k1::new();
1146 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
1147 let fd = FileDescriptor { fd: 1};
1148 peer_a.new_inbound_connection(fd.clone()).unwrap();
1149 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
1153 fn test_disconnect_peer() {
1154 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1155 // push a DisconnectPeer event to remove the node flagged by id
1156 let mut peers = create_network(2);
1157 establish_connection(&peers[0], &peers[1]);
1158 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1160 let secp_ctx = Secp256k1::new();
1161 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1163 let chan_handler = test_utils::TestChannelMessageHandler::new();
1164 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1166 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1168 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1169 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
1171 peers[0].process_events();
1172 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);