1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
9 //! LDK sends, receives, and forwards onion messages via the [`OnionMessenger`]. See its docs for
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};
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>;
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.
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!() }
47 /// # struct FakeMessageRouter {}
48 /// # impl MessageRouter for FakeMessageRouter {
49 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
50 /// # unimplemented!()
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
72 /// # struct YourCustomMessage {}
73 /// impl Writeable for YourCustomMessage {
74 /// \tfn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
76 /// \t\t// Write your custom onion message to `w`
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
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),
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);
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();
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),
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);
111 /// [offers]: <https://github.com/lightning/bolts/pull/798>
112 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
115 pub struct OnionMessenger {
116 /// A pointer to the opaque Rust object.
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.
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.
128 impl Drop for OnionMessenger {
130 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
131 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
135 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
137 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
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) };
144 impl OnionMessenger {
145 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
146 unsafe { &*ObjOps::untweak_ptr(self.inner) }
148 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
149 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
159 /// A trait defining behavior for routing an [`OnionMessage`].
161 /// [`OnionMessage`]: msgs::OnionMessage
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`].
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)>,
175 unsafe impl Send for MessageRouter {}
176 unsafe impl Sync for MessageRouter {}
178 pub(crate) extern "C" fn MessageRouter_clone_fields(orig: &MessageRouter) -> MessageRouter {
180 this_arg: orig.this_arg,
181 find_path: Clone::clone(&orig.find_path),
182 free: Clone::clone(&orig.free),
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)) })*/ })};
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 {
200 fn deref(&self) -> &Self {
204 /// Calls the free function if one is set
206 pub extern "C" fn MessageRouter_free(this_ptr: MessageRouter) { }
207 impl Drop for MessageRouter {
209 if let Some(f) = self.free {
215 use lightning::onion_message::messenger::DefaultMessageRouter as nativeDefaultMessageRouterImport;
216 pub(crate) type nativeDefaultMessageRouter = nativeDefaultMessageRouterImport;
218 /// A [`MessageRouter`] that always fails.
221 pub struct DefaultMessageRouter {
222 /// A pointer to the opaque Rust object.
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.
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.
234 impl Drop for DefaultMessageRouter {
236 if self.is_owned && !<*mut nativeDefaultMessageRouter>::is_null(self.inner) {
237 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
241 /// Frees any resources used by the DefaultMessageRouter, if is_owned is set and inner is non-NULL.
243 pub extern "C" fn DefaultMessageRouter_free(this_obj: DefaultMessageRouter) { }
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) };
250 impl DefaultMessageRouter {
251 pub(crate) fn get_native_ref(&self) -> &'static nativeDefaultMessageRouter {
252 unsafe { &*ObjOps::untweak_ptr(self.inner) }
254 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDefaultMessageRouter {
255 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
265 /// Constructs a new DefaultMessageRouter given each field
268 pub extern "C" fn DefaultMessageRouter_new() -> DefaultMessageRouter {
269 DefaultMessageRouter { inner: ObjOps::heap_alloc(lightning::onion_message::messenger::DefaultMessageRouter {}), is_owned: true }
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);
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
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 },
288 find_path: DefaultMessageRouter_MessageRouter_find_path,
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() };
301 use lightning::onion_message::messenger::OnionMessagePath as nativeOnionMessagePathImport;
302 pub(crate) type nativeOnionMessagePath = nativeOnionMessagePathImport;
304 /// A path for sending an [`msgs::OnionMessage`].
307 pub struct OnionMessagePath {
308 /// A pointer to the opaque Rust object.
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.
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.
320 impl Drop for OnionMessagePath {
322 if self.is_owned && !<*mut nativeOnionMessagePath>::is_null(self.inner) {
323 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
327 /// Frees any resources used by the OnionMessagePath, if is_owned is set and inner is non-NULL.
329 pub extern "C" fn OnionMessagePath_free(this_obj: OnionMessagePath) { }
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) };
336 impl OnionMessagePath {
337 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessagePath {
338 unsafe { &*ObjOps::untweak_ptr(self.inner) }
340 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessagePath {
341 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
351 /// Nodes on the path between the sender and the destination.
353 /// Returns a copy of the field.
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()
360 /// Nodes on the path between the sender and the destination.
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;
366 /// The recipient of the message.
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)
372 /// The recipient of the message.
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();
377 /// Constructs a new OnionMessagePath given each field
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(),
387 impl Clone for OnionMessagePath {
388 fn clone(&self) -> 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()) },
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
402 /// Creates a copy of the OnionMessagePath
403 pub extern "C" fn OnionMessagePath_clone(orig: &OnionMessagePath) -> OnionMessagePath {
406 /// The destination of an onion message.
410 pub enum Destination {
411 /// We're sending this onion message to a node.
413 crate::c_types::PublicKey),
414 /// We're sending this onion message to a blinded path.
416 crate::lightning::blinded_path::BlindedPath),
418 use lightning::onion_message::messenger::Destination as DestinationImport;
419 pub(crate) type nativeDestination = DestinationImport;
423 pub(crate) fn to_native(&self) -> nativeDestination {
425 Destination::Node (ref a, ) => {
426 let mut a_nonref = Clone::clone(a);
427 nativeDestination::Node (
428 a_nonref.into_rust(),
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()) },
440 pub(crate) fn into_native(self) -> nativeDestination {
442 Destination::Node (mut a, ) => {
443 nativeDestination::Node (
447 Destination::BlindedPath (mut a, ) => {
448 nativeDestination::BlindedPath (
449 *unsafe { Box::from_raw(a.take_inner()) },
455 pub(crate) fn from_native(native: &nativeDestination) -> Self {
457 nativeDestination::Node (ref a, ) => {
458 let mut a_nonref = Clone::clone(a);
460 crate::c_types::PublicKey::from_rust(&a_nonref),
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 },
472 pub(crate) fn native_into(native: nativeDestination) -> Self {
474 nativeDestination::Node (mut a, ) => {
476 crate::c_types::PublicKey::from_rust(&a),
479 nativeDestination::BlindedPath (mut a, ) => {
480 Destination::BlindedPath (
481 crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a), is_owned: true },
487 /// Frees any resources used by the Destination
489 pub extern "C" fn Destination_free(this_ptr: Destination) { }
490 /// Creates a copy of the Destination
492 pub extern "C" fn Destination_clone(orig: &Destination) -> Destination {
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, )
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, )
505 /// Errors that may occur when [sending an onion message].
507 /// [sending an onion message]: OnionMessenger::send_onion_message
512 /// Errored computing onion message packet keys.
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.
518 /// The provided [`Destination`] was an invalid [`BlindedPath`], due to having fewer than two
521 /// Our next-hop peer was offline or does not support onion message forwarding.
523 /// Onion message contents must have a TLV type >= 64.
525 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
527 /// Failed to retrieve our node id from the provided [`NodeSigner`].
529 /// [`NodeSigner`]: crate::sign::NodeSigner
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,
537 use lightning::onion_message::messenger::SendError as SendErrorImport;
538 pub(crate) type nativeSendError = SendErrorImport;
542 pub(crate) fn to_native(&self) -> nativeSendError {
544 SendError::Secp256k1 (ref a, ) => {
545 let mut a_nonref = Clone::clone(a);
546 nativeSendError::Secp256k1 (
547 a_nonref.into_rust(),
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,
560 pub(crate) fn into_native(self) -> nativeSendError {
562 SendError::Secp256k1 (mut a, ) => {
563 nativeSendError::Secp256k1 (
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,
577 pub(crate) fn from_native(native: &nativeSendError) -> Self {
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),
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,
595 pub(crate) fn native_into(native: nativeSendError) -> Self {
597 nativeSendError::Secp256k1 (mut a, ) => {
598 SendError::Secp256k1 (
599 crate::c_types::Secp256k1Error::from_rust(a),
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,
612 /// Frees any resources used by the SendError
614 pub extern "C" fn SendError_free(this_ptr: SendError) { }
615 /// Creates a copy of the SendError
617 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
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, )
626 /// Utility method to constructs a new TooBigPacket-variant SendError
627 pub extern "C" fn SendError_too_big_packet() -> SendError {
628 SendError::TooBigPacket}
630 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
631 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
632 SendError::TooFewBlindedHops}
634 /// Utility method to constructs a new InvalidFirstHop-variant SendError
635 pub extern "C" fn SendError_invalid_first_hop() -> SendError {
636 SendError::InvalidFirstHop}
638 /// Utility method to constructs a new InvalidMessage-variant SendError
639 pub extern "C" fn SendError_invalid_message() -> SendError {
640 SendError::InvalidMessage}
642 /// Utility method to constructs a new BufferFull-variant SendError
643 pub extern "C" fn SendError_buffer_full() -> SendError {
644 SendError::BufferFull}
646 /// Utility method to constructs a new GetNodeIdFailed-variant SendError
647 pub extern "C" fn SendError_get_node_id_failed() -> SendError {
648 SendError::GetNodeIdFailed}
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.
656 pub extern "C" fn SendError_eq(a: &SendError, b: &SendError) -> bool {
657 if &a.to_native() == &b.to_native() { true } else { false }
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
665 /// See [`OnionMessenger`] for example usage.
667 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
668 /// [`CustomMessage`]: Self::CustomMessage
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)>,
683 unsafe impl Send for CustomOnionMessageHandler {}
684 unsafe impl Sync for CustomOnionMessageHandler {}
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),
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() } }})} };
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() })};
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 {
714 fn deref(&self) -> &Self {
718 /// Calls the free function if one is set
720 pub extern "C" fn CustomOnionMessageHandler_free(this_ptr: CustomOnionMessageHandler) { }
721 impl Drop for CustomOnionMessageHandler {
723 if let Some(f) = self.free {
728 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
729 /// their respective handlers.
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 }
737 /// Send an onion message with contents `message` to the destination of `path`.
739 /// See [`OnionMessenger`] for example usage.
741 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
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() };
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);
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
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 },
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 },
776 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
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())
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() };
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())
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 }
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 }
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);
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
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 },
821 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
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 };