]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Qualify the BOLT 11 invoice type
authorJeffrey Czyz <jkczyz@gmail.com>
Thu, 13 Jul 2023 22:22:26 +0000 (17:22 -0500)
committerJeffrey Czyz <jkczyz@gmail.com>
Fri, 14 Jul 2023 20:05:11 +0000 (15:05 -0500)
A previous commit qualified the BOLT 12 invoice type. Qualify the BOLT
11 invoice type for consistency.

lightning-invoice/src/de.rs
lightning-invoice/src/lib.rs
lightning-invoice/src/payment.rs
lightning-invoice/src/ser.rs
lightning-invoice/src/utils.rs
lightning-invoice/tests/ser_de.rs

index 01adf67d1af0816bcc78ddeeacd6473f680b71bf..2e638ff14cb6405a2cf73f649c75987d562dd8e6 100644 (file)
@@ -23,7 +23,7 @@ use num_traits::{CheckedAdd, CheckedMul};
 use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
 use secp256k1::PublicKey;
 
-use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiryDelta, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
+use super::{Bolt11Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiryDelta, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
        SemanticError, PrivateRoute, ParseError, ParseOrSemanticError, Description, RawTaggedField, Currency, RawHrp, SiPrefix, RawInvoice,
        constants, SignedRawInvoice, RawDataPart, InvoiceFeatures};
 
@@ -210,7 +210,7 @@ impl FromStr for SiPrefix {
 }
 
 /// ```
-/// use lightning_invoice::Invoice;
+/// use lightning_invoice::Bolt11Invoice;
 ///
 ///
 /// let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcs\
