b3a696c586879dd808cb42d465df368ddcdca8e3
[ldk-c-bindings] / lightning-c-bindings / src / lightning / onion_message / messenger.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! LDK sends, receives, and forwards onion messages via the [`OnionMessenger`]. See its docs for
10 //! more information.
11
12 use alloc::str::FromStr;
13 use core::ffi::c_void;
14 use core::convert::Infallible;
15 use bitcoin::hashes::Hash;
16 use crate::c_types::*;
17 #[cfg(feature="no-std")]
18 use alloc::{vec::Vec, boxed::Box};
19
20
21 use lightning::onion_message::messenger::OnionMessenger as nativeOnionMessengerImport;
22 pub(crate) type nativeOnionMessenger = nativeOnionMessengerImport<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::util::logger::Logger>;
23
24 /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
25 /// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending
26 /// and receiving empty onion messages is supported.
27 ///
28 /// # Example
29 ///
30 /// ```
31 /// # extern crate bitcoin;
32 /// # use bitcoin::hashes::_export::_core::time::Duration;
33 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
34 /// # use lightning::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!() }
42 /// # }
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,
51 /// hop_node_id1);
52 /// # let destination_node_id = hop_node_id1;
53 /// #
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);
57 ///
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);
62 ///
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();
67 ///
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);
72 /// ```
73 ///
74 /// [offers]: <https://github.com/lightning/bolts/pull/798>
75 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
76 #[must_use]
77 #[repr(C)]
78 pub struct OnionMessenger {
79         /// A pointer to the opaque Rust object.
80
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.
85
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.
88         pub is_owned: bool,
89 }
90
91 impl Drop for OnionMessenger {
92         fn drop(&mut self) {
93                 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
94                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
95                 }
96         }
97 }
98 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
99 #[no_mangle]
100 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
101 #[allow(unused)]
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); }
105 }
106 #[allow(unused)]
107 impl OnionMessenger {
108         pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
109                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
110         }
111         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
112                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
113         }
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();
119                 ret
120         }
121 }
122 /// The destination of an onion message.
123 #[must_use]
124 #[repr(C)]
125 pub enum Destination {
126         /// We're sending this onion message to a node.
127         Node(
128                 crate::c_types::PublicKey),
129         /// We're sending this onion message to a blinded route.
130         BlindedRoute(
131                 crate::lightning::onion_message::blinded_route::BlindedRoute),
132 }
133 use lightning::onion_message::messenger::Destination as DestinationImport;
134 pub(crate) type nativeDestination = DestinationImport;
135
136 impl Destination {
137         #[allow(unused)]
138         pub(crate) fn into_native(self) -> nativeDestination {
139                 match self {
140                         Destination::Node (mut a, ) => {
141                                 nativeDestination::Node (
142                                         a.into_rust(),
143                                 )
144                         },
145                         Destination::BlindedRoute (mut a, ) => {
146                                 nativeDestination::BlindedRoute (
147                                         *unsafe { Box::from_raw(a.take_inner()) },
148                                 )
149                         },
150                 }
151         }
152         #[allow(unused)]
153         pub(crate) fn native_into(native: nativeDestination) -> Self {
154                 match native {
155                         nativeDestination::Node (mut a, ) => {
156                                 Destination::Node (
157                                         crate::c_types::PublicKey::from_rust(&a),
158                                 )
159                         },
160                         nativeDestination::BlindedRoute (mut a, ) => {
161                                 Destination::BlindedRoute (
162                                         crate::lightning::onion_message::blinded_route::BlindedRoute { inner: ObjOps::heap_alloc(a), is_owned: true },
163                                 )
164                         },
165                 }
166         }
167 }
168 /// Frees any resources used by the Destination
169 #[no_mangle]
170 pub extern "C" fn Destination_free(this_ptr: Destination) { }
171 #[no_mangle]
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, )
175 }
176 #[no_mangle]
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, )
180 }
181 /// Errors that may occur when [sending an onion message].
182 ///
183 /// [sending an onion message]: OnionMessenger::send_onion_message
184 #[derive(Clone)]
185 #[must_use]
186 #[repr(C)]
187 pub enum SendError {
188         /// Errored computing onion message packet keys.
189         Secp256k1(
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.
193         TooBigPacket,
194         /// The provided [`Destination`] was an invalid [`BlindedRoute`], due to having fewer than two
195         /// blinded hops.
196         TooFewBlindedHops,
197         /// Our next-hop peer was offline or does not support onion message forwarding.
198         InvalidFirstHop,
199         /// Our next-hop peer's buffer was full or our total outbound buffer was full.
200         BufferFull,
201 }
202 use lightning::onion_message::messenger::SendError as SendErrorImport;
203 pub(crate) type nativeSendError = SendErrorImport;
204
205 impl SendError {
206         #[allow(unused)]
207         pub(crate) fn to_native(&self) -> nativeSendError {
208                 match self {
209                         SendError::Secp256k1 (ref a, ) => {
210                                 let mut a_nonref = (*a).clone();
211                                 nativeSendError::Secp256k1 (
212                                         a_nonref.into_rust(),
213                                 )
214                         },
215                         SendError::TooBigPacket => nativeSendError::TooBigPacket,
216                         SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
217                         SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
218                         SendError::BufferFull => nativeSendError::BufferFull,
219                 }
220         }
221         #[allow(unused)]
222         pub(crate) fn into_native(self) -> nativeSendError {
223                 match self {
224                         SendError::Secp256k1 (mut a, ) => {
225                                 nativeSendError::Secp256k1 (
226                                         a.into_rust(),
227                                 )
228                         },
229                         SendError::TooBigPacket => nativeSendError::TooBigPacket,
230                         SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
231                         SendError::InvalidFirstHop => nativeSendError::InvalidFirstHop,
232                         SendError::BufferFull => nativeSendError::BufferFull,
233                 }
234         }
235         #[allow(unused)]
236         pub(crate) fn from_native(native: &nativeSendError) -> Self {
237                 match native {
238                         nativeSendError::Secp256k1 (ref a, ) => {
239                                 let mut a_nonref = (*a).clone();
240                                 SendError::Secp256k1 (
241                                         crate::c_types::Secp256k1Error::from_rust(a_nonref),
242                                 )
243                         },
244                         nativeSendError::TooBigPacket => SendError::TooBigPacket,
245                         nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
246                         nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
247                         nativeSendError::BufferFull => SendError::BufferFull,
248                 }
249         }
250         #[allow(unused)]
251         pub(crate) fn native_into(native: nativeSendError) -> Self {
252                 match native {
253                         nativeSendError::Secp256k1 (mut a, ) => {
254                                 SendError::Secp256k1 (
255                                         crate::c_types::Secp256k1Error::from_rust(a),
256                                 )
257                         },
258                         nativeSendError::TooBigPacket => SendError::TooBigPacket,
259                         nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
260                         nativeSendError::InvalidFirstHop => SendError::InvalidFirstHop,
261                         nativeSendError::BufferFull => SendError::BufferFull,
262                 }
263         }
264 }
265 /// Frees any resources used by the SendError
266 #[no_mangle]
267 pub extern "C" fn SendError_free(this_ptr: SendError) { }
268 /// Creates a copy of the SendError
269 #[no_mangle]
270 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
271         orig.clone()
272 }
273 #[no_mangle]
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, )
277 }
278 #[no_mangle]
279 /// Utility method to constructs a new TooBigPacket-variant SendError
280 pub extern "C" fn SendError_too_big_packet() -> SendError {
281         SendError::TooBigPacket}
282 #[no_mangle]
283 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
284 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
285         SendError::TooFewBlindedHops}
286 #[no_mangle]
287 /// Utility method to constructs a new InvalidFirstHop-variant SendError
288 pub extern "C" fn SendError_invalid_first_hop() -> SendError {
289         SendError::InvalidFirstHop}
290 #[no_mangle]
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.
296 #[must_use]
297 #[no_mangle]
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 }
301 }
302
303 /// Send an empty onion message to `destination`, routing it through `intermediate_nodes`.
304 /// See [`OnionMessenger`] for example usage.
305 ///
306 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
307 #[must_use]
308 #[no_mangle]
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() };
314         local_ret
315 }
316
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);
324                 ret
325         }
326 }
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
329 #[no_mangle]
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 },
333                 free: None,
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 },
341                         free: None,
342                         next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
343                 },
344         }
345 }
346
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())
349 }
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())
352 }
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)
355 }
356 #[must_use]
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 }
360 }
361 #[must_use]
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 }
365 }
366
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);
374                 ret
375         }
376 }
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
379 #[no_mangle]
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 },
383                 free: None,
384                 next_onion_message_for_peer: OnionMessenger_OnionMessageProvider_next_onion_message_for_peer,
385         }
386 }
387
388 #[must_use]
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 };
392         local_ret
393 }
394