1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
9 //! Data structures and encoding for `offer` messages.
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.
18 //! extern crate bitcoin;
19 //! extern crate core;
20 //! extern crate lightning;
22 //! use core::convert::TryFrom;
23 //! use core::num::NonZeroU64;
24 //! use core::time::Duration;
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};
31 //! # use lightning::blinded_path::BlindedPath;
32 //! # #[cfg(feature = \"std\")]
33 //! # use std::time::SystemTime;
35 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
36 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
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);
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())
54 //! // Encode as a bech32 string for use in a QR code.
55 //! let encoded_offer = offer.to_string();
57 //! // Parse from a bech32 string after scanning from a QR code.
58 //! let offer = encoded_offer.parse::<Offer>()?;
60 //! // Encode offer as raw bytes.
61 //! let mut bytes = Vec::new();
62 //! offer.write(&mut bytes).unwrap();
64 //! // Decode raw bytes into an offer.
65 //! let offer = Offer::try_from(bytes)?;
72 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
73 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
75 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
76 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
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};
88 use lightning::offers::offer::Offer as nativeOfferImport;
89 pub(crate) type nativeOffer = nativeOfferImport;
91 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
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`].
97 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
100 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
102 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
103 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
107 /// A pointer to the opaque Rust object.
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.
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.
119 impl Drop for Offer {
121 if self.is_owned && !<*mut nativeOffer>::is_null(self.inner) {
122 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
126 /// Frees any resources used by the Offer, if is_owned is set and inner is non-NULL.
128 pub extern "C" fn Offer_free(this_obj: Offer) { }
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) };
136 pub(crate) fn get_native_ref(&self) -> &'static nativeOffer {
137 unsafe { &*ObjOps::untweak_ptr(self.inner) }
139 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOffer {
140 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
150 impl Clone for Offer {
151 fn clone(&self) -> 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()) },
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
165 /// Creates a copy of the Offer
166 pub extern "C" fn Offer_clone(orig: &Offer) -> Offer {
169 /// Get a string which allows debug introspection of a Offer object
170 pub extern "C" fn Offer_debug_str_void(o: *const c_void) -> Str {
171 alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Offer }).into()}
172 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
173 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
174 /// for the selected chain.
177 pub extern "C" fn Offer_chains(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_ThirtyTwoBytesZ {
178 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.chains();
179 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: *item.as_ref() } }); };
183 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
184 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
187 pub extern "C" fn Offer_metadata(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_CVec_u8ZZ {
188 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.metadata();
189 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() }) };
193 /// The minimum amount required for a successful payment of a single item.
195 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
198 pub extern "C" fn Offer_amount(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Amount {
199 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount();
200 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 };
204 /// A complete description of the purpose of the payment. Intended to be displayed to the user
205 /// but with the caveat that it has not been verified in any way.
208 pub extern "C" fn Offer_description(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
209 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description();
210 crate::lightning::util::string::PrintableString { inner: ObjOps::heap_alloc(ret), is_owned: true }
213 /// Features pertaining to the offer.
216 pub extern "C" fn Offer_offer_features(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::ln::features::OfferFeatures {
217 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.offer_features();
218 crate::lightning::ln::features::OfferFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::ln::features::OfferFeatures<>) as *mut _) }, is_owned: false }
221 /// Duration since the Unix epoch when an invoice should no longer be requested.
223 /// If `None`, the offer does not expire.
226 pub extern "C" fn Offer_absolute_expiry(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::COption_u64Z {
227 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.absolute_expiry();
228 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() }) };
232 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
233 /// displayed to the user but with the caveat that it has not been verified in any way.
235 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
238 pub extern "C" fn Offer_issuer(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::util::string::PrintableString {
239 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.issuer();
240 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 };
244 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
245 /// recipient privacy by obfuscating its node id.
248 pub extern "C" fn Offer_paths(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_BlindedPathZ {
249 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.paths();
250 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 } }); };
254 /// The quantity of items supported.
257 pub extern "C" fn Offer_supported_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> crate::lightning::offers::offer::Quantity {
258 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supported_quantity();
259 crate::lightning::offers::offer::Quantity { inner: ObjOps::heap_alloc(ret), is_owned: true }
262 /// The public key used by the recipient to sign invoices.
265 pub extern "C" fn Offer_signing_pubkey(this_arg: &crate::lightning::offers::offer::Offer) -> crate::c_types::PublicKey {
266 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signing_pubkey();
267 crate::c_types::PublicKey::from_rust(&ret)
270 /// Returns whether the given chain is supported by the offer.
273 pub extern "C" fn Offer_supports_chain(this_arg: &crate::lightning::offers::offer::Offer, mut chain: crate::c_types::ThirtyTwoBytes) -> bool {
274 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_chain(::bitcoin::blockdata::constants::ChainHash::from(&chain.data));
278 /// Whether the offer has expired.
281 pub extern "C" fn Offer_is_expired(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
282 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired();
286 /// Whether the offer has expired given the duration since the Unix epoch.
289 pub extern "C" fn Offer_is_expired_no_std(this_arg: &crate::lightning::offers::offer::Offer, mut duration_since_epoch: u64) -> bool {
290 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired_no_std(core::time::Duration::from_secs(duration_since_epoch));
294 /// Returns whether the given quantity is valid for the offer.
297 pub extern "C" fn Offer_is_valid_quantity(this_arg: &crate::lightning::offers::offer::Offer, mut quantity: u64) -> bool {
298 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_valid_quantity(quantity);
302 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
304 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
307 pub extern "C" fn Offer_expects_quantity(this_arg: &crate::lightning::offers::offer::Offer) -> bool {
308 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expects_quantity();
313 /// Serialize the Offer object into a byte array which can be read by Offer_read
314 pub extern "C" fn Offer_write(obj: &crate::lightning::offers::offer::Offer) -> crate::c_types::derived::CVec_u8Z {
315 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
318 pub(crate) extern "C" fn Offer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
319 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOffer) })
322 use lightning::offers::offer::Amount as nativeAmountImport;
323 pub(crate) type nativeAmount = nativeAmountImport;
325 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
326 /// another currency.
330 /// A pointer to the opaque Rust object.
332 /// Nearly everywhere, inner must be non-null, however in places where
333 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
334 pub inner: *mut nativeAmount,
335 /// Indicates that this is the only struct which contains the same pointer.
337 /// Rust functions which take ownership of an object provided via an argument require
338 /// this to be true and invalidate the object pointed to by inner.
342 impl Drop for Amount {
344 if self.is_owned && !<*mut nativeAmount>::is_null(self.inner) {
345 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
349 /// Frees any resources used by the Amount, if is_owned is set and inner is non-NULL.
351 pub extern "C" fn Amount_free(this_obj: Amount) { }
353 /// Used only if an object of this type is returned as a trait impl by a method
354 pub(crate) extern "C" fn Amount_free_void(this_ptr: *mut c_void) {
355 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeAmount) };
359 pub(crate) fn get_native_ref(&self) -> &'static nativeAmount {
360 unsafe { &*ObjOps::untweak_ptr(self.inner) }
362 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeAmount {
363 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
365 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
366 pub(crate) fn take_inner(mut self) -> *mut nativeAmount {
367 assert!(self.is_owned);
368 let ret = ObjOps::untweak_ptr(self.inner);
369 self.inner = core::ptr::null_mut();
373 impl Clone for Amount {
374 fn clone(&self) -> Self {
376 inner: if <*mut nativeAmount>::is_null(self.inner) { core::ptr::null_mut() } else {
377 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
383 /// Used only if an object of this type is returned as a trait impl by a method
384 pub(crate) extern "C" fn Amount_clone_void(this_ptr: *const c_void) -> *mut c_void {
385 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeAmount)).clone() })) as *mut c_void
388 /// Creates a copy of the Amount
389 pub extern "C" fn Amount_clone(orig: &Amount) -> Amount {
392 /// Get a string which allows debug introspection of a Amount object
393 pub extern "C" fn Amount_debug_str_void(o: *const c_void) -> Str {
394 alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Amount }).into()}
396 use lightning::offers::offer::Quantity as nativeQuantityImport;
397 pub(crate) type nativeQuantity = nativeQuantityImport;
399 /// Quantity of items supported by an [`Offer`].
402 pub struct Quantity {
403 /// A pointer to the opaque Rust object.
405 /// Nearly everywhere, inner must be non-null, however in places where
406 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
407 pub inner: *mut nativeQuantity,
408 /// Indicates that this is the only struct which contains the same pointer.
410 /// Rust functions which take ownership of an object provided via an argument require
411 /// this to be true and invalidate the object pointed to by inner.
415 impl Drop for Quantity {
417 if self.is_owned && !<*mut nativeQuantity>::is_null(self.inner) {
418 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
422 /// Frees any resources used by the Quantity, if is_owned is set and inner is non-NULL.
424 pub extern "C" fn Quantity_free(this_obj: Quantity) { }
426 /// Used only if an object of this type is returned as a trait impl by a method
427 pub(crate) extern "C" fn Quantity_free_void(this_ptr: *mut c_void) {
428 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeQuantity) };
432 pub(crate) fn get_native_ref(&self) -> &'static nativeQuantity {
433 unsafe { &*ObjOps::untweak_ptr(self.inner) }
435 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeQuantity {
436 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
438 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
439 pub(crate) fn take_inner(mut self) -> *mut nativeQuantity {
440 assert!(self.is_owned);
441 let ret = ObjOps::untweak_ptr(self.inner);
442 self.inner = core::ptr::null_mut();
446 impl Clone for Quantity {
447 fn clone(&self) -> Self {
449 inner: if <*mut nativeQuantity>::is_null(self.inner) { core::ptr::null_mut() } else {
450 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
456 /// Used only if an object of this type is returned as a trait impl by a method
457 pub(crate) extern "C" fn Quantity_clone_void(this_ptr: *const c_void) -> *mut c_void {
458 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeQuantity)).clone() })) as *mut c_void
461 /// Creates a copy of the Quantity
462 pub extern "C" fn Quantity_clone(orig: &Quantity) -> Quantity {
465 /// Get a string which allows debug introspection of a Quantity object
466 pub extern "C" fn Quantity_debug_str_void(o: *const c_void) -> Str {
467 alloc::format!("{:?}", unsafe { o as *const crate::lightning::offers::offer::Quantity }).into()}
469 /// Read a Offer object from a string
470 pub extern "C" fn Offer_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_OfferBolt12ParseErrorZ {
471 match lightning::offers::offer::Offer::from_str(s.into_str()) {
473 crate::c_types::CResultTempl::ok(
474 crate::lightning::offers::offer::Offer { inner: ObjOps::heap_alloc(r), is_owned: true }
478 crate::c_types::CResultTempl::err(
479 crate::lightning::offers::parse::Bolt12ParseError { inner: ObjOps::heap_alloc(e), is_owned: true }