a763db63e4c95d28bbe96d78e6644cf1dee470ec
[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 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,
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_ptr(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: *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)>,
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.this_arg) }
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 impl Clone for SocketDescriptor {
134         fn clone(&self) -> Self {
135                 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(),
139                         eq: self.eq.clone(),
140                         hash: self.hash.clone(),
141                         clone: self.clone.clone(),
142                         free: self.free.clone(),
143                 }
144         }
145 }
146
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);
152                 ret
153         }
154         fn disconnect_socket(&mut self) {
155                 (self.disconnect_socket)(self.this_arg)
156         }
157 }
158
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 {
162         type Target = Self;
163         fn deref(&self) -> &Self {
164                 self
165         }
166 }
167 /// Calls the free function if one is set
168 #[no_mangle]
169 pub extern "C" fn SocketDescriptor_free(this_ptr: SocketDescriptor) { }
170 impl Drop for SocketDescriptor {
171         fn drop(&mut self) {
172                 if let Some(f) = self.free {
173                         f(self.this_arg);
174                 }
175         }
176 }
177
178 use lightning::ln::peer_handler::PeerHandleError as nativePeerHandleErrorImport;
179 type nativePeerHandleError = nativePeerHandleErrorImport;
180
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).
186 #[must_use]
187 #[repr(C)]
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,
192         pub is_owned: bool,
193 }
194
195 impl Drop for PeerHandleError {
196         fn drop(&mut self) {
197                 if self.is_owned && !self.inner.is_null() {
198                         let _ = unsafe { Box::from_raw(self.inner) };
199                 }
200         }
201 }
202 #[no_mangle]
203 pub extern "C" fn PeerHandleError_free(this_ptr: PeerHandleError) { }
204 #[allow(unused)]
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); }
208 }
209 #[allow(unused)]
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();
216                 ret
217         }
218 }
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.
221 #[no_mangle]
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;
224         (*inner_val)
225 }
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.
228 #[no_mangle]
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;
231 }
232 #[must_use]
233 #[no_mangle]
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 }
238 }
239
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>;
242
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.
245 ///
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.
251 #[must_use]
252 #[repr(C)]
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,
257         pub is_owned: bool,
258 }
259
260 impl Drop for PeerManager {
261         fn drop(&mut self) {
262                 if self.is_owned && !self.inner.is_null() {
263                         let _ = unsafe { Box::from_raw(self.inner) };
264                 }
265         }
266 }
267 #[no_mangle]
268 pub extern "C" fn PeerManager_free(this_ptr: PeerManager) { }
269 #[allow(unused)]
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); }
273 }
274 #[allow(unused)]
275 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
276 impl PeerManager {
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();
281                 ret
282         }
283 }
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.
287 #[must_use]
288 #[no_mangle]
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 }
292 }
293
294 /// Get the list of node ids for peers which have completed the initial handshake.
295 ///
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.
299 #[must_use]
300 #[no_mangle]
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) }); };
304         local_ret.into()
305 }
306
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.
310 ///
311 /// Returns a small number of bytes to send to the remote node (currently always 50).
312 ///
313 /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
314 /// socket_disconnected().
315 #[must_use]
316 #[no_mangle]
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 } }) };
320         local_ret
321 }
322
323 /// Indicates a new inbound connection has been established.
324 ///
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
328 /// immediately.
329 ///
330 /// Panics if descriptor is duplicative with some other descriptor which has not yet had
331 /// socket_disconnected called.
332 #[must_use]
333 #[no_mangle]
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 } }) };
337         local_ret
338 }
339
340 /// Indicates that there is room to write data to the given socket descriptor.
341 ///
342 /// May return an Err to indicate that the connection should be closed.
343 ///
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.
350 #[must_use]
351 #[no_mangle]
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 } }) };
355         local_ret
356 }
357
358 /// Indicates that data was read from the given socket descriptor.
359 ///
360 /// May return an Err to indicate that the connection should be closed.
361 ///
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.
365 ///
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).
368 ///
369 /// Panics if the descriptor was not previously registered in a new_*_connection event.
370 #[must_use]
371 #[no_mangle]
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 } }) };
375         local_ret
376 }
377
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).
381 #[no_mangle]
382 pub extern "C" fn PeerManager_process_events(this_arg: &PeerManager) {
383         unsafe { &*this_arg.inner }.process_events()
384 }
385
386 /// Indicates that the given socket descriptor's connection is now closed.
387 ///
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
391 /// the peer.
392 ///
393 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
394 #[no_mangle]
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)
397 }
398
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!
402 #[no_mangle]
403 pub extern "C" fn PeerManager_timer_tick_occured(this_arg: &PeerManager) {
404         unsafe { &*this_arg.inner }.timer_tick_occured()
405 }
406