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