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};
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
26 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
27 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
28 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
29 /// Note that in the disconnected case, a disconnect_event must still fire and further write
30 /// attempts may occur until that time.
31 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
32 /// trigger the next time more data can be written. Additionally, until the a send_data event
33 /// completes fully, no further read_events should trigger on the same peer!
34 /// If a read_event on this descriptor had previously returned true (indicating that read
35 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
36 /// indicating that read events on this descriptor should resume. A resume_read of false does
37 /// *not* imply that further read events should be paused.
38 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
41 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
42 /// generate no further read/write_events for the descriptor, only triggering a single
43 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
44 /// no such disconnect_event must be generated and the socket be silently disconencted).
45 pub struct PeerHandleError {}
48 channel_encryptor: PeerChannelEncryptor,
49 their_node_id: Option<PublicKey>,
51 pending_outbound_buffer: LinkedList<Vec<u8>>,
52 pending_outbound_buffer_first_msg_offset: usize,
53 awaiting_write_event: bool,
55 pending_read_buffer: Vec<u8>,
56 pending_read_buffer_pos: usize,
57 pending_read_is_header: bool,
60 struct PeerHolder<Descriptor: SocketDescriptor> {
61 peers: HashMap<Descriptor, Peer>,
62 /// Only add to this set when noise completes:
63 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
66 pub struct PeerManager<Descriptor: SocketDescriptor> {
67 message_handler: MessageHandler,
68 peers: Mutex<PeerHolder<Descriptor>>,
69 pending_events: Mutex<Vec<Event>>,
70 our_node_secret: SecretKey,
74 macro_rules! encode_msg {
75 ($msg: expr, $msg_code: expr) => {
77 let just_msg = $msg.encode();
78 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
79 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
80 encoded_msg.extend_from_slice(&just_msg[..]);
86 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
87 /// PeerIds may repeat, but only after disconnect_event() has been called.
88 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
89 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
91 message_handler: message_handler,
92 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
93 pending_events: Mutex::new(Vec::new()),
94 our_node_secret: our_node_secret,
98 /// Indicates a new outbound connection has been established to a node with the given node_id.
99 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
100 /// descriptor but must disconnect the connection immediately.
101 /// Returns some bytes to send to the remote node.
102 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
103 /// disconnect_event.
104 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
105 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
106 let res = peer_encryptor.get_act_one().to_vec();
107 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
109 let mut peers = self.peers.lock().unwrap();
110 if peers.peers.insert(descriptor, Peer {
111 channel_encryptor: peer_encryptor,
112 their_node_id: Some(their_node_id),
114 pending_outbound_buffer: LinkedList::new(),
115 pending_outbound_buffer_first_msg_offset: 0,
116 awaiting_write_event: false,
118 pending_read_buffer: pending_read_buffer,
119 pending_read_buffer_pos: 0,
120 pending_read_is_header: false,
122 panic!("PeerManager driver duplicated descriptors!");
127 /// Indicates a new inbound connection has been established.
128 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
129 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
130 /// call disconnect_event for the new descriptor but must disconnect the connection
132 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
133 /// disconnect_event.
134 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
135 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
136 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
138 let mut peers = self.peers.lock().unwrap();
139 if peers.peers.insert(descriptor, Peer {
140 channel_encryptor: peer_encryptor,
143 pending_outbound_buffer: LinkedList::new(),
144 pending_outbound_buffer_first_msg_offset: 0,
145 awaiting_write_event: false,
147 pending_read_buffer: pending_read_buffer,
148 pending_read_buffer_pos: 0,
149 pending_read_is_header: false,
151 panic!("PeerManager driver duplicated descriptors!");
156 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
157 while !peer.awaiting_write_event {
159 let next_buff = match peer.pending_outbound_buffer.front() {
163 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
165 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
166 peer.pending_outbound_buffer_first_msg_offset += data_sent;
167 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
169 peer.pending_outbound_buffer_first_msg_offset = 0;
170 peer.pending_outbound_buffer.pop_front();
172 peer.awaiting_write_event = true;
177 /// Indicates that there is room to write data to the given socket descriptor.
178 /// May return an Err to indicate that the connection should be closed.
179 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
180 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
181 /// invariants around calling write_event in case a write did not fully complete must still
182 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
183 /// Panics if the descriptor was not previously registered in a new_*_connection event.
184 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
185 let mut peers = self.peers.lock().unwrap();
186 match peers.peers.get_mut(descriptor) {
187 None => panic!("Descriptor for write_event is not already known to PeerManager"),
189 peer.awaiting_write_event = false;
190 Self::do_attempt_write_data(descriptor, peer);
196 /// Indicates that data was read from the given socket descriptor.
197 /// May return an Err to indicate that the connection should be closed.
198 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
199 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
200 /// invariants around calling write_event in case a write did not fully complete must still
201 /// hold. Note that this function will often call send_data on many peers before returning, not
203 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
204 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
205 /// that this must be true even if a send_data call with resume_read=true was made during the
206 /// course of this function!
207 /// Panics if the descriptor was not previously registered in a new_*_connection event.
208 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
209 let mut upstream_events = Vec::new();
211 let mut peers = self.peers.lock().unwrap();
212 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
213 None => panic!("Descriptor for read_event is not already known to PeerManager"),
215 assert!(peer.pending_read_buffer.len() > 0);
216 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
218 macro_rules! try_potential_handleerror {
223 //TODO: Handle e appropriately!
224 return Err(PeerHandleError{});
230 macro_rules! try_potential_decodeerror {
236 return Err(PeerHandleError{});
242 macro_rules! encode_and_send_msg {
243 ($msg: expr, $msg_code: expr) => {
244 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
248 let mut insert_node_id = None;
250 let mut read_pos = 0;
251 while read_pos < data.len() {
253 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
254 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]);
255 read_pos += data_to_copy;
256 peer.pending_read_buffer_pos += data_to_copy;
258 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
259 let next_step = peer.channel_encryptor.get_noise_step();
261 NextNoiseStep::ActOne => {
262 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
263 peer.pending_outbound_buffer.push_back(act_two);
264 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
266 NextNoiseStep::ActTwo => {
267 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
268 peer.pending_outbound_buffer.push_back(act_three);
269 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
271 insert_node_id = Some(peer.their_node_id.unwrap());
272 encode_and_send_msg!(msgs::Init {
273 global_features: msgs::GlobalFeatures::new(),
274 local_features: msgs::LocalFeatures::new(),
277 NextNoiseStep::ActThree => {
278 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
279 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
280 peer.pending_read_is_header = true;
281 peer.their_node_id = Some(their_node_id);
282 insert_node_id = Some(peer.their_node_id.unwrap());
284 NextNoiseStep::NoiseComplete => {
285 if peer.pending_read_is_header {
286 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
287 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
288 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
289 if msg_len < 2 + 16 { // Need at least the message type tag
290 return Err(PeerHandleError{});
292 peer.pending_read_is_header = false;
294 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
295 assert!(msg_data.len() >= 2);
297 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
299 // Connection control:
301 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
302 if msg.global_features.requires_unknown_bits() {
303 return Err(PeerHandleError{});
305 if msg.local_features.requires_unknown_bits() {
306 return Err(PeerHandleError{});
308 //TODO: Store features!
318 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
319 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
320 encode_and_send_msg!(resp, 33);
323 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
324 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
328 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
329 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
330 encode_and_send_msg!(resp, 35);
333 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
334 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
337 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
338 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
340 Some(resp) => encode_and_send_msg!(resp, 259),
346 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
347 try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
350 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
351 try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
355 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
356 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
359 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
360 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
363 for resp in resps.0 {
364 encode_and_send_msg!(resp, 128);
366 encode_and_send_msg!(resps.1, 132);
372 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
373 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
376 for resp in resps.0 {
377 encode_and_send_msg!(resp, 128);
379 encode_and_send_msg!(resps.1, 132);
385 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
386 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
389 for resp in resps.0 {
390 encode_and_send_msg!(resp, 128);
392 encode_and_send_msg!(resps.1, 132);
399 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
400 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
401 encode_and_send_msg!(resp, 133);
404 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
405 try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
409 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
410 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
412 136 => { }, // TODO: channel_reestablish
416 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
417 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
420 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
421 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
424 // TODO: forward msg along to all our other peers!
428 let msg = try_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
429 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
432 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
433 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
436 if (msg_type & 1) == 0 {
437 //TODO: Fail all channels. Kill the peer!
438 return Err(PeerHandleError{});
443 peer.pending_read_buffer = [0; 18].to_vec();
444 peer.pending_read_is_header = true;
448 peer.pending_read_buffer_pos = 0;
452 Self::do_attempt_write_data(peer_descriptor, peer);
454 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
458 match should_insert_node_id {
459 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
463 // TODO: There are some DoS attacks here where you can flood someone's outbound send
464 // buffer by doing things like announcing channels on another node. We should be willing to
465 // drop optional-ish messages when send buffers get full!
467 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
468 for event in events_generated.drain(..) {
469 macro_rules! get_peer_for_forwarding {
470 ($node_id: expr, $handle_no_such_peer: block) => {
472 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
473 Some(descriptor) => descriptor.clone(),
475 $handle_no_such_peer;
479 match peers.peers.get_mut(&descriptor) {
483 None => panic!("Inconsistent peers set state!"),
489 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
490 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
491 Event::PaymentReceived {..} => { /* Hand upstream */ },
493 Event::PendingHTLCsForwardable {..} => {
494 //TODO: Handle upstream in some confused form so that upstream just knows
495 //to call us somehow?
497 Event::SendFundingCreated { ref node_id, ref msg } => {
498 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
499 //TODO: generate a DiscardFunding event indicating to the wallet that
500 //they should just throw away this funding transaction
502 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
503 Self::do_attempt_write_data(&mut descriptor, peer);
506 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
507 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
508 //TODO: Do whatever we're gonna do for handling dropped messages
510 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
511 match announcement_sigs {
512 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
515 Self::do_attempt_write_data(&mut descriptor, peer);
518 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
519 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
520 //TODO: Do whatever we're gonna do for handling dropped messages
523 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
525 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
526 Self::do_attempt_write_data(&mut descriptor, peer);
529 Event::SendFulfillHTLC { ref node_id, ref msg } => {
530 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
531 //TODO: Do whatever we're gonna do for handling dropped messages
533 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
534 Self::do_attempt_write_data(&mut descriptor, peer);
537 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
538 let encoded_msg = encode_msg!(msg, 256);
539 let encoded_update_msg = encode_msg!(update_msg, 258);
541 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
542 if !peer.channel_encryptor.is_ready_for_encryption() {
545 match peer.their_node_id {
547 Some(their_node_id) => {
548 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
553 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
554 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
555 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
561 upstream_events.push(event);
567 let mut pending_events = self.pending_events.lock().unwrap();
568 for event in upstream_events.drain(..) {
569 pending_events.push(event);
575 /// Indicates that the given socket descriptor's connection is now closed.
576 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
577 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
578 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
579 pub fn disconnect_event(&self, descriptor: &Descriptor) {
580 let mut peers = self.peers.lock().unwrap();
581 let peer_option = peers.peers.remove(descriptor);
583 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
585 match peer.their_node_id {
586 Some(node_id) => { peers.node_id_to_descriptor.remove(&node_id); },
589 //TODO: Notify the chan_handler that this node disconnected, and do something about
590 //handling response messages that were queued for sending (maybe the send buffer
591 //needs to be unencrypted?)
597 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
598 fn get_and_clear_pending_events(&self) -> Vec<Event> {
599 let mut pending_events = self.pending_events.lock().unwrap();
600 let mut ret = Vec::new();
601 mem::swap(&mut ret, &mut *pending_events);