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