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};
9 use std::collections::{HashMap,LinkedList};
10 use std::sync::{Arc, Mutex};
11 use std::sync::atomic::{AtomicUsize, Ordering};
12 use std::{cmp,error,mem,hash,fmt};
14 pub struct MessageHandler {
15 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
16 pub route_handler: Arc<msgs::RoutingMessageHandler>,
19 /// Provides an object which can be used to send data to and which uniquely identifies a connection
20 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
21 /// implement Hash to meet the PeerManager API.
22 /// For efficiency, Clone should be relatively cheap for this type.
23 /// You probably want to just extend an int and put a file descriptor in a struct and implement
25 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
26 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
27 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
28 /// Note that in the disconnected case, a disconnect_event must still fire and further write
29 /// attempts may occur until that time.
30 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
31 /// trigger the next time more data can be written. Additionally, until the a send_data event
32 /// completes fully, no further read_events should trigger on the same peer!
33 /// If a read_event on this descriptor had previously returned true (indicating that read
34 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
35 /// indicating that read events on this descriptor should resume. A resume_read of false does
36 /// *not* imply that further read events should be paused.
37 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
40 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
41 /// generate no further read/write_events for the descriptor, only triggering a single
42 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
43 /// no such disconnect_event must be generated and the socket be silently disconencted).
44 pub struct PeerHandleError {
45 no_connection_possible: bool,
47 impl fmt::Debug for PeerHandleError {
48 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
49 formatter.write_str("Peer Sent Invalid Data")
52 impl fmt::Display for PeerHandleError {
53 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
54 formatter.write_str("Peer Sent Invalid Data")
57 impl error::Error for PeerHandleError {
58 fn description(&self) -> &str {
59 "Peer Sent Invalid Data"
64 channel_encryptor: PeerChannelEncryptor,
66 their_node_id: Option<PublicKey>,
67 their_global_features: Option<msgs::GlobalFeatures>,
68 their_local_features: Option<msgs::LocalFeatures>,
70 pending_outbound_buffer: LinkedList<Vec<u8>>,
71 pending_outbound_buffer_first_msg_offset: usize,
72 awaiting_write_event: bool,
74 pending_read_buffer: Vec<u8>,
75 pending_read_buffer_pos: usize,
76 pending_read_is_header: bool,
79 struct PeerHolder<Descriptor: SocketDescriptor> {
80 peers: HashMap<Descriptor, Peer>,
81 /// Only add to this set when noise completes:
82 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
85 pub struct PeerManager<Descriptor: SocketDescriptor> {
86 message_handler: MessageHandler,
87 peers: Mutex<PeerHolder<Descriptor>>,
88 pending_events: Mutex<Vec<Event>>,
89 our_node_secret: SecretKey,
90 initial_syncs_sent: AtomicUsize,
94 macro_rules! encode_msg {
95 ($msg: expr, $msg_code: expr) => {
97 let just_msg = $msg.encode();
98 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
99 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
100 encoded_msg.extend_from_slice(&just_msg[..]);
106 //TODO: Really should do something smarter for this
107 const INITIAL_SYNCS_TO_SEND: usize = 5;
109 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
110 /// PeerIds may repeat, but only after disconnect_event() has been called.
111 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
112 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
114 message_handler: message_handler,
115 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
116 pending_events: Mutex::new(Vec::new()),
117 our_node_secret: our_node_secret,
118 initial_syncs_sent: AtomicUsize::new(0),
122 /// Indicates a new outbound connection has been established to a node with the given node_id.
123 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
124 /// descriptor but must disconnect the connection immediately.
125 /// Returns some bytes to send to the remote node.
126 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
127 /// disconnect_event.
128 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
129 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
130 let res = peer_encryptor.get_act_one().to_vec();
131 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
133 let mut peers = self.peers.lock().unwrap();
134 if peers.peers.insert(descriptor, Peer {
135 channel_encryptor: peer_encryptor,
137 their_node_id: Some(their_node_id),
138 their_global_features: None,
139 their_local_features: None,
141 pending_outbound_buffer: LinkedList::new(),
142 pending_outbound_buffer_first_msg_offset: 0,
143 awaiting_write_event: false,
145 pending_read_buffer: pending_read_buffer,
146 pending_read_buffer_pos: 0,
147 pending_read_is_header: false,
149 panic!("PeerManager driver duplicated descriptors!");
154 /// Indicates a new inbound connection has been established.
155 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
156 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
157 /// call disconnect_event for the new descriptor but must disconnect the connection
159 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
160 /// disconnect_event.
161 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
162 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
163 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
165 let mut peers = self.peers.lock().unwrap();
166 if peers.peers.insert(descriptor, Peer {
167 channel_encryptor: peer_encryptor,
170 their_global_features: None,
171 their_local_features: None,
173 pending_outbound_buffer: LinkedList::new(),
174 pending_outbound_buffer_first_msg_offset: 0,
175 awaiting_write_event: false,
177 pending_read_buffer: pending_read_buffer,
178 pending_read_buffer_pos: 0,
179 pending_read_is_header: false,
181 panic!("PeerManager driver duplicated descriptors!");
186 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
187 while !peer.awaiting_write_event {
189 let next_buff = match peer.pending_outbound_buffer.front() {
193 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
195 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
196 peer.pending_outbound_buffer_first_msg_offset += data_sent;
197 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
199 peer.pending_outbound_buffer_first_msg_offset = 0;
200 peer.pending_outbound_buffer.pop_front();
202 peer.awaiting_write_event = true;
207 /// Indicates that there is room to write data to the given socket descriptor.
208 /// May return an Err to indicate that the connection should be closed.
209 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
210 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
211 /// invariants around calling write_event in case a write did not fully complete must still
212 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
213 /// Panics if the descriptor was not previously registered in a new_*_connection event.
214 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
215 let mut peers = self.peers.lock().unwrap();
216 match peers.peers.get_mut(descriptor) {
217 None => panic!("Descriptor for write_event is not already known to PeerManager"),
219 peer.awaiting_write_event = false;
220 Self::do_attempt_write_data(descriptor, peer);
226 /// Indicates that data was read from the given socket descriptor.
227 /// May return an Err to indicate that the connection should be closed.
228 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
229 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
230 /// invariants around calling write_event in case a write did not fully complete must still
231 /// hold. Note that this function will often call send_data on many peers before returning, not
233 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
234 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
235 /// that this must be true even if a send_data call with resume_read=true was made during the
236 /// course of this function!
237 /// Panics if the descriptor was not previously registered in a new_*_connection event.
238 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
239 match self.do_read_event(peer_descriptor, data) {
242 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
248 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
250 let mut peers = self.peers.lock().unwrap();
251 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
252 None => panic!("Descriptor for read_event is not already known to PeerManager"),
254 assert!(peer.pending_read_buffer.len() > 0);
255 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
257 let mut insert_node_id = None;
258 let mut read_pos = 0;
259 while read_pos < data.len() {
261 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
262 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]);
263 read_pos += data_to_copy;
264 peer.pending_read_buffer_pos += data_to_copy;
267 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
268 peer.pending_read_buffer_pos = 0;
270 macro_rules! encode_and_send_msg {
271 ($msg: expr, $msg_code: expr) => {
272 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
276 macro_rules! try_potential_handleerror {
281 println!("Got error handling message: {}!", e.err);
282 if let Some(action) = e.msg {
284 msgs::ErrorAction::UpdateFailHTLC { msg } => {
285 encode_and_send_msg!(msg, 131);
288 msgs::ErrorAction::DisconnectPeer => {
289 return Err(PeerHandleError{ no_connection_possible: false });
291 msgs::ErrorAction::IgnoreError => {
296 return Err(PeerHandleError{ no_connection_possible: false });
303 macro_rules! try_potential_decodeerror {
308 println!("Error decoding message");
310 return Err(PeerHandleError{ no_connection_possible: false });
316 macro_rules! try_ignore_potential_decodeerror {
321 println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
328 let next_step = peer.channel_encryptor.get_noise_step();
330 NextNoiseStep::ActOne => {
331 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
332 peer.pending_outbound_buffer.push_back(act_two);
333 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
335 NextNoiseStep::ActTwo => {
336 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
337 peer.pending_outbound_buffer.push_back(act_three);
338 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
339 peer.pending_read_is_header = true;
341 insert_node_id = Some(peer.their_node_id.unwrap());
342 let mut local_features = msgs::LocalFeatures::new();
343 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
344 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
345 local_features.set_initial_routing_sync();
347 encode_and_send_msg!(msgs::Init {
348 global_features: msgs::GlobalFeatures::new(),
352 NextNoiseStep::ActThree => {
353 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
354 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
355 peer.pending_read_is_header = true;
356 peer.their_node_id = Some(their_node_id);
357 insert_node_id = Some(peer.their_node_id.unwrap());
359 NextNoiseStep::NoiseComplete => {
360 if peer.pending_read_is_header {
361 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
362 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
363 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
364 if msg_len < 2 { // Need at least the message type tag
365 return Err(PeerHandleError{ no_connection_possible: false });
367 peer.pending_read_is_header = false;
369 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
370 assert!(msg_data.len() >= 2);
373 peer.pending_read_buffer = [0; 18].to_vec();
374 peer.pending_read_is_header = true;
376 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
377 if msg_type != 16 && peer.their_global_features.is_none() {
378 // Need an init message as first message
379 return Err(PeerHandleError{ no_connection_possible: false });
382 // Connection control:
384 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
385 if msg.global_features.requires_unknown_bits() {
386 return Err(PeerHandleError{ no_connection_possible: true });
388 if msg.local_features.requires_unknown_bits() {
389 return Err(PeerHandleError{ no_connection_possible: true });
391 peer.their_global_features = Some(msg.global_features);
392 peer.their_local_features = Some(msg.local_features);
395 let mut local_features = msgs::LocalFeatures::new();
396 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
397 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
398 local_features.set_initial_routing_sync();
400 encode_and_send_msg!(msgs::Init {
401 global_features: msgs::GlobalFeatures::new(),
411 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
412 if msg.ponglen < 65532 {
413 let resp = msgs::Pong { byteslen: msg.ponglen };
414 encode_and_send_msg!(resp, 19);
418 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
423 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
424 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
425 encode_and_send_msg!(resp, 33);
428 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
429 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
433 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
434 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
435 encode_and_send_msg!(resp, 35);
438 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
439 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
442 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
443 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
445 Some(resp) => encode_and_send_msg!(resp, 259),
451 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
452 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
453 if let Some(resp) = resp_options.0 {
454 encode_and_send_msg!(resp, 38);
456 if let Some(resp) = resp_options.1 {
457 encode_and_send_msg!(resp, 39);
461 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
462 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
463 if let Some(resp) = resp_option {
464 encode_and_send_msg!(resp, 39);
469 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
470 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
473 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
474 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
477 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
478 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
479 if let Some(update) = chan_update {
480 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
484 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
485 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
489 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
490 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
491 encode_and_send_msg!(resps.0, 133);
492 if let Some(resp) = resps.1 {
493 encode_and_send_msg!(resp, 132);
497 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
498 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
501 for resp in resps.update_add_htlcs {
502 encode_and_send_msg!(resp, 128);
504 for resp in resps.update_fulfill_htlcs {
505 encode_and_send_msg!(resp, 130);
507 for resp in resps.update_fail_htlcs {
508 encode_and_send_msg!(resp, 131);
510 encode_and_send_msg!(resps.commitment_signed, 132);
516 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
517 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
519 136 => { }, // TODO: channel_reestablish
523 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
524 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
527 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
528 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
531 // TODO: forward msg along to all our other peers!
535 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
536 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
539 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
540 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
543 if (msg_type & 1) == 0 {
544 return Err(PeerHandleError{ no_connection_possible: true });
554 Self::do_attempt_write_data(peer_descriptor, peer);
556 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
560 match should_insert_node_id {
561 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
568 self.process_events();
573 /// Checks for any events generated by our handlers and processes them. May be needed after eg
574 /// calls to ChannelManager::process_pending_htlc_forward.
575 pub fn process_events(&self) {
576 let mut upstream_events = Vec::new();
578 // TODO: There are some DoS attacks here where you can flood someone's outbound send
579 // buffer by doing things like announcing channels on another node. We should be willing to
580 // drop optional-ish messages when send buffers get full!
582 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
583 let mut peers = self.peers.lock().unwrap();
584 for event in events_generated.drain(..) {
585 macro_rules! get_peer_for_forwarding {
586 ($node_id: expr, $handle_no_such_peer: block) => {
588 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
589 Some(descriptor) => descriptor.clone(),
591 $handle_no_such_peer;
595 match peers.peers.get_mut(&descriptor) {
599 None => panic!("Inconsistent peers set state!"),
605 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
606 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
607 Event::PaymentReceived {..} => { /* Hand upstream */ },
608 Event::PaymentSent {..} => { /* Hand upstream */ },
609 Event::PaymentFailed {..} => { /* Hand upstream */ },
611 Event::PendingHTLCsForwardable {..} => {
612 //TODO: Handle upstream in some confused form so that upstream just knows
613 //to call us somehow?
615 Event::SendFundingCreated { ref node_id, ref msg } => {
616 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
617 //TODO: generate a DiscardFunding event indicating to the wallet that
618 //they should just throw away this funding transaction
620 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
621 Self::do_attempt_write_data(&mut descriptor, peer);
624 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
625 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
626 //TODO: Do whatever we're gonna do for handling dropped messages
628 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
629 match announcement_sigs {
630 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
633 Self::do_attempt_write_data(&mut descriptor, peer);
636 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
637 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
638 //TODO: Do whatever we're gonna do for handling dropped messages
641 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
643 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
644 Self::do_attempt_write_data(&mut descriptor, peer);
647 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
648 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
649 //TODO: Do whatever we're gonna do for handling dropped messages
651 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
652 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
653 Self::do_attempt_write_data(&mut descriptor, peer);
656 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
657 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
658 //TODO: Do whatever we're gonna do for handling dropped messages
660 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
661 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
662 Self::do_attempt_write_data(&mut descriptor, peer);
665 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
666 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
667 let encoded_msg = encode_msg!(msg, 256);
668 let encoded_update_msg = encode_msg!(update_msg, 258);
670 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
671 if !peer.channel_encryptor.is_ready_for_encryption() {
674 match peer.their_node_id {
676 Some(their_node_id) => {
677 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
682 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
683 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
684 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
689 Event::BroadcastChannelUpdate { ref msg } => {
690 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
691 let encoded_msg = encode_msg!(msg, 258);
693 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
694 if !peer.channel_encryptor.is_ready_for_encryption() {
697 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
698 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
705 upstream_events.push(event);
709 let mut pending_events = self.pending_events.lock().unwrap();
710 for event in upstream_events.drain(..) {
711 pending_events.push(event);
715 /// Indicates that the given socket descriptor's connection is now closed.
716 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
717 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
718 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
719 pub fn disconnect_event(&self, descriptor: &Descriptor) {
720 self.disconnect_event_internal(descriptor, false);
723 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
724 let mut peers = self.peers.lock().unwrap();
725 let peer_option = peers.peers.remove(descriptor);
727 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
729 match peer.their_node_id {
731 peers.node_id_to_descriptor.remove(&node_id);
732 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
741 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
742 fn get_and_clear_pending_events(&self) -> Vec<Event> {
743 let mut pending_events = self.pending_events.lock().unwrap();
744 let mut ret = Vec::new();
745 mem::swap(&mut ret, &mut *pending_events);