Update auto-generated bindings
[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 //! ```
16 //! extern crate bitcoin;
17 //! extern crate core;
18 //! extern crate lightning;
19 //!
20 //! use core::convert::TryFrom;
21 //! use core::num::NonZeroU64;
22 //! use core::time::Duration;
23 //!
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
26 //! use lightning::offers::parse::Bolt12ParseError;
27 //! use lightning::util::ser::{Readable, Writeable};
28 //!
29 //! # use lightning::blinded_path::BlindedPath;
30 //! # #[cfg(feature = \"std\")]
31 //! # use std::time::SystemTime;
32 //! #
33 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
34 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
35 //! #
36 //! # #[cfg(feature = \"std\")]
37 //! # fn build() -> Result<(), Bolt12ParseError> {
38 //! let secp_ctx = Secp256k1::new();
39 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
40 //! let pubkey = PublicKey::from(keys);
41 //!
42 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
43 //! let offer = OfferBuilder::new(\"coffee, large\".to_string(), pubkey)
44 //!     .amount_msats(20_000)
45 //!     .supported_quantity(Quantity::Unbounded)
46 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
47 //!     .issuer(\"Foo Bar\".to_string())
48 //!     .path(create_blinded_path())
49 //!     .path(create_another_blinded_path())
50 //!     .build()?;
51 //!
52 //! // Encode as a bech32 string for use in a QR code.
53 //! let encoded_offer = offer.to_string();
54 //!
55 //! // Parse from a bech32 string after scanning from a QR code.
56 //! let offer = encoded_offer.parse::<Offer>()?;
57 //!
58 //! // Encode offer as raw bytes.
59 //! let mut bytes = Vec::new();
60 //! offer.write(&mut bytes).unwrap();
61 //!
62 //! // Decode raw bytes into an offer.
63 //! let offer = Offer::try_from(bytes)?;
64 //! # Ok(())
65 //! # }
66 //! ```
67
68 use alloc::str::FromStr;
69 use alloc::string::String;
70 use core::ffi::c_void;
71 use core::convert::Infallible;
72 use bitcoin::hashes::Hash;
73 use crate::c_types::*;
74 #[cfg(feature="no-std")]
75 use alloc::{vec::Vec, boxed::Box};
76
77
78 use lightning::offers::offer::Offer as nativeOfferImport;
79 pub(crate) type nativeOffer = nativeOfferImport;
80
81 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
82 ///
83 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
84 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
85 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
86 ///
87 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
88 /// latter.
89 ///
90 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
91 ///
92 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
93 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
94 #[must_use]
95 #[repr(C)]
96 pub struct Offer {
97         /// A pointer to the opaque Rust object.
98
99         /// Nearly everywhere, inner must be non-null, however in places where
100         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
101         pub inner: *mut nativeOffer,
102         /// Indicates that this is the only struct which contains the same pointer.
103
104         /// Rust functions which take ownership of an object provided via an argument require
105         /// this to be true and invalidate the object pointed to by inner.
106         pub is_owned: bool,
107 }
108
109 impl Drop for Offer {
110         fn drop(&mut self) {
111                 if self.is_owned && !<*mut nativeOffer>::is_null(self.inner) {
112                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
113                 }
114         }
115 }
116 /// Frees any resources used by the Offer, if is_owned is set and inner is non-NULL.
117 #[no_mangle]
118 pub extern "C" fn Offer_free(this_obj: Offer) { }
119 #[allow(unused)]
120 /// Used only if an object of this type is returned as a trait impl by a method
121 pub(crate) extern "C" fn Offer_free_void(this_ptr: *mut c_void) {
122         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOffer) };
123 }
124 #[allow(unused)]
125 impl Offer {
126         pub(crate) fn get_native_ref(&self) -> &'static nativeOffer {
127                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
128         }
129         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOffer {
130                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
131         }
132         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
133         pub(crate) fn take_inner(mut self) -> *mut nativeOffer {
134                 assert!(self.is_owned);
135                 let ret = ObjOps::untweak_ptr(self.inner);
136                 self.inner = core::ptr::null_mut();
137                 ret
138         }
139 }
140 impl Clone for Offer {
141         fn clone(&self) -> Self {
142                 Self {
143                         inner: if <*mut nativeOffer>::is_null(self.inner) { core::ptr::null_mut() } else {
144                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
145                         is_owned: true,
146                 }
147         }
148 }
149 #[allow(unused)]
150 /// Used only if an object of this type is returned as a trait impl by a method
151 pub(crate) extern "C" fn Offer_clone_void(this_ptr: *const c_void) -> *mut c_void {
152         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeOffer)).clone() })) as *mut c_void
153 }
154 #[no_mangle]
155 /// Creates a copy of the Offer
156 pub extern "C" fn Offer_clone(orig: &Offer) -> Offer {
157         orig.clone()
158 }
159 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
160 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
161 /// for the selected chain.
162 #[must_use]
163 #[no_mangle]
164 pub extern "C" fn Offer_chains(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_ThirtyTwoBytesZ {
165         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.chains();
166         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.to_bytes() } }); };
167         local_ret.into()
168 }
169
170 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
171 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
172 #[must_use]
173 #[no_mangle]
174 pub extern "C" fn Offer_metadata(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_CVec_u8ZZ {
175         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.metadata();
176         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() }) };
177         local_ret
178 }
179
180 /// The minimum amount required for a successful payment of a single item.
181 ///
182 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
183 #[must_use]
184 #[no_mangle]
185 pub extern "C" fn Offer_amount(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Amount {
186         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount();
187         let mut local_ret = crate::lightning::offers::offer::Amount { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning::offers::offer::Amount<>) as *mut _ }, is_owned: false };
188         local_ret
189 }
190
191 /// A complete description of the purpose of the payment. Intended to be displayed to the user
192 /// but with the caveat that it has not been verified in any way.
193 #[must_use]
194 #[no_mangle]
195 pub extern "C" fn Offer_description(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
196         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description();
197         crate::lightning::util::string::PrintableString { inner: ObjOps::heap_alloc(ret), is_owned: true }
198 }
199
200 /// Features pertaining to the offer.
201 #[must_use]
202 #[no_mangle]
203 pub extern "C" fn Offer_offer_features(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::ln::features::OfferFeatures {
204         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.offer_features();
205         crate::lightning::ln::features::OfferFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::ln::features::OfferFeatures<>) as *mut _) }, is_owned: false }
206 }
207
208 /// Duration since the Unix epoch when an invoice should no longer be requested.
209 ///
210 /// If `None`, the offer does not expire.
211 #[must_use]
212 #[no_mangle]
213 pub extern "C" fn Offer_absolute_expiry(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_u64Z {
214         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.absolute_expiry();
215         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() }) };
216         local_ret
217 }
218
219 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
220 /// displayed to the user but with the caveat that it has not been verified in any way.
221 ///
222 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
223 #[must_use]
224 #[no_mangle]
225 pub extern "C" fn Offer_issuer(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
226         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.issuer();
227         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 };
228         local_ret
229 }
230
231 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
232 /// recipient privacy by obfuscating its node id.
233 #[must_use]
234 #[no_mangle]
235 pub extern "C" fn Offer_paths(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_BlindedPathZ {
236         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.paths();
237         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 } }); };
238         local_ret.into()
239 }
240
241 /// The quantity of items supported.
242 #[must_use]
243 #[no_mangle]
244 pub extern "C" fn Offer_supported_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Quantity {
245         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supported_quantity();
246         crate::lightning::offers::offer::Quantity { inner: ObjOps::heap_alloc(ret), is_owned: true }
247 }
248
249 /// The public key used by the recipient to sign invoices.
250 #[must_use]
251 #[no_mangle]
252 pub extern "C" fn Offer_signing_pubkey(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::PublicKey {
253         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signing_pubkey();
254         crate::c_types::PublicKey::from_rust(&ret)
255 }
256
257 /// Returns whether the given chain is supported by the offer.
258 #[must_use]
259 #[no_mangle]
260 pub extern "C" fn Offer_supports_chain(this_arg: &crate::lightning::offers::offer::Offer, mut chain: crate::c_types::ThirtyTwoBytes) -> bool {
261         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_chain(::bitcoin::blockdata::constants::ChainHash::from(&chain.data[..]));
262         ret
263 }
264
265 /// Whether the offer has expired.
266 #[must_use]
267 #[no_mangle]
268 pub extern "C" fn Offer_is_expired(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
269         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired();
270         ret
271 }
272
273 /// Returns whether the given quantity is valid for the offer.
274 #[must_use]
275 #[no_mangle]
276 pub extern "C" fn Offer_is_valid_quantity(this_arg: &crate::lightning::offers::offer::Offer, mut quantity: u64) -> bool {
277         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_valid_quantity(quantity);
278         ret
279 }
280
281 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
282 ///
283 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
284 #[must_use]
285 #[no_mangle]
286 pub extern "C" fn Offer_expects_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
287         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expects_quantity();
288         ret
289 }
290
291 #[no_mangle]
292 /// Serialize the Offer object into a byte array which can be read by Offer_read
293 pub extern "C" fn Offer_write(obj: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_u8Z {
294         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
295 }
296 #[no_mangle]
297 pub(crate) extern "C" fn Offer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
298         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOffer) })
299 }
300
301 use lightning::offers::offer::Amount as nativeAmountImport;
302 pub(crate) type nativeAmount = nativeAmountImport;
303
304 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
305 /// another currency.
306 #[must_use]
307 #[repr(C)]
308 pub struct Amount {
309         /// A pointer to the opaque Rust object.
310
311         /// Nearly everywhere, inner must be non-null, however in places where
312         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
313         pub inner: *mut nativeAmount,
314         /// Indicates that this is the only struct which contains the same pointer.
315
316         /// Rust functions which take ownership of an object provided via an argument require
317         /// this to be true and invalidate the object pointed to by inner.
318         pub is_owned: bool,
319 }
320
321 impl Drop for Amount {
322         fn drop(&mut self) {
323                 if self.is_owned && !<*mut nativeAmount>::is_null(self.inner) {
324                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
325                 }
326         }
327 }
328 /// Frees any resources used by the Amount, if is_owned is set and inner is non-NULL.
329 #[no_mangle]
330 pub extern "C" fn Amount_free(this_obj: Amount) { }
331 #[allow(unused)]
332 /// Used only if an object of this type is returned as a trait impl by a method
333 pub(crate) extern "C" fn Amount_free_void(this_ptr: *mut c_void) {
334         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeAmount) };
335 }
336 #[allow(unused)]
337 impl Amount {
338         pub(crate) fn get_native_ref(&self) -> &'static nativeAmount {
339                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
340         }
341         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeAmount {
342                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
343         }
344         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
345         pub(crate) fn take_inner(mut self) -> *mut nativeAmount {
346                 assert!(self.is_owned);
347                 let ret = ObjOps::untweak_ptr(self.inner);
348                 self.inner = core::ptr::null_mut();
349                 ret
350         }
351 }
352 impl Clone for Amount {
353         fn clone(&self) -> Self {
354                 Self {
355                         inner: if <*mut nativeAmount>::is_null(self.inner) { core::ptr::null_mut() } else {
356                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
357                         is_owned: true,
358                 }
359         }
360 }
361 #[allow(unused)]
362 /// Used only if an object of this type is returned as a trait impl by a method
363 pub(crate) extern "C" fn Amount_clone_void(this_ptr: *const c_void) -> *mut c_void {
364         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeAmount)).clone() })) as *mut c_void
365 }
366 #[no_mangle]
367 /// Creates a copy of the Amount
368 pub extern "C" fn Amount_clone(orig: &Amount) -> Amount {
369         orig.clone()
370 }
371
372 use lightning::offers::offer::Quantity as nativeQuantityImport;
373 pub(crate) type nativeQuantity = nativeQuantityImport;
374
375 /// Quantity of items supported by an [`Offer`].
376 #[must_use]
377 #[repr(C)]
378 pub struct Quantity {
379         /// A pointer to the opaque Rust object.
380
381         /// Nearly everywhere, inner must be non-null, however in places where
382         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
383         pub inner: *mut nativeQuantity,
384         /// Indicates that this is the only struct which contains the same pointer.
385
386         /// Rust functions which take ownership of an object provided via an argument require
387         /// this to be true and invalidate the object pointed to by inner.
388         pub is_owned: bool,
389 }
390
391 impl Drop for Quantity {
392         fn drop(&mut self) {
393                 if self.is_owned && !<*mut nativeQuantity>::is_null(self.inner) {
394                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
395                 }
396         }
397 }
398 /// Frees any resources used by the Quantity, if is_owned is set and inner is non-NULL.
399 #[no_mangle]
400 pub extern "C" fn Quantity_free(this_obj: Quantity) { }
401 #[allow(unused)]
402 /// Used only if an object of this type is returned as a trait impl by a method
403 pub(crate) extern "C" fn Quantity_free_void(this_ptr: *mut c_void) {
404         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeQuantity) };
405 }
406 #[allow(unused)]
407 impl Quantity {
408         pub(crate) fn get_native_ref(&self) -> &'static nativeQuantity {
409                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
410         }
411         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeQuantity {
412                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
413         }
414         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
415         pub(crate) fn take_inner(mut self) -> *mut nativeQuantity {
416                 assert!(self.is_owned);
417                 let ret = ObjOps::untweak_ptr(self.inner);
418                 self.inner = core::ptr::null_mut();
419                 ret
420         }
421 }
422 impl Clone for Quantity {
423         fn clone(&self) -> Self {
424                 Self {
425                         inner: if <*mut nativeQuantity>::is_null(self.inner) { core::ptr::null_mut() } else {
426                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
427                         is_owned: true,
428                 }
429         }
430 }
431 #[allow(unused)]
432 /// Used only if an object of this type is returned as a trait impl by a method
433 pub(crate) extern "C" fn Quantity_clone_void(this_ptr: *const c_void) -> *mut c_void {
434         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeQuantity)).clone() })) as *mut c_void
435 }
436 #[no_mangle]
437 /// Creates a copy of the Quantity
438 pub extern "C" fn Quantity_clone(orig: &Quantity) -> Quantity {
439         orig.clone()
440 }
441 #[no_mangle]
442 /// Read a Offer object from a string
443 pub extern "C" fn Offer_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_OfferBolt12ParseErrorZ {
444         match lightning::offers::offer::Offer::from_str(s.into_str()) {
445                 Ok(r) => {
446                         crate::c_types::CResultTempl::ok(
447                                 crate::lightning::offers::offer::Offer { inner: ObjOps::heap_alloc(r), is_owned: true }
448                         )
449                 },
450                 Err(e) => {
451                         crate::c_types::CResultTempl::err(
452                                 crate::lightning::offers::parse::Bolt12ParseError { inner: ObjOps::heap_alloc(e), is_owned: true }
453                         )
454                 },
455         }.into()
456 }