X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-c-bindings;a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning_invoice%2Fmod.rs;h=4afdd97ce0f8d46734a9baaaad527c3ac519b1b6;hp=ef1bb7b4672a0bfea4de67777cb0763a99147627;hb=4e715a943a67a3c846cc8af185b59cb24a4e8ae2;hpb=fb566be33e2ef66027d0ad3323b284a0435ec494 diff --git a/lightning-c-bindings/src/lightning_invoice/mod.rs b/lightning-c-bindings/src/lightning_invoice/mod.rs index ef1bb7b..4afdd97 100644 --- a/lightning-c-bindings/src/lightning_invoice/mod.rs +++ b/lightning-c-bindings/src/lightning_invoice/mod.rs @@ -15,122 +15,580 @@ //! * For constructing invoices use the `InvoiceBuilder` //! * For serializing invoices use the `Display`/`ToString` traits -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; +pub mod payment; pub mod utils; pub mod constants; mod de { -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; mod hrp_sm { -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; } #[no_mangle] /// Read a SiPrefix object from a string -pub extern "C" fn SiPrefix_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SiPrefixNoneZ { +pub extern "C" fn SiPrefix_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SiPrefixParseErrorZ { match lightning_invoice::SiPrefix::from_str(s.into_str()) { Ok(r) => { crate::c_types::CResultTempl::ok( crate::lightning_invoice::SiPrefix::native_into(r) ) }, - Err(e) => crate::c_types::CResultTempl::err(()), + Err(e) => { + crate::c_types::CResultTempl::err( + crate::lightning_invoice::ParseError::native_into(e) + ) + }, }.into() } #[no_mangle] /// Read a Invoice object from a string -pub extern "C" fn Invoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_InvoiceNoneZ { +pub extern "C" fn Invoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_InvoiceParseOrSemanticErrorZ { match lightning_invoice::Invoice::from_str(s.into_str()) { Ok(r) => { crate::c_types::CResultTempl::ok( - crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(r), is_owned: true } + ) + }, + Err(e) => { + crate::c_types::CResultTempl::err( + crate::lightning_invoice::ParseOrSemanticError::native_into(e) ) }, - Err(e) => crate::c_types::CResultTempl::err(()), }.into() } #[no_mangle] /// Read a SignedRawInvoice object from a string -pub extern "C" fn SignedRawInvoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SignedRawInvoiceNoneZ { +pub extern "C" fn SignedRawInvoice_from_str(s: crate::c_types::Str) -> crate::c_types::derived::CResult_SignedRawInvoiceParseErrorZ { match lightning_invoice::SignedRawInvoice::from_str(s.into_str()) { Ok(r) => { crate::c_types::CResultTempl::ok( - crate::lightning_invoice::SignedRawInvoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + crate::lightning_invoice::SignedRawInvoice { inner: ObjOps::heap_alloc(r), is_owned: true } + ) + }, + Err(e) => { + crate::c_types::CResultTempl::err( + crate::lightning_invoice::ParseError::native_into(e) ) }, - Err(e) => crate::c_types::CResultTempl::err(()), }.into() } +#[no_mangle] +/// Get the string representation of a ParseError object +pub extern "C" fn ParseError_to_str(o: &crate::lightning_invoice::ParseError) -> Str { + alloc::format!("{}", &o.to_native()).into() +} +#[no_mangle] +/// Get the string representation of a ParseOrSemanticError object +pub extern "C" fn ParseOrSemanticError_to_str(o: &crate::lightning_invoice::ParseOrSemanticError) -> Str { + alloc::format!("{}", &o.to_native()).into() +} } mod ser { -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; #[no_mangle] /// Get the string representation of a Invoice object pub extern "C" fn Invoice_to_str(o: &crate::lightning_invoice::Invoice) -> Str { - format!("{}", unsafe { &*o.inner }).into() + alloc::format!("{}", o.get_native_ref()).into() } #[no_mangle] /// Get the string representation of a SignedRawInvoice object pub extern "C" fn SignedRawInvoice_to_str(o: &crate::lightning_invoice::SignedRawInvoice) -> Str { - format!("{}", unsafe { &*o.inner }).into() + alloc::format!("{}", o.get_native_ref()).into() } #[no_mangle] /// Get the string representation of a Currency object pub extern "C" fn Currency_to_str(o: &crate::lightning_invoice::Currency) -> Str { - format!("{}", &o.to_native()).into() + alloc::format!("{}", &o.to_native()).into() } #[no_mangle] /// Get the string representation of a SiPrefix object pub extern "C" fn SiPrefix_to_str(o: &crate::lightning_invoice::SiPrefix) -> Str { - format!("{}", &o.to_native()).into() + alloc::format!("{}", &o.to_native()).into() } } mod tb { -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; } -/// **Call this function on startup to ensure that all assumptions about the platform are valid.** -/// -/// Unfortunately we have to make assumptions about the upper bounds of the `SystemTime` type on -/// your platform which we can't fully verify at compile time and which isn't part of it's contract. -/// To our best knowledge our assumptions hold for all platforms officially supported by rust, but -/// since this check is fast we recommend to do it anyway. +mod prelude { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} +mod sync { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} +/// Errors that indicate what is wrong with the invoice. They have some granularity for debug +/// reasons, but should generally result in an \"invalid BOLT11 invoice\" message for the user. +#[must_use] +#[derive(Clone)] +#[repr(C)] +pub enum ParseError { + Bech32Error(crate::c_types::Bech32Error), + ParseAmountError(crate::c_types::Error), + MalformedSignature(crate::c_types::Secp256k1Error), + BadPrefix, + UnknownCurrency, + UnknownSiPrefix, + MalformedHRP, + TooShortDataPart, + UnexpectedEndOfTaggedFields, + DescriptionDecodeError(crate::c_types::Error), + PaddingError, + IntegerOverflowError, + InvalidSegWitProgramLength, + InvalidPubKeyHashLength, + InvalidScriptHashLength, + InvalidRecoveryId, + InvalidSliceLength(crate::c_types::Str), + /// Not an error, but used internally to signal that a part of the invoice should be ignored + /// according to BOLT11 + Skip, +} +use lightning_invoice::ParseError as nativeParseError; +impl ParseError { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeParseError { + match self { + ParseError::Bech32Error (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseError::Bech32Error ( + a_nonref.into_rust(), + ) + }, + ParseError::ParseAmountError (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseError::ParseAmountError ( + u8::from_str_radix(" a", 10).unwrap_err() /*a_nonref*/, + ) + }, + ParseError::MalformedSignature (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseError::MalformedSignature ( + a_nonref.into_rust(), + ) + }, + ParseError::BadPrefix => nativeParseError::BadPrefix, + ParseError::UnknownCurrency => nativeParseError::UnknownCurrency, + ParseError::UnknownSiPrefix => nativeParseError::UnknownSiPrefix, + ParseError::MalformedHRP => nativeParseError::MalformedHRP, + ParseError::TooShortDataPart => nativeParseError::TooShortDataPart, + ParseError::UnexpectedEndOfTaggedFields => nativeParseError::UnexpectedEndOfTaggedFields, + ParseError::DescriptionDecodeError (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseError::DescriptionDecodeError ( + core::str::from_utf8(&[0xff]).unwrap_err() /*a_nonref*/, + ) + }, + ParseError::PaddingError => nativeParseError::PaddingError, + ParseError::IntegerOverflowError => nativeParseError::IntegerOverflowError, + ParseError::InvalidSegWitProgramLength => nativeParseError::InvalidSegWitProgramLength, + ParseError::InvalidPubKeyHashLength => nativeParseError::InvalidPubKeyHashLength, + ParseError::InvalidScriptHashLength => nativeParseError::InvalidScriptHashLength, + ParseError::InvalidRecoveryId => nativeParseError::InvalidRecoveryId, + ParseError::InvalidSliceLength (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseError::InvalidSliceLength ( + a_nonref.into_string(), + ) + }, + ParseError::Skip => nativeParseError::Skip, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeParseError { + match self { + ParseError::Bech32Error (mut a, ) => { + nativeParseError::Bech32Error ( + a.into_rust(), + ) + }, + ParseError::ParseAmountError (mut a, ) => { + nativeParseError::ParseAmountError ( + u8::from_str_radix(" a", 10).unwrap_err() /*a*/, + ) + }, + ParseError::MalformedSignature (mut a, ) => { + nativeParseError::MalformedSignature ( + a.into_rust(), + ) + }, + ParseError::BadPrefix => nativeParseError::BadPrefix, + ParseError::UnknownCurrency => nativeParseError::UnknownCurrency, + ParseError::UnknownSiPrefix => nativeParseError::UnknownSiPrefix, + ParseError::MalformedHRP => nativeParseError::MalformedHRP, + ParseError::TooShortDataPart => nativeParseError::TooShortDataPart, + ParseError::UnexpectedEndOfTaggedFields => nativeParseError::UnexpectedEndOfTaggedFields, + ParseError::DescriptionDecodeError (mut a, ) => { + nativeParseError::DescriptionDecodeError ( + core::str::from_utf8(&[0xff]).unwrap_err() /*a*/, + ) + }, + ParseError::PaddingError => nativeParseError::PaddingError, + ParseError::IntegerOverflowError => nativeParseError::IntegerOverflowError, + ParseError::InvalidSegWitProgramLength => nativeParseError::InvalidSegWitProgramLength, + ParseError::InvalidPubKeyHashLength => nativeParseError::InvalidPubKeyHashLength, + ParseError::InvalidScriptHashLength => nativeParseError::InvalidScriptHashLength, + ParseError::InvalidRecoveryId => nativeParseError::InvalidRecoveryId, + ParseError::InvalidSliceLength (mut a, ) => { + nativeParseError::InvalidSliceLength ( + a.into_string(), + ) + }, + ParseError::Skip => nativeParseError::Skip, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeParseError) -> Self { + match native { + nativeParseError::Bech32Error (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseError::Bech32Error ( + crate::c_types::Bech32Error::from_rust(a_nonref), + ) + }, + nativeParseError::ParseAmountError (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseError::ParseAmountError ( + crate::c_types::Error { _dummy: 0 } /*a_nonref*/, + ) + }, + nativeParseError::MalformedSignature (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseError::MalformedSignature ( + crate::c_types::Secp256k1Error::from_rust(a_nonref), + ) + }, + nativeParseError::BadPrefix => ParseError::BadPrefix, + nativeParseError::UnknownCurrency => ParseError::UnknownCurrency, + nativeParseError::UnknownSiPrefix => ParseError::UnknownSiPrefix, + nativeParseError::MalformedHRP => ParseError::MalformedHRP, + nativeParseError::TooShortDataPart => ParseError::TooShortDataPart, + nativeParseError::UnexpectedEndOfTaggedFields => ParseError::UnexpectedEndOfTaggedFields, + nativeParseError::DescriptionDecodeError (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseError::DescriptionDecodeError ( + crate::c_types::Error { _dummy: 0 } /*a_nonref*/, + ) + }, + nativeParseError::PaddingError => ParseError::PaddingError, + nativeParseError::IntegerOverflowError => ParseError::IntegerOverflowError, + nativeParseError::InvalidSegWitProgramLength => ParseError::InvalidSegWitProgramLength, + nativeParseError::InvalidPubKeyHashLength => ParseError::InvalidPubKeyHashLength, + nativeParseError::InvalidScriptHashLength => ParseError::InvalidScriptHashLength, + nativeParseError::InvalidRecoveryId => ParseError::InvalidRecoveryId, + nativeParseError::InvalidSliceLength (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseError::InvalidSliceLength ( + a_nonref.into(), + ) + }, + nativeParseError::Skip => ParseError::Skip, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeParseError) -> Self { + match native { + nativeParseError::Bech32Error (mut a, ) => { + ParseError::Bech32Error ( + crate::c_types::Bech32Error::from_rust(a), + ) + }, + nativeParseError::ParseAmountError (mut a, ) => { + ParseError::ParseAmountError ( + crate::c_types::Error { _dummy: 0 } /*a*/, + ) + }, + nativeParseError::MalformedSignature (mut a, ) => { + ParseError::MalformedSignature ( + crate::c_types::Secp256k1Error::from_rust(a), + ) + }, + nativeParseError::BadPrefix => ParseError::BadPrefix, + nativeParseError::UnknownCurrency => ParseError::UnknownCurrency, + nativeParseError::UnknownSiPrefix => ParseError::UnknownSiPrefix, + nativeParseError::MalformedHRP => ParseError::MalformedHRP, + nativeParseError::TooShortDataPart => ParseError::TooShortDataPart, + nativeParseError::UnexpectedEndOfTaggedFields => ParseError::UnexpectedEndOfTaggedFields, + nativeParseError::DescriptionDecodeError (mut a, ) => { + ParseError::DescriptionDecodeError ( + crate::c_types::Error { _dummy: 0 } /*a*/, + ) + }, + nativeParseError::PaddingError => ParseError::PaddingError, + nativeParseError::IntegerOverflowError => ParseError::IntegerOverflowError, + nativeParseError::InvalidSegWitProgramLength => ParseError::InvalidSegWitProgramLength, + nativeParseError::InvalidPubKeyHashLength => ParseError::InvalidPubKeyHashLength, + nativeParseError::InvalidScriptHashLength => ParseError::InvalidScriptHashLength, + nativeParseError::InvalidRecoveryId => ParseError::InvalidRecoveryId, + nativeParseError::InvalidSliceLength (mut a, ) => { + ParseError::InvalidSliceLength ( + a.into(), + ) + }, + nativeParseError::Skip => ParseError::Skip, + } + } +} +/// Frees any resources used by the ParseError +#[no_mangle] +pub extern "C" fn ParseError_free(this_ptr: ParseError) { } +/// Creates a copy of the ParseError +#[no_mangle] +pub extern "C" fn ParseError_clone(orig: &ParseError) -> ParseError { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new Bech32Error-variant ParseError +pub extern "C" fn ParseError_bech32_error(a: crate::c_types::Bech32Error) -> ParseError { + ParseError::Bech32Error(a, ) +} +#[no_mangle] +/// Utility method to constructs a new ParseAmountError-variant ParseError +pub extern "C" fn ParseError_parse_amount_error(a: crate::c_types::Error) -> ParseError { + ParseError::ParseAmountError(a, ) +} +#[no_mangle] +/// Utility method to constructs a new MalformedSignature-variant ParseError +pub extern "C" fn ParseError_malformed_signature(a: crate::c_types::Secp256k1Error) -> ParseError { + ParseError::MalformedSignature(a, ) +} +#[no_mangle] +/// Utility method to constructs a new BadPrefix-variant ParseError +pub extern "C" fn ParseError_bad_prefix() -> ParseError { + ParseError::BadPrefix} +#[no_mangle] +/// Utility method to constructs a new UnknownCurrency-variant ParseError +pub extern "C" fn ParseError_unknown_currency() -> ParseError { + ParseError::UnknownCurrency} +#[no_mangle] +/// Utility method to constructs a new UnknownSiPrefix-variant ParseError +pub extern "C" fn ParseError_unknown_si_prefix() -> ParseError { + ParseError::UnknownSiPrefix} +#[no_mangle] +/// Utility method to constructs a new MalformedHRP-variant ParseError +pub extern "C" fn ParseError_malformed_hrp() -> ParseError { + ParseError::MalformedHRP} +#[no_mangle] +/// Utility method to constructs a new TooShortDataPart-variant ParseError +pub extern "C" fn ParseError_too_short_data_part() -> ParseError { + ParseError::TooShortDataPart} +#[no_mangle] +/// Utility method to constructs a new UnexpectedEndOfTaggedFields-variant ParseError +pub extern "C" fn ParseError_unexpected_end_of_tagged_fields() -> ParseError { + ParseError::UnexpectedEndOfTaggedFields} +#[no_mangle] +/// Utility method to constructs a new DescriptionDecodeError-variant ParseError +pub extern "C" fn ParseError_description_decode_error(a: crate::c_types::Error) -> ParseError { + ParseError::DescriptionDecodeError(a, ) +} +#[no_mangle] +/// Utility method to constructs a new PaddingError-variant ParseError +pub extern "C" fn ParseError_padding_error() -> ParseError { + ParseError::PaddingError} +#[no_mangle] +/// Utility method to constructs a new IntegerOverflowError-variant ParseError +pub extern "C" fn ParseError_integer_overflow_error() -> ParseError { + ParseError::IntegerOverflowError} +#[no_mangle] +/// Utility method to constructs a new InvalidSegWitProgramLength-variant ParseError +pub extern "C" fn ParseError_invalid_seg_wit_program_length() -> ParseError { + ParseError::InvalidSegWitProgramLength} +#[no_mangle] +/// Utility method to constructs a new InvalidPubKeyHashLength-variant ParseError +pub extern "C" fn ParseError_invalid_pub_key_hash_length() -> ParseError { + ParseError::InvalidPubKeyHashLength} +#[no_mangle] +/// Utility method to constructs a new InvalidScriptHashLength-variant ParseError +pub extern "C" fn ParseError_invalid_script_hash_length() -> ParseError { + ParseError::InvalidScriptHashLength} +#[no_mangle] +/// Utility method to constructs a new InvalidRecoveryId-variant ParseError +pub extern "C" fn ParseError_invalid_recovery_id() -> ParseError { + ParseError::InvalidRecoveryId} +#[no_mangle] +/// Utility method to constructs a new InvalidSliceLength-variant ParseError +pub extern "C" fn ParseError_invalid_slice_length(a: crate::c_types::Str) -> ParseError { + ParseError::InvalidSliceLength(a, ) +} +#[no_mangle] +/// Utility method to constructs a new Skip-variant ParseError +pub extern "C" fn ParseError_skip() -> ParseError { + ParseError::Skip} +/// Indicates that something went wrong while parsing or validating the invoice. Parsing errors +/// should be mostly seen as opaque and are only there for debugging reasons. Semantic errors +/// like wrong signatures, missing fields etc. could mean that someone tampered with the invoice. +#[must_use] +#[derive(Clone)] +#[repr(C)] +pub enum ParseOrSemanticError { + /// The invoice couldn't be decoded + ParseError(crate::lightning_invoice::ParseError), + /// The invoice could be decoded but violates the BOLT11 standard + SemanticError(crate::lightning_invoice::SemanticError), +} +use lightning_invoice::ParseOrSemanticError as nativeParseOrSemanticError; +impl ParseOrSemanticError { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeParseOrSemanticError { + match self { + ParseOrSemanticError::ParseError (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseOrSemanticError::ParseError ( + a_nonref.into_native(), + ) + }, + ParseOrSemanticError::SemanticError (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeParseOrSemanticError::SemanticError ( + a_nonref.into_native(), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeParseOrSemanticError { + match self { + ParseOrSemanticError::ParseError (mut a, ) => { + nativeParseOrSemanticError::ParseError ( + a.into_native(), + ) + }, + ParseOrSemanticError::SemanticError (mut a, ) => { + nativeParseOrSemanticError::SemanticError ( + a.into_native(), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeParseOrSemanticError) -> Self { + match native { + nativeParseOrSemanticError::ParseError (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseOrSemanticError::ParseError ( + crate::lightning_invoice::ParseError::native_into(a_nonref), + ) + }, + nativeParseOrSemanticError::SemanticError (ref a, ) => { + let mut a_nonref = (*a).clone(); + ParseOrSemanticError::SemanticError ( + crate::lightning_invoice::SemanticError::native_into(a_nonref), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeParseOrSemanticError) -> Self { + match native { + nativeParseOrSemanticError::ParseError (mut a, ) => { + ParseOrSemanticError::ParseError ( + crate::lightning_invoice::ParseError::native_into(a), + ) + }, + nativeParseOrSemanticError::SemanticError (mut a, ) => { + ParseOrSemanticError::SemanticError ( + crate::lightning_invoice::SemanticError::native_into(a), + ) + }, + } + } +} +/// Frees any resources used by the ParseOrSemanticError +#[no_mangle] +pub extern "C" fn ParseOrSemanticError_free(this_ptr: ParseOrSemanticError) { } +/// Creates a copy of the ParseOrSemanticError +#[no_mangle] +pub extern "C" fn ParseOrSemanticError_clone(orig: &ParseOrSemanticError) -> ParseOrSemanticError { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new ParseError-variant ParseOrSemanticError +pub extern "C" fn ParseOrSemanticError_parse_error(a: crate::lightning_invoice::ParseError) -> ParseOrSemanticError { + ParseOrSemanticError::ParseError(a, ) +} +#[no_mangle] +/// Utility method to constructs a new SemanticError-variant ParseOrSemanticError +pub extern "C" fn ParseOrSemanticError_semantic_error(a: crate::lightning_invoice::SemanticError) -> ParseOrSemanticError { + ParseOrSemanticError::SemanticError(a, ) +} +/// The maximum timestamp as [`Duration::as_secs`] since the Unix epoch allowed by [`BOLT 11`]. /// -/// If this function fails this is considered a bug. Please open an issue describing your -/// platform and stating your current system time. +/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md + +#[no_mangle] +pub static MAX_TIMESTAMP: u64 = lightning_invoice::MAX_TIMESTAMP; +/// Default expiry time as defined by [BOLT 11]. /// -/// # Panics -/// If the check fails this function panics. By calling this function on startup you ensure that -/// this wont happen at an arbitrary later point in time. +/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md + #[no_mangle] -pub extern "C" fn check_platform() { - lightning_invoice::check_platform() -} +pub static DEFAULT_EXPIRY_TIME: u64 = lightning_invoice::DEFAULT_EXPIRY_TIME; +/// Default minimum final CLTV expiry as defined by [BOLT 11]. +/// +/// Note that this is *not* the same value as rust-lightning's minimum CLTV expiry, which is +/// provided in [`MIN_FINAL_CLTV_EXPIRY`]. +/// +/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md +/// [`MIN_FINAL_CLTV_EXPIRY`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY +#[no_mangle] +pub static DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = lightning_invoice::DEFAULT_MIN_FINAL_CLTV_EXPIRY; use lightning_invoice::Invoice as nativeInvoiceImport; -type nativeInvoice = nativeInvoiceImport; +pub(crate) type nativeInvoice = nativeInvoiceImport; /// Represents a syntactically and semantically correct lightning BOLT11 invoice. /// @@ -156,7 +614,7 @@ pub struct Invoice { impl Drop for Invoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -165,16 +623,22 @@ impl Drop for Invoice { pub extern "C" fn Invoice_free(this_obj: Invoice) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn Invoice_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn Invoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Invoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoice { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeInvoice { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } @@ -185,13 +649,13 @@ impl Invoice { pub extern "C" fn Invoice_eq(a: &Invoice, b: &Invoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for Invoice { fn clone(&self) -> Self { Self { - inner: if <*mut nativeInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeInvoice>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -208,7 +672,7 @@ pub extern "C" fn Invoice_clone(orig: &Invoice) -> Invoice { } use lightning_invoice::SignedRawInvoice as nativeSignedRawInvoiceImport; -type nativeSignedRawInvoice = nativeSignedRawInvoiceImport; +pub(crate) type nativeSignedRawInvoice = nativeSignedRawInvoiceImport; /// Represents a signed `RawInvoice` with cached hash. The signature is not checked and may be /// invalid. @@ -233,7 +697,7 @@ pub struct SignedRawInvoice { impl Drop for SignedRawInvoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeSignedRawInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -242,16 +706,22 @@ impl Drop for SignedRawInvoice { pub extern "C" fn SignedRawInvoice_free(this_obj: SignedRawInvoice) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn SignedRawInvoice_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn SignedRawInvoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeSignedRawInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl SignedRawInvoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeSignedRawInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeSignedRawInvoice { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeSignedRawInvoice { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } @@ -262,13 +732,13 @@ impl SignedRawInvoice { pub extern "C" fn SignedRawInvoice_eq(a: &SignedRawInvoice, b: &SignedRawInvoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for SignedRawInvoice { fn clone(&self) -> Self { Self { - inner: if <*mut nativeSignedRawInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeSignedRawInvoice>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -285,7 +755,7 @@ pub extern "C" fn SignedRawInvoice_clone(orig: &SignedRawInvoice) -> SignedRawIn } use lightning_invoice::RawInvoice as nativeRawInvoiceImport; -type nativeRawInvoice = nativeRawInvoiceImport; +pub(crate) type nativeRawInvoice = nativeRawInvoiceImport; /// Represents an syntactically correct Invoice for a payment on the lightning network, /// but without the signature information. @@ -310,7 +780,7 @@ pub struct RawInvoice { impl Drop for RawInvoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeRawInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -319,29 +789,35 @@ impl Drop for RawInvoice { pub extern "C" fn RawInvoice_free(this_obj: RawInvoice) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn RawInvoice_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn RawInvoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRawInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RawInvoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeRawInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRawInvoice { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeRawInvoice { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } /// data part #[no_mangle] pub extern "C" fn RawInvoice_get_data(this_ptr: &RawInvoice) -> crate::lightning_invoice::RawDataPart { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.data; - crate::lightning_invoice::RawDataPart { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().data; + crate::lightning_invoice::RawDataPart { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning_invoice::RawDataPart<>) as *mut _) }, is_owned: false } } /// data part #[no_mangle] pub extern "C" fn RawInvoice_set_data(this_ptr: &mut RawInvoice, mut val: crate::lightning_invoice::RawDataPart) { - unsafe { &mut *this_ptr.inner }.data = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.data = *unsafe { Box::from_raw(val.take_inner()) }; } /// Checks if two RawInvoices contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -350,13 +826,13 @@ pub extern "C" fn RawInvoice_set_data(this_ptr: &mut RawInvoice, mut val: crate: pub extern "C" fn RawInvoice_eq(a: &RawInvoice, b: &RawInvoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RawInvoice { fn clone(&self) -> Self { Self { - inner: if <*mut nativeRawInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeRawInvoice>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -373,7 +849,7 @@ pub extern "C" fn RawInvoice_clone(orig: &RawInvoice) -> RawInvoice { } use lightning_invoice::RawDataPart as nativeRawDataPartImport; -type nativeRawDataPart = nativeRawDataPartImport; +pub(crate) type nativeRawDataPart = nativeRawDataPartImport; /// Data of the `RawInvoice` that is encoded in the data part #[must_use] @@ -394,7 +870,7 @@ pub struct RawDataPart { impl Drop for RawDataPart { fn drop(&mut self) { if self.is_owned && !<*mut nativeRawDataPart>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -403,29 +879,35 @@ impl Drop for RawDataPart { pub extern "C" fn RawDataPart_free(this_obj: RawDataPart) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn RawDataPart_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn RawDataPart_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRawDataPart); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RawDataPart { + pub(crate) fn get_native_ref(&self) -> &'static nativeRawDataPart { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRawDataPart { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeRawDataPart { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } /// generation time of the invoice #[no_mangle] pub extern "C" fn RawDataPart_get_timestamp(this_ptr: &RawDataPart) -> crate::lightning_invoice::PositiveTimestamp { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.timestamp; - crate::lightning_invoice::PositiveTimestamp { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().timestamp; + crate::lightning_invoice::PositiveTimestamp { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning_invoice::PositiveTimestamp<>) as *mut _) }, is_owned: false } } /// generation time of the invoice #[no_mangle] pub extern "C" fn RawDataPart_set_timestamp(this_ptr: &mut RawDataPart, mut val: crate::lightning_invoice::PositiveTimestamp) { - unsafe { &mut *this_ptr.inner }.timestamp = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp = *unsafe { Box::from_raw(val.take_inner()) }; } /// Checks if two RawDataParts contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -434,13 +916,13 @@ pub extern "C" fn RawDataPart_set_timestamp(this_ptr: &mut RawDataPart, mut val: pub extern "C" fn RawDataPart_eq(a: &RawDataPart, b: &RawDataPart) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RawDataPart { fn clone(&self) -> Self { Self { - inner: if <*mut nativeRawDataPart>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeRawDataPart>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -457,14 +939,14 @@ pub extern "C" fn RawDataPart_clone(orig: &RawDataPart) -> RawDataPart { } use lightning_invoice::PositiveTimestamp as nativePositiveTimestampImport; -type nativePositiveTimestamp = nativePositiveTimestampImport; +pub(crate) type nativePositiveTimestamp = nativePositiveTimestampImport; -/// A timestamp that refers to a date after 1 January 1970 which means its representation as UNIX -/// timestamp is positive. +/// A timestamp that refers to a date after 1 January 1970. /// /// # Invariants -/// The UNIX timestamp representing the stored time has to be positive and small enough so that -/// a `EpiryTime` can be added to it without an overflow. +/// +/// The Unix timestamp representing the stored time has to be positive and no greater than +/// [`MAX_TIMESTAMP`]. #[must_use] #[repr(C)] pub struct PositiveTimestamp { @@ -483,7 +965,7 @@ pub struct PositiveTimestamp { impl Drop for PositiveTimestamp { fn drop(&mut self) { if self.is_owned && !<*mut nativePositiveTimestamp>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -492,16 +974,22 @@ impl Drop for PositiveTimestamp { pub extern "C" fn PositiveTimestamp_free(this_obj: PositiveTimestamp) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn PositiveTimestamp_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn PositiveTimestamp_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePositiveTimestamp); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PositiveTimestamp { + pub(crate) fn get_native_ref(&self) -> &'static nativePositiveTimestamp { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePositiveTimestamp { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativePositiveTimestamp { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } @@ -512,13 +1000,13 @@ impl PositiveTimestamp { pub extern "C" fn PositiveTimestamp_eq(a: &PositiveTimestamp, b: &PositiveTimestamp) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for PositiveTimestamp { fn clone(&self) -> Self { Self { - inner: if <*mut nativePositiveTimestamp>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativePositiveTimestamp>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -591,6 +1079,22 @@ impl SiPrefix { pub extern "C" fn SiPrefix_clone(orig: &SiPrefix) -> SiPrefix { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new Milli-variant SiPrefix +pub extern "C" fn SiPrefix_milli() -> SiPrefix { + SiPrefix::Milli} +#[no_mangle] +/// Utility method to constructs a new Micro-variant SiPrefix +pub extern "C" fn SiPrefix_micro() -> SiPrefix { + SiPrefix::Micro} +#[no_mangle] +/// Utility method to constructs a new Nano-variant SiPrefix +pub extern "C" fn SiPrefix_nano() -> SiPrefix { + SiPrefix::Nano} +#[no_mangle] +/// Utility method to constructs a new Pico-variant SiPrefix +pub extern "C" fn SiPrefix_pico() -> SiPrefix { + SiPrefix::Pico} /// Checks if two SiPrefixs contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -670,6 +1174,35 @@ impl Currency { pub extern "C" fn Currency_clone(orig: &Currency) -> Currency { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new Bitcoin-variant Currency +pub extern "C" fn Currency_bitcoin() -> Currency { + Currency::Bitcoin} +#[no_mangle] +/// Utility method to constructs a new BitcoinTestnet-variant Currency +pub extern "C" fn Currency_bitcoin_testnet() -> Currency { + Currency::BitcoinTestnet} +#[no_mangle] +/// Utility method to constructs a new Regtest-variant Currency +pub extern "C" fn Currency_regtest() -> Currency { + Currency::Regtest} +#[no_mangle] +/// Utility method to constructs a new Simnet-variant Currency +pub extern "C" fn Currency_simnet() -> Currency { + Currency::Simnet} +#[no_mangle] +/// Utility method to constructs a new Signet-variant Currency +pub extern "C" fn Currency_signet() -> Currency { + Currency::Signet} +/// Checks if two Currencys contain equal inner contents. +#[no_mangle] +pub extern "C" fn Currency_hash(o: &Currency) -> u64 { + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(&o.to_native(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} /// Checks if two Currencys contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -678,7 +1211,7 @@ pub extern "C" fn Currency_eq(a: &Currency, b: &Currency) -> bool { } use lightning_invoice::Sha256 as nativeSha256Import; -type nativeSha256 = nativeSha256Import; +pub(crate) type nativeSha256 = nativeSha256Import; /// SHA-256 hash #[must_use] @@ -699,7 +1232,7 @@ pub struct Sha256 { impl Drop for Sha256 { fn drop(&mut self) { if self.is_owned && !<*mut nativeSha256>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -708,33 +1241,30 @@ impl Drop for Sha256 { pub extern "C" fn Sha256_free(this_obj: Sha256) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn Sha256_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn Sha256_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeSha256); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Sha256 { + pub(crate) fn get_native_ref(&self) -> &'static nativeSha256 { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeSha256 { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeSha256 { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two Sha256s contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. -#[no_mangle] -pub extern "C" fn Sha256_eq(a: &Sha256, b: &Sha256) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } -} impl Clone for Sha256 { fn clone(&self) -> Self { Self { - inner: if <*mut nativeSha256>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeSha256>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -749,9 +1279,28 @@ pub(crate) extern "C" fn Sha256_clone_void(this_ptr: *const c_void) -> *mut c_vo pub extern "C" fn Sha256_clone(orig: &Sha256) -> Sha256 { orig.clone() } +/// Checks if two Sha256s contain equal inner contents. +#[no_mangle] +pub extern "C" fn Sha256_hash(o: &Sha256) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two Sha256s contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn Sha256_eq(a: &Sha256, b: &Sha256) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} use lightning_invoice::Description as nativeDescriptionImport; -type nativeDescription = nativeDescriptionImport; +pub(crate) type nativeDescription = nativeDescriptionImport; /// Description string /// @@ -775,7 +1324,7 @@ pub struct Description { impl Drop for Description { fn drop(&mut self) { if self.is_owned && !<*mut nativeDescription>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -784,33 +1333,30 @@ impl Drop for Description { pub extern "C" fn Description_free(this_obj: Description) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn Description_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn Description_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDescription); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Description { + pub(crate) fn get_native_ref(&self) -> &'static nativeDescription { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDescription { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeDescription { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two Descriptions contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. -#[no_mangle] -pub extern "C" fn Description_eq(a: &Description, b: &Description) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } -} impl Clone for Description { fn clone(&self) -> Self { Self { - inner: if <*mut nativeDescription>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeDescription>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -825,9 +1371,28 @@ pub(crate) extern "C" fn Description_clone_void(this_ptr: *const c_void) -> *mut pub extern "C" fn Description_clone(orig: &Description) -> Description { orig.clone() } +/// Checks if two Descriptions contain equal inner contents. +#[no_mangle] +pub extern "C" fn Description_hash(o: &Description) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two Descriptions contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn Description_eq(a: &Description, b: &Description) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} use lightning_invoice::PayeePubKey as nativePayeePubKeyImport; -type nativePayeePubKey = nativePayeePubKeyImport; +pub(crate) type nativePayeePubKey = nativePayeePubKeyImport; /// Payee public key #[must_use] @@ -848,7 +1413,7 @@ pub struct PayeePubKey { impl Drop for PayeePubKey { fn drop(&mut self) { if self.is_owned && !<*mut nativePayeePubKey>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -857,33 +1422,47 @@ impl Drop for PayeePubKey { pub extern "C" fn PayeePubKey_free(this_obj: PayeePubKey) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn PayeePubKey_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn PayeePubKey_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePayeePubKey); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PayeePubKey { + pub(crate) fn get_native_ref(&self) -> &'static nativePayeePubKey { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePayeePubKey { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativePayeePubKey { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two PayeePubKeys contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. #[no_mangle] -pub extern "C" fn PayeePubKey_eq(a: &PayeePubKey, b: &PayeePubKey) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } +pub extern "C" fn PayeePubKey_get_a(this_ptr: &PayeePubKey) -> crate::c_types::PublicKey { + let mut inner_val = &mut this_ptr.get_native_mut_ref().0; + crate::c_types::PublicKey::from_rust(&inner_val) +} +#[no_mangle] +pub extern "C" fn PayeePubKey_set_a(this_ptr: &mut PayeePubKey, mut val: crate::c_types::PublicKey) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val.into_rust(); +} +/// Constructs a new PayeePubKey given each field +#[must_use] +#[no_mangle] +pub extern "C" fn PayeePubKey_new(mut a_arg: crate::c_types::PublicKey) -> PayeePubKey { + PayeePubKey { inner: ObjOps::heap_alloc(lightning_invoice::PayeePubKey ( + a_arg.into_rust(), + )), is_owned: true } } impl Clone for PayeePubKey { fn clone(&self) -> Self { Self { - inner: if <*mut nativePayeePubKey>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativePayeePubKey>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -898,17 +1477,31 @@ pub(crate) extern "C" fn PayeePubKey_clone_void(this_ptr: *const c_void) -> *mut pub extern "C" fn PayeePubKey_clone(orig: &PayeePubKey) -> PayeePubKey { orig.clone() } +/// Checks if two PayeePubKeys contain equal inner contents. +#[no_mangle] +pub extern "C" fn PayeePubKey_hash(o: &PayeePubKey) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two PayeePubKeys contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn PayeePubKey_eq(a: &PayeePubKey, b: &PayeePubKey) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} use lightning_invoice::ExpiryTime as nativeExpiryTimeImport; -type nativeExpiryTime = nativeExpiryTimeImport; +pub(crate) type nativeExpiryTime = nativeExpiryTimeImport; /// Positive duration that defines when (relatively to the timestamp) in the future the invoice /// expires -/// -/// # Invariants -/// The number of seconds this expiry time represents has to be in the range -/// `0...(SYSTEM_TIME_MAX_UNIX_TIMESTAMP - MAX_EXPIRY_TIME)` to avoid overflows when adding it to a -/// timestamp #[must_use] #[repr(C)] pub struct ExpiryTime { @@ -927,7 +1520,7 @@ pub struct ExpiryTime { impl Drop for ExpiryTime { fn drop(&mut self) { if self.is_owned && !<*mut nativeExpiryTime>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -936,33 +1529,30 @@ impl Drop for ExpiryTime { pub extern "C" fn ExpiryTime_free(this_obj: ExpiryTime) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ExpiryTime_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn ExpiryTime_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeExpiryTime); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ExpiryTime { + pub(crate) fn get_native_ref(&self) -> &'static nativeExpiryTime { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeExpiryTime { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeExpiryTime { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two ExpiryTimes contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. -#[no_mangle] -pub extern "C" fn ExpiryTime_eq(a: &ExpiryTime, b: &ExpiryTime) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } -} impl Clone for ExpiryTime { fn clone(&self) -> Self { Self { - inner: if <*mut nativeExpiryTime>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeExpiryTime>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -977,9 +1567,28 @@ pub(crate) extern "C" fn ExpiryTime_clone_void(this_ptr: *const c_void) -> *mut pub extern "C" fn ExpiryTime_clone(orig: &ExpiryTime) -> ExpiryTime { orig.clone() } +/// Checks if two ExpiryTimes contain equal inner contents. +#[no_mangle] +pub extern "C" fn ExpiryTime_hash(o: &ExpiryTime) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two ExpiryTimes contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn ExpiryTime_eq(a: &ExpiryTime, b: &ExpiryTime) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} use lightning_invoice::MinFinalCltvExpiry as nativeMinFinalCltvExpiryImport; -type nativeMinFinalCltvExpiry = nativeMinFinalCltvExpiryImport; +pub(crate) type nativeMinFinalCltvExpiry = nativeMinFinalCltvExpiryImport; /// `min_final_cltv_expiry` to use for the last HTLC in the route #[must_use] @@ -1000,7 +1609,7 @@ pub struct MinFinalCltvExpiry { impl Drop for MinFinalCltvExpiry { fn drop(&mut self) { if self.is_owned && !<*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1009,33 +1618,47 @@ impl Drop for MinFinalCltvExpiry { pub extern "C" fn MinFinalCltvExpiry_free(this_obj: MinFinalCltvExpiry) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn MinFinalCltvExpiry_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn MinFinalCltvExpiry_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMinFinalCltvExpiry); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl MinFinalCltvExpiry { + pub(crate) fn get_native_ref(&self) -> &'static nativeMinFinalCltvExpiry { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMinFinalCltvExpiry { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeMinFinalCltvExpiry { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two MinFinalCltvExpirys contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_eq(a: &MinFinalCltvExpiry, b: &MinFinalCltvExpiry) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } +pub extern "C" fn MinFinalCltvExpiry_get_a(this_ptr: &MinFinalCltvExpiry) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().0; + *inner_val +} +#[no_mangle] +pub extern "C" fn MinFinalCltvExpiry_set_a(this_ptr: &mut MinFinalCltvExpiry, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val; +} +/// Constructs a new MinFinalCltvExpiry given each field +#[must_use] +#[no_mangle] +pub extern "C" fn MinFinalCltvExpiry_new(mut a_arg: u64) -> MinFinalCltvExpiry { + MinFinalCltvExpiry { inner: ObjOps::heap_alloc(lightning_invoice::MinFinalCltvExpiry ( + a_arg, + )), is_owned: true } } impl Clone for MinFinalCltvExpiry { fn clone(&self) -> Self { Self { - inner: if <*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1050,6 +1673,25 @@ pub(crate) extern "C" fn MinFinalCltvExpiry_clone_void(this_ptr: *const c_void) pub extern "C" fn MinFinalCltvExpiry_clone(orig: &MinFinalCltvExpiry) -> MinFinalCltvExpiry { orig.clone() } +/// Checks if two MinFinalCltvExpirys contain equal inner contents. +#[no_mangle] +pub extern "C" fn MinFinalCltvExpiry_hash(o: &MinFinalCltvExpiry) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two MinFinalCltvExpirys contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn MinFinalCltvExpiry_eq(a: &MinFinalCltvExpiry, b: &MinFinalCltvExpiry) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} /// Fallback address in case no LN payment is possible #[must_use] #[derive(Clone)] @@ -1169,6 +1811,33 @@ pub extern "C" fn Fallback_free(this_ptr: Fallback) { } pub extern "C" fn Fallback_clone(orig: &Fallback) -> Fallback { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new SegWitProgram-variant Fallback +pub extern "C" fn Fallback_seg_wit_program(version: crate::c_types::u5, program: crate::c_types::derived::CVec_u8Z) -> Fallback { + Fallback::SegWitProgram { + version, + program, + } +} +#[no_mangle] +/// Utility method to constructs a new PubKeyHash-variant Fallback +pub extern "C" fn Fallback_pub_key_hash(a: crate::c_types::TwentyBytes) -> Fallback { + Fallback::PubKeyHash(a, ) +} +#[no_mangle] +/// Utility method to constructs a new ScriptHash-variant Fallback +pub extern "C" fn Fallback_script_hash(a: crate::c_types::TwentyBytes) -> Fallback { + Fallback::ScriptHash(a, ) +} +/// Checks if two Fallbacks contain equal inner contents. +#[no_mangle] +pub extern "C" fn Fallback_hash(o: &Fallback) -> u64 { + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(&o.to_native(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} /// Checks if two Fallbacks contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -1177,7 +1846,7 @@ pub extern "C" fn Fallback_eq(a: &Fallback, b: &Fallback) -> bool { } use lightning_invoice::InvoiceSignature as nativeInvoiceSignatureImport; -type nativeInvoiceSignature = nativeInvoiceSignatureImport; +pub(crate) type nativeInvoiceSignature = nativeInvoiceSignatureImport; /// Recoverable signature #[must_use] @@ -1198,7 +1867,7 @@ pub struct InvoiceSignature { impl Drop for InvoiceSignature { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvoiceSignature>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1207,33 +1876,30 @@ impl Drop for InvoiceSignature { pub extern "C" fn InvoiceSignature_free(this_obj: InvoiceSignature) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn InvoiceSignature_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn InvoiceSignature_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoiceSignature); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InvoiceSignature { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvoiceSignature { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoiceSignature { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeInvoiceSignature { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two InvoiceSignatures contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. -#[no_mangle] -pub extern "C" fn InvoiceSignature_eq(a: &InvoiceSignature, b: &InvoiceSignature) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } -} impl Clone for InvoiceSignature { fn clone(&self) -> Self { Self { - inner: if <*mut nativeInvoiceSignature>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeInvoiceSignature>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1248,9 +1914,18 @@ pub(crate) extern "C" fn InvoiceSignature_clone_void(this_ptr: *const c_void) -> pub extern "C" fn InvoiceSignature_clone(orig: &InvoiceSignature) -> InvoiceSignature { orig.clone() } +/// Checks if two InvoiceSignatures contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn InvoiceSignature_eq(a: &InvoiceSignature, b: &InvoiceSignature) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} -use lightning_invoice::RouteHint as nativeRouteHintImport; -type nativeRouteHint = nativeRouteHintImport; +use lightning_invoice::PrivateRoute as nativePrivateRouteImport; +pub(crate) type nativePrivateRoute = nativePrivateRouteImport; /// Private routing information /// @@ -1259,12 +1934,12 @@ type nativeRouteHint = nativeRouteHintImport; /// #[must_use] #[repr(C)] -pub struct RouteHint { +pub struct PrivateRoute { /// A pointer to the opaque Rust object. /// Nearly everywhere, inner must be non-null, however in places where /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeRouteHint, + pub inner: *mut nativePrivateRoute, /// Indicates that this is the only struct which contains the same pointer. /// Rust functions which take ownership of an object provided via an argument require @@ -1272,59 +1947,75 @@ pub struct RouteHint { pub is_owned: bool, } -impl Drop for RouteHint { +impl Drop for PrivateRoute { fn drop(&mut self) { - if self.is_owned && !<*mut nativeRouteHint>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + if self.is_owned && !<*mut nativePrivateRoute>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } -/// Frees any resources used by the RouteHint, if is_owned is set and inner is non-NULL. +/// Frees any resources used by the PrivateRoute, if is_owned is set and inner is non-NULL. #[no_mangle] -pub extern "C" fn RouteHint_free(this_obj: RouteHint) { } +pub extern "C" fn PrivateRoute_free(this_obj: PrivateRoute) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn RouteHint_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRouteHint); } +pub(crate) extern "C" fn PrivateRoute_free_void(this_ptr: *mut c_void) { + unsafe { let _ = Box::from_raw(this_ptr as *mut nativePrivateRoute); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy -impl RouteHint { - pub(crate) fn take_inner(mut self) -> *mut nativeRouteHint { +impl PrivateRoute { + pub(crate) fn get_native_ref(&self) -> &'static nativePrivateRoute { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePrivateRoute { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativePrivateRoute { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// Checks if two RouteHints contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. -/// Two objects with NULL inner values will be considered "equal" here. -#[no_mangle] -pub extern "C" fn RouteHint_eq(a: &RouteHint, b: &RouteHint) -> bool { - if a.inner == b.inner { return true; } - if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } -} -impl Clone for RouteHint { +impl Clone for PrivateRoute { fn clone(&self) -> Self { Self { - inner: if <*mut nativeRouteHint>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativePrivateRoute>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn RouteHint_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeRouteHint)).clone() })) as *mut c_void +pub(crate) extern "C" fn PrivateRoute_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativePrivateRoute)).clone() })) as *mut c_void } #[no_mangle] -/// Creates a copy of the RouteHint -pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint { +/// Creates a copy of the PrivateRoute +pub extern "C" fn PrivateRoute_clone(orig: &PrivateRoute) -> PrivateRoute { orig.clone() } +/// Checks if two PrivateRoutes contain equal inner contents. +#[no_mangle] +pub extern "C" fn PrivateRoute_hash(o: &PrivateRoute) -> u64 { + if o.inner.is_null() { return 0; } + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two PrivateRoutes contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn PrivateRoute_eq(a: &PrivateRoute, b: &PrivateRoute) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} /// Disassembles the `SignedRawInvoice` into its three parts: /// 1. raw invoice /// 2. hash of the raw invoice @@ -1333,7 +2024,7 @@ pub extern "C" fn RouteHint_clone(orig: &RouteHint) -> RouteHint { #[no_mangle] pub extern "C" fn SignedRawInvoice_into_parts(mut this_arg: SignedRawInvoice) -> crate::c_types::derived::C3Tuple_RawInvoice_u832InvoiceSignatureZ { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_parts(); - let (mut orig_ret_0, mut orig_ret_1, mut orig_ret_2) = ret; let mut local_ret = (crate::lightning_invoice::RawInvoice { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1 }, crate::lightning_invoice::InvoiceSignature { inner: Box::into_raw(Box::new(orig_ret_2)), is_owned: true }).into(); + let (mut orig_ret_0, mut orig_ret_1, mut orig_ret_2) = ret; let mut local_ret = (crate::lightning_invoice::RawInvoice { inner: ObjOps::heap_alloc(orig_ret_0), is_owned: true }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1 }, crate::lightning_invoice::InvoiceSignature { inner: ObjOps::heap_alloc(orig_ret_2), is_owned: true }).into(); local_ret } @@ -1341,15 +2032,15 @@ pub extern "C" fn SignedRawInvoice_into_parts(mut this_arg: SignedRawInvoice) -> #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_raw_invoice(this_arg: &SignedRawInvoice) -> crate::lightning_invoice::RawInvoice { - let mut ret = unsafe { &*this_arg.inner }.raw_invoice(); - crate::lightning_invoice::RawInvoice { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.raw_invoice(); + crate::lightning_invoice::RawInvoice { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning_invoice::RawInvoice<>) as *mut _) }, is_owned: false } } /// The hash of the `RawInvoice` that was signed. #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_hash(this_arg: &SignedRawInvoice) -> *const [u8; 32] { - let mut ret = unsafe { &*this_arg.inner }.hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.hash(); ret } @@ -1357,16 +2048,16 @@ pub extern "C" fn SignedRawInvoice_hash(this_arg: &SignedRawInvoice) -> *const [ #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_signature(this_arg: &SignedRawInvoice) -> crate::lightning_invoice::InvoiceSignature { - let mut ret = unsafe { &*this_arg.inner }.signature(); - crate::lightning_invoice::InvoiceSignature { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signature(); + crate::lightning_invoice::InvoiceSignature { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning_invoice::InvoiceSignature<>) as *mut _) }, is_owned: false } } /// Recovers the public key used for signing the invoice from the recoverable signature. #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_recover_payee_pub_key(this_arg: &SignedRawInvoice) -> crate::c_types::derived::CResult_PayeePubKeyErrorZ { - let mut ret = unsafe { &*this_arg.inner }.recover_payee_pub_key(); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PayeePubKey { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.recover_payee_pub_key(); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PayeePubKey { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } @@ -1375,7 +2066,7 @@ pub extern "C" fn SignedRawInvoice_recover_payee_pub_key(this_arg: &SignedRawInv #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_check_signature(this_arg: &SignedRawInvoice) -> bool { - let mut ret = unsafe { &*this_arg.inner }.check_signature(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.check_signature(); ret } @@ -1383,132 +2074,169 @@ pub extern "C" fn SignedRawInvoice_check_signature(this_arg: &SignedRawInvoice) #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_hash(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.hash(); crate::c_types::ThirtyTwoBytes { data: ret } } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payment_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 { - let mut ret = unsafe { &*this_arg.inner }.payment_hash(); - let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_hash(); + let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::Sha256<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_description(this_arg: &RawInvoice) -> crate::lightning_invoice::Description { - let mut ret = unsafe { &*this_arg.inner }.description(); - let mut local_ret = crate::lightning_invoice::Description { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description(); + let mut local_ret = crate::lightning_invoice::Description { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::Description<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payee_pub_key(this_arg: &RawInvoice) -> crate::lightning_invoice::PayeePubKey { - let mut ret = unsafe { &*this_arg.inner }.payee_pub_key(); - let mut local_ret = crate::lightning_invoice::PayeePubKey { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payee_pub_key(); + let mut local_ret = crate::lightning_invoice::PayeePubKey { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::PayeePubKey<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_description_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 { - let mut ret = unsafe { &*this_arg.inner }.description_hash(); - let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description_hash(); + let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::Sha256<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_expiry_time(this_arg: &RawInvoice) -> crate::lightning_invoice::ExpiryTime { - let mut ret = unsafe { &*this_arg.inner }.expiry_time(); - let mut local_ret = crate::lightning_invoice::ExpiryTime { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expiry_time(); + let mut local_ret = crate::lightning_invoice::ExpiryTime { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::ExpiryTime<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> crate::lightning_invoice::MinFinalCltvExpiry { - let mut ret = unsafe { &*this_arg.inner }.min_final_cltv_expiry(); - let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiry { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); + let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiry { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::MinFinalCltvExpiry<>) as *mut _ }, is_owned: false }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_secret(); let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; local_ret } +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_features(this_arg: &RawInvoice) -> crate::lightning::ln::features::InvoiceFeatures { - let mut ret = unsafe { &*this_arg.inner }.features(); - let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.features(); + let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning::ln::features::InvoiceFeatures<>) as *mut _ }, is_owned: false }; local_ret } #[must_use] #[no_mangle] -pub extern "C" fn RawInvoice_routes(this_arg: &RawInvoice) -> crate::c_types::derived::CVec_RouteHintZ { - let mut ret = unsafe { &*this_arg.inner }.routes(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::RouteHint { inner: unsafe { ( (&(**item) as *const _) as *mut _) }, is_owned: false } }); }; +pub extern "C" fn RawInvoice_private_routes(this_arg: &RawInvoice) -> crate::c_types::derived::CVec_PrivateRouteZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.private_routes(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning_invoice::PrivateRoute<>) as *mut _) }, is_owned: false } }); }; local_ret.into() } #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_amount_pico_btc(this_arg: &RawInvoice) -> crate::c_types::derived::COption_u64Z { - let mut ret = unsafe { &*this_arg.inner }.amount_pico_btc(); - 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()) } }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount_pico_btc(); + 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() }) }; local_ret } #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_currency(this_arg: &RawInvoice) -> crate::lightning_invoice::Currency { - let mut ret = unsafe { &*this_arg.inner }.currency(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.currency(); crate::lightning_invoice::Currency::native_into(ret) } -/// Create a new `PositiveTimestamp` from a unix timestamp in the Range -/// `0...SYSTEM_TIME_MAX_UNIX_TIMESTAMP - MAX_EXPIRY_TIME`, otherwise return a -/// `CreationError::TimestampOutOfBounds`. +/// Creates a `PositiveTimestamp` from a Unix timestamp in the range `0..=MAX_TIMESTAMP`. +/// +/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`]. #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_from_unix_timestamp(mut unix_seconds: u64) -> crate::c_types::derived::CResult_PositiveTimestampCreationErrorZ { let mut ret = lightning_invoice::PositiveTimestamp::from_unix_timestamp(unix_seconds); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } -/// Create a new `PositiveTimestamp` from a `SystemTime` with a corresponding unix timestamp in -/// the Range `0...SYSTEM_TIME_MAX_UNIX_TIMESTAMP - MAX_EXPIRY_TIME`, otherwise return a -/// `CreationError::TimestampOutOfBounds`. +/// Creates a `PositiveTimestamp` from a [`SystemTime`] with a corresponding Unix timestamp in +/// the range `0..=MAX_TIMESTAMP`. +/// +/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`]. #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_from_system_time(mut time: u64) -> crate::c_types::derived::CResult_PositiveTimestampCreationErrorZ { let mut ret = lightning_invoice::PositiveTimestamp::from_system_time((::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(time))); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + local_ret +} + +/// Creates a `PositiveTimestamp` from a [`Duration`] since the Unix epoch in the range +/// `0..=MAX_TIMESTAMP`. +/// +/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`]. +#[must_use] +#[no_mangle] +pub extern "C" fn PositiveTimestamp_from_duration_since_epoch(mut duration: u64) -> crate::c_types::derived::CResult_PositiveTimestampCreationErrorZ { + let mut ret = lightning_invoice::PositiveTimestamp::from_duration_since_epoch(core::time::Duration::from_secs(duration)); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } -/// Returns the UNIX timestamp representing the stored time +/// Returns the Unix timestamp representing the stored time #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_as_unix_timestamp(this_arg: &PositiveTimestamp) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_unix_timestamp(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_unix_timestamp(); ret } -/// Returns a reference to the internal `SystemTime` time representation +/// Returns the duration of the stored time since the Unix epoch +#[must_use] +#[no_mangle] +pub extern "C" fn PositiveTimestamp_as_duration_since_epoch(this_arg: &PositiveTimestamp) -> u64 { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_duration_since_epoch(); + ret.as_secs() +} + +/// Returns the [`SystemTime`] representing the stored time #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_as_time(this_arg: &PositiveTimestamp) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_time(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_time(); ret.duration_since(::std::time::SystemTime::UNIX_EPOCH).expect("Times must be post-1970").as_secs() } @@ -1517,26 +2245,33 @@ pub extern "C" fn PositiveTimestamp_as_time(this_arg: &PositiveTimestamp) -> u64 #[no_mangle] pub extern "C" fn Invoice_into_signed_raw(mut this_arg: Invoice) -> crate::lightning_invoice::SignedRawInvoice { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_signed_raw(); - crate::lightning_invoice::SignedRawInvoice { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning_invoice::SignedRawInvoice { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Check that the invoice is signed correctly and that key recovery works #[must_use] #[no_mangle] pub extern "C" fn Invoice_check_signature(this_arg: &Invoice) -> crate::c_types::derived::CResult_NoneSemanticErrorZ { - let mut ret = unsafe { &*this_arg.inner }.check_signature(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.check_signature(); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; local_ret } -/// Constructs an `Invoice` from a `SignedInvoice` by checking all its invariants. +/// Constructs an `Invoice` from a `SignedRawInvoice` by checking all its invariants. /// ``` /// use lightning_invoice::*; /// -/// let invoice = \"lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdp\\ -/// \tl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcsyz3d7\\ -/// \t3gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erqz25le42c4u4ec\\ -/// \tky03ylcqca784w\"; +/// let invoice = \"lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcs\\ +/// h2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l\\ +/// 5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993\\ +/// h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqcl\\ +/// j9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9d\\ +/// ha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58a\\ +/// guqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphms\\ +/// ywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0v\\ +/// p62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh3\\ +/// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\\ +/// j5r6drg6k6zcqj0fcwg\"; /// /// let signed = invoice.parse::().unwrap(); /// @@ -1546,31 +2281,41 @@ pub extern "C" fn Invoice_check_signature(this_arg: &Invoice) -> crate::c_types: #[no_mangle] pub extern "C" fn Invoice_from_signed(mut signed_invoice: crate::lightning_invoice::SignedRawInvoice) -> crate::c_types::derived::CResult_InvoiceSemanticErrorZ { let mut ret = lightning_invoice::Invoice::from_signed(*unsafe { Box::from_raw(signed_invoice.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; local_ret } -/// Returns the `Invoice`'s timestamp (should equal it's creation time) +/// Returns the `Invoice`'s timestamp (should equal its creation time) #[must_use] #[no_mangle] pub extern "C" fn Invoice_timestamp(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.timestamp(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timestamp(); ret.duration_since(::std::time::SystemTime::UNIX_EPOCH).expect("Times must be post-1970").as_secs() } +/// Returns the `Invoice`'s timestamp as a duration since the Unix epoch +#[must_use] +#[no_mangle] +pub extern "C" fn Invoice_duration_since_epoch(this_arg: &Invoice) -> u64 { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.duration_since_epoch(); + ret.as_secs() +} + /// Returns the hash to which we will receive the preimage on completion of the payment #[must_use] #[no_mangle] pub extern "C" fn Invoice_payment_hash(this_arg: &Invoice) -> *const [u8; 32] { - let mut ret = unsafe { &*this_arg.inner }.payment_hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_hash(); ret.as_inner() } /// Get the payee's public key if one was included in the invoice +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.payee_pub_key(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payee_pub_key(); let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } }; local_ret } @@ -1578,18 +2323,19 @@ pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::P /// Get the payment secret if one was included in the invoice #[must_use] #[no_mangle] -pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.payment_secret(); - let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; - local_ret +pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> *const [u8; 32] { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_secret(); + &ret.0 } /// Get the invoice features if they were included in the invoice +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] pub extern "C" fn Invoice_features(this_arg: &Invoice) -> crate::lightning::ln::features::InvoiceFeatures { - let mut ret = unsafe { &*this_arg.inner }.features(); - let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.features(); + let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning::ln::features::InvoiceFeatures<>) as *mut _ }, is_owned: false }; local_ret } @@ -1597,7 +2343,7 @@ pub extern "C" fn Invoice_features(this_arg: &Invoice) -> crate::lightning::ln:: #[must_use] #[no_mangle] pub extern "C" fn Invoice_recover_payee_pub_key(this_arg: &Invoice) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.recover_payee_pub_key(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.recover_payee_pub_key(); crate::c_types::PublicKey::from_rust(&ret) } @@ -1605,25 +2351,51 @@ pub extern "C" fn Invoice_recover_payee_pub_key(this_arg: &Invoice) -> crate::c_ #[must_use] #[no_mangle] pub extern "C" fn Invoice_expiry_time(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.expiry_time(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expiry_time(); ret.as_secs() } +/// Returns whether the invoice has expired. +#[must_use] +#[no_mangle] +pub extern "C" fn Invoice_is_expired(this_arg: &Invoice) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_expired(); + ret +} + +/// Returns whether the expiry time would pass at the given point in time. +/// `at_time` is the timestamp as a duration since the Unix epoch. +#[must_use] +#[no_mangle] +pub extern "C" fn Invoice_would_expire(this_arg: &Invoice, mut at_time: u64) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.would_expire(core::time::Duration::from_secs(at_time)); + ret +} + /// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise /// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`]. #[must_use] #[no_mangle] pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.min_final_cltv_expiry(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); ret } /// Returns a list of all routes included in the invoice #[must_use] #[no_mangle] -pub extern "C" fn Invoice_routes(this_arg: &Invoice) -> crate::c_types::derived::CVec_RouteHintZ { - let mut ret = unsafe { &*this_arg.inner }.routes(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::RouteHint { inner: unsafe { ( (&(**item) as *const _) as *mut _) }, is_owned: false } }); }; +pub extern "C" fn Invoice_private_routes(this_arg: &Invoice) -> crate::c_types::derived::CVec_PrivateRouteZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.private_routes(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning_invoice::PrivateRoute<>) as *mut _) }, is_owned: false } }); }; + local_ret.into() +} + +/// Returns a list of all routes included in the invoice as the underlying hints +#[must_use] +#[no_mangle] +pub extern "C" fn Invoice_route_hints(this_arg: &Invoice) -> crate::c_types::derived::CVec_RouteHintZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.route_hints(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::routing::router::RouteHint { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; local_ret.into() } @@ -1631,16 +2403,16 @@ pub extern "C" fn Invoice_routes(this_arg: &Invoice) -> crate::c_types::derived: #[must_use] #[no_mangle] pub extern "C" fn Invoice_currency(this_arg: &Invoice) -> crate::lightning_invoice::Currency { - let mut ret = unsafe { &*this_arg.inner }.currency(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.currency(); crate::lightning_invoice::Currency::native_into(ret) } -/// Returns the amount if specified in the invoice as pico . +/// Returns the amount if specified in the invoice as millisatoshis. #[must_use] #[no_mangle] -pub extern "C" fn Invoice_amount_pico_btc(this_arg: &Invoice) -> crate::c_types::derived::COption_u64Z { - let mut ret = unsafe { &*this_arg.inner }.amount_pico_btc(); - 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()) } }; +pub extern "C" fn Invoice_amount_milli_satoshis(this_arg: &Invoice) -> crate::c_types::derived::COption_u64Z { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount_milli_satoshis(); + 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() }) }; local_ret } @@ -1652,7 +2424,7 @@ pub extern "C" fn Invoice_amount_pico_btc(this_arg: &Invoice) -> crate::c_types: #[no_mangle] pub extern "C" fn Description_new(mut description: crate::c_types::Str) -> crate::c_types::derived::CResult_DescriptionCreationErrorZ { let mut ret = lightning_invoice::Description::new(description.into_string()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Description { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Description { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1664,33 +2436,27 @@ pub extern "C" fn Description_into_inner(mut this_arg: Description) -> crate::c_ ret.into() } -/// Construct an `ExpiryTime` from seconds. If there exists a `PositiveTimestamp` which would -/// overflow on adding the `EpiryTime` to it then this function will return a -/// `CreationError::ExpiryTimeOutOfBounds`. +/// Construct an `ExpiryTime` from seconds. #[must_use] #[no_mangle] -pub extern "C" fn ExpiryTime_from_seconds(mut seconds: u64) -> crate::c_types::derived::CResult_ExpiryTimeCreationErrorZ { +pub extern "C" fn ExpiryTime_from_seconds(mut seconds: u64) -> crate::lightning_invoice::ExpiryTime { let mut ret = lightning_invoice::ExpiryTime::from_seconds(seconds); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; - local_ret + crate::lightning_invoice::ExpiryTime { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Construct an `ExpiryTime` from a `Duration`. If there exists a `PositiveTimestamp` which -/// would overflow on adding the `EpiryTime` to it then this function will return a -/// `CreationError::ExpiryTimeOutOfBounds`. +/// Construct an `ExpiryTime` from a `Duration`. #[must_use] #[no_mangle] -pub extern "C" fn ExpiryTime_from_duration(mut duration: u64) -> crate::c_types::derived::CResult_ExpiryTimeCreationErrorZ { - let mut ret = lightning_invoice::ExpiryTime::from_duration(std::time::Duration::from_secs(duration)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; - local_ret +pub extern "C" fn ExpiryTime_from_duration(mut duration: u64) -> crate::lightning_invoice::ExpiryTime { + let mut ret = lightning_invoice::ExpiryTime::from_duration(core::time::Duration::from_secs(duration)); + crate::lightning_invoice::ExpiryTime { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns the expiry time in seconds #[must_use] #[no_mangle] pub extern "C" fn ExpiryTime_as_seconds(this_arg: &ExpiryTime) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_seconds(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_seconds(); ret } @@ -1698,27 +2464,25 @@ pub extern "C" fn ExpiryTime_as_seconds(this_arg: &ExpiryTime) -> u64 { #[must_use] #[no_mangle] pub extern "C" fn ExpiryTime_as_duration(this_arg: &ExpiryTime) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_duration(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_duration(); ret.as_secs() } -/// Create a new (partial) route from a list of hops +/// Creates a new (partial) route from a list of hops #[must_use] #[no_mangle] -pub extern "C" fn RouteHint_new(mut hops: crate::c_types::derived::CVec_RouteHintHopZ) -> crate::c_types::derived::CResult_RouteHintCreationErrorZ { - let mut local_hops = Vec::new(); for mut item in hops.into_rust().drain(..) { local_hops.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; - let mut ret = lightning_invoice::RouteHint::new(local_hops); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::RouteHint { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; +pub extern "C" fn PrivateRoute_new(mut hops: crate::lightning::routing::router::RouteHint) -> crate::c_types::derived::CResult_PrivateRouteCreationErrorZ { + let mut ret = lightning_invoice::PrivateRoute::new(*unsafe { Box::from_raw(hops.take_inner()) }); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PrivateRoute { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } -/// Returrn the underlying vector of hops +/// Returns the underlying list of hops #[must_use] #[no_mangle] -pub extern "C" fn RouteHint_into_inner(mut this_arg: RouteHint) -> crate::c_types::derived::CVec_RouteHintHopZ { +pub extern "C" fn PrivateRoute_into_inner(mut this_arg: PrivateRoute) -> crate::lightning::routing::router::RouteHint { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_inner(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::routing::router::RouteHintHop { inner: Box::into_raw(Box::new(item)), is_owned: true } }); }; - local_ret.into() + crate::lightning::routing::router::RouteHint { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Errors that may occur when constructing a new `RawInvoice` or `Invoice` @@ -1730,10 +2494,15 @@ pub enum CreationError { DescriptionTooLong, /// The specified route has too many hops and can't be encoded RouteTooLong, - /// The unix timestamp of the supplied date is <0 or can't be represented as `SystemTime` + /// The Unix timestamp of the supplied date is less than zero or greater than 35-bits TimestampOutOfBounds, - /// The supplied expiry time could cause an overflow if added to a `PositiveTimestamp` - ExpiryTimeOutOfBounds, + /// The supplied millisatoshi amount was greater than the total bitcoin supply. + InvalidAmount, + /// Route hints were required for this invoice and were missing. Applies to + /// [phantom invoices]. + /// + /// [phantom invoices]: crate::utils::create_phantom_invoice + MissingRouteHints, } use lightning_invoice::CreationError as nativeCreationError; impl CreationError { @@ -1743,7 +2512,8 @@ impl CreationError { CreationError::DescriptionTooLong => nativeCreationError::DescriptionTooLong, CreationError::RouteTooLong => nativeCreationError::RouteTooLong, CreationError::TimestampOutOfBounds => nativeCreationError::TimestampOutOfBounds, - CreationError::ExpiryTimeOutOfBounds => nativeCreationError::ExpiryTimeOutOfBounds, + CreationError::InvalidAmount => nativeCreationError::InvalidAmount, + CreationError::MissingRouteHints => nativeCreationError::MissingRouteHints, } } #[allow(unused)] @@ -1752,7 +2522,8 @@ impl CreationError { CreationError::DescriptionTooLong => nativeCreationError::DescriptionTooLong, CreationError::RouteTooLong => nativeCreationError::RouteTooLong, CreationError::TimestampOutOfBounds => nativeCreationError::TimestampOutOfBounds, - CreationError::ExpiryTimeOutOfBounds => nativeCreationError::ExpiryTimeOutOfBounds, + CreationError::InvalidAmount => nativeCreationError::InvalidAmount, + CreationError::MissingRouteHints => nativeCreationError::MissingRouteHints, } } #[allow(unused)] @@ -1761,7 +2532,8 @@ impl CreationError { nativeCreationError::DescriptionTooLong => CreationError::DescriptionTooLong, nativeCreationError::RouteTooLong => CreationError::RouteTooLong, nativeCreationError::TimestampOutOfBounds => CreationError::TimestampOutOfBounds, - nativeCreationError::ExpiryTimeOutOfBounds => CreationError::ExpiryTimeOutOfBounds, + nativeCreationError::InvalidAmount => CreationError::InvalidAmount, + nativeCreationError::MissingRouteHints => CreationError::MissingRouteHints, } } #[allow(unused)] @@ -1770,7 +2542,8 @@ impl CreationError { nativeCreationError::DescriptionTooLong => CreationError::DescriptionTooLong, nativeCreationError::RouteTooLong => CreationError::RouteTooLong, nativeCreationError::TimestampOutOfBounds => CreationError::TimestampOutOfBounds, - nativeCreationError::ExpiryTimeOutOfBounds => CreationError::ExpiryTimeOutOfBounds, + nativeCreationError::InvalidAmount => CreationError::InvalidAmount, + nativeCreationError::MissingRouteHints => CreationError::MissingRouteHints, } } } @@ -1779,6 +2552,26 @@ impl CreationError { pub extern "C" fn CreationError_clone(orig: &CreationError) -> CreationError { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new DescriptionTooLong-variant CreationError +pub extern "C" fn CreationError_description_too_long() -> CreationError { + CreationError::DescriptionTooLong} +#[no_mangle] +/// Utility method to constructs a new RouteTooLong-variant CreationError +pub extern "C" fn CreationError_route_too_long() -> CreationError { + CreationError::RouteTooLong} +#[no_mangle] +/// Utility method to constructs a new TimestampOutOfBounds-variant CreationError +pub extern "C" fn CreationError_timestamp_out_of_bounds() -> CreationError { + CreationError::TimestampOutOfBounds} +#[no_mangle] +/// Utility method to constructs a new InvalidAmount-variant CreationError +pub extern "C" fn CreationError_invalid_amount() -> CreationError { + CreationError::InvalidAmount} +#[no_mangle] +/// Utility method to constructs a new MissingRouteHints-variant CreationError +pub extern "C" fn CreationError_missing_route_hints() -> CreationError { + CreationError::MissingRouteHints} /// Checks if two CreationErrors contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -1788,7 +2581,7 @@ pub extern "C" fn CreationError_eq(a: &CreationError, b: &CreationError) -> bool #[no_mangle] /// Get the string representation of a CreationError object pub extern "C" fn CreationError_to_str(o: &crate::lightning_invoice::CreationError) -> Str { - format!("{}", &o.to_native()).into() + alloc::format!("{}", &o.to_native()).into() } /// Errors that may occur when converting a `RawInvoice` to an `Invoice`. They relate to the /// requirements sections in BOLT #11 @@ -1804,6 +2597,9 @@ pub enum SemanticError { NoDescription, /// The invoice contains multiple descriptions and/or description hashes which isn't allowed MultipleDescriptions, + /// The invoice is missing the mandatory payment secret, which all modern lightning nodes + /// should provide. + NoPaymentSecret, /// The invoice contains multiple payment secrets MultiplePaymentSecrets, /// The invoice's features are invalid @@ -1812,6 +2608,8 @@ pub enum SemanticError { InvalidRecoveryId, /// The invoice's signature is invalid InvalidSignature, + /// The invoice's amount was not a whole number of millisatoshis + ImpreciseAmount, } use lightning_invoice::SemanticError as nativeSemanticError; impl SemanticError { @@ -1822,10 +2620,12 @@ impl SemanticError { SemanticError::MultiplePaymentHashes => nativeSemanticError::MultiplePaymentHashes, SemanticError::NoDescription => nativeSemanticError::NoDescription, SemanticError::MultipleDescriptions => nativeSemanticError::MultipleDescriptions, + SemanticError::NoPaymentSecret => nativeSemanticError::NoPaymentSecret, SemanticError::MultiplePaymentSecrets => nativeSemanticError::MultiplePaymentSecrets, SemanticError::InvalidFeatures => nativeSemanticError::InvalidFeatures, SemanticError::InvalidRecoveryId => nativeSemanticError::InvalidRecoveryId, SemanticError::InvalidSignature => nativeSemanticError::InvalidSignature, + SemanticError::ImpreciseAmount => nativeSemanticError::ImpreciseAmount, } } #[allow(unused)] @@ -1835,10 +2635,12 @@ impl SemanticError { SemanticError::MultiplePaymentHashes => nativeSemanticError::MultiplePaymentHashes, SemanticError::NoDescription => nativeSemanticError::NoDescription, SemanticError::MultipleDescriptions => nativeSemanticError::MultipleDescriptions, + SemanticError::NoPaymentSecret => nativeSemanticError::NoPaymentSecret, SemanticError::MultiplePaymentSecrets => nativeSemanticError::MultiplePaymentSecrets, SemanticError::InvalidFeatures => nativeSemanticError::InvalidFeatures, SemanticError::InvalidRecoveryId => nativeSemanticError::InvalidRecoveryId, SemanticError::InvalidSignature => nativeSemanticError::InvalidSignature, + SemanticError::ImpreciseAmount => nativeSemanticError::ImpreciseAmount, } } #[allow(unused)] @@ -1848,10 +2650,12 @@ impl SemanticError { nativeSemanticError::MultiplePaymentHashes => SemanticError::MultiplePaymentHashes, nativeSemanticError::NoDescription => SemanticError::NoDescription, nativeSemanticError::MultipleDescriptions => SemanticError::MultipleDescriptions, + nativeSemanticError::NoPaymentSecret => SemanticError::NoPaymentSecret, nativeSemanticError::MultiplePaymentSecrets => SemanticError::MultiplePaymentSecrets, nativeSemanticError::InvalidFeatures => SemanticError::InvalidFeatures, nativeSemanticError::InvalidRecoveryId => SemanticError::InvalidRecoveryId, nativeSemanticError::InvalidSignature => SemanticError::InvalidSignature, + nativeSemanticError::ImpreciseAmount => SemanticError::ImpreciseAmount, } } #[allow(unused)] @@ -1861,10 +2665,12 @@ impl SemanticError { nativeSemanticError::MultiplePaymentHashes => SemanticError::MultiplePaymentHashes, nativeSemanticError::NoDescription => SemanticError::NoDescription, nativeSemanticError::MultipleDescriptions => SemanticError::MultipleDescriptions, + nativeSemanticError::NoPaymentSecret => SemanticError::NoPaymentSecret, nativeSemanticError::MultiplePaymentSecrets => SemanticError::MultiplePaymentSecrets, nativeSemanticError::InvalidFeatures => SemanticError::InvalidFeatures, nativeSemanticError::InvalidRecoveryId => SemanticError::InvalidRecoveryId, nativeSemanticError::InvalidSignature => SemanticError::InvalidSignature, + nativeSemanticError::ImpreciseAmount => SemanticError::ImpreciseAmount, } } } @@ -1873,6 +2679,46 @@ impl SemanticError { pub extern "C" fn SemanticError_clone(orig: &SemanticError) -> SemanticError { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new NoPaymentHash-variant SemanticError +pub extern "C" fn SemanticError_no_payment_hash() -> SemanticError { + SemanticError::NoPaymentHash} +#[no_mangle] +/// Utility method to constructs a new MultiplePaymentHashes-variant SemanticError +pub extern "C" fn SemanticError_multiple_payment_hashes() -> SemanticError { + SemanticError::MultiplePaymentHashes} +#[no_mangle] +/// Utility method to constructs a new NoDescription-variant SemanticError +pub extern "C" fn SemanticError_no_description() -> SemanticError { + SemanticError::NoDescription} +#[no_mangle] +/// Utility method to constructs a new MultipleDescriptions-variant SemanticError +pub extern "C" fn SemanticError_multiple_descriptions() -> SemanticError { + SemanticError::MultipleDescriptions} +#[no_mangle] +/// Utility method to constructs a new NoPaymentSecret-variant SemanticError +pub extern "C" fn SemanticError_no_payment_secret() -> SemanticError { + SemanticError::NoPaymentSecret} +#[no_mangle] +/// Utility method to constructs a new MultiplePaymentSecrets-variant SemanticError +pub extern "C" fn SemanticError_multiple_payment_secrets() -> SemanticError { + SemanticError::MultiplePaymentSecrets} +#[no_mangle] +/// Utility method to constructs a new InvalidFeatures-variant SemanticError +pub extern "C" fn SemanticError_invalid_features() -> SemanticError { + SemanticError::InvalidFeatures} +#[no_mangle] +/// Utility method to constructs a new InvalidRecoveryId-variant SemanticError +pub extern "C" fn SemanticError_invalid_recovery_id() -> SemanticError { + SemanticError::InvalidRecoveryId} +#[no_mangle] +/// Utility method to constructs a new InvalidSignature-variant SemanticError +pub extern "C" fn SemanticError_invalid_signature() -> SemanticError { + SemanticError::InvalidSignature} +#[no_mangle] +/// Utility method to constructs a new ImpreciseAmount-variant SemanticError +pub extern "C" fn SemanticError_imprecise_amount() -> SemanticError { + SemanticError::ImpreciseAmount} /// Checks if two SemanticErrors contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -1882,7 +2728,7 @@ pub extern "C" fn SemanticError_eq(a: &SemanticError, b: &SemanticError) -> bool #[no_mangle] /// Get the string representation of a SemanticError object pub extern "C" fn SemanticError_to_str(o: &crate::lightning_invoice::SemanticError) -> Str { - format!("{}", &o.to_native()).into() + alloc::format!("{}", &o.to_native()).into() } /// When signing using a fallible method either an user-supplied `SignError` or a `CreationError` /// may occur. @@ -1962,6 +2808,16 @@ pub extern "C" fn SignOrCreationError_free(this_ptr: SignOrCreationError) { } pub extern "C" fn SignOrCreationError_clone(orig: &SignOrCreationError) -> SignOrCreationError { orig.clone() } +#[no_mangle] +/// Utility method to constructs a new SignError-variant SignOrCreationError +pub extern "C" fn SignOrCreationError_sign_error() -> SignOrCreationError { + SignOrCreationError::SignError +} +#[no_mangle] +/// Utility method to constructs a new CreationError-variant SignOrCreationError +pub extern "C" fn SignOrCreationError_creation_error(a: crate::lightning_invoice::CreationError) -> SignOrCreationError { + SignOrCreationError::CreationError(a, ) +} /// Checks if two SignOrCreationErrors contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] @@ -1971,5 +2827,5 @@ pub extern "C" fn SignOrCreationError_eq(a: &SignOrCreationError, b: &SignOrCrea #[no_mangle] /// Get the string representation of a SignOrCreationError object pub extern "C" fn SignOrCreationError_to_str(o: &crate::lightning_invoice::SignOrCreationError) -> Str { - format!("{}", &o.to_native()).into() + alloc::format!("{}", &o.to_native()).into() }