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