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