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