Invoice request raw byte encoding and decoding
[rust-lightning] / lightning / src / offers / offer.rs
index e57334f316c02745f2d53127ef3c548b3383af47..1403fbd223ec19ab8888f0e2fdaae8432dcd0cb8 100644 (file)
@@ -76,9 +76,9 @@ use core::time::Duration;
 use crate::io;
 use crate::ln::features::OfferFeatures;
 use crate::ln::msgs::MAX_VALUE_MSAT;
-use crate::offers::parse::{Bech32Encode, ParseError, SemanticError};
+use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
 use crate::onion_message::BlindedPath;
-use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
+use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
 use crate::util::string::PrintableString;
 
 use crate::prelude::*;
@@ -137,7 +137,7 @@ impl OfferBuilder {
        /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
        ///
        /// Successive calls to this method will override the previous setting.
-       pub fn amount_msats(mut self, amount_msats: u64) -> Self {
+       pub fn amount_msats(self, amount_msats: u64) -> Self {
                self.amount(Amount::Bitcoin { amount_msats })
        }
 
@@ -185,7 +185,8 @@ impl OfferBuilder {
                self
        }
 
-       /// Sets the quantity of items for [`Offer::supported_quantity`].
+       /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
+       /// [`Quantity::one`].
        ///
        /// Successive calls to this method will override the previous setting.
        pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
@@ -223,7 +224,7 @@ impl OfferBuilder {
 
 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
 ///
-/// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
+/// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
 ///
@@ -231,6 +232,8 @@ impl OfferBuilder {
 /// latter.
 ///
 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
+///
+/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
 #[derive(Clone, Debug)]
 pub struct Offer {
        // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
@@ -239,9 +242,11 @@ pub struct Offer {
        contents: OfferContents,
 }
 
-/// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
+/// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an `Invoice`.
+///
+/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
 #[derive(Clone, Debug)]
-pub(crate) struct OfferContents {
+pub(super) struct OfferContents {
        chains: Option<Vec<ChainHash>>,
        metadata: Option<Vec<u8>>,
        amount: Option<Amount>,
@@ -262,10 +267,12 @@ impl Offer {
        /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
        /// for the selected chain.
        pub fn chains(&self) -> Vec<ChainHash> {
-               self.contents.chains
-                       .as_ref()
-                       .cloned()
-                       .unwrap_or_else(|| vec![self.contents.implied_chain()])
+               self.contents.chains()
+       }
+
+       /// Returns whether the given chain is supported by the offer.
+       pub fn supports_chain(&self, chain: ChainHash) -> bool {
+               self.contents.supports_chain(chain)
        }
 
        // TODO: Link to corresponding method in `InvoiceRequest`.
@@ -277,7 +284,7 @@ impl Offer {
 
        /// The minimum amount required for a successful payment of a single item.
        pub fn amount(&self) -> Option<&Amount> {
-               self.contents.amount.as_ref()
+               self.contents.amount()
        }
 
        /// A complete description of the purpose of the payment. Intended to be displayed to the user
@@ -327,6 +334,18 @@ impl Offer {
                self.contents.supported_quantity()
        }
 
+       /// Returns whether the given quantity is valid for the offer.
+       pub fn is_valid_quantity(&self, quantity: u64) -> bool {
+               self.contents.is_valid_quantity(quantity)
+       }
+
+       /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
+       ///
+       /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
+       pub fn expects_quantity(&self) -> bool {
+               self.contents.expects_quantity()
+       }
+
        /// The public key used by the recipient to sign invoices.
        pub fn signing_pubkey(&self) -> PublicKey {
                self.contents.signing_pubkey.unwrap()
@@ -345,14 +364,56 @@ impl AsRef<[u8]> for Offer {
 }
 
 impl OfferContents {
+       pub fn chains(&self) -> Vec<ChainHash> {
+               self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
+       }
+
        pub fn implied_chain(&self) -> ChainHash {
                ChainHash::using_genesis_block(Network::Bitcoin)
        }
 
+       pub fn supports_chain(&self, chain: ChainHash) -> bool {
+               self.chains().contains(&chain)
+       }
+
+       pub fn amount(&self) -> Option<&Amount> {
+               self.amount.as_ref()
+       }
+
+       pub fn amount_msats(&self) -> u64 {
+               match self.amount() {
+                       None => 0,
+                       Some(&Amount::Bitcoin { amount_msats }) => amount_msats,
+                       Some(&Amount::Currency { .. }) => unreachable!(),
+               }
+       }
+
+       pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
+               self.amount_msats() * quantity
+       }
+
        pub fn supported_quantity(&self) -> Quantity {
                self.supported_quantity
        }
 
+       pub fn is_valid_quantity(&self, quantity: u64) -> bool {
+               match self.supported_quantity {
+                       Quantity::Bounded(n) => {
+                               let n = n.get();
+                               if n == 1 { false }
+                               else { quantity > 0 && quantity <= n }
+                       },
+                       Quantity::Unbounded => quantity > 0,
+               }
+       }
+
+       pub fn expects_quantity(&self) -> bool {
+               match self.supported_quantity {
+                       Quantity::Bounded(n) => n.get() != 1,
+                       Quantity::Unbounded => true,
+               }
+       }
+
        fn as_tlv_stream(&self) -> OfferTlvStreamRef {
                let (currency, amount) = match &self.amount {
                        None => (None, None),
@@ -394,15 +455,6 @@ impl Writeable for OfferContents {
        }
 }
 
-impl TryFrom<Vec<u8>> for Offer {
-       type Error = ParseError;
-
-       fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
-               let tlv_stream: OfferTlvStream = Readable::read(&mut &bytes[..])?;
-               Offer::try_from((bytes, tlv_stream))
-       }
-}
-
 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
 /// another currency.
 #[derive(Clone, Debug, PartialEq)]
@@ -434,7 +486,8 @@ pub enum Quantity {
 }
 
 impl Quantity {
-       fn one() -> Self {
+       /// The default quantity of one.
+       pub fn one() -> Self {
                Quantity::Bounded(NonZeroU64::new(1).unwrap())
        }
 
@@ -449,7 +502,7 @@ impl Quantity {
        }
 }
 
-tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
+tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
        (2, chains: (Vec<ChainHash>, WithoutLength)),
        (4, metadata: (Vec<u8>, WithoutLength)),
        (6, currency: CurrencyCode),
@@ -467,8 +520,6 @@ impl Bech32Encode for Offer {
        const BECH32_HRP: &'static str = "lno";
 }
 
-type ParsedOffer = (Vec<u8>, OfferTlvStream);
-
 impl FromStr for Offer {
        type Err = ParseError;
 
@@ -477,11 +528,12 @@ impl FromStr for Offer {
        }
 }
 
-impl TryFrom<ParsedOffer> for Offer {
+impl TryFrom<Vec<u8>> for Offer {
        type Error = ParseError;
 
-       fn try_from(offer: ParsedOffer) -> Result<Self, Self::Error> {
-               let (bytes, tlv_stream) = offer;
+       fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
+               let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
+               let ParsedMessage { bytes, tlv_stream } = offer;
                let contents = OfferContents::try_from(tlv_stream)?;
                Ok(Offer { bytes, contents })
        }
@@ -551,10 +603,10 @@ mod tests {
        use core::num::NonZeroU64;
        use core::time::Duration;
        use crate::ln::features::OfferFeatures;
-       use crate::ln::msgs::MAX_VALUE_MSAT;
+       use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
        use crate::offers::parse::{ParseError, SemanticError};
        use crate::onion_message::{BlindedHop, BlindedPath};
-       use crate::util::ser::Writeable;
+       use crate::util::ser::{BigSize, Writeable};
        use crate::util::string::PrintableString;
 
        fn pubkey(byte: u8) -> PublicKey {
@@ -575,6 +627,7 @@ mod tests {
 
                assert_eq!(offer.bytes, buffer.as_slice());
                assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
+               assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
                assert_eq!(offer.metadata(), None);
                assert_eq!(offer.amount(), None);
                assert_eq!(offer.description(), PrintableString("foo"));
@@ -613,6 +666,7 @@ mod tests {
                        .chain(Network::Bitcoin)
                        .build()
                        .unwrap();
+               assert!(offer.supports_chain(mainnet));
                assert_eq!(offer.chains(), vec![mainnet]);
                assert_eq!(offer.as_tlv_stream().chains, None);
 
@@ -620,6 +674,7 @@ mod tests {
                        .chain(Network::Testnet)
                        .build()
                        .unwrap();
+               assert!(offer.supports_chain(testnet));
                assert_eq!(offer.chains(), vec![testnet]);
                assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
 
@@ -628,6 +683,7 @@ mod tests {
                        .chain(Network::Testnet)
                        .build()
                        .unwrap();
+               assert!(offer.supports_chain(testnet));
                assert_eq!(offer.chains(), vec![testnet]);
                assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
 
@@ -636,6 +692,8 @@ mod tests {
                        .chain(Network::Testnet)
                        .build()
                        .unwrap();
+               assert!(offer.supports_chain(mainnet));
+               assert!(offer.supports_chain(testnet));
                assert_eq!(offer.chains(), vec![mainnet, testnet]);
                assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
        }
@@ -1003,6 +1061,22 @@ mod tests {
                        },
                }
        }
+
+       #[test]
+       fn fails_parsing_offer_with_extra_tlv_records() {
+               let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
+
+               let mut encoded_offer = Vec::new();
+               offer.write(&mut encoded_offer).unwrap();
+               BigSize(80).write(&mut encoded_offer).unwrap();
+               BigSize(32).write(&mut encoded_offer).unwrap();
+               [42u8; 32].write(&mut encoded_offer).unwrap();
+
+               match Offer::try_from(encoded_offer) {
+                       Ok(_) => panic!("expected error"),
+                       Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
+               }
+       }
 }
 
 #[cfg(test)]