1 use secp256k1::key::{SecretKey,PublicKey};
4 use ln::msgs::{MsgEncodable,MsgDecodable};
5 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
7 use util::events::{EventsProvider,Event};
8 use util::logger::Logger;
10 use std::collections::{HashMap,hash_map,LinkedList};
11 use std::sync::{Arc, Mutex};
12 use std::sync::atomic::{AtomicUsize, Ordering};
13 use std::{cmp,error,mem,hash,fmt};
15 pub struct MessageHandler {
16 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
17 pub route_handler: Arc<msgs::RoutingMessageHandler>,
20 /// Provides an object which can be used to send data to and which uniquely identifies a connection
21 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
22 /// implement Hash to meet the PeerManager API.
23 /// For efficiency, Clone should be relatively cheap for this type.
24 /// You probably want to just extend an int and put a file descriptor in a struct and implement
25 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
26 /// careful to ensure you don't have races whereby you might register a new connection with an fd
27 /// the same as a yet-to-be-disconnect_event()-ed.
28 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
29 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
30 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
31 /// Note that in the disconnected case, a disconnect_event must still fire and further write
32 /// attempts may occur until that time.
33 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
34 /// trigger the next time more data can be written. Additionally, until the a send_data event
35 /// completes fully, no further read_events should trigger on the same peer!
36 /// If a read_event on this descriptor had previously returned true (indicating that read
37 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
38 /// indicating that read events on this descriptor should resume. A resume_read of false does
39 /// *not* imply that further read events should be paused.
40 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
41 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
42 /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
43 /// No disconnect_event should be generated as a result of this call, though obviously races
44 /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
45 /// that event completing.
46 fn disconnect_socket(&mut self);
49 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
50 /// generate no further read/write_events for the descriptor, only triggering a single
51 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
52 /// no such disconnect_event must be generated and the socket be silently disconencted).
53 pub struct PeerHandleError {
54 no_connection_possible: bool,
56 impl fmt::Debug for PeerHandleError {
57 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
58 formatter.write_str("Peer Sent Invalid Data")
61 impl fmt::Display for PeerHandleError {
62 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
63 formatter.write_str("Peer Sent Invalid Data")
66 impl error::Error for PeerHandleError {
67 fn description(&self) -> &str {
68 "Peer Sent Invalid Data"
73 channel_encryptor: PeerChannelEncryptor,
75 their_node_id: Option<PublicKey>,
76 their_global_features: Option<msgs::GlobalFeatures>,
77 their_local_features: Option<msgs::LocalFeatures>,
79 pending_outbound_buffer: LinkedList<Vec<u8>>,
80 pending_outbound_buffer_first_msg_offset: usize,
81 awaiting_write_event: bool,
83 pending_read_buffer: Vec<u8>,
84 pending_read_buffer_pos: usize,
85 pending_read_is_header: bool,
88 struct PeerHolder<Descriptor: SocketDescriptor> {
89 peers: HashMap<Descriptor, Peer>,
90 /// Only add to this set when noise completes:
91 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
93 struct MutPeerHolder<'a, Descriptor: SocketDescriptor + 'a> {
94 peers: &'a mut HashMap<Descriptor, Peer>,
95 node_id_to_descriptor: &'a mut HashMap<PublicKey, Descriptor>,
97 impl<Descriptor: SocketDescriptor> PeerHolder<Descriptor> {
98 fn borrow_parts(&mut self) -> MutPeerHolder<Descriptor> {
100 peers: &mut self.peers,
101 node_id_to_descriptor: &mut self.node_id_to_descriptor,
106 pub struct PeerManager<Descriptor: SocketDescriptor> {
107 message_handler: MessageHandler,
108 peers: Mutex<PeerHolder<Descriptor>>,
109 pending_events: Mutex<Vec<Event>>,
110 our_node_secret: SecretKey,
111 initial_syncs_sent: AtomicUsize,
115 macro_rules! encode_msg {
116 ($msg: expr, $msg_code: expr) => {
118 let just_msg = $msg.encode();
119 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
120 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
121 encoded_msg.extend_from_slice(&just_msg[..]);
127 //TODO: Really should do something smarter for this
128 const INITIAL_SYNCS_TO_SEND: usize = 5;
130 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
131 /// PeerIds may repeat, but only after disconnect_event() has been called.
132 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
133 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, logger: Arc<Logger>) -> PeerManager<Descriptor> {
135 message_handler: message_handler,
136 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
137 pending_events: Mutex::new(Vec::new()),
138 our_node_secret: our_node_secret,
139 initial_syncs_sent: AtomicUsize::new(0),
144 /// Get the list of node ids for peers which have completed the initial handshake.
145 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
146 /// new_outbound_connection, however entries will only appear once the initial handshake has
147 /// completed and we are sure the remote peer has the private key for the given node_id.
148 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
149 let peers = self.peers.lock().unwrap();
150 peers.peers.values().filter_map(|p| {
151 if !p.channel_encryptor.is_ready_for_encryption() || p.their_global_features.is_none() {
158 /// Indicates a new outbound connection has been established to a node with the given node_id.
159 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
160 /// descriptor but must disconnect the connection immediately.
161 /// Returns some bytes to send to the remote node.
162 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
163 /// disconnect_event.
164 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
165 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
166 let res = peer_encryptor.get_act_one().to_vec();
167 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
169 let mut peers = self.peers.lock().unwrap();
170 if peers.peers.insert(descriptor, Peer {
171 channel_encryptor: peer_encryptor,
173 their_node_id: Some(their_node_id),
174 their_global_features: None,
175 their_local_features: None,
177 pending_outbound_buffer: LinkedList::new(),
178 pending_outbound_buffer_first_msg_offset: 0,
179 awaiting_write_event: false,
181 pending_read_buffer: pending_read_buffer,
182 pending_read_buffer_pos: 0,
183 pending_read_is_header: false,
185 panic!("PeerManager driver duplicated descriptors!");
190 /// Indicates a new inbound connection has been established.
191 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
192 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
193 /// call disconnect_event for the new descriptor but must disconnect the connection
195 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
196 /// disconnect_event.
197 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
198 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
199 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
201 let mut peers = self.peers.lock().unwrap();
202 if peers.peers.insert(descriptor, Peer {
203 channel_encryptor: peer_encryptor,
206 their_global_features: None,
207 their_local_features: None,
209 pending_outbound_buffer: LinkedList::new(),
210 pending_outbound_buffer_first_msg_offset: 0,
211 awaiting_write_event: false,
213 pending_read_buffer: pending_read_buffer,
214 pending_read_buffer_pos: 0,
215 pending_read_is_header: false,
217 panic!("PeerManager driver duplicated descriptors!");
222 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
223 while !peer.awaiting_write_event {
225 let next_buff = match peer.pending_outbound_buffer.front() {
229 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
231 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
232 peer.pending_outbound_buffer_first_msg_offset += data_sent;
233 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
235 peer.pending_outbound_buffer_first_msg_offset = 0;
236 peer.pending_outbound_buffer.pop_front();
238 peer.awaiting_write_event = true;
243 /// Indicates that there is room to write data to the given socket descriptor.
244 /// May return an Err to indicate that the connection should be closed.
245 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
246 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
247 /// invariants around calling write_event in case a write did not fully complete must still
248 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
249 /// Panics if the descriptor was not previously registered in a new_*_connection event.
250 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
251 let mut peers = self.peers.lock().unwrap();
252 match peers.peers.get_mut(descriptor) {
253 None => panic!("Descriptor for write_event is not already known to PeerManager"),
255 peer.awaiting_write_event = false;
256 Self::do_attempt_write_data(descriptor, peer);
262 /// Indicates that data was read from the given socket descriptor.
263 /// May return an Err to indicate that the connection should be closed.
264 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
265 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
266 /// invariants around calling write_event in case a write did not fully complete must still
267 /// hold. Note that this function will often call send_data on many peers before returning, not
269 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
270 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
271 /// that this must be true even if a send_data call with resume_read=true was made during the
272 /// course of this function!
273 /// Panics if the descriptor was not previously registered in a new_*_connection event.
274 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
275 match self.do_read_event(peer_descriptor, data) {
278 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
284 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
286 let mut peers_lock = self.peers.lock().unwrap();
287 let peers = peers_lock.borrow_parts();
288 let pause_read = match peers.peers.get_mut(peer_descriptor) {
289 None => panic!("Descriptor for read_event is not already known to PeerManager"),
291 assert!(peer.pending_read_buffer.len() > 0);
292 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
294 let mut read_pos = 0;
295 while read_pos < data.len() {
297 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
298 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]);
299 read_pos += data_to_copy;
300 peer.pending_read_buffer_pos += data_to_copy;
303 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
304 peer.pending_read_buffer_pos = 0;
306 macro_rules! encode_and_send_msg {
307 ($msg: expr, $msg_code: expr) => {
309 log_trace!(self, "Encoding and sending message of type {} to {}", $msg_code, log_pubkey!(peer.their_node_id.unwrap()));
310 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
315 macro_rules! try_potential_handleerror {
320 if let Some(action) = e.action {
322 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
323 //TODO: Try to push msg
324 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
325 return Err(PeerHandleError{ no_connection_possible: false });
327 msgs::ErrorAction::IgnoreError => {
328 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
331 msgs::ErrorAction::SendErrorMessage { msg } => {
332 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
333 encode_and_send_msg!(msg, 17);
338 log_debug!(self, "Got Err handling message, action not yet filled in: {}", e.err);
339 return Err(PeerHandleError{ no_connection_possible: false });
346 macro_rules! try_potential_decodeerror {
352 msgs::DecodeError::UnknownRealmByte => return Err(PeerHandleError{ no_connection_possible: false }),
353 msgs::DecodeError::UnknownRequiredFeature => {
354 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to udpate!");
357 msgs::DecodeError::BadPublicKey => return Err(PeerHandleError{ no_connection_possible: false }),
358 msgs::DecodeError::BadSignature => return Err(PeerHandleError{ no_connection_possible: false }),
359 msgs::DecodeError::BadText => return Err(PeerHandleError{ no_connection_possible: false }),
360 msgs::DecodeError::ShortRead => return Err(PeerHandleError{ no_connection_possible: false }),
361 msgs::DecodeError::ExtraAddressesPerType => {
362 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
365 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
372 macro_rules! insert_node_id {
374 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
375 hash_map::Entry::Occupied(_) => {
376 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
377 return Err(PeerHandleError{ no_connection_possible: false })
379 hash_map::Entry::Vacant(entry) => entry.insert(peer_descriptor.clone()),
384 let next_step = peer.channel_encryptor.get_noise_step();
386 NextNoiseStep::ActOne => {
387 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
388 peer.pending_outbound_buffer.push_back(act_two);
389 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
391 NextNoiseStep::ActTwo => {
392 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
393 peer.pending_outbound_buffer.push_back(act_three);
394 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
395 peer.pending_read_is_header = true;
398 let mut local_features = msgs::LocalFeatures::new();
399 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
400 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
401 local_features.set_initial_routing_sync();
403 encode_and_send_msg!(msgs::Init {
404 global_features: msgs::GlobalFeatures::new(),
408 NextNoiseStep::ActThree => {
409 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
410 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
411 peer.pending_read_is_header = true;
412 peer.their_node_id = Some(their_node_id);
415 NextNoiseStep::NoiseComplete => {
416 if peer.pending_read_is_header {
417 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
418 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
419 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
420 if msg_len < 2 { // Need at least the message type tag
421 return Err(PeerHandleError{ no_connection_possible: false });
423 peer.pending_read_is_header = false;
425 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
426 assert!(msg_data.len() >= 2);
429 peer.pending_read_buffer = [0; 18].to_vec();
430 peer.pending_read_is_header = true;
432 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
433 log_trace!(self, "Received message of type {} from {}", msg_type, log_pubkey!(peer.their_node_id.unwrap()));
434 if msg_type != 16 && peer.their_global_features.is_none() {
435 // Need an init message as first message
436 return Err(PeerHandleError{ no_connection_possible: false });
439 // Connection control:
441 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
442 if msg.global_features.requires_unknown_bits() {
443 return Err(PeerHandleError{ no_connection_possible: true });
445 if msg.local_features.requires_unknown_bits() {
446 return Err(PeerHandleError{ no_connection_possible: true });
448 if peer.their_global_features.is_some() {
449 return Err(PeerHandleError{ no_connection_possible: false });
451 peer.their_global_features = Some(msg.global_features);
452 peer.their_local_features = Some(msg.local_features);
455 let mut local_features = msgs::LocalFeatures::new();
456 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
457 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
458 local_features.set_initial_routing_sync();
460 encode_and_send_msg!(msgs::Init {
461 global_features: msgs::GlobalFeatures::new(),
467 let msg = try_potential_decodeerror!(msgs::ErrorMessage::decode(&msg_data[2..]));
468 let mut data_is_printable = true;
469 for b in msg.data.bytes() {
470 if b < 32 || b > 126 {
471 data_is_printable = false;
476 if data_is_printable {
477 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
479 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
481 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
482 if msg.channel_id == [0; 32] {
483 return Err(PeerHandleError{ no_connection_possible: true });
488 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
489 if msg.ponglen < 65532 {
490 let resp = msgs::Pong { byteslen: msg.ponglen };
491 encode_and_send_msg!(resp, 19);
495 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
500 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
501 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
502 encode_and_send_msg!(resp, 33);
505 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
506 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
510 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
511 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
512 encode_and_send_msg!(resp, 35);
515 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
516 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
519 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
520 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
522 Some(resp) => encode_and_send_msg!(resp, 259),
528 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
529 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
530 if let Some(resp) = resp_options.0 {
531 encode_and_send_msg!(resp, 38);
533 if let Some(resp) = resp_options.1 {
534 encode_and_send_msg!(resp, 39);
538 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
539 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
540 if let Some(resp) = resp_option {
541 encode_and_send_msg!(resp, 39);
546 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
547 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
550 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
551 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
554 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
555 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
556 if let Some(update) = chan_update {
557 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
561 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
562 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
566 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
567 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
568 encode_and_send_msg!(resps.0, 133);
569 if let Some(resp) = resps.1 {
570 encode_and_send_msg!(resp, 132);
574 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
575 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
578 for resp in resps.update_add_htlcs {
579 encode_and_send_msg!(resp, 128);
581 for resp in resps.update_fulfill_htlcs {
582 encode_and_send_msg!(resp, 130);
584 for resp in resps.update_fail_htlcs {
585 encode_and_send_msg!(resp, 131);
587 encode_and_send_msg!(resps.commitment_signed, 132);
593 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
594 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
596 136 => { }, // TODO: channel_reestablish
600 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
601 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
604 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
605 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
608 // TODO: forward msg along to all our other peers!
612 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
613 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
616 // TODO: forward msg along to all our other peers!
620 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
621 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
624 // TODO: forward msg along to all our other peers!
628 if (msg_type & 1) == 0 {
629 return Err(PeerHandleError{ no_connection_possible: true });
639 Self::do_attempt_write_data(peer_descriptor, peer);
641 peer.pending_outbound_buffer.len() > 10 // pause_read
648 self.process_events();
653 /// Checks for any events generated by our handlers and processes them. May be needed after eg
654 /// calls to ChannelManager::process_pending_htlc_forward.
655 pub fn process_events(&self) {
656 let mut upstream_events = Vec::new();
658 // TODO: There are some DoS attacks here where you can flood someone's outbound send
659 // buffer by doing things like announcing channels on another node. We should be willing to
660 // drop optional-ish messages when send buffers get full!
662 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
663 let mut peers = self.peers.lock().unwrap();
664 for event in events_generated.drain(..) {
665 macro_rules! get_peer_for_forwarding {
666 ($node_id: expr, $handle_no_such_peer: block) => {
668 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
669 Some(descriptor) => descriptor.clone(),
671 $handle_no_such_peer;
675 match peers.peers.get_mut(&descriptor) {
677 if peer.their_global_features.is_none() {
678 $handle_no_such_peer;
683 None => panic!("Inconsistent peers set state!"),
689 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
690 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
691 Event::PaymentReceived {..} => { /* Hand upstream */ },
692 Event::PaymentSent {..} => { /* Hand upstream */ },
693 Event::PaymentFailed {..} => { /* Hand upstream */ },
694 Event::PendingHTLCsForwardable {..} => { /* Hand upstream */ },
696 Event::SendOpenChannel { ref node_id, ref msg } => {
697 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
698 log_pubkey!(node_id),
699 log_bytes!(msg.temporary_channel_id));
700 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
701 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
703 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
704 Self::do_attempt_write_data(&mut descriptor, peer);
707 Event::SendFundingCreated { ref node_id, ref msg } => {
708 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
709 log_pubkey!(node_id),
710 log_bytes!(msg.temporary_channel_id),
711 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
712 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
713 //TODO: generate a DiscardFunding event indicating to the wallet that
714 //they should just throw away this funding transaction
716 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
717 Self::do_attempt_write_data(&mut descriptor, peer);
720 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
721 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {}{} for channel {}",
722 log_pubkey!(node_id),
723 if announcement_sigs.is_some() { " with announcement sigs" } else { "" },
724 log_bytes!(msg.channel_id));
725 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
726 //TODO: Do whatever we're gonna do for handling dropped messages
728 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
729 match announcement_sigs {
730 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
733 Self::do_attempt_write_data(&mut descriptor, peer);
736 Event::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 commitment_signed } } => {
737 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
738 log_pubkey!(node_id),
739 update_add_htlcs.len(),
740 update_fulfill_htlcs.len(),
741 update_fail_htlcs.len(),
742 log_bytes!(commitment_signed.channel_id));
743 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
744 //TODO: Do whatever we're gonna do for handling dropped messages
746 for msg in update_add_htlcs {
747 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
749 for msg in update_fulfill_htlcs {
750 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
752 for msg in update_fail_htlcs {
753 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
755 for msg in update_fail_malformed_htlcs {
756 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 135)));
758 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed, 132)));
759 Self::do_attempt_write_data(&mut descriptor, peer);
762 Event::SendShutdown { ref node_id, ref msg } => {
763 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
764 log_pubkey!(node_id),
765 log_bytes!(msg.channel_id));
766 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
767 //TODO: Do whatever we're gonna do for handling dropped messages
769 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
770 Self::do_attempt_write_data(&mut descriptor, peer);
773 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
774 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
775 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
776 let encoded_msg = encode_msg!(msg, 256);
777 let encoded_update_msg = encode_msg!(update_msg, 258);
779 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
780 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() {
783 match peer.their_node_id {
785 Some(their_node_id) => {
786 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
791 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
792 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
793 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
798 Event::BroadcastChannelUpdate { ref msg } => {
799 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
800 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
801 let encoded_msg = encode_msg!(msg, 258);
803 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
804 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_global_features.is_none() {
807 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
808 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
813 Event::HandleError { ref node_id, ref action } => {
814 if let Some(ref action) = *action {
816 msgs::ErrorAction::DisconnectPeer { ref msg } => {
817 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
818 if let Some(mut peer) = peers.peers.remove(&descriptor) {
819 if let Some(ref msg) = *msg {
820 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
821 log_pubkey!(node_id),
823 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
824 // This isn't guaranteed to work, but if there is enough free
825 // room in the send buffer, put the error message there...
826 Self::do_attempt_write_data(&mut descriptor, &mut peer);
828 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
831 descriptor.disconnect_socket();
832 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
835 msgs::ErrorAction::IgnoreError => {
838 msgs::ErrorAction::SendErrorMessage { ref msg } => {
839 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
840 log_pubkey!(node_id),
842 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
843 //TODO: Do whatever we're gonna do for handling dropped messages
845 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
846 Self::do_attempt_write_data(&mut descriptor, peer);
850 log_error!(self, "Got no-action HandleError Event in peer_handler for node {}, no such events should ever be generated!", log_pubkey!(node_id));
856 upstream_events.push(event);
860 let mut pending_events = self.pending_events.lock().unwrap();
861 for event in upstream_events.drain(..) {
862 pending_events.push(event);
866 /// Indicates that the given socket descriptor's connection is now closed.
867 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
868 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
869 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
870 pub fn disconnect_event(&self, descriptor: &Descriptor) {
871 self.disconnect_event_internal(descriptor, false);
874 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
875 let mut peers = self.peers.lock().unwrap();
876 let peer_option = peers.peers.remove(descriptor);
878 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
880 match peer.their_node_id {
882 peers.node_id_to_descriptor.remove(&node_id);
883 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
892 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
893 fn get_and_clear_pending_events(&self) -> Vec<Event> {
894 let mut pending_events = self.pending_events.lock().unwrap();
895 let mut ret = Vec::new();
896 mem::swap(&mut ret, &mut *pending_events);
903 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
906 use util::test_utils;
907 use util::logger::Logger;
909 use secp256k1::Secp256k1;
910 use secp256k1::key::{SecretKey, PublicKey};
912 use rand::{thread_rng, Rng};
914 use std::sync::{Arc};
916 #[derive(PartialEq, Eq, Clone, Hash)]
917 struct FileDescriptor {
921 impl SocketDescriptor for FileDescriptor {
922 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
923 assert!(write_offset < data.len());
924 data.len() - write_offset
927 fn disconnect_socket(&mut self) {}
930 fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
931 let secp_ctx = Secp256k1::new();
932 let mut peers = Vec::new();
933 let mut rng = thread_rng();
934 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
936 for _ in 0..peer_count {
937 let chan_handler = test_utils::TestChannelMessageHandler::new();
938 let router = test_utils::TestRoutingMessageHandler::new();
940 let mut key_slice = [0;32];
941 rng.fill_bytes(&mut key_slice);
942 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
944 let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
945 let peer = PeerManager::new(msg_handler, node_id, Arc::clone(&logger));
952 fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
953 let secp_ctx = Secp256k1::new();
954 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
955 let fd = FileDescriptor { fd: 1};
956 peer_a.new_inbound_connection(fd.clone()).unwrap();
957 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
961 fn test_disconnect_peer() {
962 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
963 // push an DisconnectPeer event to remove the node flagged by id
964 let mut peers = create_network(2);
965 establish_connection(&peers[0], &peers[1]);
966 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
968 let secp_ctx = Secp256k1::new();
969 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
971 let chan_handler = test_utils::TestChannelMessageHandler::new();
972 chan_handler.pending_events.lock().unwrap().push(events::Event::HandleError {
974 action: Some(msgs::ErrorAction::DisconnectPeer { msg: None }),
976 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
977 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
979 peers[0].process_events();
980 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);