e9894dd9b72990107162efb5f6c04d02b1c23bdd
[rust-lightning] / lightning-c-bindings / src / ln / peer_handler.rs
1 //! Top level peer message handling and socket handling logic lives here.
2 //!
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.
8
9 use std::ffi::c_void;
10 use bitcoin::hashes::Hash;
11 use crate::c_types::*;
12
13
14 use lightning::ln::peer_handler::MessageHandler as nativeMessageHandlerImport;
15 type nativeMessageHandler = nativeMessageHandlerImport<crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler>;
16
17 /// Provides references to trait impls which handle different types of messages.
18 #[must_use]
19 #[repr(C)]
20 pub struct MessageHandler {
21         /// Nearly everywhere, 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,
24         pub is_owned: bool,
25 }
26
27 impl Drop for MessageHandler {
28         fn drop(&mut self) {
29                 if self.is_owned && !self.inner.is_null() {
30                         let _ = unsafe { Box::from_raw(self.inner) };
31                 }
32         }
33 }
34 #[no_mangle]
35 pub extern "C" fn MessageHandler_free(this_ptr: MessageHandler) { }
36 #[allow(unused)]
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); }
40 }
41 #[allow(unused)]
42 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
43 impl MessageHandler {
44         pub(crate) fn take_inner(mut self) -> *mut nativeMessageHandler {
45                 assert!(self.is_owned);
46                 let ret = self.inner;
47                 self.inner = std::ptr::null_mut();
48                 ret
49         }
50 }
51 /// A message handler which handles messages specific to channels. Usually this is just a
52 /// ChannelManager object.
53 #[no_mangle]
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;
56         &(*inner_val)
57 }
58 /// A message handler which handles messages specific to channels. Usually this is just a
59 /// ChannelManager object.
60 #[no_mangle]
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;
63 }
64 /// A message handler which handles messages updating our knowledge of the network channel
65 /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
66 #[no_mangle]
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;
69         &(*inner_val)
70 }
71 /// A message handler which handles messages updating our knowledge of the network channel
72 /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
73 #[no_mangle]
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;
76 }
77 #[must_use]
78 #[no_mangle]
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,
83         })), is_owned: true }
84 }
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.
88 ///
89 /// For efficiency, Clone should be relatively cheap for this type.
90 ///
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().
96 #[repr(C)]
97 pub struct SocketDescriptor {
98         pub this_arg: *mut c_void,
99         /// Attempts to send some data from the given slice to the peer.
100         ///
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.
104         ///
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!
108         ///
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.
113         #[must_use]
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: &SocketDescriptor) -> 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)>,
125 }
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) }
129 }
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)) }
132 }
133 #[no_mangle]
134 pub extern "C" fn SocketDescriptor_clone(orig: &SocketDescriptor) -> SocketDescriptor {
135         SocketDescriptor {
136                 this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
137                 send_data: orig.send_data.clone(),
138                 disconnect_socket: orig.disconnect_socket.clone(),
139                 eq: orig.eq.clone(),
140                 hash: orig.hash.clone(),
141                 clone: orig.clone.clone(),
142                 free: orig.free.clone(),
143         }
144 }
145 impl Clone for SocketDescriptor {
146         fn clone(&self) -> Self {
147                 SocketDescriptor_clone(self)
148         }
149 }
150
151 use lightning::ln::peer_handler::SocketDescriptor as rustSocketDescriptor;
152 impl rustSocketDescriptor for SocketDescriptor {
153         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
154                 let mut local_data = crate::c_types::u8slice::from_slice(data);
155                 let mut ret = (self.send_data)(self.this_arg, local_data, resume_read);
156                 ret
157         }
158         fn disconnect_socket(&mut self) {
159                 (self.disconnect_socket)(self.this_arg)
160         }
161 }
162
163 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
164 // directly as a Deref trait in higher-level structs:
165 impl std::ops::Deref for SocketDescriptor {
166         type Target = Self;
167         fn deref(&self) -> &Self {
168                 self
169         }
170 }
171 /// Calls the free function if one is set
172 #[no_mangle]
173 pub extern "C" fn SocketDescriptor_free(this_ptr: SocketDescriptor) { }
174 impl Drop for SocketDescriptor {
175         fn drop(&mut self) {
176                 if let Some(f) = self.free {
177                         f(self.this_arg);
178                 }
179         }
180 }
181
182 use lightning::ln::peer_handler::PeerHandleError as nativePeerHandleErrorImport;
183 type nativePeerHandleError = nativePeerHandleErrorImport;
184
185 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
186 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
187 /// descriptor.
188 #[must_use]
189 #[repr(C)]
190 pub struct PeerHandleError {
191         /// Nearly everywhere, inner must be non-null, however in places where
192         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
193         pub inner: *mut nativePeerHandleError,
194         pub is_owned: bool,
195 }
196
197 impl Drop for PeerHandleError {
198         fn drop(&mut self) {
199                 if self.is_owned && !self.inner.is_null() {
200                         let _ = unsafe { Box::from_raw(self.inner) };
201                 }
202         }
203 }
204 #[no_mangle]
205 pub extern "C" fn PeerHandleError_free(this_ptr: PeerHandleError) { }
206 #[allow(unused)]
207 /// Used only if an object of this type is returned as a trait impl by a method
208 extern "C" fn PeerHandleError_free_void(this_ptr: *mut c_void) {
209         unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerHandleError); }
210 }
211 #[allow(unused)]
212 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
213 impl PeerHandleError {
214         pub(crate) fn take_inner(mut self) -> *mut nativePeerHandleError {
215                 assert!(self.is_owned);
216                 let ret = self.inner;
217                 self.inner = std::ptr::null_mut();
218                 ret
219         }
220 }
221 /// Used to indicate that we probably can't make any future connections to this peer, implying
222 /// we should go ahead and force-close any channels we have with it.
223 #[no_mangle]
224 pub extern "C" fn PeerHandleError_get_no_connection_possible(this_ptr: &PeerHandleError) -> bool {
225         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.no_connection_possible;
226         (*inner_val)
227 }
228 /// Used to indicate that we probably can't make any future connections to this peer, implying
229 /// we should go ahead and force-close any channels we have with it.
230 #[no_mangle]
231 pub extern "C" fn PeerHandleError_set_no_connection_possible(this_ptr: &mut PeerHandleError, mut val: bool) {
232         unsafe { &mut *this_ptr.inner }.no_connection_possible = val;
233 }
234 #[must_use]
235 #[no_mangle]
236 pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> PeerHandleError {
237         PeerHandleError { inner: Box::into_raw(Box::new(nativePeerHandleError {
238                 no_connection_possible: no_connection_possible_arg,
239         })), is_owned: true }
240 }
241 impl Clone for PeerHandleError {
242         fn clone(&self) -> Self {
243                 Self {
244                         inner: if self.inner.is_null() { std::ptr::null_mut() } else {
245                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
246                         is_owned: true,
247                 }
248         }
249 }
250 #[allow(unused)]
251 /// Used only if an object of this type is returned as a trait impl by a method
252 pub(crate) extern "C" fn PeerHandleError_clone_void(this_ptr: *const c_void) -> *mut c_void {
253         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePeerHandleError)).clone() })) as *mut c_void
254 }
255 #[no_mangle]
256 pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleError {
257         orig.clone()
258 }
259
260 use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport;
261 type nativePeerManager = nativePeerManagerImport<crate::ln::peer_handler::SocketDescriptor, crate::ln::msgs::ChannelMessageHandler, crate::ln::msgs::RoutingMessageHandler, crate::util::logger::Logger>;
262
263 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
264 /// events into messages which it passes on to its MessageHandlers.
265 ///
266 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
267 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
268 /// essentially you should default to using a SimpleRefPeerManager, and use a
269 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
270 /// you're using lightning-net-tokio.
271 #[must_use]
272 #[repr(C)]
273 pub struct PeerManager {
274         /// Nearly everywhere, inner must be non-null, however in places where
275         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
276         pub inner: *mut nativePeerManager,
277         pub is_owned: bool,
278 }
279
280 impl Drop for PeerManager {
281         fn drop(&mut self) {
282                 if self.is_owned && !self.inner.is_null() {
283                         let _ = unsafe { Box::from_raw(self.inner) };
284                 }
285         }
286 }
287 #[no_mangle]
288 pub extern "C" fn PeerManager_free(this_ptr: PeerManager) { }
289 #[allow(unused)]
290 /// Used only if an object of this type is returned as a trait impl by a method
291 extern "C" fn PeerManager_free_void(this_ptr: *mut c_void) {
292         unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerManager); }
293 }
294 #[allow(unused)]
295 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
296 impl PeerManager {
297         pub(crate) fn take_inner(mut self) -> *mut nativePeerManager {
298                 assert!(self.is_owned);
299                 let ret = self.inner;
300                 self.inner = std::ptr::null_mut();
301                 ret
302         }
303 }
304 /// Constructs a new PeerManager with the given message handlers and node_id secret key
305 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
306 /// cryptographically secure random bytes.
307 #[must_use]
308 #[no_mangle]
309 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 {
310         let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger);
311         PeerManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
312 }
313
314 /// Get the list of node ids for peers which have completed the initial handshake.
315 ///
316 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
317 /// new_outbound_connection, however entries will only appear once the initial handshake has
318 /// completed and we are sure the remote peer has the private key for the given node_id.
319 #[must_use]
320 #[no_mangle]
321 pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate::c_types::derived::CVec_PublicKeyZ {
322         let mut ret = unsafe { &*this_arg.inner }.get_peer_node_ids();
323         let mut local_ret = Vec::new(); for item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); };
324         local_ret.into()
325 }
326
327 /// Indicates a new outbound connection has been established to a node with the given node_id.
328 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
329 /// descriptor but must disconnect the connection immediately.
330 ///
331 /// Returns a small number of bytes to send to the remote node (currently always 50).
332 ///
333 /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
334 /// socket_disconnected().
335 #[must_use]
336 #[no_mangle]
337 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 {
338         let mut ret = unsafe { &*this_arg.inner }.new_outbound_connection(their_node_id.into_rust(), descriptor);
339         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() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
340         local_ret
341 }
342
343 /// Indicates a new inbound connection has been established.
344 ///
345 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
346 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
347 /// call socket_disconnected for the new descriptor but must disconnect the connection
348 /// immediately.
349 ///
350 /// Panics if descriptor is duplicative with some other descriptor which has not yet had
351 /// socket_disconnected called.
352 #[must_use]
353 #[no_mangle]
354 pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut descriptor: crate::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ {
355         let mut ret = unsafe { &*this_arg.inner }.new_inbound_connection(descriptor);
356         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
357         local_ret
358 }
359
360 /// Indicates that there is room to write data to the given socket descriptor.
361 ///
362 /// May return an Err to indicate that the connection should be closed.
363 ///
364 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
365 /// new_*\\_connection) before returning. Thus, be very careful with reentrancy issues! The
366 /// invariants around calling write_buffer_space_avail in case a write did not fully complete
367 /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
368 /// here isn't sufficient! Panics if the descriptor was not previously registered in a
369 /// new_\\*_connection event.
370 #[must_use]
371 #[no_mangle]
372 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 {
373         let mut ret = unsafe { &*this_arg.inner }.write_buffer_space_avail(descriptor);
374         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
375         local_ret
376 }
377
378 /// Indicates that data was read from the given socket descriptor.
379 ///
380 /// May return an Err to indicate that the connection should be closed.
381 ///
382 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
383 /// Thus, however, you almost certainly want to call process_events() after any read_event to
384 /// generate send_data calls to handle responses.
385 ///
386 /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
387 /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
388 ///
389 /// Panics if the descriptor was not previously registered in a new_*_connection event.
390 #[must_use]
391 #[no_mangle]
392 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 {
393         let mut ret = unsafe { &*this_arg.inner }.read_event(peer_descriptor, data.to_slice());
394         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
395         local_ret
396 }
397
398 /// Checks for any events generated by our handlers and processes them. Includes sending most
399 /// response messages as well as messages generated by calls to handler functions directly (eg
400 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
401 #[no_mangle]
402 pub extern "C" fn PeerManager_process_events(this_arg: &PeerManager) {
403         unsafe { &*this_arg.inner }.process_events()
404 }
405
406 /// Indicates that the given socket descriptor's connection is now closed.
407 ///
408 /// This must only be called if the socket has been disconnected by the peer or your own
409 /// decision to disconnect it and must NOT be called in any case where other parts of this
410 /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
411 /// the peer.
412 ///
413 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
414 #[no_mangle]
415 pub extern "C" fn PeerManager_socket_disconnected(this_arg: &PeerManager, descriptor: &crate::ln::peer_handler::SocketDescriptor) {
416         unsafe { &*this_arg.inner }.socket_disconnected(descriptor)
417 }
418
419 /// Disconnect a peer given its node id.
420 ///
421 /// Set no_connection_possible to true to prevent any further connection with this peer,
422 /// force-closing any channels we have with it.
423 ///
424 /// If a peer is connected, this will call `disconnect_socket` on the descriptor for the peer,
425 /// so be careful about reentrancy issues.
426 #[no_mangle]
427 pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &PeerManager, mut node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
428         unsafe { &*this_arg.inner }.disconnect_by_node_id(node_id.into_rust(), no_connection_possible)
429 }
430
431 /// This function should be called roughly once every 30 seconds.
432 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
433 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
434 #[no_mangle]
435 pub extern "C" fn PeerManager_timer_tick_occured(this_arg: &PeerManager) {
436         unsafe { &*this_arg.inner }.timer_tick_occured()
437 }
438