0c989038b718922f4fd92c1ce204e4b1877ebaef
[ldk-c-bindings] / lightning-c-bindings / src / lightning / onion_message / messenger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! LDK sends, receives, and forwards onion messages via the [`OnionMessenger`]. See its docs for
10 //! more information.
11
12 use alloc::str::FromStr;
13 use core::ffi::c_void;
14 use core::convert::Infallible;
15 use bitcoin::hashes::Hash;
16 use crate::c_types::*;
17 #[cfg(feature="no-std")]
18 use alloc::{vec::Vec, boxed::Box};
19
20
21 use lightning::onion_message::messenger::OnionMessenger as nativeOnionMessengerImport;
22 pub(crate) type nativeOnionMessenger = nativeOnionMessengerImport<crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::util::logger::Logger, crate::lightning::onion_message::messenger::MessageRouter, crate::lightning::onion_message::offers::OffersMessageHandler, crate::lightning::onion_message::messenger::CustomOnionMessageHandler>;
23
24 /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
25 /// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending
26 /// and receiving custom onion messages is supported.
27 ///
28 /// # Example
29 ///
30 /// ```
31 /// # extern crate bitcoin;
32 /// # use bitcoin::hashes::_export::_core::time::Duration;
33 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
34 /// # use lightning::blinded_path::BlindedPath;
35 /// # use lightning::sign::KeysManager;
36 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
37 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessenger, OnionMessagePath};
38 /// # use lightning::onion_message::packet::{CustomOnionMessageContents, OnionMessageContents};
39 /// # use lightning::util::logger::{Logger, Record};
40 /// # use lightning::util::ser::{Writeable, Writer};
41 /// # use lightning::io;
42 /// # use std::sync::Arc;
43 /// # struct FakeLogger;
44 /// # impl Logger for FakeLogger {
45 /// #     fn log(&self, record: &Record) { unimplemented!() }
46 /// # }
47 /// # struct FakeMessageRouter {}
48 /// # impl MessageRouter for FakeMessageRouter {
49 /// #     fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
50 /// #         unimplemented!()
51 /// #     }
52 /// # }
53 /// # let seed = [42u8; 32];
54 /// # let time = Duration::from_secs(123456);
55 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
56 /// # let logger = Arc::new(FakeLogger {});
57 /// # let node_secret = SecretKey::from_slice(&hex::decode(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
58 /// # let secp_ctx = Secp256k1::new();
59 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
60 /// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1, hop_node_id1);
61 /// # let destination_node_id = hop_node_id1;
62 /// # let message_router = Arc::new(FakeMessageRouter {});
63 /// # let custom_message_handler = IgnoringMessageHandler {};
64 /// # let offers_message_handler = IgnoringMessageHandler {};
65 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
66 /// // ChannelManager.
67 /// let onion_messenger = OnionMessenger::new(
68 ///     &keys_manager, &keys_manager, logger, message_router, &offers_message_handler,
69 ///     &custom_message_handler
70 /// );
71 ///
72 /// # struct YourCustomMessage {}
73 /// impl Writeable for YourCustomMessage {
74 /// \tfn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
75 /// \t\t# Ok(())
76 /// \t\t// Write your custom onion message to `w`
77 /// \t}
78 /// }
79 /// impl CustomOnionMessageContents for YourCustomMessage {
80 /// \tfn tlv_type(&self) -> u64 {
81 /// \t\t# let your_custom_message_type = 42;
82 /// \t\tyour_custom_message_type
83 /// \t}
84 /// }
85 /// // Send a custom onion message to a node id.
86 /// let path = OnionMessagePath {
87 /// \tintermediate_nodes: vec![hop_node_id1, hop_node_id2],
88 /// \tdestination: Destination::Node(destination_node_id),
89 /// };
90 /// let reply_path = None;
91 /// # let your_custom_message = YourCustomMessage {};
92 /// let message = OnionMessageContents::Custom(your_custom_message);
93 /// onion_messenger.send_onion_message(path, message, reply_path);
94 ///
95 /// // Create a blinded path to yourself, for someone to send an onion message to.
96 /// # let your_node_id = hop_node_id1;
97 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
98 /// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
99 ///
100 /// // Send a custom onion message to a blinded path.
101 /// let path = OnionMessagePath {
102 /// \tintermediate_nodes: vec![hop_node_id1, hop_node_id2],
103 /// \tdestination: Destination::BlindedPath(blinded_path),
104 /// };
105 /// let reply_path = None;
106 /// # let your_custom_message = YourCustomMessage {};
107 /// let message = OnionMessageContents::Custom(your_custom_message);
108 /// onion_messenger.send_onion_message(path, message, reply_path);
109 /// ```
110 ///
111 /// [offers]: <https://github.com/lightning/bolts/pull/798>
112 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
113 #[must_use]
114 #[repr(C)]
115 pub struct OnionMessenger {
116         /// A pointer to the opaque Rust object.
117
118         /// Nearly everywhere, inner must be non-null, however in places where
119         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
120         pub inner: *mut nativeOnionMessenger,
121         /// Indicates that this is the only struct which contains the same pointer.
122
123         /// Rust functions which take ownership of an object provided via an argument require
124         /// this to be true and invalidate the object pointed to by inner.
125         pub is_owned: bool,
126 }
127
128 impl Drop for OnionMessenger {
129         fn drop(&mut self) {
130                 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
131                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
132                 }
133         }
134 }
135 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
136 #[no_mangle]
137 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
138 #[allow(unused)]
139 /// Used only if an object of this type is returned as a trait impl by a method
140 pub(crate) extern "C" fn OnionMessenger_free_void(this_ptr: *mut c_void) {
141         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessenger) };
142 }
143 #[allow(unused)]
144 impl OnionMessenger {
145         pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
146                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
147         }
148         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
149                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
150         }
151         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
152         pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessenger {
153                 assert!(self.is_owned);
154                 let ret = ObjOps::untweak_ptr(self.inner);
155                 self.inner = core::ptr::null_mut();
156                 ret
157         }
158 }
159 /// A trait defining behavior for routing an [`OnionMessage`].
160 ///
161 /// [`OnionMessage`]: msgs::OnionMessage
162 #[repr(C)]
163 pub struct MessageRouter {
164         /// An opaque pointer which is passed to your function implementations as an argument.
165         /// This has no meaning in the LDK, and can be NULL or any other value.
166         pub this_arg: *mut c_void,
167         /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
168         ///
169         /// [`OnionMessage`]: msgs::OnionMessage
170         pub find_path: extern "C" fn (this_arg: *const c_void, sender: crate::c_types::PublicKey, peers: crate::c_types::derived::CVec_PublicKeyZ, destination: crate::lightning::onion_message::messenger::Destination) -> crate::c_types::derived::CResult_OnionMessagePathNoneZ,
171         /// Frees any resources associated with this object given its this_arg pointer.
172         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
173         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
174 }
175 unsafe impl Send for MessageRouter {}
176 unsafe impl Sync for MessageRouter {}
177 #[no_mangle]
178 pub(crate) extern "C" fn MessageRouter_clone_fields(orig: &MessageRouter) -> MessageRouter {
179         MessageRouter {
180                 this_arg: orig.this_arg,
181                 find_path: Clone::clone(&orig.find_path),
182                 free: Clone::clone(&orig.free),
183         }
184 }
185
186 use lightning::onion_message::messenger::MessageRouter as rustMessageRouter;
187 impl rustMessageRouter for MessageRouter {
188         fn find_path(&self, mut sender: bitcoin::secp256k1::PublicKey, mut peers: Vec<bitcoin::secp256k1::PublicKey>, mut destination: lightning::onion_message::messenger::Destination) -> Result<lightning::onion_message::messenger::OnionMessagePath, ()> {
189                 let mut local_peers = Vec::new(); for mut item in peers.drain(..) { local_peers.push( { crate::c_types::PublicKey::from_rust(&item) }); };
190                 let mut ret = (self.find_path)(self.this_arg, crate::c_types::PublicKey::from_rust(&sender), local_peers.into(), crate::lightning::onion_message::messenger::Destination::native_into(destination));
191                 let mut local_ret = match ret.result_ok { true => Ok( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).take_inner()) } }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
192                 local_ret
193         }
194 }
195
196 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
197 // directly as a Deref trait in higher-level structs:
198 impl core::ops::Deref for MessageRouter {
199         type Target = Self;
200         fn deref(&self) -> &Self {
201                 self
202         }
203 }
204 /// Calls the free function if one is set
205 #[no_mangle]
206 pub extern "C" fn MessageRouter_free(this_ptr: MessageRouter) { }
207 impl Drop for MessageRouter {
208         fn drop(&mut self) {
209                 if let Some(f) = self.free {
210                         f(self.this_arg);
211                 }
212         }
213 }
214
215 use lightning::onion_message::messenger::DefaultMessageRouter as nativeDefaultMessageRouterImport;
216 pub(crate) type nativeDefaultMessageRouter = nativeDefaultMessageRouterImport;
217
218 /// A [`MessageRouter`] that always fails.
219 #[must_use]
220 #[repr(C)]
221 pub struct DefaultMessageRouter {
222         /// A pointer to the opaque Rust object.
223
224         /// Nearly everywhere, inner must be non-null, however in places where
225         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
226         pub inner: *mut nativeDefaultMessageRouter,
227         /// Indicates that this is the only struct which contains the same pointer.
228
229         /// Rust functions which take ownership of an object provided via an argument require
230         /// this to be true and invalidate the object pointed to by inner.
231         pub is_owned: bool,
232 }
233
234 impl Drop for DefaultMessageRouter {
235         fn drop(&mut self) {
236                 if self.is_owned && !<*mut nativeDefaultMessageRouter>::is_null(self.inner) {
237                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
238                 }
239         }
240 }
241 /// Frees any resources used by the DefaultMessageRouter, if is_owned is set and inner is non-NULL.
242 #[no_mangle]
243 pub extern "C" fn DefaultMessageRouter_free(this_obj: DefaultMessageRouter) { }
244 #[allow(unused)]
245 /// Used only if an object of this type is returned as a trait impl by a method
246 pub(crate) extern "C" fn DefaultMessageRouter_free_void(this_ptr: *mut c_void) {
247         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeDefaultMessageRouter) };
248 }
249 #[allow(unused)]
250 impl DefaultMessageRouter {
251         pub(crate) fn get_native_ref(&self) -> &'static nativeDefaultMessageRouter {
252                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
253         }
254         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDefaultMessageRouter {
255                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
256         }
257         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
258         pub(crate) fn take_inner(mut self) -> *mut nativeDefaultMessageRouter {
259                 assert!(self.is_owned);
260                 let ret = ObjOps::untweak_ptr(self.inner);
261                 self.inner = core::ptr::null_mut();
262                 ret
263         }
264 }
265 /// Constructs a new DefaultMessageRouter given each field
266 #[must_use]
267 #[no_mangle]
268 pub extern "C" fn DefaultMessageRouter_new() -> DefaultMessageRouter {
269         DefaultMessageRouter { inner: ObjOps::heap_alloc(lightning::onion_message::messenger::DefaultMessageRouter {}), is_owned: true }
270 }
271 impl From<nativeDefaultMessageRouter> for crate::lightning::onion_message::messenger::MessageRouter {
272         fn from(obj: nativeDefaultMessageRouter) -> Self {
273                 let mut rust_obj = DefaultMessageRouter { inner: ObjOps::heap_alloc(obj), is_owned: true };
274                 let mut ret = DefaultMessageRouter_as_MessageRouter(&rust_obj);
275                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
276                 rust_obj.inner = core::ptr::null_mut();
277                 ret.free = Some(DefaultMessageRouter_free_void);
278                 ret
279         }
280 }
281 /// Constructs a new MessageRouter which calls the relevant methods on this_arg.
282 /// This copies the `inner` pointer in this_arg and thus the returned MessageRouter must be freed before this_arg is
283 #[no_mangle]
284 pub extern "C" fn DefaultMessageRouter_as_MessageRouter(this_arg: &DefaultMessageRouter) -> crate::lightning::onion_message::messenger::MessageRouter {
285         crate::lightning::onion_message::messenger::MessageRouter {
286                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
287                 free: None,
288                 find_path: DefaultMessageRouter_MessageRouter_find_path,
289         }
290 }
291
292 #[must_use]
293 extern "C" fn DefaultMessageRouter_MessageRouter_find_path(this_arg: *const c_void, mut sender: crate::c_types::PublicKey, mut peers: crate::c_types::derived::CVec_PublicKeyZ, mut destination: crate::lightning::onion_message::messenger::Destination) -> crate::c_types::derived::CResult_OnionMessagePathNoneZ {
294         let mut local_peers = Vec::new(); for mut item in peers.into_rust().drain(..) { local_peers.push( { item.into_rust() }); };
295         let mut ret = <nativeDefaultMessageRouter as lightning::onion_message::messenger::MessageRouter<>>::find_path(unsafe { &mut *(this_arg as *mut nativeDefaultMessageRouter) }, sender.into_rust(), local_peers, destination.into_native());
296         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::onion_message::messenger::OnionMessagePath { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
297         local_ret
298 }
299
300
301 use lightning::onion_message::messenger::OnionMessagePath as nativeOnionMessagePathImport;
302 pub(crate) type nativeOnionMessagePath = nativeOnionMessagePathImport;
303
304 /// A path for sending an [`msgs::OnionMessage`].
305 #[must_use]
306 #[repr(C)]
307 pub struct OnionMessagePath {
308         /// A pointer to the opaque Rust object.
309
310         /// Nearly everywhere, inner must be non-null, however in places where
311         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
312         pub inner: *mut nativeOnionMessagePath,
313         /// Indicates that this is the only struct which contains the same pointer.
314
315         /// Rust functions which take ownership of an object provided via an argument require
316         /// this to be true and invalidate the object pointed to by inner.
317         pub is_owned: bool,
318 }
319
320 impl Drop for OnionMessagePath {
321         fn drop(&mut self) {
322                 if self.is_owned && !<*mut nativeOnionMessagePath>::is_null(self.inner) {
323                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
324                 }
325         }
326 }
327 /// Frees any resources used by the OnionMessagePath, if is_owned is set and inner is non-NULL.
328 #[no_mangle]
329 pub extern "C" fn OnionMessagePath_free(this_obj: OnionMessagePath) { }
330 #[allow(unused)]
331 /// Used only if an object of this type is returned as a trait impl by a method
332 pub(crate) extern "C" fn OnionMessagePath_free_void(this_ptr: *mut c_void) {
333         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessagePath) };
334 }
335 #[allow(unused)]
336 impl OnionMessagePath {
337         pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessagePath {
338                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
339         }
340         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessagePath {
341                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
342         }
343         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
344         pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessagePath {
345                 assert!(self.is_owned);
346                 let ret = ObjOps::untweak_ptr(self.inner);
347                 self.inner = core::ptr::null_mut();
348                 ret
349         }
350 }
351 /// Nodes on the path between the sender and the destination.
352 ///
353 /// Returns a copy of the field.
354 #[no_mangle]
355 pub extern "C" fn OnionMessagePath_get_intermediate_nodes(this_ptr: &OnionMessagePath) -> crate::c_types::derived::CVec_PublicKeyZ {
356         let mut inner_val = this_ptr.get_native_mut_ref().intermediate_nodes.clone();
357         let mut local_inner_val = Vec::new(); for mut item in inner_val.drain(..) { local_inner_val.push( { crate::c_types::PublicKey::from_rust(&item) }); };
358         local_inner_val.into()
359 }
360 /// Nodes on the path between the sender and the destination.
361 #[no_mangle]
362 pub extern "C" fn OnionMessagePath_set_intermediate_nodes(this_ptr: &mut OnionMessagePath, mut val: crate::c_types::derived::CVec_PublicKeyZ) {
363         let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
364         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.intermediate_nodes = local_val;
365 }
366 /// The recipient of the message.
367 #[no_mangle]
368 pub extern "C" fn OnionMessagePath_get_destination(this_ptr: &OnionMessagePath) -> crate::lightning::onion_message::messenger::Destination {
369         let mut inner_val = &mut this_ptr.get_native_mut_ref().destination;
370         crate::lightning::onion_message::messenger::Destination::from_native(inner_val)
371 }
372 /// The recipient of the message.
373 #[no_mangle]
374 pub extern "C" fn OnionMessagePath_set_destination(this_ptr: &mut OnionMessagePath, mut val: crate::lightning::onion_message::messenger::Destination) {
375         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.destination = val.into_native();
376 }
377 /// Constructs a new OnionMessagePath given each field
378 #[must_use]
379 #[no_mangle]
380 pub extern "C" fn OnionMessagePath_new(mut intermediate_nodes_arg: crate::c_types::derived::CVec_PublicKeyZ, mut destination_arg: crate::lightning::onion_message::messenger::Destination) -> OnionMessagePath {
381         let mut local_intermediate_nodes_arg = Vec::new(); for mut item in intermediate_nodes_arg.into_rust().drain(..) { local_intermediate_nodes_arg.push( { item.into_rust() }); };
382         OnionMessagePath { inner: ObjOps::heap_alloc(nativeOnionMessagePath {
383                 intermediate_nodes: local_intermediate_nodes_arg,
384                 destination: destination_arg.into_native(),
385         }), is_owned: true }
386 }
387 impl Clone for OnionMessagePath {
388         fn clone(&self) -> Self {
389                 Self {
390                         inner: if <*mut nativeOnionMessagePath>::is_null(self.inner) { core::ptr::null_mut() } else {
391                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
392                         is_owned: true,
393                 }
394         }
395 }
396 #[allow(unused)]
397 /// Used only if an object of this type is returned as a trait impl by a method
398 pub(crate) extern "C" fn OnionMessagePath_clone_void(this_ptr: *const c_void) -> *mut c_void {
399         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOnionMessagePath)).clone() })) as *mut c_void
400 }
401 #[no_mangle]
402 /// Creates a copy of the OnionMessagePath
403 pub extern "C" fn OnionMessagePath_clone(orig: &OnionMessagePath) -> OnionMessagePath {
404         orig.clone()
405 }
406 /// The destination of an onion message.
407 #[derive(Clone)]
408 #[must_use]
409 #[repr(C)]
410 pub enum Destination {
411         /// We're sending this onion message to a node.
412         Node(
413                 crate::c_types::PublicKey),
414         /// We're sending this onion message to a blinded path.
415         BlindedPath(
416                 crate::lightning::blinded_path::BlindedPath),
417 }
418 use lightning::onion_message::messenger::Destination as DestinationImport;
419 pub(crate) type nativeDestination = DestinationImport;
420
421 impl Destination {
422         #[allow(unused)]
423         pub(crate) fn to_native(&self) -> nativeDestination {
424                 match self {
425                         Destination::Node (ref a, ) => {
426                                 let mut a_nonref = Clone::clone(a);
427                                 nativeDestination::Node (
428                                         a_nonref.into_rust(),
429                                 )
430                         },
431                         Destination::BlindedPath (ref a, ) => {
432                                 let mut a_nonref = Clone::clone(a);
433                                 nativeDestination::BlindedPath (
434                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
435                                 )
436                         },
437                 }
438         }
439         #[allow(unused)]
440         pub(crate) fn into_native(self) -> nativeDestination {
441                 match self {
442                         Destination::Node (mut a, ) => {
443                                 nativeDestination::Node (
444                                         a.into_rust(),
445                                 )
446                         },
447                         Destination::BlindedPath (mut a, ) => {
448                                 nativeDestination::BlindedPath (
449                                         *unsafe { Box::from_raw(a.take_inner()) },
450                                 )
451                         },
452                 }
453         }
454         #[allow(unused)]
455         pub(crate) fn from_native(native: &nativeDestination) -> Self {
456                 match native {
457                         nativeDestination::Node (ref a, ) => {
458                                 let mut a_nonref = Clone::clone(a);
459                                 Destination::Node (
460                                         crate::c_types::PublicKey::from_rust(&a_nonref),
461                                 )
462                         },
463                         nativeDestination::BlindedPath (ref a, ) => {
464                                 let mut a_nonref = Clone::clone(a);
465                                 Destination::BlindedPath (
466                                         crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
467                                 )
468                         },
469                 }
470         }
471         #[allow(unused)]
472         pub(crate) fn native_into(native: nativeDestination) -> Self {
473                 match native {
474                         nativeDestination::Node (mut a, ) => {
475                                 Destination::Node (
476                                         crate::c_types::PublicKey::from_rust(&a),
477                                 )
478                         },
479                         nativeDestination::BlindedPath (mut a, ) => {
480                                 Destination::BlindedPath (
481                                         crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a), is_owned: true },
482                                 )
483                         },
484                 }
485         }
486 }
487 /// Frees any resources used by the Destination
488 #[no_mangle]
489 pub extern "C" fn Destination_free(this_ptr: Destination) { }
490 /// Creates a copy of the Destination
491 #[no_mangle]
492 pub extern "C" fn Destination_clone(orig: &Destination) -> Destination {
493         orig.clone()
494 }
495 #[no_mangle]
496 /// Utility method to constructs a new Node-variant Destination
497 pub extern "C" fn Destination_node(a: crate::c_types::PublicKey) -> Destination {
498         Destination::Node(a, )
499 }
500 #[no_mangle]
501 /// Utility method to constructs a new BlindedPath-variant Destination
502 pub extern "C" fn Destination_blinded_path(a: crate::lightning::blinded_path::BlindedPath) -> Destination {
503         Destination::BlindedPath(a, )
504 }
505 /// Errors that may occur when [sending an onion message].
506 ///
507 /// [sending an onion message]: OnionMessenger::send_onion_message
508 #[derive(Clone)]
509 #[must_use]
510 #[repr(C)]
511 pub enum SendError {
512         /// Errored computing onion message packet keys.
513         Secp256k1(
514                 crate::c_types::Secp256k1Error),
515         /// Because implementations such as Eclair will drop onion messages where the message packet
516         /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
517         TooBigPacket,
518         /// The provided [`Destination`] was an invalid [`BlindedPath`], due to having fewer than two
519         /// blinded hops.
520         TooFewBlindedHops,
521         /// Our next-hop peer was offline or does not support onion message forwarding.
522         InvalidFirstHop,
523         /// Onion message contents must have a TLV type >= 64.
524         InvalidMessage,
525         /// Our next-hop peer's buffer was full or our total outbound buffer was full.
526         BufferFull,
527         /// Failed to retrieve our node id from the provided [`NodeSigner`].
528         ///
529         /// [`NodeSigner`]: crate::sign::NodeSigner
530         GetNodeIdFailed,
531         /// We attempted to send to a blinded path where we are the introduction node, and failed to
532         /// advance the blinded path to make the second hop the new introduction node. Either
533         /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
534         /// new blinding point, or we were attempting to send to ourselves.
535         BlindedPathAdvanceFailed,
536 }
537 use lightning::onion_message::messenger::SendError as SendErrorImport;
538 pub(crate) type nativeSendError = SendErrorImport;
539
540 impl SendError {
541         #[allow(unused)]
542         pub(crate) fn to_native(&self) -> nativeSendError {
543                 match self {
544                         SendError::Secp256k1 (ref a, ) => {
545                                 let mut a_nonref = Clone::clone(a);
546                                 nativeSendError::Secp256k1 (
547                                         a_nonref.into_rust(),
548                                 )
549                         },
550                         SendError::TooBigPacket => nativeSendError::TooBigPacket,
551                         SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
552                         SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
553                         SendError::InvalidMessage => nativeSendError::InvalidMessage,
554                         SendError::BufferFull => nativeSendError::BufferFull,
555                         SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
556                         SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
557                 }
558         }
559         #[allow(unused)]
560         pub(crate) fn into_native(self) -> nativeSendError {
561                 match self {
562                         SendError::Secp256k1 (mut a, ) => {
563                                 nativeSendError::Secp256k1 (
564                                         a.into_rust(),
565                                 )
566                         },
567                         SendError::TooBigPacket => nativeSendError::TooBigPacket,
568                         SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
569                         SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
570                         SendError::InvalidMessage => nativeSendError::InvalidMessage,
571                         SendError::BufferFull => nativeSendError::BufferFull,
572                         SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
573                         SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
574                 }
575         }
576         #[allow(unused)]
577         pub(crate) fn from_native(native: &nativeSendError) -> Self {
578                 match native {
579                         nativeSendError::Secp256k1 (ref a, ) => {
580                                 let mut a_nonref = Clone::clone(a);
581                                 SendError::Secp256k1 (
582                                         crate::c_types::Secp256k1Error::from_rust(a_nonref),
583                                 )
584                         },
585                         nativeSendError::TooBigPacket => SendError::TooBigPacket,
586                         nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
587                         nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
588                         nativeSendError::InvalidMessage => SendError::InvalidMessage,
589                         nativeSendError::BufferFull => SendError::BufferFull,
590                         nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
591                         nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
592                 }
593         }
594         #[allow(unused)]
595         pub(crate) fn native_into(native: nativeSendError) -> Self {
596                 match native {
597                         nativeSendError::Secp256k1 (mut a, ) => {
598                                 SendError::Secp256k1 (
599                                         crate::c_types::Secp256k1Error::from_rust(a),
600                                 )
601                         },
602                         nativeSendError::TooBigPacket => SendError::TooBigPacket,
603                         nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
604                         nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
605                         nativeSendError::InvalidMessage => SendError::InvalidMessage,
606                         nativeSendError::BufferFull => SendError::BufferFull,
607                         nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
608                         nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
609                 }
610         }
611 }
612 /// Frees any resources used by the SendError
613 #[no_mangle]
614 pub extern "C" fn SendError_free(this_ptr: SendError) { }
615 /// Creates a copy of the SendError
616 #[no_mangle]
617 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
618         orig.clone()
619 }
620 #[no_mangle]
621 /// Utility method to constructs a new Secp256k1-variant SendError
622 pub extern "C" fn SendError_secp256k1(a: crate::c_types::Secp256k1Error) -> SendError {
623         SendError::Secp256k1(a, )
624 }
625 #[no_mangle]
626 /// Utility method to constructs a new TooBigPacket-variant SendError
627 pub extern "C" fn SendError_too_big_packet() -> SendError {
628         SendError::TooBigPacket}
629 #[no_mangle]
630 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
631 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
632         SendError::TooFewBlindedHops}
633 #[no_mangle]
634 /// Utility method to constructs a new InvalidFirstHop-variant SendError
635 pub extern "C" fn SendError_invalid_first_hop() -> SendError {
636         SendError::InvalidFirstHop}
637 #[no_mangle]
638 /// Utility method to constructs a new InvalidMessage-variant SendError
639 pub extern "C" fn SendError_invalid_message() -> SendError {
640         SendError::InvalidMessage}
641 #[no_mangle]
642 /// Utility method to constructs a new BufferFull-variant SendError
643 pub extern "C" fn SendError_buffer_full() -> SendError {
644         SendError::BufferFull}
645 #[no_mangle]
646 /// Utility method to constructs a new GetNodeIdFailed-variant SendError
647 pub extern "C" fn SendError_get_node_id_failed() -> SendError {
648         SendError::GetNodeIdFailed}
649 #[no_mangle]
650 /// Utility method to constructs a new BlindedPathAdvanceFailed-variant SendError
651 pub extern "C" fn SendError_blinded_path_advance_failed() -> SendError {
652         SendError::BlindedPathAdvanceFailed}
653 /// Checks if two SendErrors contain equal inner contents.
654 /// This ignores pointers and is_owned flags and looks at the values in fields.
655 #[no_mangle]
656 pub extern "C" fn SendError_eq(a: &SendError, b: &SendError) -> bool {
657         if &a.to_native() == &b.to_native() { true } else { false }
658 }
659 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
660 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
661 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
662 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
663 /// message types.
664 ///
665 /// See [`OnionMessenger`] for example usage.
666 ///
667 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
668 /// [`CustomMessage`]: Self::CustomMessage
669 #[repr(C)]
670 pub struct CustomOnionMessageHandler {
671         /// An opaque pointer which is passed to your function implementations as an argument.
672         /// This has no meaning in the LDK, and can be NULL or any other value.
673         pub this_arg: *mut c_void,
674         /// Called with the custom message that was received, returning a response to send, if any.
675         pub handle_custom_message: extern "C" fn (this_arg: *const c_void, msg: crate::lightning::onion_message::packet::CustomOnionMessageContents) -> crate::c_types::derived::COption_CustomOnionMessageContentsZ,
676         /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
677         /// message type is unknown.
678         pub read_custom_message: extern "C" fn (this_arg: *const c_void, message_type: u64, buffer: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_CustomOnionMessageContentsZDecodeErrorZ,
679         /// Frees any resources associated with this object given its this_arg pointer.
680         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
681         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
682 }
683 unsafe impl Send for CustomOnionMessageHandler {}
684 unsafe impl Sync for CustomOnionMessageHandler {}
685 #[no_mangle]
686 pub(crate) extern "C" fn CustomOnionMessageHandler_clone_fields(orig: &CustomOnionMessageHandler) -> CustomOnionMessageHandler {
687         CustomOnionMessageHandler {
688                 this_arg: orig.this_arg,
689                 handle_custom_message: Clone::clone(&orig.handle_custom_message),
690                 read_custom_message: Clone::clone(&orig.read_custom_message),
691                 free: Clone::clone(&orig.free),
692         }
693 }
694
695 use lightning::onion_message::messenger::CustomOnionMessageHandler as rustCustomOnionMessageHandler;
696 impl rustCustomOnionMessageHandler for CustomOnionMessageHandler {
697         type CustomMessage = crate::lightning::onion_message::packet::CustomOnionMessageContents;
698         fn handle_custom_message(&self, mut msg: crate::lightning::onion_message::packet::CustomOnionMessageContents) -> Option<crate::lightning::onion_message::packet::CustomOnionMessageContents> {
699                 let mut ret = (self.handle_custom_message)(self.this_arg, Into::into(msg));
700                 let mut local_ret = { /*ret*/ let ret_opt = ret; if ret_opt.is_none() { None } else { Some({ { { ret_opt.take() } }})} };
701                 local_ret
702         }
703         fn read_custom_message<R:crate::c_types::io::Read>(&self, mut message_type: u64, mut buffer: &mut R) -> Result<Option<crate::lightning::onion_message::packet::CustomOnionMessageContents>, lightning::ln::msgs::DecodeError> {
704                 let mut ret = (self.read_custom_message)(self.this_arg, message_type, crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec(buffer)));
705                 let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = { /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ let ret_0_opt = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }); if ret_0_opt.is_none() { None } else { Some({ { { ret_0_opt.take() } }})} }; local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
706                 local_ret
707         }
708 }
709
710 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
711 // directly as a Deref trait in higher-level structs:
712 impl core::ops::Deref for CustomOnionMessageHandler {
713         type Target = Self;
714         fn deref(&self) -> &Self {
715                 self
716         }
717 }
718 /// Calls the free function if one is set
719 #[no_mangle]
720 pub extern "C" fn CustomOnionMessageHandler_free(this_ptr: CustomOnionMessageHandler) { }
721 impl Drop for CustomOnionMessageHandler {
722         fn drop(&mut self) {
723                 if let Some(f) = self.free {
724                         f(self.this_arg);
725                 }
726         }
727 }
728 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
729 /// their respective handlers.
730 #[must_use]
731 #[no_mangle]
732 pub extern "C" fn OnionMessenger_new(mut entropy_source: crate::lightning::sign::EntropySource, mut node_signer: crate::lightning::sign::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut message_router: crate::lightning::onion_message::messenger::MessageRouter, mut offers_handler: crate::lightning::onion_message::offers::OffersMessageHandler, mut custom_handler: crate::lightning::onion_message::messenger::CustomOnionMessageHandler) -> crate::lightning::onion_message::messenger::OnionMessenger {
733         let mut ret = lightning::onion_message::messenger::OnionMessenger::new(entropy_source, node_signer, logger, message_router, offers_handler, custom_handler);
734         crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(ret), is_owned: true }
735 }
736
737 /// Send an onion message with contents `message` to the destination of `path`.
738 ///
739 /// See [`OnionMessenger`] for example usage.
740 ///
741 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
742 #[must_use]
743 #[no_mangle]
744 pub extern "C" fn OnionMessenger_send_onion_message(this_arg: &crate::lightning::onion_message::messenger::OnionMessenger, mut path: crate::lightning::onion_message::messenger::OnionMessagePath, mut message: crate::lightning::onion_message::packet::OnionMessageContents, mut reply_path: crate::lightning::blinded_path::BlindedPath) -> crate::c_types::derived::CResult_NoneSendErrorZ {
745         let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
746         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_onion_message(*unsafe { Box::from_raw(path.take_inner()) }, message.into_native(), local_reply_path);
747         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::lightning::onion_message::messenger::SendError::native_into(e) }).into() };
748         local_ret
749 }
750
751 impl From<nativeOnionMessenger> for crate::lightning::ln::msgs::OnionMessageHandler {
752         fn from(obj: nativeOnionMessenger) -> Self {
753                 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
754                 let mut ret = OnionMessenger_as_OnionMessageHandler(&rust_obj);
755                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
756                 rust_obj.inner = core::ptr::null_mut();
757                 ret.free = Some(OnionMessenger_free_void);
758                 ret
759         }
760 }
761 /// Constructs a new OnionMessageHandler which calls the relevant methods on this_arg.
762 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageHandler must be freed before this_arg is
763 #[no_mangle]
764 pub extern "C" fn OnionMessenger_as_OnionMessageHandler(this_arg: &OnionMessenger) -> crate::lightning::ln::msgs::OnionMessageHandler {
765         crate::lightning::ln::msgs::OnionMessageHandler {
766                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
767                 free: None,
768                 handle_onion_message: OnionMessenger_OnionMessageHandler_handle_onion_message,
769                 peer_connected: OnionMessenger_OnionMessageHandler_peer_connected,
770                 peer_disconnected: OnionMessenger_OnionMessageHandler_peer_disconnected,
771                 provided_node_features: OnionMessenger_OnionMessageHandler_provided_node_features,
772                 provided_init_features: OnionMessenger_OnionMessageHandler_provided_init_features,
773                 OnionMessageProvider: crate::lightning::events::OnionMessageProvider {
774                         this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
775                         free: None,
776                         next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
777                 },
778         }
779 }
780
781 extern "C" fn OnionMessenger_OnionMessageHandler_handle_onion_message(this_arg: *const c_void, mut peer_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OnionMessage) {
782         <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::handle_onion_message(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &peer_node_id.into_rust(), msg.get_native_ref())
783 }
784 #[must_use]
785 extern "C" fn OnionMessenger_OnionMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ {
786         let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), init.get_native_ref(), inbound);
787         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
788         local_ret
789 }
790 extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) {
791         <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust())
792 }
793 #[must_use]
794 extern "C" fn OnionMessenger_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures {
795         let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_node_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, );
796         crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
797 }
798 #[must_use]
799 extern "C" fn OnionMessenger_OnionMessageHandler_provided_init_features(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) -> crate::lightning::ln::features::InitFeatures {
800         let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_init_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust());
801         crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
802 }
803
804 impl From<nativeOnionMessenger> for crate::lightning::events::OnionMessageProvider {
805         fn from(obj: nativeOnionMessenger) -> Self {
806                 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
807                 let mut ret = OnionMessenger_as_OnionMessageProvider(&rust_obj);
808                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
809                 rust_obj.inner = core::ptr::null_mut();
810                 ret.free = Some(OnionMessenger_free_void);
811                 ret
812         }
813 }
814 /// Constructs a new OnionMessageProvider which calls the relevant methods on this_arg.
815 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageProvider must be freed before this_arg is
816 #[no_mangle]
817 pub extern "C" fn OnionMessenger_as_OnionMessageProvider(this_arg: &OnionMessenger) -> crate::lightning::events::OnionMessageProvider {
818         crate::lightning::events::OnionMessageProvider {
819                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
820                 free: None,
821                 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
822         }
823 }
824
825 #[must_use]
826 extern "C" fn OnionMessenger_OnionMessageProvider_next_onion_message_for_peer(this_arg: *const c_void, mut peer_node_id: crate::c_types::PublicKey) -> crate::lightning::ln::msgs::OnionMessage {
827         let mut ret = <nativeOnionMessenger as lightning::events::OnionMessageProvider<>>::next_onion_message_for_peer(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, peer_node_id.into_rust());
828         let mut local_ret = crate::lightning::ln::msgs::OnionMessage { inner: if ret.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true };
829         local_ret
830 }
831