+ /// Only one item. Use when only a single item can be requested.
+ One,
+}
+
+impl Quantity {
+ fn to_tlv_record(&self) -> Option<u64> {
+ match self {
+ Quantity::Bounded(n) => Some(n.get()),
+ Quantity::Unbounded => Some(0),
+ Quantity::One => None,
+ }
+ }
+}
+
+/// Valid type range for offer TLV records.
+pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
+
+/// TLV record type for [`Offer::metadata`].
+const OFFER_METADATA_TYPE: u64 = 4;
+
+/// TLV record type for [`Offer::signing_pubkey`].
+const OFFER_NODE_ID_TYPE: u64 = 22;
+
+tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
+ (2, chains: (Vec<ChainHash>, WithoutLength)),
+ (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
+ (6, currency: CurrencyCode),
+ (8, amount: (u64, HighZeroBytesDroppedBigSize)),
+ (10, description: (String, WithoutLength)),
+ (12, features: (OfferFeatures, WithoutLength)),
+ (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
+ (16, paths: (Vec<BlindedPath>, WithoutLength)),
+ (18, issuer: (String, WithoutLength)),
+ (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
+ (OFFER_NODE_ID_TYPE, node_id: PublicKey),
+});
+
+impl Bech32Encode for Offer {
+ const BECH32_HRP: &'static str = "lno";
+}
+
+impl FromStr for Offer {
+ type Err = Bolt12ParseError;
+
+ fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
+ Self::from_bech32_str(s)
+ }
+}
+
+impl TryFrom<Vec<u8>> for Offer {
+ type Error = Bolt12ParseError;
+
+ 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 })
+ }
+}
+
+impl TryFrom<OfferTlvStream> for OfferContents {
+ type Error = Bolt12SemanticError;
+
+ fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
+ let OfferTlvStream {
+ chains, metadata, currency, amount, description, features, absolute_expiry, paths,
+ issuer, quantity_max, node_id,
+ } = tlv_stream;
+
+ let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
+
+ let amount = match (currency, amount) {
+ (None, None) => None,
+ (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
+ return Err(Bolt12SemanticError::InvalidAmount);
+ },
+ (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
+ (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
+ (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
+ };
+
+ let description = match description {
+ None => return Err(Bolt12SemanticError::MissingDescription),
+ Some(description) => description,
+ };
+
+ let features = features.unwrap_or_else(OfferFeatures::empty);
+
+ let absolute_expiry = absolute_expiry
+ .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
+
+ let supported_quantity = match quantity_max {
+ None => Quantity::One,
+ Some(0) => Quantity::Unbounded,
+ Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
+ };
+
+ let signing_pubkey = match node_id {
+ None => return Err(Bolt12SemanticError::MissingSigningPubkey),
+ Some(node_id) => node_id,
+ };
+
+ Ok(OfferContents {
+ chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
+ supported_quantity, signing_pubkey,
+ })
+ }
+}
+
+impl core::fmt::Display for Offer {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
+ self.fmt_bech32_str(f)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
+
+ use bitcoin::blockdata::constants::ChainHash;
+ use bitcoin::network::constants::Network;
+ use bitcoin::secp256k1::Secp256k1;
+ use core::convert::TryFrom;
+ use core::num::NonZeroU64;
+ use core::time::Duration;
+ use crate::blinded_path::{BlindedHop, BlindedPath};
+ use crate::sign::KeyMaterial;
+ use crate::ln::features::OfferFeatures;
+ use crate::ln::inbound_payment::ExpandedKey;
+ use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
+ use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
+ use crate::offers::test_utils::*;
+ use crate::util::ser::{BigSize, Writeable};
+ use crate::util::string::PrintableString;
+
+ #[test]
+ fn builds_offer_with_defaults() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
+
+ let mut buffer = Vec::new();
+ offer.write(&mut buffer).unwrap();
+
+ 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"));
+ assert_eq!(offer.offer_features(), &OfferFeatures::empty());
+ assert_eq!(offer.absolute_expiry(), None);
+ #[cfg(feature = "std")]
+ assert!(!offer.is_expired());
+ assert_eq!(offer.paths(), &[]);
+ assert_eq!(offer.issuer(), None);
+ assert_eq!(offer.supported_quantity(), Quantity::One);
+ assert_eq!(offer.signing_pubkey(), pubkey(42));
+
+ assert_eq!(
+ offer.as_tlv_stream(),
+ OfferTlvStreamRef {
+ chains: None,
+ metadata: None,
+ currency: None,
+ amount: None,
+ description: Some(&String::from("foo")),
+ features: None,
+ absolute_expiry: None,
+ paths: None,
+ issuer: None,
+ quantity_max: None,
+ node_id: Some(&pubkey(42)),
+ },
+ );
+
+ if let Err(e) = Offer::try_from(buffer) {
+ panic!("error parsing offer: {:?}", e);
+ }
+ }
+
+ #[test]
+ fn builds_offer_with_chains() {
+ let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
+ let testnet = ChainHash::using_genesis_block(Network::Testnet);
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .chain(Network::Bitcoin)
+ .build()
+ .unwrap();
+ assert!(offer.supports_chain(mainnet));
+ assert_eq!(offer.chains(), vec![mainnet]);
+ assert_eq!(offer.as_tlv_stream().chains, None);
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .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]));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .chain(Network::Testnet)
+ .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]));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .chain(Network::Bitcoin)
+ .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]));
+ }
+
+ #[test]
+ fn builds_offer_with_metadata() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .metadata(vec![42; 32]).unwrap()
+ .build()
+ .unwrap();
+ assert_eq!(offer.metadata(), Some(&vec![42; 32]));
+ assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .metadata(vec![42; 32]).unwrap()
+ .metadata(vec![43; 32]).unwrap()
+ .build()
+ .unwrap();
+ assert_eq!(offer.metadata(), Some(&vec![43; 32]));
+ assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
+ }
+
+ #[test]
+ fn builds_offer_with_metadata_derived() {
+ let desc = "foo".to_string();
+ let node_id = recipient_pubkey();
+ let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
+ let entropy = FixedEntropy {};
+ let secp_ctx = Secp256k1::new();
+
+ let offer = OfferBuilder
+ ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
+ .amount_msats(1000)
+ .build().unwrap();
+ assert_eq!(offer.signing_pubkey(), node_id);
+
+ let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
+
+ // Fails verification with altered offer field
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.amount = Some(100);
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ let invoice_request = Offer::try_from(encoded_offer).unwrap()
+ .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
+
+ // Fails verification with altered metadata
+ let mut tlv_stream = offer.as_tlv_stream();
+ let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
+ tlv_stream.metadata = Some(&metadata);
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ let invoice_request = Offer::try_from(encoded_offer).unwrap()
+ .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
+ }
+
+ #[test]
+ fn builds_offer_with_derived_signing_pubkey() {
+ let desc = "foo".to_string();
+ let node_id = recipient_pubkey();
+ let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
+ let entropy = FixedEntropy {};
+ let secp_ctx = Secp256k1::new();
+
+ let blinded_path = BlindedPath {
+ introduction_node_id: pubkey(40),
+ blinding_point: pubkey(41),
+ blinded_hops: vec![
+ BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
+ BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
+ ],
+ };
+
+ let offer = OfferBuilder
+ ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
+ .amount_msats(1000)
+ .path(blinded_path)
+ .build().unwrap();
+ assert_ne!(offer.signing_pubkey(), node_id);
+
+ let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
+
+ // Fails verification with altered offer field
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.amount = Some(100);
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ let invoice_request = Offer::try_from(encoded_offer).unwrap()
+ .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
+
+ // Fails verification with altered signing pubkey
+ let mut tlv_stream = offer.as_tlv_stream();
+ let signing_pubkey = pubkey(1);
+ tlv_stream.node_id = Some(&signing_pubkey);
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ let invoice_request = Offer::try_from(encoded_offer).unwrap()
+ .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
+ .build().unwrap()
+ .sign(payer_sign).unwrap();
+ assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
+ }
+
+ #[test]
+ fn builds_offer_with_amount() {
+ let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
+ let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .amount_msats(1000)
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.amount(), Some(&bitcoin_amount));
+ assert_eq!(tlv_stream.amount, Some(1000));
+ assert_eq!(tlv_stream.currency, None);
+
+ let builder = OfferBuilder::new("foo".into(), pubkey(42))
+ .amount(currency_amount.clone());
+ let tlv_stream = builder.offer.as_tlv_stream();
+ assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
+ assert_eq!(tlv_stream.amount, Some(10));
+ assert_eq!(tlv_stream.currency, Some(b"USD"));
+ match builder.build() {
+ Ok(_) => panic!("expected error"),
+ Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
+ }
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .amount(currency_amount.clone())
+ .amount(bitcoin_amount.clone())
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(tlv_stream.amount, Some(1000));
+ assert_eq!(tlv_stream.currency, None);
+
+ let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
+ match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
+ Ok(_) => panic!("expected error"),
+ Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
+ }
+ }
+
+ #[test]
+ fn builds_offer_with_features() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .features_unchecked(OfferFeatures::unknown())
+ .build()
+ .unwrap();
+ assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
+ assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .features_unchecked(OfferFeatures::unknown())
+ .features_unchecked(OfferFeatures::empty())
+ .build()
+ .unwrap();
+ assert_eq!(offer.offer_features(), &OfferFeatures::empty());
+ assert_eq!(offer.as_tlv_stream().features, None);
+ }
+
+ #[test]
+ fn builds_offer_with_absolute_expiry() {
+ let future_expiry = Duration::from_secs(u64::max_value());
+ let past_expiry = Duration::from_secs(0);
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .absolute_expiry(future_expiry)
+ .build()
+ .unwrap();
+ #[cfg(feature = "std")]
+ assert!(!offer.is_expired());
+ assert_eq!(offer.absolute_expiry(), Some(future_expiry));
+ assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .absolute_expiry(future_expiry)
+ .absolute_expiry(past_expiry)
+ .build()
+ .unwrap();
+ #[cfg(feature = "std")]
+ assert!(offer.is_expired());
+ assert_eq!(offer.absolute_expiry(), Some(past_expiry));
+ assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
+ }
+
+ #[test]
+ fn builds_offer_with_paths() {
+ let paths = vec![
+ BlindedPath {
+ introduction_node_id: pubkey(40),
+ blinding_point: pubkey(41),
+ blinded_hops: vec![
+ BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
+ BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
+ ],
+ },
+ BlindedPath {
+ introduction_node_id: pubkey(40),
+ blinding_point: pubkey(41),
+ blinded_hops: vec![
+ BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
+ BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
+ ],
+ },
+ ];
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .path(paths[0].clone())
+ .path(paths[1].clone())
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.paths(), paths.as_slice());
+ assert_eq!(offer.signing_pubkey(), pubkey(42));
+ assert_ne!(pubkey(42), pubkey(44));
+ assert_eq!(tlv_stream.paths, Some(&paths));
+ assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
+ }
+
+ #[test]
+ fn builds_offer_with_issuer() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .issuer("bar".into())
+ .build()
+ .unwrap();
+ assert_eq!(offer.issuer(), Some(PrintableString("bar")));
+ assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .issuer("bar".into())
+ .issuer("baz".into())
+ .build()
+ .unwrap();
+ assert_eq!(offer.issuer(), Some(PrintableString("baz")));
+ assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
+ }
+
+ #[test]
+ fn builds_offer_with_supported_quantity() {
+ let one = NonZeroU64::new(1).unwrap();
+ let ten = NonZeroU64::new(10).unwrap();
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::One)
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.supported_quantity(), Quantity::One);
+ assert_eq!(tlv_stream.quantity_max, None);
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Unbounded)
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
+ assert_eq!(tlv_stream.quantity_max, Some(0));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Bounded(ten))
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
+ assert_eq!(tlv_stream.quantity_max, Some(10));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Bounded(one))
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
+ assert_eq!(tlv_stream.quantity_max, Some(1));
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Bounded(ten))
+ .supported_quantity(Quantity::One)
+ .build()
+ .unwrap();
+ let tlv_stream = offer.as_tlv_stream();
+ assert_eq!(offer.supported_quantity(), Quantity::One);
+ assert_eq!(tlv_stream.quantity_max, None);
+ }
+
+ #[test]
+ fn fails_requesting_invoice_with_unknown_required_features() {
+ match OfferBuilder::new("foo".into(), pubkey(42))
+ .features_unchecked(OfferFeatures::unknown())
+ .build().unwrap()
+ .request_invoice(vec![1; 32], pubkey(43))
+ {
+ Ok(_) => panic!("expected error"),
+ Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_chains() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .chain(Network::Bitcoin)
+ .chain(Network::Testnet)
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_amount() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .amount(Amount::Bitcoin { amount_msats: 1000 })
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.amount = Some(1000);
+ tlv_stream.currency = Some(b"USD");
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ if let Err(e) = Offer::try_from(encoded_offer) {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.amount = None;
+ tlv_stream.currency = Some(b"USD");
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ match Offer::try_from(encoded_offer) {
+ Ok(_) => panic!("expected error"),
+ Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
+ }
+
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
+ tlv_stream.currency = None;
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ match Offer::try_from(encoded_offer) {
+ Ok(_) => panic!("expected error"),
+ Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_description() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.description = None;
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ match Offer::try_from(encoded_offer) {
+ Ok(_) => panic!("expected error"),
+ Err(e) => {
+ assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
+ },
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_paths() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .path(BlindedPath {
+ introduction_node_id: pubkey(40),
+ blinding_point: pubkey(41),
+ blinded_hops: vec![
+ BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
+ BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
+ ],
+ })
+ .path(BlindedPath {
+ introduction_node_id: pubkey(40),
+ blinding_point: pubkey(41),
+ blinded_hops: vec![
+ BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
+ BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
+ ],
+ })
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
+ builder.offer.paths = Some(vec![]);
+
+ let offer = builder.build().unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_quantity() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::One)
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Unbounded)
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let offer = OfferBuilder::new("foo".into(), pubkey(42))
+ .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
+ .build()
+ .unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+ }
+
+ #[test]
+ fn parses_offer_with_node_id() {
+ let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
+ if let Err(e) = offer.to_string().parse::<Offer>() {
+ panic!("error parsing offer: {:?}", e);
+ }
+
+ let mut tlv_stream = offer.as_tlv_stream();
+ tlv_stream.node_id = None;
+
+ let mut encoded_offer = Vec::new();
+ tlv_stream.write(&mut encoded_offer).unwrap();
+
+ match Offer::try_from(encoded_offer) {
+ Ok(_) => panic!("expected error"),
+ Err(e) => {
+ assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
+ },
+ }
+ }
+
+ #[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, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod bech32_tests {
+ use super::{Bolt12ParseError, Offer};
+ use bitcoin::bech32;
+ use crate::ln::msgs::DecodeError;
+
+ #[test]
+ fn encodes_offer_as_bech32_without_checksum() {
+ let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
+ let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
+ let reencoded_offer = offer.to_string();
+ dbg!(reencoded_offer.parse::<Offer>().unwrap());
+ assert_eq!(reencoded_offer, encoded_offer);
+ }
+
+ #[test]
+ fn parses_bech32_encoded_offers() {
+ let offers = [
+ // BOLT 12 test vectors
+ "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
+ "l+no1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
+ "lno1pqps7sjqpgt+yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+5k7msjzfpy7nz5yqcn+ygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+5xvxg",
+ "lno1pqps7sjqpgt+ yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+ 5k7msjzfpy7nz5yqcn+\nygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+\r\n 5xvxg",
+ ];
+ for encoded_offer in &offers {
+ if let Err(e) = encoded_offer.parse::<Offer>() {
+ panic!("Invalid offer ({:?}): {}", e, encoded_offer);
+ }
+ }
+ }
+
+ #[test]
+ fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
+ let offers = [
+ // BOLT 12 test vectors
+ "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+",
+ "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+ ",
+ "+lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
+ "+ lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
+ "ln++o1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
+ ];
+ for encoded_offer in &offers {
+ match encoded_offer.parse::<Offer>() {
+ Ok(_) => panic!("Valid offer: {}", encoded_offer),
+ Err(e) => assert_eq!(e, Bolt12ParseError::InvalidContinuation),
+ }
+ }
+
+ }
+
+ #[test]
+ fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
+ let encoded_offer = "lni1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
+ match encoded_offer.parse::<Offer>() {
+ Ok(_) => panic!("Valid offer: {}", encoded_offer),
+ Err(e) => assert_eq!(e, Bolt12ParseError::InvalidBech32Hrp),
+ }
+ }
+
+ #[test]
+ fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
+ let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxo";
+ match encoded_offer.parse::<Offer>() {
+ Ok(_) => panic!("Valid offer: {}", encoded_offer),
+ Err(e) => assert_eq!(e, Bolt12ParseError::Bech32(bech32::Error::InvalidChar('o'))),
+ }
+ }
+
+ #[test]
+ fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
+ let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxgqqqqq";
+ match encoded_offer.parse::<Offer>() {
+ Ok(_) => panic!("Valid offer: {}", encoded_offer),
+ Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
+ }
+ }