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 this [`OnionMessenger`], which lives here,
10 //! as well as various types, traits, and utilities that it uses.
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 [`OnionMessage`]s.
27 /// # Handling Messages
29 /// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
30 /// messages to peers or delegating to the appropriate handler for the message type. Currently, the
31 /// available handlers are:
32 /// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
33 /// * [`CustomOnionMessageHandler`], for handling user-defined message types
35 /// # Sending Messages
37 /// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
38 /// a message, the matched handler may return a response message which `OnionMessenger` will send
44 /// # extern crate bitcoin;
45 /// # use bitcoin::hashes::_export::_core::time::Duration;
46 /// # use bitcoin::hashes::hex::FromHex;
47 /// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
48 /// # use lightning::blinded_path::BlindedPath;
49 /// # use lightning::sign::{EntropySource, KeysManager};
50 /// # use lightning::ln::peer_handler::IgnoringMessageHandler;
51 /// # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
52 /// # use lightning::onion_message::packet::OnionMessageContents;
53 /// # use lightning::util::logger::{Logger, Record};
54 /// # use lightning::util::ser::{Writeable, Writer};
55 /// # use lightning::io;
56 /// # use std::sync::Arc;
57 /// # struct FakeLogger;
58 /// # impl Logger for FakeLogger {
59 /// # fn log(&self, record: Record) { println!(\"{:?}\" , record); }
61 /// # struct FakeMessageRouter {}
62 /// # impl MessageRouter for FakeMessageRouter {
63 /// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
64 /// # let secp_ctx = Secp256k1::new();
65 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
66 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
67 /// # let hop_node_id2 = hop_node_id1;
68 /// # Ok(OnionMessagePath {
69 /// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
71 /// # first_node_addresses: None,
74 /// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
75 /// # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
76 /// # ) -> Result<Vec<BlindedPath>, ()> {
80 /// # let seed = [42u8; 32];
81 /// # let time = Duration::from_secs(123456);
82 /// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
83 /// # let logger = Arc::new(FakeLogger {});
84 /// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
85 /// # let secp_ctx = Secp256k1::new();
86 /// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
87 /// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
88 /// # let destination_node_id = hop_node_id1;
89 /// # let message_router = Arc::new(FakeMessageRouter {});
90 /// # let custom_message_handler = IgnoringMessageHandler {};
91 /// # let offers_message_handler = IgnoringMessageHandler {};
92 /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
93 /// // ChannelManager.
94 /// let onion_messenger = OnionMessenger::new(
95 /// &keys_manager, &keys_manager, logger, message_router, &offers_message_handler,
96 /// &custom_message_handler
99 /// # #[derive(Debug, Clone)]
100 /// # struct YourCustomMessage {}
101 /// impl Writeable for YourCustomMessage {
102 /// \tfn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
104 /// \t\t// Write your custom onion message to `w`
107 /// impl OnionMessageContents for YourCustomMessage {
108 /// \tfn tlv_type(&self) -> u64 {
109 /// \t\t# let your_custom_message_type = 42;
110 /// \t\tyour_custom_message_type
113 /// // Send a custom onion message to a node id.
114 /// let destination = Destination::Node(destination_node_id);
115 /// let reply_path = None;
116 /// # let message = YourCustomMessage {};
117 /// onion_messenger.send_onion_message(message, destination, reply_path);
119 /// // Create a blinded path to yourself, for someone to send an onion message to.
120 /// # let your_node_id = hop_node_id1;
121 /// let hops = [hop_node_id3, hop_node_id4, your_node_id];
122 /// let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
124 /// // Send a custom onion message to a blinded path.
125 /// let destination = Destination::BlindedPath(blinded_path);
126 /// let reply_path = None;
127 /// # let message = YourCustomMessage {};
128 /// onion_messenger.send_onion_message(message, destination, reply_path);
131 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
132 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
135 pub struct OnionMessenger {
136 /// A pointer to the opaque Rust object.
138 /// Nearly everywhere, inner must be non-null, however in places where
139 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
140 pub inner: *mut nativeOnionMessenger,
141 /// Indicates that this is the only struct which contains the same pointer.
143 /// Rust functions which take ownership of an object provided via an argument require
144 /// this to be true and invalidate the object pointed to by inner.
148 impl Drop for OnionMessenger {
150 if self.is_owned && !<*mut nativeOnionMessenger>::is_null(self.inner) {
151 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
155 /// Frees any resources used by the OnionMessenger, if is_owned is set and inner is non-NULL.
157 pub extern "C" fn OnionMessenger_free(this_obj: OnionMessenger) { }
159 /// Used only if an object of this type is returned as a trait impl by a method
160 pub(crate) extern "C" fn OnionMessenger_free_void(this_ptr: *mut c_void) {
161 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessenger) };
164 impl OnionMessenger {
165 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessenger {
166 unsafe { &*ObjOps::untweak_ptr(self.inner) }
168 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessenger {
169 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
171 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
172 pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessenger {
173 assert!(self.is_owned);
174 let ret = ObjOps::untweak_ptr(self.inner);
175 self.inner = core::ptr::null_mut();
179 /// A trait defining behavior for routing an [`OnionMessage`].
181 pub struct MessageRouter {
182 /// An opaque pointer which is passed to your function implementations as an argument.
183 /// This has no meaning in the LDK, and can be NULL or any other value.
184 pub this_arg: *mut c_void,
185 /// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
186 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,
187 /// Creates [`BlindedPath`]s to the `recipient` node. The nodes in `peers` are assumed to be
188 /// direct peers with the `recipient`.
189 pub create_blinded_paths: extern "C" fn (this_arg: *const c_void, recipient: crate::c_types::PublicKey, peers: crate::c_types::derived::CVec_PublicKeyZ) -> crate::c_types::derived::CResult_CVec_BlindedPathZNoneZ,
190 /// Frees any resources associated with this object given its this_arg pointer.
191 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
192 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
194 unsafe impl Send for MessageRouter {}
195 unsafe impl Sync for MessageRouter {}
197 pub(crate) fn MessageRouter_clone_fields(orig: &MessageRouter) -> MessageRouter {
199 this_arg: orig.this_arg,
200 find_path: Clone::clone(&orig.find_path),
201 create_blinded_paths: Clone::clone(&orig.create_blinded_paths),
202 free: Clone::clone(&orig.free),
206 use lightning::onion_message::messenger::MessageRouter as rustMessageRouter;
207 impl rustMessageRouter for MessageRouter {
208 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, ()> {
209 let mut local_peers = Vec::new(); for mut item in peers.drain(..) { local_peers.push( { crate::c_types::PublicKey::from_rust(&item) }); };
210 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));
211 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)) })*/ })};
214 fn create_blinded_paths<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, mut recipient: bitcoin::secp256k1::PublicKey, mut peers: Vec<bitcoin::secp256k1::PublicKey>, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> Result<Vec<lightning::blinded_path::BlindedPath>, ()> {
215 let mut local_peers = Vec::new(); for mut item in peers.drain(..) { local_peers.push( { crate::c_types::PublicKey::from_rust(&item) }); };
216 let mut ret = (self.create_blinded_paths)(self.this_arg, crate::c_types::PublicKey::from_rust(&recipient), local_peers.into());
217 let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = Vec::new(); for mut item in (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust().drain(..) { local_ret_0.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
222 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
223 // directly as a Deref trait in higher-level structs:
224 impl core::ops::Deref for MessageRouter {
226 fn deref(&self) -> &Self {
230 impl core::ops::DerefMut for MessageRouter {
231 fn deref_mut(&mut self) -> &mut Self {
235 /// Calls the free function if one is set
237 pub extern "C" fn MessageRouter_free(this_ptr: MessageRouter) { }
238 impl Drop for MessageRouter {
240 if let Some(f) = self.free {
246 use lightning::onion_message::messenger::DefaultMessageRouter as nativeDefaultMessageRouterImport;
247 pub(crate) type nativeDefaultMessageRouter = nativeDefaultMessageRouterImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger, crate::lightning::sign::EntropySource>;
249 /// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
252 pub struct DefaultMessageRouter {
253 /// A pointer to the opaque Rust object.
255 /// Nearly everywhere, inner must be non-null, however in places where
256 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
257 pub inner: *mut nativeDefaultMessageRouter,
258 /// Indicates that this is the only struct which contains the same pointer.
260 /// Rust functions which take ownership of an object provided via an argument require
261 /// this to be true and invalidate the object pointed to by inner.
265 impl Drop for DefaultMessageRouter {
267 if self.is_owned && !<*mut nativeDefaultMessageRouter>::is_null(self.inner) {
268 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
272 /// Frees any resources used by the DefaultMessageRouter, if is_owned is set and inner is non-NULL.
274 pub extern "C" fn DefaultMessageRouter_free(this_obj: DefaultMessageRouter) { }
276 /// Used only if an object of this type is returned as a trait impl by a method
277 pub(crate) extern "C" fn DefaultMessageRouter_free_void(this_ptr: *mut c_void) {
278 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeDefaultMessageRouter) };
281 impl DefaultMessageRouter {
282 pub(crate) fn get_native_ref(&self) -> &'static nativeDefaultMessageRouter {
283 unsafe { &*ObjOps::untweak_ptr(self.inner) }
285 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDefaultMessageRouter {
286 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
288 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
289 pub(crate) fn take_inner(mut self) -> *mut nativeDefaultMessageRouter {
290 assert!(self.is_owned);
291 let ret = ObjOps::untweak_ptr(self.inner);
292 self.inner = core::ptr::null_mut();
296 /// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
299 pub extern "C" fn DefaultMessageRouter_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut entropy_source: crate::lightning::sign::EntropySource) -> crate::lightning::onion_message::messenger::DefaultMessageRouter {
300 let mut ret = lightning::onion_message::messenger::DefaultMessageRouter::new(network_graph.get_native_ref(), entropy_source);
301 crate::lightning::onion_message::messenger::DefaultMessageRouter { inner: ObjOps::heap_alloc(ret), is_owned: true }
304 impl From<nativeDefaultMessageRouter> for crate::lightning::onion_message::messenger::MessageRouter {
305 fn from(obj: nativeDefaultMessageRouter) -> Self {
306 let rust_obj = crate::lightning::onion_message::messenger::DefaultMessageRouter { inner: ObjOps::heap_alloc(obj), is_owned: true };
307 let mut ret = DefaultMessageRouter_as_MessageRouter(&rust_obj);
308 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
309 core::mem::forget(rust_obj);
310 ret.free = Some(DefaultMessageRouter_free_void);
314 /// Constructs a new MessageRouter which calls the relevant methods on this_arg.
315 /// This copies the `inner` pointer in this_arg and thus the returned MessageRouter must be freed before this_arg is
317 pub extern "C" fn DefaultMessageRouter_as_MessageRouter(this_arg: &DefaultMessageRouter) -> crate::lightning::onion_message::messenger::MessageRouter {
318 crate::lightning::onion_message::messenger::MessageRouter {
319 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
321 find_path: DefaultMessageRouter_MessageRouter_find_path,
322 create_blinded_paths: DefaultMessageRouter_MessageRouter_create_blinded_paths,
327 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 {
328 let mut local_peers = Vec::new(); for mut item in peers.into_rust().drain(..) { local_peers.push( { item.into_rust() }); };
329 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());
330 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() };
334 extern "C" fn DefaultMessageRouter_MessageRouter_create_blinded_paths(this_arg: *const c_void, mut recipient: crate::c_types::PublicKey, mut peers: crate::c_types::derived::CVec_PublicKeyZ) -> crate::c_types::derived::CResult_CVec_BlindedPathZNoneZ {
335 let mut local_peers = Vec::new(); for mut item in peers.into_rust().drain(..) { local_peers.push( { item.into_rust() }); };
336 let mut ret = <nativeDefaultMessageRouter as lightning::onion_message::messenger::MessageRouter<>>::create_blinded_paths(unsafe { &mut *(this_arg as *mut nativeDefaultMessageRouter) }, recipient.into_rust(), local_peers, secp256k1::global::SECP256K1);
337 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
342 use lightning::onion_message::messenger::OnionMessagePath as nativeOnionMessagePathImport;
343 pub(crate) type nativeOnionMessagePath = nativeOnionMessagePathImport;
345 /// A path for sending an [`OnionMessage`].
348 pub struct OnionMessagePath {
349 /// A pointer to the opaque Rust object.
351 /// Nearly everywhere, inner must be non-null, however in places where
352 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
353 pub inner: *mut nativeOnionMessagePath,
354 /// Indicates that this is the only struct which contains the same pointer.
356 /// Rust functions which take ownership of an object provided via an argument require
357 /// this to be true and invalidate the object pointed to by inner.
361 impl Drop for OnionMessagePath {
363 if self.is_owned && !<*mut nativeOnionMessagePath>::is_null(self.inner) {
364 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
368 /// Frees any resources used by the OnionMessagePath, if is_owned is set and inner is non-NULL.
370 pub extern "C" fn OnionMessagePath_free(this_obj: OnionMessagePath) { }
372 /// Used only if an object of this type is returned as a trait impl by a method
373 pub(crate) extern "C" fn OnionMessagePath_free_void(this_ptr: *mut c_void) {
374 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOnionMessagePath) };
377 impl OnionMessagePath {
378 pub(crate) fn get_native_ref(&self) -> &'static nativeOnionMessagePath {
379 unsafe { &*ObjOps::untweak_ptr(self.inner) }
381 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOnionMessagePath {
382 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
384 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
385 pub(crate) fn take_inner(mut self) -> *mut nativeOnionMessagePath {
386 assert!(self.is_owned);
387 let ret = ObjOps::untweak_ptr(self.inner);
388 self.inner = core::ptr::null_mut();
392 /// Nodes on the path between the sender and the destination.
394 /// Returns a copy of the field.
396 pub extern "C" fn OnionMessagePath_get_intermediate_nodes(this_ptr: &OnionMessagePath) -> crate::c_types::derived::CVec_PublicKeyZ {
397 let mut inner_val = this_ptr.get_native_mut_ref().intermediate_nodes.clone();
398 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) }); };
399 local_inner_val.into()
401 /// Nodes on the path between the sender and the destination.
403 pub extern "C" fn OnionMessagePath_set_intermediate_nodes(this_ptr: &mut OnionMessagePath, mut val: crate::c_types::derived::CVec_PublicKeyZ) {
404 let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
405 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.intermediate_nodes = local_val;
407 /// The recipient of the message.
409 pub extern "C" fn OnionMessagePath_get_destination(this_ptr: &OnionMessagePath) -> crate::lightning::onion_message::messenger::Destination {
410 let mut inner_val = &mut this_ptr.get_native_mut_ref().destination;
411 crate::lightning::onion_message::messenger::Destination::from_native(inner_val)
413 /// The recipient of the message.
415 pub extern "C" fn OnionMessagePath_set_destination(this_ptr: &mut OnionMessagePath, mut val: crate::lightning::onion_message::messenger::Destination) {
416 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.destination = val.into_native();
418 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
420 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
421 /// this to initiate such a connection.
423 /// Returns a copy of the field.
425 pub extern "C" fn OnionMessagePath_get_first_node_addresses(this_ptr: &OnionMessagePath) -> crate::c_types::derived::COption_CVec_SocketAddressZZ {
426 let mut inner_val = this_ptr.get_native_mut_ref().first_node_addresses.clone();
427 let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_CVec_SocketAddressZZ::None } else { crate::c_types::derived::COption_CVec_SocketAddressZZ::Some( { let mut local_inner_val_0 = Vec::new(); for mut item in inner_val.unwrap().drain(..) { local_inner_val_0.push( { crate::lightning::ln::msgs::SocketAddress::native_into(item) }); }; local_inner_val_0.into() }) };
430 /// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
432 /// Only needs to be set if a connection to the node is required. [`OnionMessenger`] may use
433 /// this to initiate such a connection.
435 pub extern "C" fn OnionMessagePath_set_first_node_addresses(this_ptr: &mut OnionMessagePath, mut val: crate::c_types::derived::COption_CVec_SocketAddressZZ) {
436 let mut local_val = { /*val*/ let val_opt = val; if val_opt.is_none() { None } else { Some({ { let mut local_val_0 = Vec::new(); for mut item in { val_opt.take() }.into_rust().drain(..) { local_val_0.push( { item.into_native() }); }; local_val_0 }})} };
437 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_node_addresses = local_val;
439 /// Constructs a new OnionMessagePath given each field
442 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, mut first_node_addresses_arg: crate::c_types::derived::COption_CVec_SocketAddressZZ) -> OnionMessagePath {
443 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() }); };
444 let mut local_first_node_addresses_arg = { /*first_node_addresses_arg*/ let first_node_addresses_arg_opt = first_node_addresses_arg; if first_node_addresses_arg_opt.is_none() { None } else { Some({ { let mut local_first_node_addresses_arg_0 = Vec::new(); for mut item in { first_node_addresses_arg_opt.take() }.into_rust().drain(..) { local_first_node_addresses_arg_0.push( { item.into_native() }); }; local_first_node_addresses_arg_0 }})} };
445 OnionMessagePath { inner: ObjOps::heap_alloc(nativeOnionMessagePath {
446 intermediate_nodes: local_intermediate_nodes_arg,
447 destination: destination_arg.into_native(),
448 first_node_addresses: local_first_node_addresses_arg,
451 impl Clone for OnionMessagePath {
452 fn clone(&self) -> Self {
454 inner: if <*mut nativeOnionMessagePath>::is_null(self.inner) { core::ptr::null_mut() } else {
455 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
461 /// Used only if an object of this type is returned as a trait impl by a method
462 pub(crate) extern "C" fn OnionMessagePath_clone_void(this_ptr: *const c_void) -> *mut c_void {
463 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeOnionMessagePath)).clone() })) as *mut c_void
466 /// Creates a copy of the OnionMessagePath
467 pub extern "C" fn OnionMessagePath_clone(orig: &OnionMessagePath) -> OnionMessagePath {
470 /// Returns the first node in the path.
473 pub extern "C" fn OnionMessagePath_first_node(this_arg: &crate::lightning::onion_message::messenger::OnionMessagePath) -> crate::c_types::PublicKey {
474 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.first_node();
475 crate::c_types::PublicKey::from_rust(&ret)
478 /// The destination of an onion message.
482 pub enum Destination {
483 /// We're sending this onion message to a node.
485 crate::c_types::PublicKey),
486 /// We're sending this onion message to a blinded path.
488 crate::lightning::blinded_path::BlindedPath),
490 use lightning::onion_message::messenger::Destination as DestinationImport;
491 pub(crate) type nativeDestination = DestinationImport;
495 pub(crate) fn to_native(&self) -> nativeDestination {
497 Destination::Node (ref a, ) => {
498 let mut a_nonref = Clone::clone(a);
499 nativeDestination::Node (
500 a_nonref.into_rust(),
503 Destination::BlindedPath (ref a, ) => {
504 let mut a_nonref = Clone::clone(a);
505 nativeDestination::BlindedPath (
506 *unsafe { Box::from_raw(a_nonref.take_inner()) },
512 pub(crate) fn into_native(self) -> nativeDestination {
514 Destination::Node (mut a, ) => {
515 nativeDestination::Node (
519 Destination::BlindedPath (mut a, ) => {
520 nativeDestination::BlindedPath (
521 *unsafe { Box::from_raw(a.take_inner()) },
527 pub(crate) fn from_native(native: &DestinationImport) -> Self {
528 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeDestination) };
530 nativeDestination::Node (ref a, ) => {
531 let mut a_nonref = Clone::clone(a);
533 crate::c_types::PublicKey::from_rust(&a_nonref),
536 nativeDestination::BlindedPath (ref a, ) => {
537 let mut a_nonref = Clone::clone(a);
538 Destination::BlindedPath (
539 crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
545 pub(crate) fn native_into(native: nativeDestination) -> Self {
547 nativeDestination::Node (mut a, ) => {
549 crate::c_types::PublicKey::from_rust(&a),
552 nativeDestination::BlindedPath (mut a, ) => {
553 Destination::BlindedPath (
554 crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(a), is_owned: true },
560 /// Frees any resources used by the Destination
562 pub extern "C" fn Destination_free(this_ptr: Destination) { }
563 /// Creates a copy of the Destination
565 pub extern "C" fn Destination_clone(orig: &Destination) -> Destination {
569 /// Used only if an object of this type is returned as a trait impl by a method
570 pub(crate) extern "C" fn Destination_clone_void(this_ptr: *const c_void) -> *mut c_void {
571 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Destination)).clone() })) as *mut c_void
574 /// Used only if an object of this type is returned as a trait impl by a method
575 pub(crate) extern "C" fn Destination_free_void(this_ptr: *mut c_void) {
576 let _ = unsafe { Box::from_raw(this_ptr as *mut Destination) };
579 /// Utility method to constructs a new Node-variant Destination
580 pub extern "C" fn Destination_node(a: crate::c_types::PublicKey) -> Destination {
581 Destination::Node(a, )
584 /// Utility method to constructs a new BlindedPath-variant Destination
585 pub extern "C" fn Destination_blinded_path(a: crate::lightning::blinded_path::BlindedPath) -> Destination {
586 Destination::BlindedPath(a, )
588 /// Result of successfully [sending an onion message].
590 /// [sending an onion message]: OnionMessenger::send_onion_message
594 pub enum SendSuccess {
595 /// The message was buffered and will be sent once it is processed by
596 /// [`OnionMessageHandler::next_onion_message_for_peer`].
598 /// The message was buffered and will be sent once the node is connected as a peer and it is
599 /// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
600 BufferedAwaitingConnection(
601 crate::c_types::PublicKey),
603 use lightning::onion_message::messenger::SendSuccess as SendSuccessImport;
604 pub(crate) type nativeSendSuccess = SendSuccessImport;
608 pub(crate) fn to_native(&self) -> nativeSendSuccess {
610 SendSuccess::Buffered => nativeSendSuccess::Buffered,
611 SendSuccess::BufferedAwaitingConnection (ref a, ) => {
612 let mut a_nonref = Clone::clone(a);
613 nativeSendSuccess::BufferedAwaitingConnection (
614 a_nonref.into_rust(),
620 pub(crate) fn into_native(self) -> nativeSendSuccess {
622 SendSuccess::Buffered => nativeSendSuccess::Buffered,
623 SendSuccess::BufferedAwaitingConnection (mut a, ) => {
624 nativeSendSuccess::BufferedAwaitingConnection (
631 pub(crate) fn from_native(native: &SendSuccessImport) -> Self {
632 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeSendSuccess) };
634 nativeSendSuccess::Buffered => SendSuccess::Buffered,
635 nativeSendSuccess::BufferedAwaitingConnection (ref a, ) => {
636 let mut a_nonref = Clone::clone(a);
637 SendSuccess::BufferedAwaitingConnection (
638 crate::c_types::PublicKey::from_rust(&a_nonref),
644 pub(crate) fn native_into(native: nativeSendSuccess) -> Self {
646 nativeSendSuccess::Buffered => SendSuccess::Buffered,
647 nativeSendSuccess::BufferedAwaitingConnection (mut a, ) => {
648 SendSuccess::BufferedAwaitingConnection (
649 crate::c_types::PublicKey::from_rust(&a),
655 /// Frees any resources used by the SendSuccess
657 pub extern "C" fn SendSuccess_free(this_ptr: SendSuccess) { }
658 /// Creates a copy of the SendSuccess
660 pub extern "C" fn SendSuccess_clone(orig: &SendSuccess) -> SendSuccess {
664 /// Used only if an object of this type is returned as a trait impl by a method
665 pub(crate) extern "C" fn SendSuccess_clone_void(this_ptr: *const c_void) -> *mut c_void {
666 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const SendSuccess)).clone() })) as *mut c_void
669 /// Used only if an object of this type is returned as a trait impl by a method
670 pub(crate) extern "C" fn SendSuccess_free_void(this_ptr: *mut c_void) {
671 let _ = unsafe { Box::from_raw(this_ptr as *mut SendSuccess) };
674 /// Utility method to constructs a new Buffered-variant SendSuccess
675 pub extern "C" fn SendSuccess_buffered() -> SendSuccess {
676 SendSuccess::Buffered}
678 /// Utility method to constructs a new BufferedAwaitingConnection-variant SendSuccess
679 pub extern "C" fn SendSuccess_buffered_awaiting_connection(a: crate::c_types::PublicKey) -> SendSuccess {
680 SendSuccess::BufferedAwaitingConnection(a, )
682 /// Get a string which allows debug introspection of a SendSuccess object
683 pub extern "C" fn SendSuccess_debug_str_void(o: *const c_void) -> Str {
684 alloc::format!("{:?}", unsafe { o as *const crate::lightning::onion_message::messenger::SendSuccess }).into()}
685 /// Checks if two SendSuccesss contain equal inner contents.
686 /// This ignores pointers and is_owned flags and looks at the values in fields.
688 pub extern "C" fn SendSuccess_eq(a: &SendSuccess, b: &SendSuccess) -> bool {
689 if &a.to_native() == &b.to_native() { true } else { false }
691 /// Errors that may occur when [sending an onion message].
693 /// [sending an onion message]: OnionMessenger::send_onion_message
698 /// Errored computing onion message packet keys.
700 crate::c_types::Secp256k1Error),
701 /// Because implementations such as Eclair will drop onion messages where the message packet
702 /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
704 /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
707 /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
709 crate::c_types::PublicKey),
710 /// A path from the sender to the destination could not be found by the [`MessageRouter`].
712 /// Onion message contents must have a TLV type >= 64.
714 /// Our next-hop peer's buffer was full or our total outbound buffer was full.
716 /// Failed to retrieve our node id from the provided [`NodeSigner`].
718 /// [`NodeSigner`]: crate::sign::NodeSigner
720 /// We attempted to send to a blinded path where we are the introduction node, and failed to
721 /// advance the blinded path to make the second hop the new introduction node. Either
722 /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
723 /// new blinding point, or we were attempting to send to ourselves.
724 BlindedPathAdvanceFailed,
726 use lightning::onion_message::messenger::SendError as SendErrorImport;
727 pub(crate) type nativeSendError = SendErrorImport;
731 pub(crate) fn to_native(&self) -> nativeSendError {
733 SendError::Secp256k1 (ref a, ) => {
734 let mut a_nonref = Clone::clone(a);
735 nativeSendError::Secp256k1 (
736 a_nonref.into_rust(),
739 SendError::TooBigPacket => nativeSendError::TooBigPacket,
740 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
741 SendError::InvalidFirstHop (ref a, ) => {
742 let mut a_nonref = Clone::clone(a);
743 nativeSendError::InvalidFirstHop (
744 a_nonref.into_rust(),
747 SendError::PathNotFound => nativeSendError::PathNotFound,
748 SendError::InvalidMessage => nativeSendError::InvalidMessage,
749 SendError::BufferFull => nativeSendError::BufferFull,
750 SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
751 SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
755 pub(crate) fn into_native(self) -> nativeSendError {
757 SendError::Secp256k1 (mut a, ) => {
758 nativeSendError::Secp256k1 (
762 SendError::TooBigPacket => nativeSendError::TooBigPacket,
763 SendError::TooFewBlindedHops => nativeSendError::TooFewBlindedHops,
764 SendError::InvalidFirstHop (mut a, ) => {
765 nativeSendError::InvalidFirstHop (
769 SendError::PathNotFound => nativeSendError::PathNotFound,
770 SendError::InvalidMessage => nativeSendError::InvalidMessage,
771 SendError::BufferFull => nativeSendError::BufferFull,
772 SendError::GetNodeIdFailed => nativeSendError::GetNodeIdFailed,
773 SendError::BlindedPathAdvanceFailed => nativeSendError::BlindedPathAdvanceFailed,
777 pub(crate) fn from_native(native: &SendErrorImport) -> Self {
778 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeSendError) };
780 nativeSendError::Secp256k1 (ref a, ) => {
781 let mut a_nonref = Clone::clone(a);
782 SendError::Secp256k1 (
783 crate::c_types::Secp256k1Error::from_rust(a_nonref),
786 nativeSendError::TooBigPacket => SendError::TooBigPacket,
787 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
788 nativeSendError::InvalidFirstHop (ref a, ) => {
789 let mut a_nonref = Clone::clone(a);
790 SendError::InvalidFirstHop (
791 crate::c_types::PublicKey::from_rust(&a_nonref),
794 nativeSendError::PathNotFound => SendError::PathNotFound,
795 nativeSendError::InvalidMessage => SendError::InvalidMessage,
796 nativeSendError::BufferFull => SendError::BufferFull,
797 nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
798 nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
802 pub(crate) fn native_into(native: nativeSendError) -> Self {
804 nativeSendError::Secp256k1 (mut a, ) => {
805 SendError::Secp256k1 (
806 crate::c_types::Secp256k1Error::from_rust(a),
809 nativeSendError::TooBigPacket => SendError::TooBigPacket,
810 nativeSendError::TooFewBlindedHops => SendError::TooFewBlindedHops,
811 nativeSendError::InvalidFirstHop (mut a, ) => {
812 SendError::InvalidFirstHop (
813 crate::c_types::PublicKey::from_rust(&a),
816 nativeSendError::PathNotFound => SendError::PathNotFound,
817 nativeSendError::InvalidMessage => SendError::InvalidMessage,
818 nativeSendError::BufferFull => SendError::BufferFull,
819 nativeSendError::GetNodeIdFailed => SendError::GetNodeIdFailed,
820 nativeSendError::BlindedPathAdvanceFailed => SendError::BlindedPathAdvanceFailed,
824 /// Frees any resources used by the SendError
826 pub extern "C" fn SendError_free(this_ptr: SendError) { }
827 /// Creates a copy of the SendError
829 pub extern "C" fn SendError_clone(orig: &SendError) -> SendError {
833 /// Used only if an object of this type is returned as a trait impl by a method
834 pub(crate) extern "C" fn SendError_clone_void(this_ptr: *const c_void) -> *mut c_void {
835 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const SendError)).clone() })) as *mut c_void
838 /// Used only if an object of this type is returned as a trait impl by a method
839 pub(crate) extern "C" fn SendError_free_void(this_ptr: *mut c_void) {
840 let _ = unsafe { Box::from_raw(this_ptr as *mut SendError) };
843 /// Utility method to constructs a new Secp256k1-variant SendError
844 pub extern "C" fn SendError_secp256k1(a: crate::c_types::Secp256k1Error) -> SendError {
845 SendError::Secp256k1(a, )
848 /// Utility method to constructs a new TooBigPacket-variant SendError
849 pub extern "C" fn SendError_too_big_packet() -> SendError {
850 SendError::TooBigPacket}
852 /// Utility method to constructs a new TooFewBlindedHops-variant SendError
853 pub extern "C" fn SendError_too_few_blinded_hops() -> SendError {
854 SendError::TooFewBlindedHops}
856 /// Utility method to constructs a new InvalidFirstHop-variant SendError
857 pub extern "C" fn SendError_invalid_first_hop(a: crate::c_types::PublicKey) -> SendError {
858 SendError::InvalidFirstHop(a, )
861 /// Utility method to constructs a new PathNotFound-variant SendError
862 pub extern "C" fn SendError_path_not_found() -> SendError {
863 SendError::PathNotFound}
865 /// Utility method to constructs a new InvalidMessage-variant SendError
866 pub extern "C" fn SendError_invalid_message() -> SendError {
867 SendError::InvalidMessage}
869 /// Utility method to constructs a new BufferFull-variant SendError
870 pub extern "C" fn SendError_buffer_full() -> SendError {
871 SendError::BufferFull}
873 /// Utility method to constructs a new GetNodeIdFailed-variant SendError
874 pub extern "C" fn SendError_get_node_id_failed() -> SendError {
875 SendError::GetNodeIdFailed}
877 /// Utility method to constructs a new BlindedPathAdvanceFailed-variant SendError
878 pub extern "C" fn SendError_blinded_path_advance_failed() -> SendError {
879 SendError::BlindedPathAdvanceFailed}
880 /// Get a string which allows debug introspection of a SendError object
881 pub extern "C" fn SendError_debug_str_void(o: *const c_void) -> Str {
882 alloc::format!("{:?}", unsafe { o as *const crate::lightning::onion_message::messenger::SendError }).into()}
883 /// Checks if two SendErrors contain equal inner contents.
884 /// This ignores pointers and is_owned flags and looks at the values in fields.
886 pub extern "C" fn SendError_eq(a: &SendError, b: &SendError) -> bool {
887 if &a.to_native() == &b.to_native() { true } else { false }
889 /// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
890 /// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
891 /// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
892 /// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
895 /// See [`OnionMessenger`] for example usage.
897 /// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
898 /// [`CustomMessage`]: Self::CustomMessage
900 pub struct CustomOnionMessageHandler {
901 /// An opaque pointer which is passed to your function implementations as an argument.
902 /// This has no meaning in the LDK, and can be NULL or any other value.
903 pub this_arg: *mut c_void,
904 /// Called with the custom message that was received, returning a response to send, if any.
906 /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
907 pub handle_custom_message: extern "C" fn (this_arg: *const c_void, msg: crate::lightning::onion_message::packet::OnionMessageContents) -> crate::c_types::derived::COption_OnionMessageContentsZ,
908 /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
909 /// message type is unknown.
910 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_OnionMessageContentsZDecodeErrorZ,
911 /// Releases any [`Self::CustomMessage`]s that need to be sent.
913 /// Typically, this is used for messages initiating a message flow rather than in response to
914 /// another message. The latter should use the return value of [`Self::handle_custom_message`].
915 pub release_pending_custom_messages: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OnionMessageContentsDestinationBlindedPathZZ,
916 /// Frees any resources associated with this object given its this_arg pointer.
917 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
918 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
920 unsafe impl Send for CustomOnionMessageHandler {}
921 unsafe impl Sync for CustomOnionMessageHandler {}
923 pub(crate) fn CustomOnionMessageHandler_clone_fields(orig: &CustomOnionMessageHandler) -> CustomOnionMessageHandler {
924 CustomOnionMessageHandler {
925 this_arg: orig.this_arg,
926 handle_custom_message: Clone::clone(&orig.handle_custom_message),
927 read_custom_message: Clone::clone(&orig.read_custom_message),
928 release_pending_custom_messages: Clone::clone(&orig.release_pending_custom_messages),
929 free: Clone::clone(&orig.free),
933 use lightning::onion_message::messenger::CustomOnionMessageHandler as rustCustomOnionMessageHandler;
934 impl rustCustomOnionMessageHandler for CustomOnionMessageHandler {
935 type CustomMessage = crate::lightning::onion_message::packet::OnionMessageContents;
936 fn handle_custom_message(&self, mut msg: crate::lightning::onion_message::packet::OnionMessageContents) -> Option<crate::lightning::onion_message::packet::OnionMessageContents> {
937 let mut ret = (self.handle_custom_message)(self.this_arg, Into::into(msg));
938 let mut local_ret = { /*ret*/ let ret_opt = ret; if ret_opt.is_none() { None } else { Some({ { { ret_opt.take() } }})} };
941 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::OnionMessageContents>, lightning::ln::msgs::DecodeError> {
942 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)));
943 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() })};
946 fn release_pending_custom_messages(&self) -> Vec<(crate::lightning::onion_message::packet::OnionMessageContents, lightning::onion_message::messenger::Destination, Option<lightning::blinded_path::BlindedPath>)> {
947 let mut ret = (self.release_pending_custom_messages)(self.this_arg);
948 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_2 = if orig_ret_0_2.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_2.take_inner()) } }) }; let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_native(), local_orig_ret_0_2); local_ret_0 }); };
953 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
954 // directly as a Deref trait in higher-level structs:
955 impl core::ops::Deref for CustomOnionMessageHandler {
957 fn deref(&self) -> &Self {
961 impl core::ops::DerefMut for CustomOnionMessageHandler {
962 fn deref_mut(&mut self) -> &mut Self {
966 /// Calls the free function if one is set
968 pub extern "C" fn CustomOnionMessageHandler_free(this_ptr: CustomOnionMessageHandler) { }
969 impl Drop for CustomOnionMessageHandler {
971 if let Some(f) = self.free {
976 /// A processed incoming onion message, containing either a Forward (another onion message)
977 /// or a Receive payload with decrypted contents.
981 pub enum PeeledOnion {
982 /// Forwarded onion, with the next node id and a new onion
984 crate::c_types::PublicKey,
985 crate::lightning::ln::msgs::OnionMessage),
986 /// Received onion message, with decrypted contents, path_id, and reply path
988 crate::lightning::onion_message::packet::ParsedOnionMessageContents,
990 /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
991 crate::c_types::ThirtyTwoBytes,
993 /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
994 crate::lightning::blinded_path::BlindedPath),
996 use lightning::onion_message::messenger::PeeledOnion as PeeledOnionImport;
997 pub(crate) type nativePeeledOnion = PeeledOnionImport<crate::lightning::onion_message::packet::OnionMessageContents>;
1001 pub(crate) fn to_native(&self) -> nativePeeledOnion {
1003 PeeledOnion::Forward (ref a, ref b, ) => {
1004 let mut a_nonref = Clone::clone(a);
1005 let mut b_nonref = Clone::clone(b);
1006 nativePeeledOnion::Forward (
1007 a_nonref.into_rust(),
1008 *unsafe { Box::from_raw(b_nonref.take_inner()) },
1011 PeeledOnion::Receive (ref a, ref b, ref c, ) => {
1012 let mut a_nonref = Clone::clone(a);
1013 let mut b_nonref = Clone::clone(b);
1014 let mut local_b_nonref = if b_nonref.data == [0; 32] { None } else { Some( { b_nonref.data }) };
1015 let mut c_nonref = Clone::clone(c);
1016 let mut local_c_nonref = if c_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(c_nonref.take_inner()) } }) };
1017 nativePeeledOnion::Receive (
1018 a_nonref.into_native(),
1026 pub(crate) fn into_native(self) -> nativePeeledOnion {
1028 PeeledOnion::Forward (mut a, mut b, ) => {
1029 nativePeeledOnion::Forward (
1031 *unsafe { Box::from_raw(b.take_inner()) },
1034 PeeledOnion::Receive (mut a, mut b, mut c, ) => {
1035 let mut local_b = if b.data == [0; 32] { None } else { Some( { b.data }) };
1036 let mut local_c = if c.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(c.take_inner()) } }) };
1037 nativePeeledOnion::Receive (
1046 pub(crate) fn from_native(native: &PeeledOnionImport<crate::lightning::onion_message::packet::OnionMessageContents>) -> Self {
1047 let native = unsafe { &*(native as *const _ as *const c_void as *const nativePeeledOnion) };
1049 nativePeeledOnion::Forward (ref a, ref b, ) => {
1050 let mut a_nonref = Clone::clone(a);
1051 let mut b_nonref = Clone::clone(b);
1052 PeeledOnion::Forward (
1053 crate::c_types::PublicKey::from_rust(&a_nonref),
1054 crate::lightning::ln::msgs::OnionMessage { inner: ObjOps::heap_alloc(b_nonref), is_owned: true },
1057 nativePeeledOnion::Receive (ref a, ref b, ref c, ) => {
1058 let mut a_nonref = Clone::clone(a);
1059 let mut b_nonref = Clone::clone(b);
1060 let mut local_b_nonref = if b_nonref.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else { { crate::c_types::ThirtyTwoBytes { data: (b_nonref.unwrap()) } } };
1061 let mut c_nonref = Clone::clone(c);
1062 let mut local_c_nonref = crate::lightning::blinded_path::BlindedPath { inner: if c_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((c_nonref.unwrap())) } }, is_owned: true };
1063 PeeledOnion::Receive (
1064 crate::lightning::onion_message::packet::ParsedOnionMessageContents::native_into(a_nonref),
1072 pub(crate) fn native_into(native: nativePeeledOnion) -> Self {
1074 nativePeeledOnion::Forward (mut a, mut b, ) => {
1075 PeeledOnion::Forward (
1076 crate::c_types::PublicKey::from_rust(&a),
1077 crate::lightning::ln::msgs::OnionMessage { inner: ObjOps::heap_alloc(b), is_owned: true },
1080 nativePeeledOnion::Receive (mut a, mut b, mut c, ) => {
1081 let mut local_b = if b.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else { { crate::c_types::ThirtyTwoBytes { data: (b.unwrap()) } } };
1082 let mut local_c = crate::lightning::blinded_path::BlindedPath { inner: if c.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((c.unwrap())) } }, is_owned: true };
1083 PeeledOnion::Receive (
1084 crate::lightning::onion_message::packet::ParsedOnionMessageContents::native_into(a),
1092 /// Frees any resources used by the PeeledOnion
1094 pub extern "C" fn PeeledOnion_free(this_ptr: PeeledOnion) { }
1095 /// Creates a copy of the PeeledOnion
1097 pub extern "C" fn PeeledOnion_clone(orig: &PeeledOnion) -> PeeledOnion {
1101 /// Used only if an object of this type is returned as a trait impl by a method
1102 pub(crate) extern "C" fn PeeledOnion_clone_void(this_ptr: *const c_void) -> *mut c_void {
1103 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const PeeledOnion)).clone() })) as *mut c_void
1106 /// Used only if an object of this type is returned as a trait impl by a method
1107 pub(crate) extern "C" fn PeeledOnion_free_void(this_ptr: *mut c_void) {
1108 let _ = unsafe { Box::from_raw(this_ptr as *mut PeeledOnion) };
1111 /// Utility method to constructs a new Forward-variant PeeledOnion
1112 pub extern "C" fn PeeledOnion_forward(a: crate::c_types::PublicKey,b: crate::lightning::ln::msgs::OnionMessage) -> PeeledOnion {
1113 PeeledOnion::Forward(a, b, )
1116 /// Utility method to constructs a new Receive-variant PeeledOnion
1117 pub extern "C" fn PeeledOnion_receive(a: crate::lightning::onion_message::packet::ParsedOnionMessageContents,b: crate::c_types::ThirtyTwoBytes,c: crate::lightning::blinded_path::BlindedPath) -> PeeledOnion {
1118 PeeledOnion::Receive(a, b, c, )
1120 /// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
1123 /// Returns the node id of the peer to send the message to, the message itself, and any addresses
1124 /// need to connect to the first node.
1126 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
1128 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 contents: crate::lightning::onion_message::packet::OnionMessageContents, mut reply_path: crate::lightning::blinded_path::BlindedPath) -> crate::c_types::derived::CResult_C3Tuple_PublicKeyOnionMessageCOption_CVec_SocketAddressZZZSendErrorZ {
1129 let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
1130 let mut ret = lightning::onion_message::messenger::create_onion_message::<crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::onion_message::packet::OnionMessageContents>(entropy_source, node_signer, secp256k1::global::SECP256K1, *unsafe { Box::from_raw(path.take_inner()) }, contents, local_reply_path);
1131 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, mut orig_ret_0_2) = o; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_none() { crate::c_types::derived::COption_CVec_SocketAddressZZ::None } else { crate::c_types::derived::COption_CVec_SocketAddressZZ::Some( { let mut local_orig_ret_0_2_0 = Vec::new(); for mut item in orig_ret_0_2.unwrap().drain(..) { local_orig_ret_0_2_0.push( { crate::lightning::ln::msgs::SocketAddress::native_into(item) }); }; local_orig_ret_0_2_0.into() }) }; 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 }, local_orig_ret_0_2).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::onion_message::messenger::SendError::native_into(e) }).into() };
1135 /// Decode one layer of an incoming [`OnionMessage`].
1137 /// Returns either the next layer of the onion for forwarding or the decrypted content for the
1140 pub extern "C" fn peel_onion_message(msg: &crate::lightning::ln::msgs::OnionMessage, mut node_signer: crate::lightning::sign::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut custom_handler: crate::lightning::onion_message::messenger::CustomOnionMessageHandler) -> crate::c_types::derived::CResult_PeeledOnionNoneZ {
1141 let mut ret = lightning::onion_message::messenger::peel_onion_message::<crate::lightning::sign::NodeSigner, crate::lightning::util::logger::Logger, crate::lightning::onion_message::messenger::CustomOnionMessageHandler>(msg.get_native_ref(), secp256k1::global::SECP256K1, node_signer, logger, custom_handler);
1142 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::onion_message::messenger::PeeledOnion::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
1146 /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
1147 /// their respective handlers.
1150 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 {
1151 let mut ret = lightning::onion_message::messenger::OnionMessenger::new(entropy_source, node_signer, logger, message_router, offers_handler, custom_handler);
1152 crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(ret), is_owned: true }
1155 /// Sends an [`OnionMessage`] with the given `contents` to `destination`.
1157 /// See [`OnionMessenger`] for example usage.
1159 /// Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
1162 pub extern "C" fn OnionMessenger_send_onion_message(this_arg: &crate::lightning::onion_message::messenger::OnionMessenger, mut contents: crate::lightning::onion_message::packet::OnionMessageContents, mut destination: crate::lightning::onion_message::messenger::Destination, mut reply_path: crate::lightning::blinded_path::BlindedPath) -> crate::c_types::derived::CResult_SendSuccessSendErrorZ {
1163 let mut local_reply_path = if reply_path.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(reply_path.take_inner()) } }) };
1164 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_onion_message(contents, destination.into_native(), local_reply_path);
1165 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::onion_message::messenger::SendSuccess::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::onion_message::messenger::SendError::native_into(e) }).into() };
1169 impl From<nativeOnionMessenger> for crate::lightning::ln::msgs::OnionMessageHandler {
1170 fn from(obj: nativeOnionMessenger) -> Self {
1171 let rust_obj = crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(obj), is_owned: true };
1172 let mut ret = OnionMessenger_as_OnionMessageHandler(&rust_obj);
1173 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1174 core::mem::forget(rust_obj);
1175 ret.free = Some(OnionMessenger_free_void);
1179 /// Constructs a new OnionMessageHandler which calls the relevant methods on this_arg.
1180 /// This copies the `inner` pointer in this_arg and thus the returned OnionMessageHandler must be freed before this_arg is
1182 pub extern "C" fn OnionMessenger_as_OnionMessageHandler(this_arg: &OnionMessenger) -> crate::lightning::ln::msgs::OnionMessageHandler {
1183 crate::lightning::ln::msgs::OnionMessageHandler {
1184 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1186 get_and_clear_connections_needed: OnionMessenger_OnionMessageHandler_get_and_clear_connections_needed,
1187 handle_onion_message: OnionMessenger_OnionMessageHandler_handle_onion_message,
1188 next_onion_message_for_peer: OnionMessenger_OnionMessageHandler_next_onion_message_for_peer,
1189 peer_connected: OnionMessenger_OnionMessageHandler_peer_connected,
1190 peer_disconnected: OnionMessenger_OnionMessageHandler_peer_disconnected,
1191 timer_tick_occurred: OnionMessenger_OnionMessageHandler_timer_tick_occurred,
1192 provided_node_features: OnionMessenger_OnionMessageHandler_provided_node_features,
1193 provided_init_features: OnionMessenger_OnionMessageHandler_provided_init_features,
1198 extern "C" fn OnionMessenger_OnionMessageHandler_get_and_clear_connections_needed(this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_PublicKeyCVec_SocketAddressZZZ {
1199 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::get_and_clear_connections_needed(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, );
1200 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::lightning::ln::msgs::SocketAddress::native_into(item) }); }; let mut local_ret_0 = (crate::c_types::PublicKey::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }); };
1203 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) {
1204 <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())
1207 extern "C" fn OnionMessenger_OnionMessageHandler_next_onion_message_for_peer(this_arg: *const c_void, mut peer_node_id: crate::c_types::PublicKey) -> crate::lightning::ln::msgs::OnionMessage {
1208 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::next_onion_message_for_peer(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, peer_node_id.into_rust());
1209 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 };
1213 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 {
1214 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);
1215 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() };
1218 extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) {
1219 <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust())
1221 extern "C" fn OnionMessenger_OnionMessageHandler_timer_tick_occurred(this_arg: *const c_void) {
1222 <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::timer_tick_occurred(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, )
1225 extern "C" fn OnionMessenger_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures {
1226 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_node_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, );
1227 crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
1230 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 {
1231 let mut ret = <nativeOnionMessenger as lightning::ln::msgs::OnionMessageHandler<>>::provided_init_features(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust());
1232 crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }