0ae9fd6438d91aadcbeec94b145cdd005b07de47
[ldk-c-bindings] / lightning-c-bindings / src / lightning / offers / offer.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 //! Data structures and encoding for `offer` messages.
10 //!
11 //! An [`Offer`] represents an \"offer to be paid.\" It is typically constructed by a merchant and
12 //! published as a QR code to be scanned by a customer. The customer uses the offer to request an
13 //! invoice from the merchant to be paid.
14 //!
15 //! # Example
16 //!
17 //! ```
18 //! extern crate bitcoin;
19 //! extern crate core;
20 //! extern crate lightning;
21 //!
22 //! use core::convert::TryFrom;
23 //! use core::num::NonZeroU64;
24 //! use core::time::Duration;
25 //!
26 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
27 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
28 //! use lightning::offers::parse::Bolt12ParseError;
29 //! use lightning::util::ser::{Readable, Writeable};
30 //!
31 //! # use lightning::blinded_path::BlindedPath;
32 //! # #[cfg(feature = \"std\")]
33 //! # use std::time::SystemTime;
34 //! #
35 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
36 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
37 //! #
38 //! # #[cfg(feature = \"std\")]
39 //! # fn build() -> Result<(), Bolt12ParseError> {
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
42 //! let pubkey = PublicKey::from(keys);
43 //!
44 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
45 //! let offer = OfferBuilder::new(pubkey)
46 //!     .description(\"coffee, large\".to_string())
47 //!     .amount_msats(20_000)
48 //!     .supported_quantity(Quantity::Unbounded)
49 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //!     .issuer(\"Foo Bar\".to_string())
51 //!     .path(create_blinded_path())
52 //!     .path(create_another_blinded_path())
53 //!     .build()?;
54 //!
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
57 //!
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
60 //!
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
64 //!
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
67 //! # Ok(())
68 //! # }
69 //! ```
70 //!
71 //! # Note
72 //!
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
75 //!
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
78
79 use alloc::str::FromStr;
80 use alloc::string::String;
81 use core::ffi::c_void;
82 use core::convert::Infallible;
83 use bitcoin::hashes::Hash;
84 use crate::c_types::*;
85 #[cfg(feature="no-std")]
86 use alloc::{vec::Vec, boxed::Box};
87
88
89 use lightning::offers::offer::OfferId as nativeOfferIdImport;
90 pub(crate) type nativeOfferId = nativeOfferIdImport;
91
92 /// An identifier for an [`Offer`] built using [`DerivedMetadata`].
93 #[must_use]
94 #[repr(C)]
95 pub struct OfferId {
96         /// A pointer to the opaque Rust object.
97
98         /// Nearly everywhere, inner must be non-null, however in places where
99         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
100         pub inner: *mut nativeOfferId,
101         /// Indicates that this is the only struct which contains the same pointer.
102
103         /// Rust functions which take ownership of an object provided via an argument require
104         /// this to be true and invalidate the object pointed to by inner.
105         pub is_owned: bool,
106 }
107
108 impl Drop for OfferId {
109         fn drop(&mut self) {
110                 if self.is_owned && !<*mut nativeOfferId>::is_null(self.inner) {
111                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
112                 }
113         }
114 }
115 /// Frees any resources used by the OfferId, if is_owned is set and inner is non-NULL.
116 #[no_mangle]
117 pub extern "C" fn OfferId_free(this_obj: OfferId) { }
118 #[allow(unused)]
119 /// Used only if an object of this type is returned as a trait impl by a method
120 pub(crate) extern "C" fn OfferId_free_void(this_ptr: *mut c_void) {
121         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOfferId) };
122 }
123 #[allow(unused)]
124 impl OfferId {
125         pub(crate) fn get_native_ref(&self) -> &'static nativeOfferId {
126                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
127         }
128         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOfferId {
129                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
130         }
131         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
132         pub(crate) fn take_inner(mut self) -> *mut nativeOfferId {
133                 assert!(self.is_owned);
134                 let ret = ObjOps::untweak_ptr(self.inner);
135                 self.inner = core::ptr::null_mut();
136                 ret
137         }
138 }
139 #[no_mangle]
140 pub extern "C" fn OfferId_get_a(this_ptr: &OfferId) -> *const [u8; 32] {
141         let mut inner_val = &mut this_ptr.get_native_mut_ref().0;
142         inner_val
143 }
144 #[no_mangle]
145 pub extern "C" fn OfferId_set_a(this_ptr: &mut OfferId, mut val: crate::c_types::ThirtyTwoBytes) {
146         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.data;
147 }
148 /// Constructs a new OfferId given each field
149 #[must_use]
150 #[no_mangle]
151 pub extern "C" fn OfferId_new(mut a_arg: crate::c_types::ThirtyTwoBytes) -> OfferId {
152         OfferId { inner: ObjOps::heap_alloc(lightning::offers::offer::OfferId (
153                 a_arg.data,
154         )), is_owned: true }
155 }
156 impl Clone for OfferId {
157         fn clone(&self) -> Self {
158                 Self {
159                         inner: if <*mut nativeOfferId>::is_null(self.inner) { core::ptr::null_mut() } else {
160                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
161                         is_owned: true,
162                 }
163         }
164 }
165 #[allow(unused)]
166 /// Used only if an object of this type is returned as a trait impl by a method
167 pub(crate) extern "C" fn OfferId_clone_void(this_ptr: *const c_void) -> *mut c_void {
168         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeOfferId)).clone() })) as *mut c_void
169 }
170 #[no_mangle]
171 /// Creates a copy of the OfferId
172 pub extern "C" fn OfferId_clone(orig: &OfferId) -> OfferId {
173         orig.clone()
174 }
175 /// Get a string which allows debug introspection of a OfferId object
176 pub extern "C" fn OfferId_debug_str_void(o: *const c_void) -> Str {
177         alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::OfferId }).into()}
178 /// Checks if two OfferIds contain equal inner contents.
179 /// This ignores pointers and is_owned flags and looks at the values in fields.
180 /// Two objects with NULL inner values will be considered "equal" here.
181 #[no_mangle]
182 pub extern "C" fn OfferId_eq(a: &OfferId, b: &OfferId) -> bool {
183         if a.inner == b.inner { return true; }
184         if a.inner.is_null() || b.inner.is_null() { return false; }
185         if a.get_native_ref() == b.get_native_ref() { true } else { false }
186 }
187 #[no_mangle]
188 /// Serialize the OfferId object into a byte array which can be read by OfferId_read
189 pub extern "C" fn OfferId_write(obj: &crate::lightning::offers::offer::OfferId) -> crate::c_types::derived::CVec_u8Z {
190         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
191 }
192 #[allow(unused)]
193 pub(crate) extern "C" fn OfferId_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
194         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOfferId) })
195 }
196 #[no_mangle]
197 /// Read a OfferId from a byte array, created by OfferId_write
198 pub extern "C" fn OfferId_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OfferIdDecodeErrorZ {
199         let res: Result<lightning::offers::offer::OfferId, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
200         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::offer::OfferId { 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() };
201         local_res
202 }
203
204 use lightning::offers::offer::Offer as nativeOfferImport;
205 pub(crate) type nativeOffer = nativeOfferImport;
206
207 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
208 ///
209 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
210 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
211 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
212 ///
213 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
214 /// latter.
215 ///
216 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
217 ///
218 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
219 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
220 #[must_use]
221 #[repr(C)]
222 pub struct Offer {
223         /// A pointer to the opaque Rust object.
224
225         /// Nearly everywhere, inner must be non-null, however in places where
226         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
227         pub inner: *mut nativeOffer,
228         /// Indicates that this is the only struct which contains the same pointer.
229
230         /// Rust functions which take ownership of an object provided via an argument require
231         /// this to be true and invalidate the object pointed to by inner.
232         pub is_owned: bool,
233 }
234
235 impl Drop for Offer {
236         fn drop(&mut self) {
237                 if self.is_owned && !<*mut nativeOffer>::is_null(self.inner) {
238                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
239                 }
240         }
241 }
242 /// Frees any resources used by the Offer, if is_owned is set and inner is non-NULL.
243 #[no_mangle]
244 pub extern "C" fn Offer_free(this_obj: Offer) { }
245 #[allow(unused)]
246 /// Used only if an object of this type is returned as a trait impl by a method
247 pub(crate) extern "C" fn Offer_free_void(this_ptr: *mut c_void) {
248         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOffer) };
249 }
250 #[allow(unused)]
251 impl Offer {
252         pub(crate) fn get_native_ref(&self) -> &'static nativeOffer {
253                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
254         }
255         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOffer {
256                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
257         }
258         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
259         pub(crate) fn take_inner(mut self) -> *mut nativeOffer {
260                 assert!(self.is_owned);
261                 let ret = ObjOps::untweak_ptr(self.inner);
262                 self.inner = core::ptr::null_mut();
263                 ret
264         }
265 }
266 impl Clone for Offer {
267         fn clone(&self) -> Self {
268                 Self {
269                         inner: if <*mut nativeOffer>::is_null(self.inner) { core::ptr::null_mut() } else {
270                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
271                         is_owned: true,
272                 }
273         }
274 }
275 #[allow(unused)]
276 /// Used only if an object of this type is returned as a trait impl by a method
277 pub(crate) extern "C" fn Offer_clone_void(this_ptr: *const c_void) -> *mut c_void {
278         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeOffer)).clone() })) as *mut c_void
279 }
280 #[no_mangle]
281 /// Creates a copy of the Offer
282 pub extern "C" fn Offer_clone(orig: &Offer) -> Offer {
283         orig.clone()
284 }
285 /// Get a string which allows debug introspection of a Offer object
286 pub extern "C" fn Offer_debug_str_void(o: *const c_void) -> Str {
287         alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Offer }).into()}
288 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
289 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
290 /// for the selected chain.
291 #[must_use]
292 #[no_mangle]
293 pub extern "C" fn Offer_chains(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_ThirtyTwoBytesZ {
294         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.chains();
295         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: *item.as_ref() } }); };
296         local_ret.into()
297 }
298
299 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
300 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
301 #[must_use]
302 #[no_mangle]
303 pub extern "C" fn Offer_metadata(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_CVec_u8ZZ {
304         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.metadata();
305         let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option<Enum> is otherwise un-expressable. */ { let mut local_ret_0 = Vec::new(); for mut item in (*ret.as_ref().unwrap()).clone().drain(..) { local_ret_0.push( { item }); }; local_ret_0.into() }) };
306         local_ret
307 }
308
309 /// The minimum amount required for a successful payment of a single item.
310 #[must_use]
311 #[no_mangle]
312 pub extern "C" fn Offer_amount(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_AmountZ {
313         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount();
314         let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_AmountZ::None } else { crate::c_types::derived::COption_AmountZ::Some( { crate::lightning::offers::offer::Amount::native_into(ret.unwrap()) }) };
315         local_ret
316 }
317
318 /// A complete description of the purpose of the payment. Intended to be displayed to the user
319 /// but with the caveat that it has not been verified in any way.
320 ///
321 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
322 #[must_use]
323 #[no_mangle]
324 pub extern "C" fn Offer_description(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
325         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description();
326         let mut local_ret = crate::lightning::util::string::PrintableString { inner: if ret.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true };
327         local_ret
328 }
329
330 /// Features pertaining to the offer.
331 #[must_use]
332 #[no_mangle]
333 pub extern "C" fn Offer_offer_features(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::ln::features::OfferFeatures {
334         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.offer_features();
335         crate::lightning::ln::features::OfferFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::ln::features::OfferFeatures<>) as *mut _) }, is_owned: false }
336 }
337
338 /// Duration since the Unix epoch when an invoice should no longer be requested.
339 ///
340 /// If `None`, the offer does not expire.
341 #[must_use]
342 #[no_mangle]
343 pub extern "C" fn Offer_absolute_expiry(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_u64Z {
344         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.absolute_expiry();
345         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().as_secs() }) };
346         local_ret
347 }
348
349 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
350 /// displayed to the user but with the caveat that it has not been verified in any way.
351 ///
352 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
353 #[must_use]
354 #[no_mangle]
355 pub extern "C" fn Offer_issuer(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
356         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.issuer();
357         let mut local_ret = crate::lightning::util::string::PrintableString { inner: if ret.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true };
358         local_ret
359 }
360
361 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
362 /// recipient privacy by obfuscating its node id.
363 #[must_use]
364 #[no_mangle]
365 pub extern "C" fn Offer_paths(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_BlindedPathZ {
366         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.paths();
367         let mut local_ret_clone = Vec::new(); local_ret_clone.extend_from_slice(ret); let mut ret = local_ret_clone; let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
368         local_ret.into()
369 }
370
371 /// The quantity of items supported.
372 #[must_use]
373 #[no_mangle]
374 pub extern "C" fn Offer_supported_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Quantity {
375         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supported_quantity();
376         crate::lightning::offers::offer::Quantity::native_into(ret)
377 }
378
379 /// The public key used by the recipient to sign invoices.
380 ///
381 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
382 #[must_use]
383 #[no_mangle]
384 pub extern "C" fn Offer_signing_pubkey(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::PublicKey {
385         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signing_pubkey();
386         let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else {  { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } };
387         local_ret
388 }
389
390 /// Returns the id of the offer.
391 #[must_use]
392 #[no_mangle]
393 pub extern "C" fn Offer_id(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::OfferId {
394         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.id();
395         crate::lightning::offers::offer::OfferId { inner: ObjOps::heap_alloc(ret), is_owned: true }
396 }
397
398 /// Returns whether the given chain is supported by the offer.
399 #[must_use]
400 #[no_mangle]
401 pub extern "C" fn Offer_supports_chain(this_arg: &crate::lightning::offers::offer::Offer, mut chain: crate::c_types::ThirtyTwoBytes) -> bool {
402         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_chain(::bitcoin::blockdata::constants::ChainHash::from(&chain.data));
403         ret
404 }
405
406 /// Whether the offer has expired.
407 #[must_use]
408 #[no_mangle]
409 pub extern "C" fn Offer_is_expired(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
410         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired();
411         ret
412 }
413
414 /// Whether the offer has expired given the duration since the Unix epoch.
415 #[must_use]
416 #[no_mangle]
417 pub extern "C" fn Offer_is_expired_no_std(this_arg: &crate::lightning::offers::offer::Offer, mut duration_since_epoch: u64) -> bool {
418         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired_no_std(core::time::Duration::from_secs(duration_since_epoch));
419         ret
420 }
421
422 /// Returns whether the given quantity is valid for the offer.
423 #[must_use]
424 #[no_mangle]
425 pub extern "C" fn Offer_is_valid_quantity(this_arg: &crate::lightning::offers::offer::Offer, mut quantity: u64) -> bool {
426         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_valid_quantity(quantity);
427         ret
428 }
429
430 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
431 ///
432 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
433 #[must_use]
434 #[no_mangle]
435 pub extern "C" fn Offer_expects_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
436         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expects_quantity();
437         ret
438 }
439
440 /// Similar to [`Offer::request_invoice`] except it:
441 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
442 ///   request,
443 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
444 ///   such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
445 ///   requested using a base [`ExpandedKey`] from which the payer id was derived, and
446 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
447 ///   be used when sending the payment for the requested invoice.
448 ///
449 /// Useful to protect the sender's privacy.
450 ///
451 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
452 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
453 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
454 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
455 #[must_use]
456 #[no_mangle]
457 pub extern "C" fn Offer_request_invoice_deriving_payer_id(this_arg: &crate::lightning::offers::offer::Offer, expanded_key: &crate::lightning::ln::inbound_payment::ExpandedKey, mut entropy_source: crate::lightning::sign::EntropySource, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_InvoiceRequestWithDerivedPayerIdBuilderBolt12SemanticErrorZ {
458         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice_deriving_payer_id(expanded_key.get_native_ref(), entropy_source, secp256k1::global::SECP256K1, ::lightning::ln::channelmanager::PaymentId(payment_id.data));
459         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithDerivedPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
460         local_ret
461 }
462
463 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
464 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
465 ///
466 /// Useful for recurring payments using the same `payer_id` with different invoices.
467 ///
468 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
469 #[must_use]
470 #[no_mangle]
471 pub extern "C" fn Offer_request_invoice_deriving_metadata(this_arg: &crate::lightning::offers::offer::Offer, mut payer_id: crate::c_types::PublicKey, expanded_key: &crate::lightning::ln::inbound_payment::ExpandedKey, mut entropy_source: crate::lightning::sign::EntropySource, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_InvoiceRequestWithExplicitPayerIdBuilderBolt12SemanticErrorZ {
472         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice_deriving_metadata(payer_id.into_rust(), expanded_key.get_native_ref(), entropy_source, ::lightning::ln::channelmanager::PaymentId(payment_id.data));
473         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithExplicitPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
474         local_ret
475 }
476
477 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
478 /// which will be reflected in the `Bolt12Invoice` response.
479 ///
480 /// The `metadata` is useful for including information about the derivation of `payer_id` such
481 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
482 /// hashing in the signature calculation.
483 ///
484 /// This should not leak any information such as by using a simple BIP-32 derivation path.
485 /// Otherwise, payments may be correlated.
486 ///
487 /// Errors if the offer contains unknown required features.
488 ///
489 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
490 #[must_use]
491 #[no_mangle]
492 pub extern "C" fn Offer_request_invoice(this_arg: &crate::lightning::offers::offer::Offer, mut metadata: crate::c_types::derived::CVec_u8Z, mut payer_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_InvoiceRequestWithExplicitPayerIdBuilderBolt12SemanticErrorZ {
493         let mut local_metadata = Vec::new(); for mut item in metadata.into_rust().drain(..) { local_metadata.push( { item }); };
494         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_invoice(local_metadata, payer_id.into_rust());
495         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice_request::InvoiceRequestWithExplicitPayerIdBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
496         local_ret
497 }
498
499 /// Generates a non-cryptographic 64-bit hash of the Offer.
500 #[no_mangle]
501 pub extern "C" fn Offer_hash(o: &Offer) -> u64 {
502         if o.inner.is_null() { return 0; }
503         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
504         #[allow(deprecated)]
505         let mut hasher = core::hash::SipHasher::new();
506         core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
507         core::hash::Hasher::finish(&hasher)
508 }
509 #[no_mangle]
510 /// Serialize the Offer object into a byte array which can be read by Offer_read
511 pub extern "C" fn Offer_write(obj: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_u8Z {
512         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
513 }
514 #[allow(unused)]
515 pub(crate) extern "C" fn Offer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
516         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOffer) })
517 }
518 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
519 /// another currency.
520 #[derive(Clone)]
521 #[must_use]
522 #[repr(C)]
523 pub enum Amount {
524         /// An amount of bitcoin.
525         Bitcoin {
526                 /// The amount in millisatoshi.
527                 amount_msats: u64,
528         },
529         /// An amount of currency specified using ISO 4712.
530         Currency {
531                 /// The currency that the amount is denominated in.
532                 iso4217_code: crate::c_types::ThreeBytes,
533                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
534                 amount: u64,
535         },
536 }
537 use lightning::offers::offer::Amount as AmountImport;
538 pub(crate) type nativeAmount = AmountImport;
539
540 impl Amount {
541         #[allow(unused)]
542         pub(crate) fn to_native(&self) -> nativeAmount {
543                 match self {
544                         Amount::Bitcoin {ref amount_msats, } => {
545                                 let mut amount_msats_nonref = Clone::clone(amount_msats);
546                                 nativeAmount::Bitcoin {
547                                         amount_msats: amount_msats_nonref,
548                                 }
549                         },
550                         Amount::Currency {ref iso4217_code, ref amount, } => {
551                                 let mut iso4217_code_nonref = Clone::clone(iso4217_code);
552                                 let mut amount_nonref = Clone::clone(amount);
553                                 nativeAmount::Currency {
554                                         iso4217_code: iso4217_code_nonref.data,
555                                         amount: amount_nonref,
556                                 }
557                         },
558                 }
559         }
560         #[allow(unused)]
561         pub(crate) fn into_native(self) -> nativeAmount {
562                 match self {
563                         Amount::Bitcoin {mut amount_msats, } => {
564                                 nativeAmount::Bitcoin {
565                                         amount_msats: amount_msats,
566                                 }
567                         },
568                         Amount::Currency {mut iso4217_code, mut amount, } => {
569                                 nativeAmount::Currency {
570                                         iso4217_code: iso4217_code.data,
571                                         amount: amount,
572                                 }
573                         },
574                 }
575         }
576         #[allow(unused)]
577         pub(crate) fn from_native(native: &AmountImport) -> Self {
578                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeAmount) };
579                 match native {
580                         nativeAmount::Bitcoin {ref amount_msats, } => {
581                                 let mut amount_msats_nonref = Clone::clone(amount_msats);
582                                 Amount::Bitcoin {
583                                         amount_msats: amount_msats_nonref,
584                                 }
585                         },
586                         nativeAmount::Currency {ref iso4217_code, ref amount, } => {
587                                 let mut iso4217_code_nonref = Clone::clone(iso4217_code);
588                                 let mut amount_nonref = Clone::clone(amount);
589                                 Amount::Currency {
590                                         iso4217_code: crate::c_types::ThreeBytes { data: iso4217_code_nonref },
591                                         amount: amount_nonref,
592                                 }
593                         },
594                 }
595         }
596         #[allow(unused)]
597         pub(crate) fn native_into(native: nativeAmount) -> Self {
598                 match native {
599                         nativeAmount::Bitcoin {mut amount_msats, } => {
600                                 Amount::Bitcoin {
601                                         amount_msats: amount_msats,
602                                 }
603                         },
604                         nativeAmount::Currency {mut iso4217_code, mut amount, } => {
605                                 Amount::Currency {
606                                         iso4217_code: crate::c_types::ThreeBytes { data: iso4217_code },
607                                         amount: amount,
608                                 }
609                         },
610                 }
611         }
612 }
613 /// Frees any resources used by the Amount
614 #[no_mangle]
615 pub extern "C" fn Amount_free(this_ptr: Amount) { }
616 /// Creates a copy of the Amount
617 #[no_mangle]
618 pub extern "C" fn Amount_clone(orig: &Amount) -> Amount {
619         orig.clone()
620 }
621 #[allow(unused)]
622 /// Used only if an object of this type is returned as a trait impl by a method
623 pub(crate) extern "C" fn Amount_clone_void(this_ptr: *const c_void) -> *mut c_void {
624         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Amount)).clone() })) as *mut c_void
625 }
626 #[allow(unused)]
627 /// Used only if an object of this type is returned as a trait impl by a method
628 pub(crate) extern "C" fn Amount_free_void(this_ptr: *mut c_void) {
629         let _ = unsafe { Box::from_raw(this_ptr as *mut Amount) };
630 }
631 #[no_mangle]
632 /// Utility method to constructs a new Bitcoin-variant Amount
633 pub extern "C" fn Amount_bitcoin(amount_msats: u64) -> Amount {
634         Amount::Bitcoin {
635                 amount_msats,
636         }
637 }
638 #[no_mangle]
639 /// Utility method to constructs a new Currency-variant Amount
640 pub extern "C" fn Amount_currency(iso4217_code: crate::c_types::ThreeBytes, amount: u64) -> Amount {
641         Amount::Currency {
642                 iso4217_code,
643                 amount,
644         }
645 }
646 /// Get a string which allows debug introspection of a Amount object
647 pub extern "C" fn Amount_debug_str_void(o: *const c_void) -> Str {
648         alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Amount }).into()}
649 /// Quantity of items supported by an [`Offer`].
650 #[derive(Clone)]
651 #[must_use]
652 #[repr(C)]
653 pub enum Quantity {
654         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
655         /// but is limited (e.g., because of per customer or inventory limits).
656         ///
657         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
658         /// is supported.
659         Bounded(
660                 u64),
661         /// One or more items. Use when more than one item can be requested without any limit.
662         Unbounded,
663         /// Only one item. Use when only a single item can be requested.
664         One,
665 }
666 use lightning::offers::offer::Quantity as QuantityImport;
667 pub(crate) type nativeQuantity = QuantityImport;
668
669 impl Quantity {
670         #[allow(unused)]
671         pub(crate) fn to_native(&self) -> nativeQuantity {
672                 match self {
673                         Quantity::Bounded (ref a, ) => {
674                                 let mut a_nonref = Clone::clone(a);
675                                 nativeQuantity::Bounded (
676                                         core::num::NonZeroU64::new(a_nonref).expect("Value must be non-zero"),
677                                 )
678                         },
679                         Quantity::Unbounded => nativeQuantity::Unbounded,
680                         Quantity::One => nativeQuantity::One,
681                 }
682         }
683         #[allow(unused)]
684         pub(crate) fn into_native(self) -> nativeQuantity {
685                 match self {
686                         Quantity::Bounded (mut a, ) => {
687                                 nativeQuantity::Bounded (
688                                         core::num::NonZeroU64::new(a).expect("Value must be non-zero"),
689                                 )
690                         },
691                         Quantity::Unbounded => nativeQuantity::Unbounded,
692                         Quantity::One => nativeQuantity::One,
693                 }
694         }
695         #[allow(unused)]
696         pub(crate) fn from_native(native: &QuantityImport) -> Self {
697                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeQuantity) };
698                 match native {
699                         nativeQuantity::Bounded (ref a, ) => {
700                                 let mut a_nonref = Clone::clone(a);
701                                 Quantity::Bounded (
702                                         a_nonref.into(),
703                                 )
704                         },
705                         nativeQuantity::Unbounded => Quantity::Unbounded,
706                         nativeQuantity::One => Quantity::One,
707                 }
708         }
709         #[allow(unused)]
710         pub(crate) fn native_into(native: nativeQuantity) -> Self {
711                 match native {
712                         nativeQuantity::Bounded (mut a, ) => {
713                                 Quantity::Bounded (
714                                         a.into(),
715                                 )
716                         },
717                         nativeQuantity::Unbounded => Quantity::Unbounded,
718                         nativeQuantity::One => Quantity::One,
719                 }
720         }
721 }
722 /// Frees any resources used by the Quantity
723 #[no_mangle]
724 pub extern "C" fn Quantity_free(this_ptr: Quantity) { }
725 /// Creates a copy of the Quantity
726 #[no_mangle]
727 pub extern "C" fn Quantity_clone(orig: &Quantity) -> Quantity {
728         orig.clone()
729 }
730 #[allow(unused)]
731 /// Used only if an object of this type is returned as a trait impl by a method
732 pub(crate) extern "C" fn Quantity_clone_void(this_ptr: *const c_void) -> *mut c_void {
733         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Quantity)).clone() })) as *mut c_void
734 }
735 #[allow(unused)]
736 /// Used only if an object of this type is returned as a trait impl by a method
737 pub(crate) extern "C" fn Quantity_free_void(this_ptr: *mut c_void) {
738         let _ = unsafe { Box::from_raw(this_ptr as *mut Quantity) };
739 }
740 #[no_mangle]
741 /// Utility method to constructs a new Bounded-variant Quantity
742 pub extern "C" fn Quantity_bounded(a: u64) -> Quantity {
743         Quantity::Bounded(a, )
744 }
745 #[no_mangle]
746 /// Utility method to constructs a new Unbounded-variant Quantity
747 pub extern "C" fn Quantity_unbounded() -> Quantity {
748         Quantity::Unbounded}
749 #[no_mangle]
750 /// Utility method to constructs a new One-variant Quantity
751 pub extern "C" fn Quantity_one() -> Quantity {
752         Quantity::One}
753 /// Get a string which allows debug introspection of a Quantity object
754 pub extern "C" fn Quantity_debug_str_void(o: *const c_void) -> Str {
755         alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Quantity }).into()}
756 #[no_mangle]
757 /// Read a Offer object from a string
758 pub extern "C" fn Offer_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_OfferBolt12ParseErrorZ {
759         match lightning::offers::offer::Offer::from_str(s.into_str()) {
760                 Ok(r) => {
761                         crate::c_types::CResultTempl::ok(
762                                 crate::lightning::offers::offer::Offer { inner: ObjOps::heap_alloc(r), is_owned: true }
763                         )
764                 },
765                 Err(e) => {
766                         crate::c_types::CResultTempl::err(
767                                 crate::lightning::offers::parse::Bolt12ParseError { inner: ObjOps::heap_alloc(e), is_owned: true }
768                         )
769                 },
770         }.into()
771 }