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