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::chain::keysinterface::Sign, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::util::logger::Logger>;
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 empty 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::chain::keysinterface::{InMemorySigner, KeysManager, KeysInterface};
35 /// # use lightning::onion_message::messenger::{Destination, OnionMessenger};
36 /// # use lightning::onion_message::blinded_route::BlindedRoute;
37 /// # use lightning::util::logger::{Logger, Record};
38 /// # use std::sync::Arc;
39 /// # struct FakeLogger {};
40 /// # impl Logger for FakeLogger {
41 /// # fn log(&self, record: &Record) { unimplemented!() }
43 /// # let seed = [42u8; 32];
44 /// # let time = Duration::from_secs(123456);
45 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
46 /// # let logger = Arc::new(FakeLogger {});
47 /// # let node_secret = SecretKey::from_slice(&hex::decode(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
48 /// # let secp_ctx = Secp256k1::new();
49 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
50 /// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1,
52 /// # let destination_node_id = hop_node_id1;
54 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
55 /// // ChannelManager.
56 /// let onion_messenger = OnionMessenger::new(&keys_manager, logger);
58 /// // Send an empty onion message to a node id.
59 /// let intermediate_hops = [hop_node_id1, hop_node_id2];
60 /// let reply_path = None;
61 /// onion_messenger.send_onion_message(&intermediate_hops, Destination::Node(destination_node_id), reply_path);
63 /// // Create a blinded route to yourself, for someone to send an onion message to.
64 /// # let your_node_id = hop_node_id1;
65 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
66 /// let blinded_route = BlindedRoute::new(&hops, &keys_manager, &secp_ctx).unwrap();
68 /// // Send an empty onion message to a blinded route.
69 /// # let intermediate_hops = [hop_node_id1, hop_node_id2];
70 /// let reply_path = None;
71 /// onion_messenger.send_onion_message(&intermediate_hops, Destination::BlindedRoute(blinded_route), reply_path);
74 /// [offers]: <https://github.com/lightning/bolts/pull/798>
75 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
78 pub struct OnionMessenger {
79 /// A pointer to the opaque Rust object.
81 /// Nearly everywhere, inner must be non-null, however in places where
82 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
83 pub inner: *mut nativeOnionMessenger,
84 /// Indicates that this is the only struct which contains the same pointer.
86 /// Rust functions which take ownership of an object provided via an argument require
87 /// this to be true and invalidate the object pointed to by inner.
91 impl Drop for OnionMessenger {
93 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
94 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
98 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
100 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
102 /// Used only if an object of this type is returned as a trait impl by a method
103 pub(crate) extern "C" fn OnionMessenger_free_void(this_ptr: *mut c_void) {
104 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeOnionMessenger); }
107 impl OnionMessenger {
108 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
109 unsafe { &*ObjOps::untweak_ptr(self.inner) }
111 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
112 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
114 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
115 pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessenger {
116 assert!(self.is_owned);
117 let ret = ObjOps::untweak_ptr(self.inner);
118 self.inner = core::ptr::null_mut();
122 /// The destination of an onion message.
125 pub enum Destination {
126 /// We're sending this onion message to a node.
128 crate::c_types::PublicKey),
129 /// We're sending this onion message to a blinded route.
131 crate::lightning::onion_message::blinded_route::BlindedRoute),
133 use lightning::onion_message::messenger::Destination as DestinationImport;
134 pub(crate) type nativeDestination = DestinationImport;
138 pub(crate) fn into_native(self) -> nativeDestination {
140 Destination::Node (mut a, ) => {
141 nativeDestination::Node (
145 Destination::BlindedRoute (mut a, ) => {
146 nativeDestination::BlindedRoute (
147 *unsafe { Box::from_raw(a.take_inner()) },
153 pub(crate) fn native_into(native: nativeDestination) -> Self {
155 nativeDestination::Node (mut a, ) => {
157 crate::c_types::PublicKey::from_rust(&a),
160 nativeDestination::BlindedRoute (mut a, ) => {
161 Destination::BlindedRoute (
162 crate::lightning::onion_message::blinded_route::BlindedRoute { inner: ObjOps::heap_alloc(a), is_owned: true },
168 /// Frees any resources used by the Destination
170 pub extern "C" fn Destination_free(this_ptr: Destination) { }
172 /// Utility method to constructs a new Node-variant Destination
173 pub extern "C" fn Destination_node(a: crate::c_types::PublicKey) -> Destination {
174 Destination::Node(a, )
177 /// Utility method to constructs a new BlindedRoute-variant Destination
178 pub extern "C" fn Destination_blinded_route(a: crate::lightning::onion_message::blinded_route::BlindedRoute) -> Destination {
179 Destination::BlindedRoute(a, )
181 /// Errors that may occur when [sending an onion message].
183 /// [sending an onion message]: OnionMessenger::send_onion_message
188 /// Errored computing onion message packet keys.
190 crate::c_types::Secp256k1Error),
191 /// Because implementations such as Eclair will drop onion messages where the message packet
192 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
194 /// The provided [`Destination`] was an invalid [`BlindedRoute`], due to having fewer than two
197 /// Our next-hop peer was offline or does not support onion message forwarding.
199 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
202 use lightning::onion_message::messenger::SendError as SendErrorImport;
203 pub(crate) type nativeSendError = SendErrorImport;
207 pub(crate) fn to_native(&self) -> nativeSendError {
209 SendError::Secp256k1 (ref a, ) => {
210 let mut a_nonref = (*a).clone();
211 nativeSendError::Secp256k1 (
212 a_nonref.into_rust(),
215 SendError::TooBigPacket => nativeSendError::TooBigPacket,
216 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
217 SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
218 SendError::BufferFull => nativeSendError::BufferFull,
222 pub(crate) fn into_native(self) -> nativeSendError {
224 SendError::Secp256k1 (mut a, ) => {
225 nativeSendError::Secp256k1 (
229 SendError::TooBigPacket => nativeSendError::TooBigPacket,
230 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
231 SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
232 SendError::BufferFull => nativeSendError::BufferFull,
236 pub(crate) fn from_native(native: &nativeSendError) -> Self {
238 nativeSendError::Secp256k1 (ref a, ) => {
239 let mut a_nonref = (*a).clone();
240 SendError::Secp256k1 (
241 crate::c_types::Secp256k1Error::from_rust(a_nonref),
244 nativeSendError::TooBigPacket => SendError::TooBigPacket,
245 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
246 nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
247 nativeSendError::BufferFull => SendError::BufferFull,
251 pub(crate) fn native_into(native: nativeSendError) -> Self {
253 nativeSendError::Secp256k1 (mut a, ) => {
254 SendError::Secp256k1 (
255 crate::c_types::Secp256k1Error::from_rust(a),
258 nativeSendError::TooBigPacket => SendError::TooBigPacket,
259 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
260 nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
261 nativeSendError::BufferFull => SendError::BufferFull,
265 /// Frees any resources used by the SendError
267 pub extern "C" fn SendError_free(this_ptr: SendError) { }
268 /// Creates a copy of the SendError
270 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
274 /// Utility method to constructs a new Secp256k1-variant SendError
275 pub extern "C" fn SendError_secp256k1(a: crate::c_types::Secp256k1Error) -> SendError {
276 SendError::Secp256k1(a, )
279 /// Utility method to constructs a new TooBigPacket-variant SendError
280 pub extern "C" fn SendError_too_big_packet() -> SendError {
281 SendError::TooBigPacket}
283 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
284 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
285 SendError::TooFewBlindedHops}
287 /// Utility method to constructs a new InvalidFirstHop-variant SendError
288 pub extern "C" fn SendError_invalid_first_hop() -> SendError {
289 SendError::InvalidFirstHop}
291 /// Utility method to constructs a new BufferFull-variant SendError
292 pub extern "C" fn SendError_buffer_full() -> SendError {
293 SendError::BufferFull}
294 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
295 /// their respective handlers.
298 pub extern "C" fn OnionMessenger_new(mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::onion_message::messenger::OnionMessenger {
299 let mut ret = lightning::onion_message::messenger::OnionMessenger::new(keys_manager, logger);
300 crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(ret), is_owned: true }
303 /// Send an empty onion message to `destination`, routing it through `intermediate_nodes`.
304 /// See [`OnionMessenger`] for example usage.
306 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
309 pub extern "C" fn OnionMessenger_send_onion_message(this_arg: &crate::lightning::onion_message::messenger::OnionMessenger, mut intermediate_nodes: crate::c_types::derived::CVec_PublicKeyZ, mut destination: crate::lightning::onion_message::messenger::Destination, mut reply_path: crate::lightning::onion_message::blinded_route::BlindedRoute) -> crate::c_types::derived::CResult_NoneSendErrorZ {
310 let mut local_intermediate_nodes = Vec::new(); for mut item in intermediate_nodes.into_rust().drain(..) { local_intermediate_nodes.push( { item.into_rust() }); };
311 let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
312 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_onion_message(&local_intermediate_nodes[..], destination.into_native(), local_reply_path);
313 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() };
317 impl From<nativeOnionMessenger> for crate::lightning::ln::msgs::OnionMessageHandler {
318 fn from(obj: nativeOnionMessenger) -> Self {
319 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
320 let mut ret = OnionMessenger_as_OnionMessageHandler(&rust_obj);
321 // 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
322 rust_obj.inner = core::ptr::null_mut();
323 ret.free = Some(OnionMessenger_free_void);
327 /// Constructs a new OnionMessageHandler which calls the relevant methods on this_arg.
328 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageHandler must be freed before this_arg is
330 pub extern "C" fn OnionMessenger_as_OnionMessageHandler(this_arg: &OnionMessenger) -> crate::lightning::ln::msgs::OnionMessageHandler {
331 crate::lightning::ln::msgs::OnionMessageHandler {
332 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
334 handle_onion_message: OnionMessenger_OnionMessageHandler_handle_onion_message,
335 peer_connected: OnionMessenger_OnionMessageHandler_peer_connected,
336 peer_disconnected: OnionMessenger_OnionMessageHandler_peer_disconnected,
337 provided_node_features: OnionMessenger_OnionMessageHandler_provided_node_features,
338 provided_init_features: OnionMessenger_OnionMessageHandler_provided_init_features,
339 OnionMessageProvider: crate::lightning::util::events::OnionMessageProvider {
340 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
342 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
347 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) {
348 <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())
350 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) {
351 <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), init.get_native_ref())
353 extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
354 <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), no_connection_possible)
357 extern "C" fn OnionMessenger_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures {
358 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_node_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, );
359 crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
362 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 {
363 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_init_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust());
364 crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
367 impl From<nativeOnionMessenger> for crate::lightning::util::events::OnionMessageProvider {
368 fn from(obj: nativeOnionMessenger) -> Self {
369 let mut rust_obj = OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
370 let mut ret = OnionMessenger_as_OnionMessageProvider(&rust_obj);
371 // 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
372 rust_obj.inner = core::ptr::null_mut();
373 ret.free = Some(OnionMessenger_free_void);
377 /// Constructs a new OnionMessageProvider which calls the relevant methods on this_arg.
378 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageProvider must be freed before this_arg is
380 pub extern "C" fn OnionMessenger_as_OnionMessageProvider(this_arg: &OnionMessenger) -> crate::lightning::util::events::OnionMessageProvider {
381 crate::lightning::util::events::OnionMessageProvider {
382 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
384 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
389 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 {
390 let mut ret = <nativeOnionMessenger as lightning::util::events::OnionMessageProvider<>>::next_onion_message_for_peer(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, peer_node_id.into_rust());
391 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 };