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 NetGraphmsgHandler) with messages
7 //! they should handle, and encoding/sending response messages.
10 use bitcoin::hashes::Hash;
11 use crate::c_types::*;
14 use lightning::ln::peer_handler::MessageHandler as nativeMessageHandlerImport;
15 type nativeMessageHandler = nativeMessageHandlerImport<crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler>;
17 /// Provides references to trait impls which handle different types of messages.
20 pub struct MessageHandler {
21 /// Nearly everyhwere, inner must be non-null, however in places where
22 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
23 pub inner: *mut nativeMessageHandler,
27 impl Drop for MessageHandler {
29 if self.is_owned && !self.inner.is_null() {
30 let _ = unsafe { Box::from_raw(self.inner) };
35 pub extern "C" fn MessageHandler_free(this_ptr: MessageHandler) { }
37 /// Used only if an object of this type is returned as a trait impl by a method
38 extern "C" fn MessageHandler_free_void(this_ptr: *mut c_void) {
39 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMessageHandler); }
42 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
44 pub(crate) fn take_ptr(mut self) -> *mut nativeMessageHandler {
45 assert!(self.is_owned);
47 self.inner = std::ptr::null_mut();
51 /// A message handler which handles messages specific to channels. Usually this is just a
52 /// ChannelManager object.
54 pub extern "C" fn MessageHandler_get_chan_handler(this_ptr: &MessageHandler) -> *const crate::ln::msgs::ChannelMessageHandler {
55 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chan_handler;
58 /// A message handler which handles messages specific to channels. Usually this is just a
59 /// ChannelManager object.
61 pub extern "C" fn MessageHandler_set_chan_handler(this_ptr: &mut MessageHandler, mut val: crate::ln::msgs::ChannelMessageHandler) {
62 unsafe { &mut *this_ptr.inner }.chan_handler = val;
64 /// A message handler which handles messages updating our knowledge of the network channel
65 /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
67 pub extern "C" fn MessageHandler_get_route_handler(this_ptr: &MessageHandler) -> *const crate::ln::msgs::RoutingMessageHandler {
68 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.route_handler;
71 /// A message handler which handles messages updating our knowledge of the network channel
72 /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
74 pub extern "C" fn MessageHandler_set_route_handler(this_ptr: &mut MessageHandler, mut val: crate::ln::msgs::RoutingMessageHandler) {
75 unsafe { &mut *this_ptr.inner }.route_handler = val;
79 pub extern "C" fn MessageHandler_new(mut chan_handler_arg: crate::ln::msgs::ChannelMessageHandler, mut route_handler_arg: crate::ln::msgs::RoutingMessageHandler) -> MessageHandler {
80 MessageHandler { inner: Box::into_raw(Box::new(nativeMessageHandler {
81 chan_handler: chan_handler_arg,
82 route_handler: route_handler_arg,
85 /// Provides an object which can be used to send data to and which uniquely identifies a connection
86 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
87 /// implement Hash to meet the PeerManager API.
89 /// For efficiency, Clone should be relatively cheap for this type.
91 /// You probably want to just extend an int and put a file descriptor in a struct and implement
92 /// send_data. Note that if you are using a higher-level net library that may call close() itself,
93 /// be careful to ensure you don't have races whereby you might register a new connection with an
94 /// fd which is the same as a previous one which has yet to be removed via
95 /// PeerManager::socket_disconnected().
97 pub struct SocketDescriptor {
98 pub this_arg: *mut c_void,
99 /// Attempts to send some data from the given slice to the peer.
101 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
102 /// Note that in the disconnected case, socket_disconnected must still fire and further write
103 /// attempts may occur until that time.
105 /// If the returned size is smaller than data.len(), a write_available event must
106 /// trigger the next time more data can be written. Additionally, until the a send_data event
107 /// completes fully, no further read_events should trigger on the same peer!
109 /// If a read_event on this descriptor had previously returned true (indicating that read
110 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
111 /// indicating that read events on this descriptor should resume. A resume_read of false does
112 /// *not* imply that further read events should be paused.
114 pub send_data: extern "C" fn (this_arg: *mut c_void, data: crate::c_types::u8slice, resume_read: bool) -> usize,
115 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
116 /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
117 /// this descriptor. No socket_disconnected call should be generated as a result of this call,
118 /// though races may occur whereby disconnect_socket is called after a call to
119 /// socket_disconnected but prior to socket_disconnected returning.
120 pub disconnect_socket: extern "C" fn (this_arg: *mut c_void),
121 pub eq: extern "C" fn (this_arg: *const c_void, other_arg: *const c_void) -> bool,
122 pub hash: extern "C" fn (this_arg: *const c_void) -> u64,
123 pub clone: Option<extern "C" fn (this_arg: *const c_void) -> *mut c_void>,
124 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
126 impl std::cmp::Eq for SocketDescriptor {}
127 impl std::cmp::PartialEq for SocketDescriptor {
128 fn eq(&self, o: &Self) -> bool { (self.eq)(self.this_arg, o.this_arg) }
130 impl std::hash::Hash for SocketDescriptor {
131 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) { hasher.write_u64((self.hash)(self.this_arg)) }
133 impl Clone for SocketDescriptor {
134 fn clone(&self) -> Self {
136 this_arg: if let Some(f) = self.clone { (f)(self.this_arg) } else { self.this_arg },
137 send_data: self.send_data.clone(),
138 disconnect_socket: self.disconnect_socket.clone(),
140 hash: self.hash.clone(),
141 clone: self.clone.clone(),
142 free: self.free.clone(),
147 use lightning::ln::peer_handler::SocketDescriptor as rustSocketDescriptor;
148 impl rustSocketDescriptor for SocketDescriptor {
149 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
150 let mut local_data = crate::c_types::u8slice::from_slice(data);
151 let mut ret = (self.send_data)(self.this_arg, local_data, resume_read);
154 fn disconnect_socket(&mut self) {
155 (self.disconnect_socket)(self.this_arg)
159 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
160 // directly as a Deref trait in higher-level structs:
161 impl std::ops::Deref for SocketDescriptor {
163 fn deref(&self) -> &Self {
167 /// Calls the free function if one is set
169 pub extern "C" fn SocketDescriptor_free(this_ptr: SocketDescriptor) { }
170 impl Drop for SocketDescriptor {
172 if let Some(f) = self.free {
178 use lightning::ln::peer_handler::PeerHandleError as nativePeerHandleErrorImport;
179 type nativePeerHandleError = nativePeerHandleErrorImport;
181 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
182 /// generate no further read_event/write_buffer_space_avail calls for the descriptor, only
183 /// triggering a single socket_disconnected call (unless it was provided in response to a
184 /// new_*_connection event, in which case no such socket_disconnected() must be called and the
185 /// socket silently disconencted).
188 pub struct PeerHandleError {
189 /// Nearly everyhwere, inner must be non-null, however in places where
190 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
191 pub inner: *mut nativePeerHandleError,
195 impl Drop for PeerHandleError {
197 if self.is_owned && !self.inner.is_null() {
198 let _ = unsafe { Box::from_raw(self.inner) };
203 pub extern "C" fn PeerHandleError_free(this_ptr: PeerHandleError) { }
205 /// Used only if an object of this type is returned as a trait impl by a method
206 extern "C" fn PeerHandleError_free_void(this_ptr: *mut c_void) {
207 unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerHandleError); }
210 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
211 impl PeerHandleError {
212 pub(crate) fn take_ptr(mut self) -> *mut nativePeerHandleError {
213 assert!(self.is_owned);
214 let ret = self.inner;
215 self.inner = std::ptr::null_mut();
219 /// Used to indicate that we probably can't make any future connections to this peer, implying
220 /// we should go ahead and force-close any channels we have with it.
222 pub extern "C" fn PeerHandleError_get_no_connection_possible(this_ptr: &PeerHandleError) -> bool {
223 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.no_connection_possible;
226 /// Used to indicate that we probably can't make any future connections to this peer, implying
227 /// we should go ahead and force-close any channels we have with it.
229 pub extern "C" fn PeerHandleError_set_no_connection_possible(this_ptr: &mut PeerHandleError, mut val: bool) {
230 unsafe { &mut *this_ptr.inner }.no_connection_possible = val;
234 pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> PeerHandleError {
235 PeerHandleError { inner: Box::into_raw(Box::new(nativePeerHandleError {
236 no_connection_possible: no_connection_possible_arg,
237 })), is_owned: true }
240 use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport;
241 type nativePeerManager = nativePeerManagerImport<crate::ln::peer_handler::SocketDescriptor, crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler, crate::util::logger::Logger>;
243 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
244 /// events into messages which it passes on to its MessageHandlers.
246 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
247 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
248 /// essentially you should default to using a SimpleRefPeerManager, and use a
249 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
250 /// you're using lightning-net-tokio.
253 pub struct PeerManager {
254 /// Nearly everyhwere, inner must be non-null, however in places where
255 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
256 pub inner: *mut nativePeerManager,
260 impl Drop for PeerManager {
262 if self.is_owned && !self.inner.is_null() {
263 let _ = unsafe { Box::from_raw(self.inner) };
268 pub extern "C" fn PeerManager_free(this_ptr: PeerManager) { }
270 /// Used only if an object of this type is returned as a trait impl by a method
271 extern "C" fn PeerManager_free_void(this_ptr: *mut c_void) {
272 unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerManager); }
275 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
277 pub(crate) fn take_ptr(mut self) -> *mut nativePeerManager {
278 assert!(self.is_owned);
279 let ret = self.inner;
280 self.inner = std::ptr::null_mut();
284 /// Constructs a new PeerManager with the given message handlers and node_id secret key
285 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
286 /// cryptographically secure random bytes.
289 pub extern "C" fn PeerManager_new(mut message_handler: crate::ln::peer_handler::MessageHandler, mut our_node_secret: crate::c_types::SecretKey, ephemeral_random_data: *const [u8; 32], mut logger: crate::util::logger::Logger) -> PeerManager {
290 let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_ptr()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger);
291 PeerManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
294 /// Get the list of node ids for peers which have completed the initial handshake.
296 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
297 /// new_outbound_connection, however entries will only appear once the initial handshake has
298 /// completed and we are sure the remote peer has the private key for the given node_id.
301 pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate::c_types::derived::CVec_PublicKeyZ {
302 let mut ret = unsafe { &*this_arg.inner }.get_peer_node_ids();
303 let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); };
307 /// Indicates a new outbound connection has been established to a node with the given node_id.
308 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
309 /// descriptor but must disconnect the connection immediately.
311 /// Returns a small number of bytes to send to the remote node (currently always 50).
313 /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
314 /// socket_disconnected().
317 pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mut their_node_id: crate::c_types::PublicKey, mut descriptor: crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_CVec_u8ZPeerHandleErrorZ {
318 let mut ret = unsafe { &*this_arg.inner }.new_outbound_connection(their_node_id.into_rust(), descriptor);
319 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for item in o.drain(..) { local_ret_0.push( { item }); }; local_ret_0.into() }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
323 /// Indicates a new inbound connection has been established.
325 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
326 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
327 /// call socket_disconnected for the new descriptor but must disconnect the connection
330 /// Panics if descriptor is duplicative with some other descriptor which has not yet had
331 /// socket_disconnected called.
334 pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut descriptor: crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ {
335 let mut ret = unsafe { &*this_arg.inner }.new_inbound_connection(descriptor);
336 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
340 /// Indicates that there is room to write data to the given socket descriptor.
342 /// May return an Err to indicate that the connection should be closed.
344 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
345 /// new_*\\_connection) before returning. Thus, be very careful with reentrancy issues! The
346 /// invariants around calling write_buffer_space_avail in case a write did not fully complete
347 /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
348 /// here isn't sufficient! Panics if the descriptor was not previously registered in a
349 /// new_\\*_connection event.
352 pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, descriptor: &mut crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ {
353 let mut ret = unsafe { &*this_arg.inner }.write_buffer_space_avail(descriptor);
354 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
358 /// Indicates that data was read from the given socket descriptor.
360 /// May return an Err to indicate that the connection should be closed.
362 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
363 /// Thus, however, you almost certainly want to call process_events() after any read_event to
364 /// generate send_data calls to handle responses.
366 /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
367 /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
369 /// Panics if the descriptor was not previously registered in a new_*_connection event.
372 pub extern "C" fn PeerManager_read_event(this_arg: &PeerManager, peer_descriptor: &mut crate::ln::peer_handler::SocketDescriptor, mut data: crate::c_types::u8slice) -> crate::c_types::derived::CResult_boolPeerHandleErrorZ {
373 let mut ret = unsafe { &*this_arg.inner }.read_event(peer_descriptor, data.to_slice());
374 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }) };
378 /// Checks for any events generated by our handlers and processes them. Includes sending most
379 /// response messages as well as messages generated by calls to handler functions directly (eg
380 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
382 pub extern "C" fn PeerManager_process_events(this_arg: &PeerManager) {
383 unsafe { &*this_arg.inner }.process_events()
386 /// Indicates that the given socket descriptor's connection is now closed.
388 /// This must only be called if the socket has been disconnected by the peer or your own
389 /// decision to disconnect it and must NOT be called in any case where other parts of this
390 /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
393 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
395 pub extern "C" fn PeerManager_socket_disconnected(this_arg: &PeerManager, descriptor: &crate::ln::peer_handler::SocketDescriptor) {
396 unsafe { &*this_arg.inner }.socket_disconnected(descriptor)
399 /// This function should be called roughly once every 30 seconds.
400 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
401 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
403 pub extern "C" fn PeerManager_timer_tick_occured(this_arg: &PeerManager) {
404 unsafe { &*this_arg.inner }.timer_tick_occured()