Update auto-generated bindings to 0.0.113
[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`] uses its [`Router`] parameterization for optionally notifying scorers upon
18 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
19 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
20 //! and [`Event::ProbeSuccessful`].
21 //!
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
27 //!
28 //! # Example
29 //!
30 //! ```
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
34 //! #
35 //! # use lightning::io;
36 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
37 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
38 //! # use lightning::ln::msgs::LightningError;
39 //! # use lightning::routing::gossip::NodeId;
40 //! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router};
41 //! # use lightning::routing::scoring::{ChannelUsage, Score};
42 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
43 //! # use lightning::util::logger::{Logger, Record};
44 //! # use lightning::util::ser::{Writeable, Writer};
45 //! # use lightning_invoice::Invoice;
46 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry};
47 //! # use secp256k1::PublicKey;
48 //! # use std::cell::RefCell;
49 //! # use std::ops::Deref;
50 //! #
51 //! # struct FakeEventProvider {}
52 //! # impl EventsProvider for FakeEventProvider {
53 //! #     fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
54 //! # }
55 //! #
56 //! # struct FakePayer {}
57 //! # impl Payer for FakePayer {
58 //! #     fn node_id(&self) -> PublicKey { unimplemented!() }
59 //! #     fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
60 //! #     fn send_payment(
61 //! #         &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
62 //! #         payment_id: PaymentId
63 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
64 //! #     fn send_spontaneous_payment(
65 //! #         &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
66 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
67 //! #     fn retry_payment(
68 //! #         &self, route: &Route, payment_id: PaymentId
69 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
70 //! #     fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
71 //! #     fn inflight_htlcs(&self) -> InFlightHtlcs { unimplemented!() }
72 //! # }
73 //! #
74 //! # struct FakeRouter {}
75 //! # impl Router for FakeRouter {
76 //! #     fn find_route(
77 //! #         &self, payer: &PublicKey, params: &RouteParameters,
78 //! #         first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
79 //! #     ) -> Result<Route, LightningError> { unimplemented!() }
80 //! #     fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {  unimplemented!() }
81 //! #     fn notify_payment_path_successful(&self, path: &[&RouteHop]) {  unimplemented!() }
82 //! #     fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {  unimplemented!() }
83 //! #     fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { 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, &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::router::Router, 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         let _ = unsafe { 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 ///
202 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
203 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
204 ///
205 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
206 ///
207 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
208 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
209 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
210 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
211 ///
212 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
213 #[repr(C)]
214 pub struct Payer {
215         /// An opaque pointer which is passed to your function implementations as an argument.
216         /// This has no meaning in the LDK, and can be NULL or any other value.
217         pub this_arg: *mut c_void,
218         /// Returns the payer's node id.
219         #[must_use]
220         pub node_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey,
221         /// Returns the payer's channels.
222         #[must_use]
223         pub first_hops: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_ChannelDetailsZ,
224         /// Sends a payment over the Lightning Network using the given [`Route`].
225         ///
226         /// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None
227         #[must_use]
228         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, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ,
229         /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
230         #[must_use]
231         pub send_spontaneous_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_preimage: crate::c_types::ThirtyTwoBytes, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ,
232         /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
233         #[must_use]
234         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,
235         /// Signals that no further retries for the given payment will occur.
236         pub abandon_payment: extern "C" fn (this_arg: *const c_void, payment_id: crate::c_types::ThirtyTwoBytes),
237         /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
238         /// across payments.
239         #[must_use]
240         pub inflight_htlcs: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::router::InFlightHtlcs,
241         /// Frees any resources associated with this object given its this_arg pointer.
242         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
243         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
244 }
245 unsafe impl Send for Payer {}
246 unsafe impl Sync for Payer {}
247 #[no_mangle]
248 pub(crate) extern "C" fn Payer_clone_fields(orig: &Payer) -> Payer {
249         Payer {
250                 this_arg: orig.this_arg,
251                 node_id: Clone::clone(&orig.node_id),
252                 first_hops: Clone::clone(&orig.first_hops),
253                 send_payment: Clone::clone(&orig.send_payment),
254                 send_spontaneous_payment: Clone::clone(&orig.send_spontaneous_payment),
255                 retry_payment: Clone::clone(&orig.retry_payment),
256                 abandon_payment: Clone::clone(&orig.abandon_payment),
257                 inflight_htlcs: Clone::clone(&orig.inflight_htlcs),
258                 free: Clone::clone(&orig.free),
259         }
260 }
261
262 use lightning_invoice::payment::Payer as rustPayer;
263 impl rustPayer for Payer {
264         fn node_id(&self) -> secp256k1::PublicKey {
265                 let mut ret = (self.node_id)(self.this_arg);
266                 ret.into_rust()
267         }
268         fn first_hops(&self) -> Vec<lightning::ln::channelmanager::ChannelDetails> {
269                 let mut ret = (self.first_hops)(self.this_arg);
270                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
271                 local_ret
272         }
273         fn send_payment(&self, mut route: &lightning::routing::router::Route, mut payment_hash: lightning::ln::PaymentHash, mut payment_secret: &Option<lightning::ln::PaymentSecret>, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> {
274                 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 } } };
275                 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, crate::c_types::ThirtyTwoBytes { data: payment_id.0 });
276                 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() })};
277                 local_ret
278         }
279         fn send_spontaneous_payment(&self, mut route: &lightning::routing::router::Route, mut payment_preimage: lightning::ln::PaymentPreimage, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> {
280                 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 }, crate::c_types::ThirtyTwoBytes { data: payment_id.0 });
281                 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() })};
282                 local_ret
283         }
284         fn retry_payment(&self, mut route: &lightning::routing::router::Route, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> {
285                 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 });
286                 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() })};
287                 local_ret
288         }
289         fn abandon_payment(&self, mut payment_id: lightning::ln::channelmanager::PaymentId) {
290                 (self.abandon_payment)(self.this_arg, crate::c_types::ThirtyTwoBytes { data: payment_id.0 })
291         }
292         fn inflight_htlcs(&self) -> lightning::routing::router::InFlightHtlcs {
293                 let mut ret = (self.inflight_htlcs)(self.this_arg);
294                 *unsafe { Box::from_raw(ret.take_inner()) }
295         }
296 }
297
298 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
299 // directly as a Deref trait in higher-level structs:
300 impl core::ops::Deref for Payer {
301         type Target = Self;
302         fn deref(&self) -> &Self {
303                 self
304         }
305 }
306 /// Calls the free function if one is set
307 #[no_mangle]
308 pub extern "C" fn Payer_free(this_ptr: Payer) { }
309 impl Drop for Payer {
310         fn drop(&mut self) {
311                 if let Some(f) = self.free {
312                         f(self.this_arg);
313                 }
314         }
315 }
316 /// Strategies available to retry payment path failures for an [`Invoice`].
317 ///
318 #[derive(Clone)]
319 #[must_use]
320 #[repr(C)]
321 pub enum Retry {
322         /// Max number of attempts to retry payment.
323         ///
324         /// Note that this is the number of *path* failures, not full payment retries. For multi-path
325         /// payments, if this is less than the total number of paths, we will never even retry all of the
326         /// payment's paths.
327         Attempts(
328                 usize),
329         /// Time elapsed before abandoning retries for a payment.
330         Timeout(
331                 u64),
332 }
333 use lightning_invoice::payment::Retry as RetryImport;
334 pub(crate) type nativeRetry = RetryImport;
335
336 impl Retry {
337         #[allow(unused)]
338         pub(crate) fn to_native(&self) -> nativeRetry {
339                 match self {
340                         Retry::Attempts (ref a, ) => {
341                                 let mut a_nonref = Clone::clone(a);
342                                 nativeRetry::Attempts (
343                                         a_nonref,
344                                 )
345                         },
346                         Retry::Timeout (ref a, ) => {
347                                 let mut a_nonref = Clone::clone(a);
348                                 nativeRetry::Timeout (
349                                         core::time::Duration::from_secs(a_nonref),
350                                 )
351                         },
352                 }
353         }
354         #[allow(unused)]
355         pub(crate) fn into_native(self) -> nativeRetry {
356                 match self {
357                         Retry::Attempts (mut a, ) => {
358                                 nativeRetry::Attempts (
359                                         a,
360                                 )
361                         },
362                         Retry::Timeout (mut a, ) => {
363                                 nativeRetry::Timeout (
364                                         core::time::Duration::from_secs(a),
365                                 )
366                         },
367                 }
368         }
369         #[allow(unused)]
370         pub(crate) fn from_native(native: &nativeRetry) -> Self {
371                 match native {
372                         nativeRetry::Attempts (ref a, ) => {
373                                 let mut a_nonref = Clone::clone(a);
374                                 Retry::Attempts (
375                                         a_nonref,
376                                 )
377                         },
378                         nativeRetry::Timeout (ref a, ) => {
379                                 let mut a_nonref = Clone::clone(a);
380                                 Retry::Timeout (
381                                         a_nonref.as_secs(),
382                                 )
383                         },
384                 }
385         }
386         #[allow(unused)]
387         pub(crate) fn native_into(native: nativeRetry) -> Self {
388                 match native {
389                         nativeRetry::Attempts (mut a, ) => {
390                                 Retry::Attempts (
391                                         a,
392                                 )
393                         },
394                         nativeRetry::Timeout (mut a, ) => {
395                                 Retry::Timeout (
396                                         a.as_secs(),
397                                 )
398                         },
399                 }
400         }
401 }
402 /// Frees any resources used by the Retry
403 #[no_mangle]
404 pub extern "C" fn Retry_free(this_ptr: Retry) { }
405 /// Creates a copy of the Retry
406 #[no_mangle]
407 pub extern "C" fn Retry_clone(orig: &Retry) -> Retry {
408         orig.clone()
409 }
410 #[no_mangle]
411 /// Utility method to constructs a new Attempts-variant Retry
412 pub extern "C" fn Retry_attempts(a: usize) -> Retry {
413         Retry::Attempts(a, )
414 }
415 #[no_mangle]
416 /// Utility method to constructs a new Timeout-variant Retry
417 pub extern "C" fn Retry_timeout(a: u64) -> Retry {
418         Retry::Timeout(a, )
419 }
420 /// Checks if two Retrys contain equal inner contents.
421 /// This ignores pointers and is_owned flags and looks at the values in fields.
422 #[no_mangle]
423 pub extern "C" fn Retry_eq(a: &Retry, b: &Retry) -> bool {
424         if &a.to_native() == &b.to_native() { true } else { false }
425 }
426 /// Checks if two Retrys contain equal inner contents.
427 #[no_mangle]
428 pub extern "C" fn Retry_hash(o: &Retry) -> u64 {
429         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
430         #[allow(deprecated)]
431         let mut hasher = core::hash::SipHasher::new();
432         core::hash::Hash::hash(&o.to_native(), &mut hasher);
433         core::hash::Hasher::finish(&hasher)
434 }
435 /// An error that may occur when making a payment.
436 #[derive(Clone)]
437 #[must_use]
438 #[repr(C)]
439 pub enum PaymentError {
440         /// An error resulting from the provided [`Invoice`] or payment hash.
441         Invoice(
442                 crate::c_types::Str),
443         /// An error occurring when finding a route.
444         Routing(
445                 crate::lightning::ln::msgs::LightningError),
446         /// An error occurring when sending a payment.
447         Sending(
448                 crate::lightning::ln::channelmanager::PaymentSendFailure),
449 }
450 use lightning_invoice::payment::PaymentError as PaymentErrorImport;
451 pub(crate) type nativePaymentError = PaymentErrorImport;
452
453 impl PaymentError {
454         #[allow(unused)]
455         pub(crate) fn to_native(&self) -> nativePaymentError {
456                 match self {
457                         PaymentError::Invoice (ref a, ) => {
458                                 let mut a_nonref = Clone::clone(a);
459                                 nativePaymentError::Invoice (
460                                         a_nonref.into_str(),
461                                 )
462                         },
463                         PaymentError::Routing (ref a, ) => {
464                                 let mut a_nonref = Clone::clone(a);
465                                 nativePaymentError::Routing (
466                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
467                                 )
468                         },
469                         PaymentError::Sending (ref a, ) => {
470                                 let mut a_nonref = Clone::clone(a);
471                                 nativePaymentError::Sending (
472                                         a_nonref.into_native(),
473                                 )
474                         },
475                 }
476         }
477         #[allow(unused)]
478         pub(crate) fn into_native(self) -> nativePaymentError {
479                 match self {
480                         PaymentError::Invoice (mut a, ) => {
481                                 nativePaymentError::Invoice (
482                                         a.into_str(),
483                                 )
484                         },
485                         PaymentError::Routing (mut a, ) => {
486                                 nativePaymentError::Routing (
487                                         *unsafe { Box::from_raw(a.take_inner()) },
488                                 )
489                         },
490                         PaymentError::Sending (mut a, ) => {
491                                 nativePaymentError::Sending (
492                                         a.into_native(),
493                                 )
494                         },
495                 }
496         }
497         #[allow(unused)]
498         pub(crate) fn from_native(native: &nativePaymentError) -> Self {
499                 match native {
500                         nativePaymentError::Invoice (ref a, ) => {
501                                 let mut a_nonref = Clone::clone(a);
502                                 PaymentError::Invoice (
503                                         a_nonref.into(),
504                                 )
505                         },
506                         nativePaymentError::Routing (ref a, ) => {
507                                 let mut a_nonref = Clone::clone(a);
508                                 PaymentError::Routing (
509                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
510                                 )
511                         },
512                         nativePaymentError::Sending (ref a, ) => {
513                                 let mut a_nonref = Clone::clone(a);
514                                 PaymentError::Sending (
515                                         crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a_nonref),
516                                 )
517                         },
518                 }
519         }
520         #[allow(unused)]
521         pub(crate) fn native_into(native: nativePaymentError) -> Self {
522                 match native {
523                         nativePaymentError::Invoice (mut a, ) => {
524                                 PaymentError::Invoice (
525                                         a.into(),
526                                 )
527                         },
528                         nativePaymentError::Routing (mut a, ) => {
529                                 PaymentError::Routing (
530                                         crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a), is_owned: true },
531                                 )
532                         },
533                         nativePaymentError::Sending (mut a, ) => {
534                                 PaymentError::Sending (
535                                         crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a),
536                                 )
537                         },
538                 }
539         }
540 }
541 /// Frees any resources used by the PaymentError
542 #[no_mangle]
543 pub extern "C" fn PaymentError_free(this_ptr: PaymentError) { }
544 /// Creates a copy of the PaymentError
545 #[no_mangle]
546 pub extern "C" fn PaymentError_clone(orig: &PaymentError) -> PaymentError {
547         orig.clone()
548 }
549 #[no_mangle]
550 /// Utility method to constructs a new Invoice-variant PaymentError
551 pub extern "C" fn PaymentError_invoice(a: crate::c_types::Str) -> PaymentError {
552         PaymentError::Invoice(a, )
553 }
554 #[no_mangle]
555 /// Utility method to constructs a new Routing-variant PaymentError
556 pub extern "C" fn PaymentError_routing(a: crate::lightning::ln::msgs::LightningError) -> PaymentError {
557         PaymentError::Routing(a, )
558 }
559 #[no_mangle]
560 /// Utility method to constructs a new Sending-variant PaymentError
561 pub extern "C" fn PaymentError_sending(a: crate::lightning::ln::channelmanager::PaymentSendFailure) -> PaymentError {
562         PaymentError::Sending(a, )
563 }
564 /// Creates an invoice payer that retries failed payment paths.
565 ///
566 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
567 /// `retry` has been exceeded for a given [`Invoice`].
568 #[must_use]
569 #[no_mangle]
570 pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment::Payer, mut router: crate::lightning::routing::router::Router, 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 {
571         let mut ret = lightning_invoice::payment::InvoicePayer::new(payer, router, logger, event_handler, retry.into_native());
572         crate::lightning_invoice::payment::InvoicePayer { inner: ObjOps::heap_alloc(ret), is_owned: true }
573 }
574
575 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
576 ///
577 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
578 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
579 /// a second payment with the same [`PaymentHash`] is never sent.
580 ///
581 /// If you wish to use a different payment idempotency token, see
582 /// [`Self::pay_invoice_with_id`].
583 #[must_use]
584 #[no_mangle]
585 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 {
586         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice(invoice.get_native_ref());
587         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() };
588         local_ret
589 }
590
591 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
592 /// in case a retry is needed.
593 ///
594 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
595 /// payment completes or fails, no idempotency guarantees are made.
596 ///
597 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
598 /// has never been paid before.
599 ///
600 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
601 /// token.
602 #[must_use]
603 #[no_mangle]
604 pub extern "C" fn InvoicePayer_pay_invoice_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentErrorZ {
605         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice_with_id(invoice.get_native_ref(), ::lightning::ln::channelmanager::PaymentId(payment_id.data));
606         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
607         local_ret
608 }
609
610 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
611 /// case a retry is needed.
612 ///
613 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
614 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
615 /// a second payment with the same [`PaymentHash`] is never sent.
616 ///
617 /// If you wish to use a different payment idempotency token, see
618 /// [`Self::pay_zero_value_invoice_with_id`].
619 #[must_use]
620 #[no_mangle]
621 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 {
622         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice(invoice.get_native_ref(), amount_msats);
623         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() };
624         local_ret
625 }
626
627 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
628 /// caching the invoice for later use in case a retry is needed.
629 ///
630 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
631 /// payment completes or fails, no idempotency guarantees are made.
632 ///
633 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
634 /// has never been paid before.
635 ///
636 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
637 /// idempotency token.
638 #[must_use]
639 #[no_mangle]
640 pub extern "C" fn InvoicePayer_pay_zero_value_invoice_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentErrorZ {
641         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice_with_id(invoice.get_native_ref(), amount_msats, ::lightning::ln::channelmanager::PaymentId(payment_id.data));
642         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
643         local_ret
644 }
645
646 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
647 /// case a retry is needed.
648 ///
649 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
650 /// as long as the payment is still pending. Once the payment completes or fails, you must
651 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
652 #[must_use]
653 #[no_mangle]
654 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 {
655         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);
656         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() };
657         local_ret
658 }
659
660 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
661 /// caching the invoice for later use in case a retry is needed.
662 ///
663 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
664 /// payment completes or fails, no idempotency guarantees are made.
665 ///
666 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
667 /// [`PaymentHash`] has never been paid before.
668 #[must_use]
669 #[no_mangle]
670 pub extern "C" fn InvoicePayer_pay_pubkey_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_NonePaymentErrorZ {
671         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_pubkey_with_id(pubkey.into_rust(), ::lightning::ln::PaymentPreimage(payment_preimage.data), ::lightning::ln::channelmanager::PaymentId(payment_id.data), amount_msats, final_cltv_expiry_delta);
672         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() };
673         local_ret
674 }
675
676 /// Removes the payment cached by the given payment hash.
677 ///
678 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
679 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
680 #[no_mangle]
681 pub extern "C" fn InvoicePayer_remove_cached_payment(this_arg: &crate::lightning_invoice::payment::InvoicePayer, payment_hash: *const [u8; 32]) {
682         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.remove_cached_payment(&::lightning::ln::PaymentHash(unsafe { *payment_hash }))
683 }
684
685 impl From<nativeInvoicePayer> for crate::lightning::util::events::EventHandler {
686         fn from(obj: nativeInvoicePayer) -> Self {
687                 let mut rust_obj = InvoicePayer { inner: ObjOps::heap_alloc(obj), is_owned: true };
688                 let mut ret = InvoicePayer_as_EventHandler(&rust_obj);
689                 // 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
690                 rust_obj.inner = core::ptr::null_mut();
691                 ret.free = Some(InvoicePayer_free_void);
692                 ret
693         }
694 }
695 /// Constructs a new EventHandler which calls the relevant methods on this_arg.
696 /// This copies the `inner` pointer in this_arg and thus the returned EventHandler must be freed before this_arg is
697 #[no_mangle]
698 pub extern "C" fn InvoicePayer_as_EventHandler(this_arg: &InvoicePayer) -> crate::lightning::util::events::EventHandler {
699         crate::lightning::util::events::EventHandler {
700                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
701                 free: None,
702                 handle_event: InvoicePayer_EventHandler_handle_event,
703         }
704 }
705
706 extern "C" fn InvoicePayer_EventHandler_handle_event(this_arg: *const c_void, mut event: crate::lightning::util::events::Event) {
707         <nativeInvoicePayer as lightning::util::events::EventHandler<>>::handle_event(unsafe { &mut *(this_arg as *mut nativeInvoicePayer) }, event.into_native())
708 }
709