@@ -225,14 +225,14 @@ impl FromStr for SiPrefix {
 /// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\
 /// j5r6drg6k6zcqj0fcwg";
 ///
-/// assert!(invoice.parse::<Invoice>().is_ok());
+/// assert!(invoice.parse::<Bolt11Invoice>().is_ok());
 /// ```
-impl FromStr for Invoice {
+impl FromStr for Bolt11Invoice {
        type Err = ParseOrSemanticError;
 
        fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
                let signed = s.parse::<SignedRawInvoice>()?;
-               Ok(Invoice::from_signed(signed)?)
+               Ok(Bolt11Invoice::from_signed(signed)?)
        }
 }
 
@@ -251,10 +251,10 @@ impl FromStr for Invoice {
 /// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\
 /// j5r6drg6k6zcqj0fcwg";
 ///
-/// let parsed_1 = invoice.parse::<Invoice>();
+/// let parsed_1 = invoice.parse::<Bolt11Invoice>();
 ///
 /// let parsed_2 = match invoice.parse::<SignedRawInvoice>() {
-///    Ok(signed) => match Invoice::from_signed(signed) {
+///    Ok(signed) => match Bolt11Invoice::from_signed(signed) {
 ///            Ok(invoice) => Ok(invoice),
 ///            Err(e) => Err(ParseOrSemanticError::SemanticError(e)),
 ///    },
index 454a67f635205c5269edfd5b802dd9bce0fccbba..94566ba73783e9cca3e7fe7e02a9d8feaf10f065 100644 (file)
 //! invoices and functions to create, encode and decode these. If you just want to use the standard
 //! en-/decoding functionality this should get you started:
 //!
-//!   * For parsing use `str::parse::<Invoice>(&self)` (see [`Invoice::from_str`])
+//!   * For parsing use `str::parse::<Bolt11Invoice>(&self)` (see [`Bolt11Invoice::from_str`])
 //!   * For constructing invoices use the [`InvoiceBuilder`]
 //!   * For serializing invoices use the [`Display`]/[`ToString`] traits
 //!
-//! [`Invoice::from_str`]: crate::Invoice#impl-FromStr
+//! [`Bolt11Invoice::from_str`]: crate::Bolt11Invoice#impl-FromStr
 
 #[cfg(not(any(feature = "std", feature = "no-std")))]
 compile_error!("at least one of the `std` or `no-std` features must be enabled");
@@ -164,8 +164,8 @@ pub const DEFAULT_EXPIRY_TIME: u64 = 3600;
 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
 pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA: u64 = 18;
 
-/// Builder for [`Invoice`]s. It's the most convenient and advised way to use this library. It ensures
-/// that only a semantically and syntactically correct Invoice can be built using it.
+/// Builder for [`Bolt11Invoice`]s. It's the most convenient and advised way to use this library. It
+/// ensures that only a semantically and syntactically correct invoice can be built using it.
 ///
 /// ```
 /// extern crate secp256k1;
@@ -243,14 +243,14 @@ pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S:
 
 /// Represents a syntactically and semantically correct lightning BOLT11 invoice.
 ///
-/// There are three ways to construct an `Invoice`:
+/// There are three ways to construct a `Bolt11Invoice`:
 ///  1. using [`InvoiceBuilder`]
-///  2. using [`Invoice::from_signed`]
-///  3. using `str::parse::<Invoice>(&str)` (see [`Invoice::from_str`])
+///  2. using [`Bolt11Invoice::from_signed`]
+///  3. using `str::parse::<Bolt11Invoice>(&str)` (see [`Bolt11Invoice::from_str`])
 ///
-/// [`Invoice::from_str`]: crate::Invoice#impl-FromStr
+/// [`Bolt11Invoice::from_str`]: crate::Bolt11Invoice#impl-FromStr
 #[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
-pub struct Invoice {
+pub struct Bolt11Invoice {
        signed_invoice: SignedRawInvoice,
 }
 
@@ -291,11 +291,11 @@ pub struct SignedRawInvoice {
        signature: InvoiceSignature,
 }
 
-/// Represents an syntactically correct [`Invoice`] for a payment on the lightning network,
+/// Represents an syntactically correct [`Bolt11Invoice`] for a payment on the lightning network,
 /// but without the signature information.
 /// Decoding and encoding should not lead to information loss but may lead to different hashes.
 ///
-/// For methods without docs see the corresponding methods in [`Invoice`].
+/// For methods without docs see the corresponding methods in [`Bolt11Invoice`].
 #[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
 pub struct RawInvoice {
        /// human readable part
@@ -807,7 +807,7 @@ impl<M: tb::Bool> InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::Tru
        /// Builds and signs an invoice using the supplied `sign_function`. This function MAY NOT fail
        /// and MUST produce a recoverable signature valid for the given hash and if applicable also for
        /// the included payee public key.
-       pub fn build_signed<F>(self, sign_function: F) -> Result<Invoice, CreationError>
+       pub fn build_signed<F>(self, sign_function: F) -> Result<Bolt11Invoice, CreationError>
                where F: FnOnce(&Message) -> RecoverableSignature
        {
                let invoice = self.try_build_signed::<_, ()>(|hash| {
@@ -824,7 +824,7 @@ impl<M: tb::Bool> InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::Tru
        /// Builds and signs an invoice using the supplied `sign_function`. This function MAY fail with
        /// an error of type `E` and MUST produce a recoverable signature valid for the given hash and
        /// if applicable also for the included payee public key.
-       pub fn try_build_signed<F, E>(self, sign_function: F) -> Result<Invoice, SignOrCreationError<E>>
+       pub fn try_build_signed<F, E>(self, sign_function: F) -> Result<Bolt11Invoice, SignOrCreationError<E>>
                where F: FnOnce(&Message) -> Result<RecoverableSignature, E>
        {
                let raw = match self.build_raw() {
@@ -837,7 +837,7 @@ impl<M: tb::Bool> InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::Tru
                        Err(e) => return Err(SignOrCreationError::SignError(e)),
                };
 
-               let invoice = Invoice {
+               let invoice = Bolt11Invoice {
                        signed_invoice: signed,
                };
 
@@ -1142,13 +1142,13 @@ impl From<PositiveTimestamp> for SystemTime {
        }
 }
 
-impl Invoice {
+impl Bolt11Invoice {
        /// The hash of the [`RawInvoice`] that was signed.
        pub fn signable_hash(&self) -> [u8; 32] {
                self.signed_invoice.hash
        }
 
-       /// Transform the `Invoice` into its unchecked version.
+       /// Transform the `Bolt11Invoice` into its unchecked version.
        pub fn into_signed_raw(self) -> SignedRawInvoice {
                self.signed_invoice
        }
@@ -1252,7 +1252,7 @@ impl Invoice {
                Ok(())
        }
 
-       /// Constructs an `Invoice` from a [`SignedRawInvoice`] by checking all its invariants.
+       /// Constructs a `Bolt11Invoice` from a [`SignedRawInvoice`] by checking all its invariants.
        /// ```
        /// use lightning_invoice::*;
        ///
@@ -1270,10 +1270,10 @@ impl Invoice {
        ///
        /// let signed = invoice.parse::<SignedRawInvoice>().unwrap();
        ///
-       /// assert!(Invoice::from_signed(signed).is_ok());
+       /// assert!(Bolt11Invoice::from_signed(signed).is_ok());
        /// ```
        pub fn from_signed(signed_invoice: SignedRawInvoice) -> Result<Self, SemanticError> {
-               let invoice = Invoice {
+               let invoice = Bolt11Invoice {
                        signed_invoice,
                };
                invoice.check_field_counts()?;
@@ -1284,18 +1284,18 @@ impl Invoice {
                Ok(invoice)
        }
 
-       /// Returns the `Invoice`'s timestamp (should equal its creation time)
+       /// Returns the `Bolt11Invoice`'s timestamp (should equal its creation time)
        #[cfg(feature = "std")]
        pub fn timestamp(&self) -> SystemTime {
                self.signed_invoice.raw_invoice().data.timestamp.as_time()
        }
 
-       /// Returns the `Invoice`'s timestamp as a duration since the Unix epoch
+       /// Returns the `Bolt11Invoice`'s timestamp as a duration since the Unix epoch
        pub fn duration_since_epoch(&self) -> Duration {
                self.signed_invoice.raw_invoice().data.timestamp.0
        }
 
-       /// Returns an iterator over all tagged fields of this Invoice.
+       /// Returns an iterator over all tagged fields of this `Bolt11Invoice`.
        ///
        /// This is not exported to bindings users as there is not yet a manual mapping for a FilterMap
        pub fn tagged_fields(&self)
@@ -1607,7 +1607,7 @@ impl Deref for SignedRawInvoice {
        }
 }
 
-/// Errors that may occur when constructing a new [`RawInvoice`] or [`Invoice`]
+/// Errors that may occur when constructing a new [`RawInvoice`] or [`Bolt11Invoice`]
 #[derive(Eq, PartialEq, Debug, Clone)]
 pub enum CreationError {
        /// The supplied description string was longer than 639 __bytes__ (see [`Description::new`])
@@ -1651,8 +1651,8 @@ impl Display for CreationError {
 #[cfg(feature = "std")]
 impl std::error::Error for CreationError { }
 
-/// Errors that may occur when converting a [`RawInvoice`] to an [`Invoice`]. They relate to the
-/// requirements sections in BOLT #11
+/// Errors that may occur when converting a [`RawInvoice`] to a [`Bolt11Invoice`]. They relate to
+/// the requirements sections in BOLT #11
 #[derive(Eq, PartialEq, Debug, Clone)]
 pub enum SemanticError {
        /// The invoice is missing the mandatory payment hash
@@ -1728,16 +1728,16 @@ impl<S> Display for SignOrCreationError<S> {
 }
 
 #[cfg(feature = "serde")]
-impl Serialize for Invoice {
+impl Serialize for Bolt11Invoice {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
                serializer.serialize_str(self.to_string().as_str())
        }
 }
 #[cfg(feature = "serde")]
-impl<'de> Deserialize<'de> for Invoice {
-       fn deserialize<D>(deserializer: D) -> Result<Invoice, D::Error> where D: Deserializer<'de> {
+impl<'de> Deserialize<'de> for Bolt11Invoice {
+       fn deserialize<D>(deserializer: D) -> Result<Bolt11Invoice, D::Error> where D: Deserializer<'de> {
                let bolt11 = String::deserialize(deserializer)?
-                       .parse::<Invoice>()
+                       .parse::<Bolt11Invoice>()
                        .map_err(|e| D::Error::custom(format_args!("{:?}", e)))?;
 
                Ok(bolt11)
@@ -1866,7 +1866,7 @@ mod test {
                use lightning::ln::features::InvoiceFeatures;
                use secp256k1::Secp256k1;
                use secp256k1::SecretKey;
-               use crate::{RawInvoice, RawHrp, RawDataPart, Currency, Sha256, PositiveTimestamp, Invoice,
+               use crate::{Bolt11Invoice, RawInvoice, RawHrp, RawDataPart, Currency, Sha256, PositiveTimestamp, 
                         SemanticError};
 
                let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
@@ -1898,7 +1898,7 @@ mod test {
                        invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
 
                // Missing feature bits
                let invoice = {
@@ -1907,7 +1907,7 @@ mod test {
                        invoice.data.tagged_fields.push(Features(InvoiceFeatures::empty()).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
 
                let mut payment_secret_features = InvoiceFeatures::empty();
                payment_secret_features.set_payment_secret_required();
@@ -1919,14 +1919,14 @@ mod test {
                        invoice.data.tagged_fields.push(Features(payment_secret_features.clone()).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert!(Invoice::from_signed(invoice).is_ok());
+               assert!(Bolt11Invoice::from_signed(invoice).is_ok());
 
                // No payment secret or features
                let invoice = {
                        let invoice = invoice_template.clone();
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
 
                // No payment secret or feature bits
                let invoice = {
@@ -1934,7 +1934,7 @@ mod test {
                        invoice.data.tagged_fields.push(Features(InvoiceFeatures::empty()).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
 
                // Missing payment secret
                let invoice = {
@@ -1942,7 +1942,7 @@ mod test {
                        invoice.data.tagged_fields.push(Features(payment_secret_features).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
 
                // Multiple payment secrets
                let invoice = {
@@ -1951,7 +1951,7 @@ mod test {
                        invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
                }.unwrap();
-               assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::MultiplePaymentSecrets));
+               assert_eq!(Bolt11Invoice::from_signed(invoice), Err(SemanticError::MultiplePaymentSecrets));
        }
 
        #[test]
@@ -2176,7 +2176,7 @@ mod test {
                                Ok(secp_ctx.sign_ecdsa_recoverable(hash, &privkey))
                        })
                        .unwrap();
-               let invoice = Invoice::from_signed(signed_invoice).unwrap();
+               let invoice = Bolt11Invoice::from_signed(signed_invoice).unwrap();
 
                assert_eq!(invoice.min_final_cltv_expiry_delta(), DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA);
                assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
@@ -2202,7 +2202,7 @@ mod test {
                                Ok(secp_ctx.sign_ecdsa_recoverable(hash, &privkey))
                        })
                        .unwrap();
-               let invoice = Invoice::from_signed(signed_invoice).unwrap();
+               let invoice = Bolt11Invoice::from_signed(signed_invoice).unwrap();
 
                assert!(invoice.would_expire(Duration::from_secs(1234567 + DEFAULT_EXPIRY_TIME + 1)));
        }
@@ -2221,9 +2221,9 @@ mod test {
                        p62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh3\
                        8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\
                        j5r6drg6k6zcqj0fcwg";
-               let invoice = invoice_str.parse::<super::Invoice>().unwrap();
+               let invoice = invoice_str.parse::<super::Bolt11Invoice>().unwrap();
                let serialized_invoice = serde_json::to_string(&invoice).unwrap();
-               let deserialized_invoice: super::Invoice = serde_json::from_str(serialized_invoice.as_str()).unwrap();
+               let deserialized_invoice: super::Bolt11Invoice = serde_json::from_str(serialized_invoice.as_str()).unwrap();
                assert_eq!(invoice, deserialized_invoice);
                assert_eq!(invoice_str, deserialized_invoice.to_string().as_str());
                assert_eq!(invoice_str, serialized_invoice.as_str().trim_matches('\"'));
index bf161dbbf0ebc34e78bf5309761621f4ad1662ee..42408540ee41e7a9e1f9d8ba6c711c6def7b565d 100644 (file)
@@ -9,7 +9,7 @@
 
 //! Convenient utilities for paying Lightning invoices and sending spontaneous payments.
 
-use crate::Invoice;
+use crate::Bolt11Invoice;
 
 use bitcoin_hashes::Hash;
 
@@ -25,15 +25,15 @@ use core::fmt::Debug;
 use core::ops::Deref;
 use core::time::Duration;
 
-/// Pays the given [`Invoice`], retrying if needed based on [`Retry`].
+/// Pays the given [`Bolt11Invoice`], retrying if needed based on [`Retry`].
 ///
-/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
+/// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
 /// with the same [`PaymentHash`] is never sent.
 ///
 /// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`].
 pub fn pay_invoice<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
-       invoice: &Invoice, retry_strategy: Retry,
+       invoice: &Bolt11Invoice, retry_strategy: Retry,
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
 ) -> Result<PaymentId, PaymentError>
 where
@@ -51,17 +51,18 @@ where
                .map(|()| payment_id)
 }
 
-/// Pays the given [`Invoice`] with a custom idempotency key, retrying if needed based on [`Retry`].
+/// Pays the given [`Bolt11Invoice`] with a custom idempotency key, retrying if needed based on
+/// [`Retry`].
 ///
 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
 /// payment completes or fails, no idempotency guarantees are made.
 ///
-/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
-/// has never been paid before.
+/// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
+/// [`PaymentHash`] has never been paid before.
 ///
 /// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token.
 pub fn pay_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
-       invoice: &Invoice, payment_id: PaymentId, retry_strategy: Retry,
+       invoice: &Bolt11Invoice, payment_id: PaymentId, retry_strategy: Retry,
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
 ) -> Result<(), PaymentError>
 where
@@ -78,17 +79,17 @@ where
        pay_invoice_using_amount(invoice, amt_msat, payment_id, retry_strategy, channelmanager)
 }
 
-/// Pays the given zero-value [`Invoice`] using the given amount, retrying if needed based on
+/// Pays the given zero-value [`Bolt11Invoice`] using the given amount, retrying if needed based on
 /// [`Retry`].
 ///
-/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
+/// [`Bolt11Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
 /// as the payment is still pending. If the payment succeeds, you must ensure that a second payment
 /// with the same [`PaymentHash`] is never sent.
 ///
 /// If you wish to use a different payment idempotency token, see
 /// [`pay_zero_value_invoice_with_id`].
 pub fn pay_zero_value_invoice<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
-       invoice: &Invoice, amount_msats: u64, retry_strategy: Retry,
+       invoice: &Bolt11Invoice, amount_msats: u64, retry_strategy: Retry,
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
 ) -> Result<PaymentId, PaymentError>
 where
@@ -107,19 +108,19 @@ where
                .map(|()| payment_id)
 }
 
-/// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
+/// Pays the given zero-value [`Bolt11Invoice`] using the given amount and custom idempotency key,
 /// retrying if needed based on [`Retry`].
 ///
 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
 /// payment completes or fails, no idempotency guarantees are made.
 ///
-/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
-/// has never been paid before.
+/// You should ensure that the [`Bolt11Invoice::payment_hash`] is unique and the same
+/// [`PaymentHash`] has never been paid before.
 ///
 /// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
 /// idempotency token.
 pub fn pay_zero_value_invoice_with_id<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
-       invoice: &Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
+       invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>
 ) -> Result<(), PaymentError>
 where
@@ -141,7 +142,7 @@ where
 }
 
 fn pay_invoice_using_amount<P: Deref>(
-       invoice: &Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
+       invoice: &Bolt11Invoice, amount_msats: u64, payment_id: PaymentId, retry_strategy: Retry,
        payer: P
 ) -> Result<(), PaymentError> where P::Target: Payer {
        let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
@@ -164,20 +165,20 @@ fn pay_invoice_using_amount<P: Deref>(
        payer.send_payment(payment_hash, recipient_onion, payment_id, route_params, retry_strategy)
 }
 
-fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
+fn expiry_time_from_unix_epoch(invoice: &Bolt11Invoice) -> Duration {
        invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
 }
 
 /// An error that may occur when making a payment.
 #[derive(Clone, Debug, PartialEq, Eq)]
 pub enum PaymentError {
-       /// An error resulting from the provided [`Invoice`] or payment hash.
+       /// An error resulting from the provided [`Bolt11Invoice`] or payment hash.
        Invoice(&'static str),
        /// An error occurring when sending a payment.
        Sending(RetryableSendFailure),
 }
 
-/// A trait defining behavior of an [`Invoice`] payer.
+/// A trait defining behavior of a [`Bolt11Invoice`] payer.
 ///
 /// Useful for unit testing internal methods.
 trait Payer {
@@ -283,7 +284,7 @@ mod tests {
                duration_since_epoch
        }
 
-       fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
+       fn invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
                let payment_hash = Sha256::hash(&payment_preimage.0);
                let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
 
@@ -300,7 +301,7 @@ mod tests {
                        .unwrap()
        }
 
-       fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
+       fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Bolt11Invoice {
                let payment_hash = Sha256::hash(&payment_preimage.0);
                let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
 
index 0dca180cab370a79e9358b89d7f1e1d2e51a8c95..a29f3e665e09c4ad1761932964f93fb95c833743 100644 (file)
@@ -3,7 +3,7 @@ use core::fmt::{Display, Formatter};
 use bech32::{ToBase32, u5, WriteBase32, Base32Len};
 use crate::prelude::*;
 
-use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiryDelta, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
+use super::{Bolt11Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiryDelta, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
        PrivateRoute, Description, RawTaggedField, Currency, RawHrp, SiPrefix, constants, SignedRawInvoice, RawDataPart};
 
 /// Converts a stream of bytes written to it to base32. On finalization the according padding will
@@ -106,7 +106,7 @@ fn bytes_size_to_base32_size(byte_size: usize) -> usize {
        }
 }
 
-impl Display for Invoice {
+impl Display for Bolt11Invoice {
        fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
                self.signed_invoice.fmt(f)
        }
index 199aad064694c975d6e97cc132e3b460a84c1b71..8d11d54e64f4d892383ee37851d094059bf47026 100644 (file)
@@ -1,6 +1,6 @@
 //! Convenient utilities to create an invoice.
 
-use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
+use crate::{Bolt11Invoice, CreationError, Currency, InvoiceBuilder, SignOrCreationError};
 
 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
 use bech32::ToBase32;
@@ -64,7 +64,7 @@ pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
        amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
        invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
        node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
 where
        ES::Target: EntropySource,
        NS::Target: NodeSigner,
@@ -120,7 +120,7 @@ pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Der
        amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
        description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
        node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
 where
        ES::Target: EntropySource,
        NS::Target: NodeSigner,
@@ -139,7 +139,7 @@ fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
        amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
        invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
        node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
 where
        ES::Target: EntropySource,
        NS::Target: NodeSigner,
@@ -219,7 +219,7 @@ where
        let data_without_signature = raw_invoice.data.to_base32();
        let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
        match signed_raw_invoice {
-               Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
+               Ok(inv) => Ok(Bolt11Invoice::from_signed(inv).unwrap()),
                Err(e) => Err(SignOrCreationError::SignError(e))
        }
 }
@@ -333,7 +333,7 @@ pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Der
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
        min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
        T::Target: BroadcasterInterface,
@@ -374,7 +374,7 @@ pub fn create_invoice_from_channelmanager_with_description_hash<M: Deref, T: Der
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
        invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
 where
        M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
        T::Target: BroadcasterInterface,
@@ -404,7 +404,7 @@ pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_sin
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
        duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
                where
                        M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
                        T::Target: BroadcasterInterface,
@@ -429,7 +429,7 @@ pub fn create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T:
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
        invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
                where
                        M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
                        T::Target: BroadcasterInterface,
@@ -453,7 +453,7 @@ fn _create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T: Der
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
        duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
                where
                        M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
                        T::Target: BroadcasterInterface,
@@ -486,7 +486,7 @@ pub fn create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_
        channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
        network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
        invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
        where
                M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
                T::Target: BroadcasterInterface,
@@ -516,7 +516,7 @@ fn _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_has
        network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
        invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
        min_final_cltv_expiry_delta: Option<u16>,
-) -> Result<Invoice, SignOrCreationError<()>>
+) -> Result<Bolt11Invoice, SignOrCreationError<()>>
        where
                M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
                T::Target: BroadcasterInterface,
@@ -571,7 +571,7 @@ fn _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_has
        let data_without_signature = raw_invoice.data.to_base32();
        let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
        match signed_raw_invoice {
-               Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
+               Ok(inv) => Ok(Bolt11Invoice::from_signed(inv).unwrap()),
                Err(e) => Err(SignOrCreationError::SignError(e))
        }
 }
index ef5a4d32b30a0caa7c397217fb808a64ca2be877..437d7418a185e31bcbce823840806886b5eeaadc 100644 (file)
@@ -412,35 +412,35 @@ fn invoice_deserialize() {
                }
                assert_eq!(deserialized_hunks, parsed_hunks);
 
-               Invoice::from_signed(serialized.parse::<SignedRawInvoice>().unwrap()).unwrap();
+               Bolt11Invoice::from_signed(serialized.parse::<SignedRawInvoice>().unwrap()).unwrap();
        }
 }
 
 #[test]
 fn test_bolt_invalid_invoices() {
        // Tests the BOLT 11 invalid invoice test vectors
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc25m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5vdhkven9v5sxyetpdeessp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9q4psqqqqqqqqqqqqqqqqsgqtqyx5vggfcsll4wu246hz02kp85x4katwsk9639we5n5yngc3yhqkm35jnjw4len8vrnqnf5ejh0mzj9n3vz2px97evektfm2l6wqccp3y7372"
                ), Err(ParseOrSemanticError::SemanticError(SemanticError::InvalidFeatures)));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrnt"
                ), Err(ParseOrSemanticError::ParseError(ParseError::Bech32Error(bech32::Error::InvalidChecksum))));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny"
                ), Err(ParseOrSemanticError::ParseError(ParseError::Bech32Error(bech32::Error::MissingSeparator))));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "LNBC2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpquwpc4curk03c9wlrswe78q4eyqc7d8d0xqzpuyk0sg5g70me25alkluzd2x62aysf2pyy8edtjeevuv4p2d5p76r4zkmneet7uvyakky2zr4cusd45tftc9c5fh0nnqpnl2jfll544esqchsrny"
                ), Err(ParseOrSemanticError::ParseError(ParseError::Bech32Error(bech32::Error::MixedCase))));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqwgt7mcn5yqw3yx0w94pswkpq6j9uh6xfqqqtsk4tnarugeektd4hg5975x9am52rz4qskukxdmjemg92vvqz8nvmsye63r5ykel43pgz7zq0g2"
                ), Err(ParseOrSemanticError::SemanticError(SemanticError::InvalidSignature)));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6na6hlh"
                ), Err(ParseOrSemanticError::ParseError(ParseError::TooShortDataPart)));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc2500x1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgqrrzc4cvfue4zp3hggxp47ag7xnrlr8vgcmkjxk3j5jqethnumgkpqp23z9jclu3v0a7e0aruz366e9wqdykw6dxhdzcjjhldxq0w6wgqcnu43j"
                ), Err(ParseOrSemanticError::ParseError(ParseError::UnknownSiPrefix)));
-       assert_eq!(Invoice::from_str(
+       assert_eq!(Bolt11Invoice::from_str(
                "lnbc2500000001p1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4jsxqzpusp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygs9qrsgq0lzc236j96a95uv0m3umg28gclm5lqxtqqwk32uuk4k6673k6n5kfvx3d2h8s295fad45fdhmusm8sjudfhlf6dcsxmfvkeywmjdkxcp99202x"
                ), Err(ParseOrSemanticError::SemanticError(SemanticError::ImpreciseAmount)));
 }