Update auto-generated bindings
[ldk-c-bindings] / lightning-c-bindings / src / lightning_invoice / payment.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 //! A module for paying Lightning invoices and sending spontaneous payments.
10 //!
11 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
12 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
13 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
14 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
15 //! applicable.
16 //!
17 //! [`InvoicePayer`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
18 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
19 //! [`Event::PaymentPathSuccessful`] events, respectively.
20 //!
21 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
22 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
23 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
24 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
25 //! along the events to the user-provided handler.
26 //!
27 //! # Example
28 //!
29 //! ```
30 //! # extern crate lightning;
31 //! # extern crate lightning_invoice;
32 //! # extern crate secp256k1;
33 //! #
34 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
35 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
36 //! # use lightning::ln::msgs::LightningError;
37 //! # use lightning::routing::scoring::Score;
38 //! # use lightning::routing::network_graph::NodeId;
39 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
40 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
41 //! # use lightning::util::logger::{Logger, Record};
42 //! # use lightning::util::ser::{Writeable, Writer};
43 //! # use lightning_invoice::Invoice;
44 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
45 //! # use secp256k1::key::PublicKey;
46 //! # use std::cell::RefCell;
47 //! # use std::ops::Deref;
48 //! #
49 //! # struct FakeEventProvider {}
50 //! # impl EventsProvider for FakeEventProvider {
51 //! #     fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
52 //! # }
53 //! #
54 //! # struct FakePayer {}
55 //! # impl Payer for FakePayer {
56 //! #     fn node_id(&self) -> PublicKey { unimplemented!() }
57 //! #     fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
58 //! #     fn send_payment(
59 //! #         &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
60 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
61 //! #     fn send_spontaneous_payment(
62 //! #         &self, route: &Route, payment_preimage: PaymentPreimage
63 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
64 //! #     fn retry_payment(
65 //! #         &self, route: &Route, payment_id: PaymentId
66 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
67 //! #     fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
68 //! # }
69 //! #
70 //! # struct FakeRouter {}
71 //! # impl<S: Score> Router<S> for FakeRouter {
72 //! #     fn find_route(
73 //! #         &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
74 //! #         first_hops: Option<&[&ChannelDetails]>, scorer: &S
75 //! #     ) -> Result<Route, LightningError> { unimplemented!() }
76 //! # }
77 //! #
78 //! # struct FakeScorer {}
79 //! # impl Writeable for FakeScorer {
80 //! #     fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); }
81 //! # }
82 //! # impl Score for FakeScorer {
83 //! #     fn channel_penalty_msat(
84 //! #         &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
85 //! #     ) -> u64 { 0 }
86 //! #     fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
87 //! #     fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
88 //! # }
89 //! #
90 //! # struct FakeLogger {}
91 //! # impl Logger for FakeLogger {
92 //! #     fn log(&self, record: &Record) { unimplemented!() }
93 //! # }
94 //! #
95 //! # fn main() {
96 //! let event_handler = |event: &Event| {
97 //!     match event {
98 //!         Event::PaymentPathFailed { .. } => println!(\"payment failed after retries\"),
99 //!         Event::PaymentSent { .. } => println!(\"payment successful\"),
100 //!         _ => {},
101 //!     }
102 //! };
103 //! # let payer = FakePayer {};
104 //! # let router = FakeRouter {};
105 //! # let scorer = RefCell::new(FakeScorer {});
106 //! # let logger = FakeLogger {};
107 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
108 //!
109 //! let invoice = \"...\";
110 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
111 //!     invoice_payer.pay_invoice(&invoice).unwrap();
112 //!
113 //! # let event_provider = FakeEventProvider {};
114 //!     loop {
115 //!         event_provider.process_pending_events(&invoice_payer);
116 //!     }
117 //! }
118 //! # }
119 //! ```
120 //!
121 //! # Note
122 //!
123 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
124 //! as updates to the network graph or changes to channel scores should be applied prior to
125 //! retries, typically by way of composing [`EventHandler`]s accordingly.
126
127 use alloc::str::FromStr;
128 use core::ffi::c_void;
129 use core::convert::Infallible;
130 use bitcoin::hashes::Hash;
131 use crate::c_types::*;
132 #[cfg(feature="no-std")]
133 use alloc::{vec::Vec, boxed::Box};
134
135
136 use lightning_invoice::payment::InvoicePayer as nativeInvoicePayerImport;
137 pub(crate) type nativeInvoicePayer = nativeInvoicePayerImport<crate::lightning_invoice::payment::Payer, crate::lightning::routing::scoring::Score, crate::lightning_invoice::payment::Router, &'static lightning::routing::scoring::MultiThreadedLockableScore<crate::lightning::routing::scoring::Score>, crate::lightning::util::logger::Logger, crate::lightning::util::events::EventHandler>;
138
139 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
140 ///
141 /// See [module-level documentation] for details.
142 ///
143 /// [module-level documentation]: crate::payment
144 #[must_use]
145 #[repr(C)]
146 pub struct InvoicePayer {
147         /// A pointer to the opaque Rust object.
148
149         /// Nearly everywhere, inner must be non-null, however in places where
150         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
151         pub inner: *mut nativeInvoicePayer,
152         /// Indicates that this is the only struct which contains the same pointer.
153
154         /// Rust functions which take ownership of an object provided via an argument require
155         /// this to be true and invalidate the object pointed to by inner.
156         pub is_owned: bool,
157 }
158
159 impl Drop for InvoicePayer {
160         fn drop(&mut self) {
161                 if self.is_owned && !<*mut nativeInvoicePayer>::is_null(self.inner) {
162                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
163                 }
164         }
165 }
166 /// Frees any resources used by the InvoicePayer, if is_owned is set and inner is non-NULL.
167 #[no_mangle]
168 pub extern "C" fn InvoicePayer_free(this_obj: InvoicePayer) { }
169 #[allow(unused)]
170 /// Used only if an object of this type is returned as a trait impl by a method
171 pub(crate) extern "C" fn InvoicePayer_free_void(this_ptr: *mut c_void) {
172         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoicePayer); }
173 }
174 #[allow(unused)]
175 impl InvoicePayer {
176         pub(crate) fn get_native_ref(&self) -> &'static nativeInvoicePayer {
177                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
178         }
179         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoicePayer {
180                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
181         }
182         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
183         pub(crate) fn take_inner(mut self) -> *mut nativeInvoicePayer {
184                 assert!(self.is_owned);
185                 let ret = ObjOps::untweak_ptr(self.inner);
186                 self.inner = core::ptr::null_mut();
187                 ret
188         }
189 }
190 /// A trait defining behavior of an [`Invoice`] payer.
191 #[repr(C)]
192 pub struct Payer {
193         /// An opaque pointer which is passed to your function implementations as an argument.
194         /// This has no meaning in the LDK, and can be NULL or any other value.
195         pub this_arg: *mut c_void,
196         /// Returns the payer's node id.
197         #[must_use]
198         pub node_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey,
199         /// Returns the payer's channels.
200         #[must_use]
201         pub first_hops: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_ChannelDetailsZ,
202         /// Sends a payment over the Lightning Network using the given [`Route`].
203         ///
204         /// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None
205         #[must_use]
206         pub send_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_hash: crate::c_types::ThirtyTwoBytes, payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentIdPaymentSendFailureZ,
207         /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
208         #[must_use]
209         pub send_spontaneous_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_preimage: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentIdPaymentSendFailureZ,
210         /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
211         #[must_use]
212         pub retry_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ,
213         /// Signals that no further retries for the given payment will occur.
214         pub abandon_payment: extern "C" fn (this_arg: *const c_void, payment_id: crate::c_types::ThirtyTwoBytes),
215         /// Frees any resources associated with this object given its this_arg pointer.
216         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
217         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
218 }
219 unsafe impl Send for Payer {}
220 unsafe impl Sync for Payer {}
221 #[no_mangle]
222 pub(crate) extern "C" fn Payer_clone_fields(orig: &Payer) -> Payer {
223         Payer {
224                 this_arg: orig.this_arg,
225                 node_id: Clone::clone(&orig.node_id),
226                 first_hops: Clone::clone(&orig.first_hops),
227                 send_payment: Clone::clone(&orig.send_payment),
228                 send_spontaneous_payment: Clone::clone(&orig.send_spontaneous_payment),
229                 retry_payment: Clone::clone(&orig.retry_payment),
230                 abandon_payment: Clone::clone(&orig.abandon_payment),
231                 free: Clone::clone(&orig.free),
232         }
233 }
234
235 use lightning_invoice::payment::Payer as rustPayer;
236 impl rustPayer for Payer {
237         fn node_id(&self) -> secp256k1::key::PublicKey {
238                 let mut ret = (self.node_id)(self.this_arg);
239                 ret.into_rust()
240         }
241         fn first_hops(&self) -> Vec<lightning::ln::channelmanager::ChannelDetails> {
242                 let mut ret = (self.first_hops)(self.this_arg);
243                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
244                 local_ret
245         }
246         fn send_payment(&self, mut route: &lightning::routing::router::Route, mut payment_hash: lightning::ln::PaymentHash, mut payment_secret: &Option<lightning::ln::PaymentSecret>) -> Result<lightning::ln::channelmanager::PaymentId, lightning::ln::channelmanager::PaymentSendFailure> {
247                 let mut local_payment_secret = if payment_secret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (payment_secret.unwrap()).0 } } };
248                 let mut ret = (self.send_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, local_payment_secret);
249                 let mut local_ret = match ret.result_ok { true => Ok( { ::lightning::ln::channelmanager::PaymentId((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).data) }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
250                 local_ret
251         }
252         fn send_spontaneous_payment(&self, mut route: &lightning::routing::router::Route, mut payment_preimage: lightning::ln::PaymentPreimage) -> Result<lightning::ln::channelmanager::PaymentId, lightning::ln::channelmanager::PaymentSendFailure> {
253                 let mut ret = (self.send_spontaneous_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_preimage.0 });
254                 let mut local_ret = match ret.result_ok { true => Ok( { ::lightning::ln::channelmanager::PaymentId((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).data) }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
255                 local_ret
256         }
257         fn retry_payment(&self, mut route: &lightning::routing::router::Route, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> {
258                 let mut ret = (self.retry_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_id.0 });
259                 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
260                 local_ret
261         }
262         fn abandon_payment(&self, mut payment_id: lightning::ln::channelmanager::PaymentId) {
263                 (self.abandon_payment)(self.this_arg, crate::c_types::ThirtyTwoBytes { data: payment_id.0 })
264         }
265 }
266
267 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
268 // directly as a Deref trait in higher-level structs:
269 impl core::ops::Deref for Payer {
270         type Target = Self;
271         fn deref(&self) -> &Self {
272                 self
273         }
274 }
275 /// Calls the free function if one is set
276 #[no_mangle]
277 pub extern "C" fn Payer_free(this_ptr: Payer) { }
278 impl Drop for Payer {
279         fn drop(&mut self) {
280                 if let Some(f) = self.free {
281                         f(self.this_arg);
282                 }
283         }
284 }
285 /// A trait defining behavior for routing an [`Invoice`] payment.
286 #[repr(C)]
287 pub struct Router {
288         /// An opaque pointer which is passed to your function implementations as an argument.
289         /// This has no meaning in the LDK, and can be NULL or any other value.
290         pub this_arg: *mut c_void,
291         /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
292         ///
293         /// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None
294         #[must_use]
295         pub find_route: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, params: &crate::lightning::routing::router::RouteParameters, payment_hash: *const [u8; 32], first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, scorer: &crate::lightning::routing::scoring::Score) -> crate::c_types::derived::CResult_RouteLightningErrorZ,
296         /// Frees any resources associated with this object given its this_arg pointer.
297         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
298         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
299 }
300 unsafe impl Send for Router {}
301 unsafe impl Sync for Router {}
302 #[no_mangle]
303 pub(crate) extern "C" fn Router_clone_fields(orig: &Router) -> Router {
304         Router {
305                 this_arg: orig.this_arg,
306                 find_route: Clone::clone(&orig.find_route),
307                 free: Clone::clone(&orig.free),
308         }
309 }
310
311 use lightning_invoice::payment::Router as rustRouter;
312 impl rustRouter<crate::lightning::routing::scoring::Score> for Router {
313         fn find_route(&self, mut payer: &secp256k1::key::PublicKey, mut params: &lightning::routing::router::RouteParameters, mut payment_hash: &lightning::ln::PaymentHash, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut scorer: &crate::lightning::routing::scoring::Score) -> Result<lightning::routing::router::Route, lightning::ln::msgs::LightningError> {
314                 let mut local_first_hops_base = if first_hops.is_none() { SmartPtr::null() } else { SmartPtr::from_obj( { let mut local_first_hops_0 = Vec::new(); for item in (first_hops.unwrap()).iter() { local_first_hops_0.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::ln::channelmanager::ChannelDetails<>) as *mut _) }, is_owned: false } }); }; local_first_hops_0.into() }) }; let mut local_first_hops = *local_first_hops_base;
315                 let mut ret = (self.find_route)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, &payment_hash.0, local_first_hops, scorer);
316                 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((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
317                 local_ret
318         }
319 }
320
321 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
322 // directly as a Deref trait in higher-level structs:
323 impl core::ops::Deref for Router {
324         type Target = Self;
325         fn deref(&self) -> &Self {
326                 self
327         }
328 }
329 /// Calls the free function if one is set
330 #[no_mangle]
331 pub extern "C" fn Router_free(this_ptr: Router) { }
332 impl Drop for Router {
333         fn drop(&mut self) {
334                 if let Some(f) = self.free {
335                         f(self.this_arg);
336                 }
337         }
338 }
339
340 use lightning_invoice::payment::RetryAttempts as nativeRetryAttemptsImport;
341 pub(crate) type nativeRetryAttempts = nativeRetryAttemptsImport;
342
343 /// Number of attempts to retry payment path failures for an [`Invoice`].
344 ///
345 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
346 /// payments, if this is less than the total number of paths, we will never even retry all of the
347 /// payment's paths.
348 #[must_use]
349 #[repr(C)]
350 pub struct RetryAttempts {
351         /// A pointer to the opaque Rust object.
352
353         /// Nearly everywhere, inner must be non-null, however in places where
354         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
355         pub inner: *mut nativeRetryAttempts,
356         /// Indicates that this is the only struct which contains the same pointer.
357
358         /// Rust functions which take ownership of an object provided via an argument require
359         /// this to be true and invalidate the object pointed to by inner.
360         pub is_owned: bool,
361 }
362
363 impl Drop for RetryAttempts {
364         fn drop(&mut self) {
365                 if self.is_owned && !<*mut nativeRetryAttempts>::is_null(self.inner) {
366                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
367                 }
368         }
369 }
370 /// Frees any resources used by the RetryAttempts, if is_owned is set and inner is non-NULL.
371 #[no_mangle]
372 pub extern "C" fn RetryAttempts_free(this_obj: RetryAttempts) { }
373 #[allow(unused)]
374 /// Used only if an object of this type is returned as a trait impl by a method
375 pub(crate) extern "C" fn RetryAttempts_free_void(this_ptr: *mut c_void) {
376         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRetryAttempts); }
377 }
378 #[allow(unused)]
379 impl RetryAttempts {
380         pub(crate) fn get_native_ref(&self) -> &'static nativeRetryAttempts {
381                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
382         }
383         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRetryAttempts {
384                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
385         }
386         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
387         pub(crate) fn take_inner(mut self) -> *mut nativeRetryAttempts {
388                 assert!(self.is_owned);
389                 let ret = ObjOps::untweak_ptr(self.inner);
390                 self.inner = core::ptr::null_mut();
391                 ret
392         }
393 }
394 #[no_mangle]
395 pub extern "C" fn RetryAttempts_get_a(this_ptr: &RetryAttempts) -> usize {
396         let mut inner_val = &mut this_ptr.get_native_mut_ref().0;
397         *inner_val
398 }
399 #[no_mangle]
400 pub extern "C" fn RetryAttempts_set_a(this_ptr: &mut RetryAttempts, mut val: usize) {
401         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val;
402 }
403 /// Constructs a new RetryAttempts given each field
404 #[must_use]
405 #[no_mangle]
406 pub extern "C" fn RetryAttempts_new(mut a_arg: usize) -> RetryAttempts {
407         RetryAttempts { inner: ObjOps::heap_alloc(lightning_invoice::payment::RetryAttempts (
408                 a_arg,
409         )), is_owned: true }
410 }
411 impl Clone for RetryAttempts {
412         fn clone(&self) -> Self {
413                 Self {
414                         inner: if <*mut nativeRetryAttempts>::is_null(self.inner) { core::ptr::null_mut() } else {
415                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
416                         is_owned: true,
417                 }
418         }
419 }
420 #[allow(unused)]
421 /// Used only if an object of this type is returned as a trait impl by a method
422 pub(crate) extern "C" fn RetryAttempts_clone_void(this_ptr: *const c_void) -> *mut c_void {
423         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRetryAttempts)).clone() })) as *mut c_void
424 }
425 #[no_mangle]
426 /// Creates a copy of the RetryAttempts
427 pub extern "C" fn RetryAttempts_clone(orig: &RetryAttempts) -> RetryAttempts {
428         orig.clone()
429 }
430 /// Checks if two RetryAttemptss contain equal inner contents.
431 /// This ignores pointers and is_owned flags and looks at the values in fields.
432 /// Two objects with NULL inner values will be considered "equal" here.
433 #[no_mangle]
434 pub extern "C" fn RetryAttempts_eq(a: &RetryAttempts, b: &RetryAttempts) -> bool {
435         if a.inner == b.inner { return true; }
436         if a.inner.is_null() || b.inner.is_null() { return false; }
437         if a.get_native_ref() == b.get_native_ref() { true } else { false }
438 }
439 /// Checks if two RetryAttemptss contain equal inner contents.
440 #[no_mangle]
441 pub extern "C" fn RetryAttempts_hash(o: &RetryAttempts) -> u64 {
442         if o.inner.is_null() { return 0; }
443         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
444         #[allow(deprecated)]
445         let mut hasher = core::hash::SipHasher::new();
446         core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
447         core::hash::Hasher::finish(&hasher)
448 }
449 /// An error that may occur when making a payment.
450 #[must_use]
451 #[derive(Clone)]
452 #[repr(C)]
453 pub enum PaymentError {
454         /// An error resulting from the provided [`Invoice`] or payment hash.
455         Invoice(crate::c_types::Str),
456         /// An error occurring when finding a route.
457         Routing(crate::lightning::ln::msgs::LightningError),
458         /// An error occurring when sending a payment.
459         Sending(crate::lightning::ln::channelmanager::PaymentSendFailure),
460 }
461 use lightning_invoice::payment::PaymentError as nativePaymentError;
462 impl PaymentError {
463         #[allow(unused)]
464         pub(crate) fn to_native(&self) -> nativePaymentError {
465                 match self {
466                         PaymentError::Invoice (ref a, ) => {
467                                 let mut a_nonref = (*a).clone();
468                                 nativePaymentError::Invoice (
469                                         a_nonref.into_str(),
470                                 )
471                         },
472                         PaymentError::Routing (ref a, ) => {
473                                 let mut a_nonref = (*a).clone();
474                                 nativePaymentError::Routing (
475                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
476                                 )
477                         },
478                         PaymentError::Sending (ref a, ) => {
479                                 let mut a_nonref = (*a).clone();
480                                 nativePaymentError::Sending (
481                                         a_nonref.into_native(),
482                                 )
483                         },
484                 }
485         }
486         #[allow(unused)]
487         pub(crate) fn into_native(self) -> nativePaymentError {
488                 match self {
489                         PaymentError::Invoice (mut a, ) => {
490                                 nativePaymentError::Invoice (
491                                         a.into_str(),
492                                 )
493                         },
494                         PaymentError::Routing (mut a, ) => {
495                                 nativePaymentError::Routing (
496                                         *unsafe { Box::from_raw(a.take_inner()) },
497                                 )
498                         },
499                         PaymentError::Sending (mut a, ) => {
500                                 nativePaymentError::Sending (
501                                         a.into_native(),
502                                 )
503                         },
504                 }
505         }
506         #[allow(unused)]
507         pub(crate) fn from_native(native: &nativePaymentError) -> Self {
508                 match native {
509                         nativePaymentError::Invoice (ref a, ) => {
510                                 let mut a_nonref = (*a).clone();
511                                 PaymentError::Invoice (
512                                         a_nonref.into(),
513                                 )
514                         },
515                         nativePaymentError::Routing (ref a, ) => {
516                                 let mut a_nonref = (*a).clone();
517                                 PaymentError::Routing (
518                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
519                                 )
520                         },
521                         nativePaymentError::Sending (ref a, ) => {
522                                 let mut a_nonref = (*a).clone();
523                                 PaymentError::Sending (
524                                         crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a_nonref),
525                                 )
526                         },
527                 }
528         }
529         #[allow(unused)]
530         pub(crate) fn native_into(native: nativePaymentError) -> Self {
531                 match native {
532                         nativePaymentError::Invoice (mut a, ) => {
533                                 PaymentError::Invoice (
534                                         a.into(),
535                                 )
536                         },
537                         nativePaymentError::Routing (mut a, ) => {
538                                 PaymentError::Routing (
539                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a), is_owned: true },
540                                 )
541                         },
542                         nativePaymentError::Sending (mut a, ) => {
543                                 PaymentError::Sending (
544                                         crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a),
545                                 )
546                         },
547                 }
548         }
549 }
550 /// Frees any resources used by the PaymentError
551 #[no_mangle]
552 pub extern "C" fn PaymentError_free(this_ptr: PaymentError) { }
553 /// Creates a copy of the PaymentError
554 #[no_mangle]
555 pub extern "C" fn PaymentError_clone(orig: &PaymentError) -> PaymentError {
556         orig.clone()
557 }
558 #[no_mangle]
559 /// Utility method to constructs a new Invoice-variant PaymentError
560 pub extern "C" fn PaymentError_invoice(a: crate::c_types::Str) -> PaymentError {
561         PaymentError::Invoice(a, )
562 }
563 #[no_mangle]
564 /// Utility method to constructs a new Routing-variant PaymentError
565 pub extern "C" fn PaymentError_routing(a: crate::lightning::ln::msgs::LightningError) -> PaymentError {
566         PaymentError::Routing(a, )
567 }
568 #[no_mangle]
569 /// Utility method to constructs a new Sending-variant PaymentError
570 pub extern "C" fn PaymentError_sending(a: crate::lightning::ln::channelmanager::PaymentSendFailure) -> PaymentError {
571         PaymentError::Sending(a, )
572 }
573 /// Creates an invoice payer that retries failed payment paths.
574 ///
575 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
576 /// `retry_attempts` has been exceeded for a given [`Invoice`].
577 #[must_use]
578 #[no_mangle]
579 pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment::Payer, mut router: crate::lightning_invoice::payment::Router, scorer: &crate::lightning::routing::scoring::MultiThreadedLockableScore, mut logger: crate::lightning::util::logger::Logger, mut event_handler: crate::lightning::util::events::EventHandler, mut retry_attempts: crate::lightning_invoice::payment::RetryAttempts) -> InvoicePayer {
580         let mut ret = lightning_invoice::payment::InvoicePayer::new(payer, router, scorer.get_native_ref(), logger, event_handler, *unsafe { Box::from_raw(retry_attempts.take_inner()) });
581         InvoicePayer { inner: ObjOps::heap_alloc(ret), is_owned: true }
582 }
583
584 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
585 ///
586 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
587 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
588 /// for you.
589 #[must_use]
590 #[no_mangle]
591 pub extern "C" fn InvoicePayer_pay_invoice(this_arg: &InvoicePayer, invoice: &crate::lightning_invoice::Invoice) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ {
592         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice(invoice.get_native_ref());
593         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
594         local_ret
595 }
596
597 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
598 /// case a retry is needed.
599 ///
600 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
601 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
602 /// for you.
603 #[must_use]
604 #[no_mangle]
605 pub extern "C" fn InvoicePayer_pay_zero_value_invoice(this_arg: &InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ {
606         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice(invoice.get_native_ref(), amount_msats);
607         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
608         local_ret
609 }
610
611 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
612 /// case a retry is needed.
613 ///
614 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
615 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
616 #[must_use]
617 #[no_mangle]
618 pub extern "C" fn InvoicePayer_pay_pubkey(this_arg: &InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ {
619         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_pubkey(pubkey.into_rust(), ::lightning::ln::PaymentPreimage(payment_preimage.data), amount_msats, final_cltv_expiry_delta);
620         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
621         local_ret
622 }
623
624 /// Removes the payment cached by the given payment hash.
625 ///
626 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
627 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
628 #[no_mangle]
629 pub extern "C" fn InvoicePayer_remove_cached_payment(this_arg: &InvoicePayer, payment_hash: *const [u8; 32]) {
630         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.remove_cached_payment(&::lightning::ln::PaymentHash(unsafe { *payment_hash }))
631 }
632
633 impl From<nativeInvoicePayer> for crate::lightning::util::events::EventHandler {
634         fn from(obj: nativeInvoicePayer) -> Self {
635                 let mut rust_obj = InvoicePayer { inner: ObjOps::heap_alloc(obj), is_owned: true };
636                 let mut ret = InvoicePayer_as_EventHandler(&rust_obj);
637                 // 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
638                 rust_obj.inner = core::ptr::null_mut();
639                 ret.free = Some(InvoicePayer_free_void);
640                 ret
641         }
642 }
643 /// Constructs a new EventHandler which calls the relevant methods on this_arg.
644 /// This copies the `inner` pointer in this_arg and thus the returned EventHandler must be freed before this_arg is
645 #[no_mangle]
646 pub extern "C" fn InvoicePayer_as_EventHandler(this_arg: &InvoicePayer) -> crate::lightning::util::events::EventHandler {
647         crate::lightning::util::events::EventHandler {
648                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
649                 free: None,
650                 handle_event: InvoicePayer_EventHandler_handle_event,
651         }
652 }
653
654 extern "C" fn InvoicePayer_EventHandler_handle_event(this_arg: *const c_void, event: &crate::lightning::util::events::Event) {
655         <nativeInvoicePayer as lightning::util::events::EventHandler<>>::handle_event(unsafe { &mut *(this_arg as *mut nativeInvoicePayer) }, &event.to_native())
656 }
657