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 alloc::string::String;
14 use core::ffi::c_void;
15 use core::convert::Infallible;
16 use bitcoin::hashes::Hash;
17 use crate::c_types::*;
18 #[cfg(feature="no-std")]
19 use alloc::{vec::Vec, boxed::Box};
22 use lightning::onion_message::messenger::OnionMessenger as nativeOnionMessengerImport;
23 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>;
25 /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
26 /// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending
27 /// and receiving custom onion messages is supported.
32 /// # extern crate bitcoin;
33 /// # use bitcoin::hashes::_export::_core::time::Duration;
34 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
35 /// # use lightning::blinded_path::BlindedPath;
36 /// # use lightning::sign::KeysManager;
37 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
38 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessenger, OnionMessagePath};
39 /// # use lightning::onion_message::packet::{CustomOnionMessageContents, OnionMessageContents};
40 /// # use lightning::util::logger::{Logger, Record};
41 /// # use lightning::util::ser::{Writeable, Writer};
42 /// # use lightning::io;
43 /// # use std::sync::Arc;
44 /// # struct FakeLogger;
45 /// # impl Logger for FakeLogger {
46 /// # fn log(&self, record: &Record) { unimplemented!() }
48 /// # struct FakeMessageRouter {}
49 /// # impl MessageRouter for FakeMessageRouter {
50 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
51 /// # unimplemented!()
54 /// # let seed = [42u8; 32];
55 /// # let time = Duration::from_secs(123456);
56 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
57 /// # let logger = Arc::new(FakeLogger {});
58 /// # let node_secret = SecretKey::from_slice(&hex::decode(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
59 /// # let secp_ctx = Secp256k1::new();
60 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
61 /// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1, hop_node_id1);
62 /// # let destination_node_id = hop_node_id1;
63 /// # let message_router = Arc::new(FakeMessageRouter {});
64 /// # let custom_message_handler = IgnoringMessageHandler {};
65 /// # let offers_message_handler = IgnoringMessageHandler {};
66 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
67 /// // ChannelManager.
68 /// let onion_messenger = OnionMessenger::new(
69 /// &keys_manager, &keys_manager, logger, message_router, &offers_message_handler,
70 /// &custom_message_handler
73 /// # #[derive(Clone)]
74 /// # struct YourCustomMessage {}
75 /// impl Writeable for YourCustomMessage {
76 /// \tfn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
78 /// \t\t// Write your custom onion message to `w`
81 /// impl CustomOnionMessageContents for YourCustomMessage {
82 /// \tfn tlv_type(&self) -> u64 {
83 /// \t\t# let your_custom_message_type = 42;
84 /// \t\tyour_custom_message_type
87 /// // Send a custom onion message to a node id.
88 /// let path = OnionMessagePath {
89 /// \tintermediate_nodes: vec![hop_node_id1, hop_node_id2],
90 /// \tdestination: Destination::Node(destination_node_id),
92 /// let reply_path = None;
93 /// # let your_custom_message = YourCustomMessage {};
94 /// let message = OnionMessageContents::Custom(your_custom_message);
95 /// onion_messenger.send_onion_message(path, message, reply_path);
97 /// // Create a blinded path to yourself, for someone to send an onion message to.
98 /// # let your_node_id = hop_node_id1;
99 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
100 /// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
102 /// // Send a custom onion message to a blinded path.
103 /// let path = OnionMessagePath {
104 /// \tintermediate_nodes: vec![hop_node_id1, hop_node_id2],
105 /// \tdestination: Destination::BlindedPath(blinded_path),
107 /// let reply_path = None;
108 /// # let your_custom_message = YourCustomMessage {};
109 /// let message = OnionMessageContents::Custom(your_custom_message);
110 /// onion_messenger.send_onion_message(path, message, reply_path);
113 /// [offers]: <https://github.com/lightning/bolts/pull/798>
114 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
117 pub struct OnionMessenger {
118 /// A pointer to the opaque Rust object.
120 /// Nearly everywhere, inner must be non-null, however in places where
121 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
122 pub inner: *mut nativeOnionMessenger,
123 /// Indicates that this is the only struct which contains the same pointer.
125 /// Rust functions which take ownership of an object provided via an argument require
126 /// this to be true and invalidate the object pointed to by inner.
130 impl Drop for OnionMessenger {
132 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
133 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
137 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
139 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
141 /// Used only if an object of this type is returned as a trait impl by a method
142 pub(crate) extern "C" fn OnionMessenger_free_void(this_ptr: *mut c_void) {
143 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessenger) };
146 impl OnionMessenger {
147 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
148 unsafe { &*ObjOps::untweak_ptr(self.inner) }
150 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
151 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
153 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
154 pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessenger {
155 assert!(self.is_owned);
156 let ret = ObjOps::untweak_ptr(self.inner);
157 self.inner = core::ptr::null_mut();
161 /// A trait defining behavior for routing an [`OnionMessage`].
163 /// [`OnionMessage`]: msgs::OnionMessage
165 pub struct MessageRouter {
166 /// An opaque pointer which is passed to your function implementations as an argument.
167 /// This has no meaning in the LDK, and can be NULL or any other value.
168 pub this_arg: *mut c_void,
169 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
171 /// [`OnionMessage`]: msgs::OnionMessage
172 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,
173 /// Frees any resources associated with this object given its this_arg pointer.
174 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
175 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
177 unsafe impl Send for MessageRouter {}
178 unsafe impl Sync for MessageRouter {}
179 pub(crate) fn MessageRouter_clone_fields(orig: &MessageRouter) -> MessageRouter {
181 this_arg: orig.this_arg,
182 find_path: Clone::clone(&orig.find_path),
183 free: Clone::clone(&orig.free),
187 use lightning::onion_message::messenger::MessageRouter as rustMessageRouter;
188 impl rustMessageRouter for MessageRouter {
189 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, ()> {
190 let mut local_peers = Vec::new(); for mut item in peers.drain(..) { local_peers.push( { crate::c_types::PublicKey::from_rust(&item) }); };
191 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));
192 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)) })*/ })};
197 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
198 // directly as a Deref trait in higher-level structs:
199 impl core::ops::Deref for MessageRouter {
201 fn deref(&self) -> &Self {
205 impl core::ops::DerefMut for MessageRouter {
206 fn deref_mut(&mut self) -> &mut Self {
210 /// Calls the free function if one is set
212 pub extern "C" fn MessageRouter_free(this_ptr: MessageRouter) { }
213 impl Drop for MessageRouter {
215 if let Some(f) = self.free {
221 use lightning::onion_message::messenger::DefaultMessageRouter as nativeDefaultMessageRouterImport;
222 pub(crate) type nativeDefaultMessageRouter = nativeDefaultMessageRouterImport;
224 /// A [`MessageRouter`] that always fails.
227 pub struct DefaultMessageRouter {
228 /// A pointer to the opaque Rust object.
230 /// Nearly everywhere, inner must be non-null, however in places where
231 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
232 pub inner: *mut nativeDefaultMessageRouter,
233 /// Indicates that this is the only struct which contains the same pointer.
235 /// Rust functions which take ownership of an object provided via an argument require
236 /// this to be true and invalidate the object pointed to by inner.
240 impl Drop for DefaultMessageRouter {
242 if self.is_owned && !<*mut nativeDefaultMessageRouter>::is_null(self.inner) {
243 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
247 /// Frees any resources used by the DefaultMessageRouter, if is_owned is set and inner is non-NULL.
249 pub extern "C" fn DefaultMessageRouter_free(this_obj: DefaultMessageRouter) { }
251 /// Used only if an object of this type is returned as a trait impl by a method
252 pub(crate) extern "C" fn DefaultMessageRouter_free_void(this_ptr: *mut c_void) {
253 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeDefaultMessageRouter) };
256 impl DefaultMessageRouter {
257 pub(crate) fn get_native_ref(&self) -> &'static nativeDefaultMessageRouter {
258 unsafe { &*ObjOps::untweak_ptr(self.inner) }
260 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDefaultMessageRouter {
261 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
263 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
264 pub(crate) fn take_inner(mut self) -> *mut nativeDefaultMessageRouter {
265 assert!(self.is_owned);
266 let ret = ObjOps::untweak_ptr(self.inner);
267 self.inner = core::ptr::null_mut();
271 /// Constructs a new DefaultMessageRouter given each field
274 pub extern "C" fn DefaultMessageRouter_new() -> DefaultMessageRouter {
275 DefaultMessageRouter { inner: ObjOps::heap_alloc(lightning::onion_message::messenger::DefaultMessageRouter {}), is_owned: true }
277 impl From<nativeDefaultMessageRouter> for crate::lightning::onion_message::messenger::MessageRouter {
278 fn from(obj: nativeDefaultMessageRouter) -> Self {
279 let mut rust_obj = DefaultMessageRouter { inner: ObjOps::heap_alloc(obj), is_owned: true };
280 let mut ret = DefaultMessageRouter_as_MessageRouter(&rust_obj);
281 // 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
282 rust_obj.inner = core::ptr::null_mut();
283 ret.free = Some(DefaultMessageRouter_free_void);
287 /// Constructs a new MessageRouter which calls the relevant methods on this_arg.
288 /// This copies the `inner` pointer in this_arg and thus the returned MessageRouter must be freed before this_arg is
290 pub extern "C" fn DefaultMessageRouter_as_MessageRouter(this_arg: &DefaultMessageRouter) -> crate::lightning::onion_message::messenger::MessageRouter {
291 crate::lightning::onion_message::messenger::MessageRouter {
292 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
294 find_path: DefaultMessageRouter_MessageRouter_find_path,
299 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 {
300 let mut local_peers = Vec::new(); for mut item in peers.into_rust().drain(..) { local_peers.push( { item.into_rust() }); };
301 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());
302 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() };
307 use lightning::onion_message::messenger::OnionMessagePath as nativeOnionMessagePathImport;
308 pub(crate) type nativeOnionMessagePath = nativeOnionMessagePathImport;
310 /// A path for sending an [`msgs::OnionMessage`].
313 pub struct OnionMessagePath {
314 /// A pointer to the opaque Rust object.
316 /// Nearly everywhere, inner must be non-null, however in places where
317 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
318 pub inner: *mut nativeOnionMessagePath,
319 /// Indicates that this is the only struct which contains the same pointer.
321 /// Rust functions which take ownership of an object provided via an argument require
322 /// this to be true and invalidate the object pointed to by inner.
326 impl Drop for OnionMessagePath {
328 if self.is_owned && !<*mut nativeOnionMessagePath>::is_null(self.inner) {
329 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
333 /// Frees any resources used by the OnionMessagePath, if is_owned is set and inner is non-NULL.
335 pub extern "C" fn OnionMessagePath_free(this_obj: OnionMessagePath) { }
337 /// Used only if an object of this type is returned as a trait impl by a method
338 pub(crate) extern "C" fn OnionMessagePath_free_void(this_ptr: *mut c_void) {
339 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessagePath) };
342 impl OnionMessagePath {
343 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessagePath {
344 unsafe { &*ObjOps::untweak_ptr(self.inner) }
346 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessagePath {
347 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
349 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
350 pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessagePath {
351 assert!(self.is_owned);
352 let ret = ObjOps::untweak_ptr(self.inner);
353 self.inner = core::ptr::null_mut();
357 /// Nodes on the path between the sender and the destination.
359 /// Returns a copy of the field.
361 pub extern "C" fn OnionMessagePath_get_intermediate_nodes(this_ptr: &OnionMessagePath) -> crate::c_types::derived::CVec_PublicKeyZ {
362 let mut inner_val = this_ptr.get_native_mut_ref().intermediate_nodes.clone();
363 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) }); };
364 local_inner_val.into()
366 /// Nodes on the path between the sender and the destination.
368 pub extern "C" fn OnionMessagePath_set_intermediate_nodes(this_ptr: &mut OnionMessagePath, mut val: crate::c_types::derived::CVec_PublicKeyZ) {
369 let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
370 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.intermediate_nodes = local_val;
372 /// The recipient of the message.
374 pub extern "C" fn OnionMessagePath_get_destination(this_ptr: &OnionMessagePath) -> crate::lightning::onion_message::messenger::Destination {
375 let mut inner_val = &mut this_ptr.get_native_mut_ref().destination;
376 crate::lightning::onion_message::messenger::Destination::from_native(inner_val)
378 /// The recipient of the message.
380 pub extern "C" fn OnionMessagePath_set_destination(this_ptr: &mut OnionMessagePath, mut val: crate::lightning::onion_message::messenger::Destination) {
381 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.destination = val.into_native();
383 /// Constructs a new OnionMessagePath given each field
386 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 {
387 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() }); };
388 OnionMessagePath { inner: ObjOps::heap_alloc(nativeOnionMessagePath {
389 intermediate_nodes: local_intermediate_nodes_arg,
390 destination: destination_arg.into_native(),
393 impl Clone for OnionMessagePath {
394 fn clone(&self) -> Self {
396 inner: if <*mut nativeOnionMessagePath>::is_null(self.inner) { core::ptr::null_mut() } else {
397 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
403 /// Used only if an object of this type is returned as a trait impl by a method
404 pub(crate) extern "C" fn OnionMessagePath_clone_void(this_ptr: *const c_void) -> *mut c_void {
405 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOnionMessagePath)).clone() })) as *mut c_void
408 /// Creates a copy of the OnionMessagePath
409 pub extern "C" fn OnionMessagePath_clone(orig: &OnionMessagePath) -> OnionMessagePath {
412 /// The destination of an onion message.
416 pub enum Destination {
417 /// We're sending this onion message to a node.
419 crate::c_types::PublicKey),
420 /// We're sending this onion message to a blinded path.
422 crate::lightning::blinded_path::BlindedPath),
424 use lightning::onion_message::messenger::Destination as DestinationImport;
425 pub(crate) type nativeDestination = DestinationImport;
429 pub(crate) fn to_native(&self) -> nativeDestination {
431 Destination::Node (ref a, ) => {
432 let mut a_nonref = Clone::clone(a);
433 nativeDestination::Node (
434 a_nonref.into_rust(),
437 Destination::BlindedPath (ref a, ) => {
438 let mut a_nonref = Clone::clone(a);
439 nativeDestination::BlindedPath (
440 *unsafe { Box::from_raw(a_nonref.take_inner()) },
446 pub(crate) fn into_native(self) -> nativeDestination {
448 Destination::Node (mut a, ) => {
449 nativeDestination::Node (
453 Destination::BlindedPath (mut a, ) => {
454 nativeDestination::BlindedPath (
455 *unsafe { Box::from_raw(a.take_inner()) },
461 pub(crate) fn from_native(native: &nativeDestination) -> Self {
463 nativeDestination::Node (ref a, ) => {
464 let mut a_nonref = Clone::clone(a);
466 crate::c_types::PublicKey::from_rust(&a_nonref),
469 nativeDestination::BlindedPath (ref a, ) => {
470 let mut a_nonref = Clone::clone(a);
471 Destination::BlindedPath (
472 crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
478 pub(crate) fn native_into(native: nativeDestination) -> Self {
480 nativeDestination::Node (mut a, ) => {
482 crate::c_types::PublicKey::from_rust(&a),
485 nativeDestination::BlindedPath (mut a, ) => {
486 Destination::BlindedPath (
487 crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a), is_owned: true },
493 /// Frees any resources used by the Destination
495 pub extern "C" fn Destination_free(this_ptr: Destination) { }
496 /// Creates a copy of the Destination
498 pub extern "C" fn Destination_clone(orig: &Destination) -> Destination {
502 /// Utility method to constructs a new Node-variant Destination
503 pub extern "C" fn Destination_node(a: crate::c_types::PublicKey) -> Destination {
504 Destination::Node(a, )
507 /// Utility method to constructs a new BlindedPath-variant Destination
508 pub extern "C" fn Destination_blinded_path(a: crate::lightning::blinded_path::BlindedPath) -> Destination {
509 Destination::BlindedPath(a, )
511 /// Errors that may occur when [sending an onion message].
513 /// [sending an onion message]: OnionMessenger::send_onion_message
518 /// Errored computing onion message packet keys.
520 crate::c_types::Secp256k1Error),
521 /// Because implementations such as Eclair will drop onion messages where the message packet
522 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
524 /// The provided [`Destination`] was an invalid [`BlindedPath`], due to having fewer than two
527 /// Our next-hop peer was offline or does not support onion message forwarding.
529 /// Onion message contents must have a TLV type >= 64.
531 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
533 /// Failed to retrieve our node id from the provided [`NodeSigner`].
535 /// [`NodeSigner`]: crate::sign::NodeSigner
537 /// We attempted to send to a blinded path where we are the introduction node, and failed to
538 /// advance the blinded path to make the second hop the new introduction node. Either
539 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
540 /// new blinding point, or we were attempting to send to ourselves.
541 BlindedPathAdvanceFailed,
543 use lightning::onion_message::messenger::SendError as SendErrorImport;
544 pub(crate) type nativeSendError = SendErrorImport;
548 pub(crate) fn to_native(&self) -> nativeSendError {
550 SendError::Secp256k1 (ref a, ) => {
551 let mut a_nonref = Clone::clone(a);
552 nativeSendError::Secp256k1 (
553 a_nonref.into_rust(),
556 SendError::TooBigPacket => nativeSendError::TooBigPacket,
557 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
558 SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
559 SendError::InvalidMessage => nativeSendError::InvalidMessage,
560 SendError::BufferFull => nativeSendError::BufferFull,
561 SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
562 SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
566 pub(crate) fn into_native(self) -> nativeSendError {
568 SendError::Secp256k1 (mut a, ) => {
569 nativeSendError::Secp256k1 (
573 SendError::TooBigPacket => nativeSendError::TooBigPacket,
574 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
575 SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
576 SendError::InvalidMessage => nativeSendError::InvalidMessage,
577 SendError::BufferFull => nativeSendError::BufferFull,
578 SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
579 SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
583 pub(crate) fn from_native(native: &nativeSendError) -> Self {
585 nativeSendError::Secp256k1 (ref a, ) => {
586 let mut a_nonref = Clone::clone(a);
587 SendError::Secp256k1 (
588 crate::c_types::Secp256k1Error::from_rust(a_nonref),
591 nativeSendError::TooBigPacket => SendError::TooBigPacket,
592 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
593 nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
594 nativeSendError::InvalidMessage => SendError::InvalidMessage,
595 nativeSendError::BufferFull => SendError::BufferFull,
596 nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
597 nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
601 pub(crate) fn native_into(native: nativeSendError) -> Self {
603 nativeSendError::Secp256k1 (mut a, ) => {
604 SendError::Secp256k1 (
605 crate::c_types::Secp256k1Error::from_rust(a),
608 nativeSendError::TooBigPacket => SendError::TooBigPacket,
609 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
610 nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
611 nativeSendError::InvalidMessage => SendError::InvalidMessage,
612 nativeSendError::BufferFull => SendError::BufferFull,
613 nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
614 nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
618 /// Frees any resources used by the SendError
620 pub extern "C" fn SendError_free(this_ptr: SendError) { }
621 /// Creates a copy of the SendError
623 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
627 /// Utility method to constructs a new Secp256k1-variant SendError
628 pub extern "C" fn SendError_secp256k1(a: crate::c_types::Secp256k1Error) -> SendError {
629 SendError::Secp256k1(a, )
632 /// Utility method to constructs a new TooBigPacket-variant SendError
633 pub extern "C" fn SendError_too_big_packet() -> SendError {
634 SendError::TooBigPacket}
636 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
637 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
638 SendError::TooFewBlindedHops}
640 /// Utility method to constructs a new InvalidFirstHop-variant SendError
641 pub extern "C" fn SendError_invalid_first_hop() -> SendError {
642 SendError::InvalidFirstHop}
644 /// Utility method to constructs a new InvalidMessage-variant SendError
645 pub extern "C" fn SendError_invalid_message() -> SendError {
646 SendError::InvalidMessage}
648 /// Utility method to constructs a new BufferFull-variant SendError
649 pub extern "C" fn SendError_buffer_full() -> SendError {
650 SendError::BufferFull}
652 /// Utility method to constructs a new GetNodeIdFailed-variant SendError
653 pub extern "C" fn SendError_get_node_id_failed() -> SendError {
654 SendError::GetNodeIdFailed}
656 /// Utility method to constructs a new BlindedPathAdvanceFailed-variant SendError
657 pub extern "C" fn SendError_blinded_path_advance_failed() -> SendError {
658 SendError::BlindedPathAdvanceFailed}
659 /// Checks if two SendErrors contain equal inner contents.
660 /// This ignores pointers and is_owned flags and looks at the values in fields.
662 pub extern "C" fn SendError_eq(a: &SendError, b: &SendError) -> bool {
663 if &a.to_native() == &b.to_native() { true } else { false }
665 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
666 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
667 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
668 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
671 /// See [`OnionMessenger`] for example usage.
673 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
674 /// [`CustomMessage`]: Self::CustomMessage
676 pub struct CustomOnionMessageHandler {
677 /// An opaque pointer which is passed to your function implementations as an argument.
678 /// This has no meaning in the LDK, and can be NULL or any other value.
679 pub this_arg: *mut c_void,
680 /// Called with the custom message that was received, returning a response to send, if any.
681 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,
682 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
683 /// message type is unknown.
684 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,
685 /// Frees any resources associated with this object given its this_arg pointer.
686 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
687 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
689 unsafe impl Send for CustomOnionMessageHandler {}
690 unsafe impl Sync for CustomOnionMessageHandler {}
691 pub(crate) fn CustomOnionMessageHandler_clone_fields(orig: &CustomOnionMessageHandler) -> CustomOnionMessageHandler {
692 CustomOnionMessageHandler {
693 this_arg: orig.this_arg,
694 handle_custom_message: Clone::clone(&orig.handle_custom_message),
695 read_custom_message: Clone::clone(&orig.read_custom_message),
696 free: Clone::clone(&orig.free),
700 use lightning::onion_message::messenger::CustomOnionMessageHandler as rustCustomOnionMessageHandler;
701 impl rustCustomOnionMessageHandler for CustomOnionMessageHandler {
702 type CustomMessage = crate::lightning::onion_message::packet::CustomOnionMessageContents;
703 fn handle_custom_message(&self, mut msg: crate::lightning::onion_message::packet::CustomOnionMessageContents) -> Option<crate::lightning::onion_message::packet::CustomOnionMessageContents> {
704 let mut ret = (self.handle_custom_message)(self.this_arg, Into::into(msg));
705 let mut local_ret = { /*ret*/ let ret_opt = ret; if ret_opt.is_none() { None } else { Some({ { { ret_opt.take() } }})} };
708 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> {
709 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)));
710 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() })};
715 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
716 // directly as a Deref trait in higher-level structs:
717 impl core::ops::Deref for CustomOnionMessageHandler {
719 fn deref(&self) -> &Self {
723 impl core::ops::DerefMut for CustomOnionMessageHandler {
724 fn deref_mut(&mut self) -> &mut Self {
728 /// Calls the free function if one is set
730 pub extern "C" fn CustomOnionMessageHandler_free(this_ptr: CustomOnionMessageHandler) { }
731 impl Drop for CustomOnionMessageHandler {
733 if let Some(f) = self.free {
738 /// Create an onion message with contents `message` to the destination of `path`.
739 /// Returns (introduction_node_id, onion_msg)
741 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
743 pub extern "C" fn create_onion_message(entropy_source: &crate::lightning::sign::EntropySource, node_signer: &crate::lightning::sign::NodeSigner, 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_C2Tuple_PublicKeyOnionMessageZSendErrorZ {
744 let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
745 let mut ret = lightning::onion_message::messenger::create_onion_message::<crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::onion_message::packet::CustomOnionMessageContents>(entropy_source, node_signer, secp256k1::global::SECP256K1, *unsafe { Box::from_raw(path.take_inner()) }, message.into_native(), local_reply_path);
746 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::PublicKey::from_rust(&orig_ret_0_0), crate::lightning::ln::msgs::OnionMessage { inner: ObjOps::heap_alloc(orig_ret_0_1), is_owned: true }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::onion_message::messenger::SendError::native_into(e) }).into() };
750 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
751 /// their respective handlers.
754 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 {
755 let mut ret = lightning::onion_message::messenger::OnionMessenger::new(entropy_source, node_signer, logger, message_router, offers_handler, custom_handler);
756 crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(ret), is_owned: true }
759 /// Send an onion message with contents `message` to the destination of `path`.
761 /// See [`OnionMessenger`] for example usage.
763 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
766 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 {
767 let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
768 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);
769 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() };
773 impl From<nativeOnionMessenger> for crate::lightning::ln::msgs::OnionMessageHandler {
774 fn from(obj: nativeOnionMessenger) -> Self {
775 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
776 let mut ret = OnionMessenger_as_OnionMessageHandler(&rust_obj);
777 // 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
778 rust_obj.inner = core::ptr::null_mut();
779 ret.free = Some(OnionMessenger_free_void);
783 /// Constructs a new OnionMessageHandler which calls the relevant methods on this_arg.
784 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageHandler must be freed before this_arg is
786 pub extern "C" fn OnionMessenger_as_OnionMessageHandler(this_arg: &OnionMessenger) -> crate::lightning::ln::msgs::OnionMessageHandler {
787 crate::lightning::ln::msgs::OnionMessageHandler {
788 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
790 handle_onion_message: OnionMessenger_OnionMessageHandler_handle_onion_message,
791 peer_connected: OnionMessenger_OnionMessageHandler_peer_connected,
792 peer_disconnected: OnionMessenger_OnionMessageHandler_peer_disconnected,
793 provided_node_features: OnionMessenger_OnionMessageHandler_provided_node_features,
794 provided_init_features: OnionMessenger_OnionMessageHandler_provided_init_features,
795 OnionMessageProvider: crate::lightning::events::OnionMessageProvider {
796 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
798 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
803 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) {
804 <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())
807 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 {
808 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);
809 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() };
812 extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) {
813 <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust())
816 extern "C" fn OnionMessenger_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures {
817 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_node_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, );
818 crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
821 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 {
822 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_init_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust());
823 crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
826 impl From<nativeOnionMessenger> for crate::lightning::events::OnionMessageProvider {
827 fn from(obj: nativeOnionMessenger) -> Self {
828 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
829 let mut ret = OnionMessenger_as_OnionMessageProvider(&rust_obj);
830 // 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
831 rust_obj.inner = core::ptr::null_mut();
832 ret.free = Some(OnionMessenger_free_void);
836 /// Constructs a new OnionMessageProvider which calls the relevant methods on this_arg.
837 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageProvider must be freed before this_arg is
839 pub extern "C" fn OnionMessenger_as_OnionMessageProvider(this_arg: &OnionMessenger) -> crate::lightning::events::OnionMessageProvider {
840 crate::lightning::events::OnionMessageProvider {
841 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
843 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
848 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 {
849 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());
850 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 };