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