1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `offer` messages.
12 //! An [`Offer`] represents an "offer to be paid." It is typically constructed by a merchant and
13 //! published as a QR code to be scanned by a customer. The customer uses the offer to request an
14 //! invoice from the merchant to be paid.
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
25 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
26 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
27 //! use lightning::offers::parse::ParseError;
28 //! use lightning::util::ser::{Readable, Writeable};
30 //! # use lightning::onion_message::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # #[cfg(feature = "std")]
38 //! # fn build() -> Result<(), ParseError> {
39 //! let secp_ctx = Secp256k1::new();
40 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
41 //! let pubkey = PublicKey::from(keys);
43 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
44 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
45 //! .amount_msats(20_000)
46 //! .supported_quantity(Quantity::Unbounded)
47 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
48 //! .issuer("Foo Bar".to_string())
49 //! .path(create_blinded_path())
50 //! .path(create_another_blinded_path())
53 //! // Encode as a bech32 string for use in a QR code.
54 //! let encoded_offer = offer.to_string();
56 //! // Parse from a bech32 string after scanning from a QR code.
57 //! let offer = encoded_offer.parse::<Offer>()?;
59 //! // Encode offer as raw bytes.
60 //! let mut bytes = Vec::new();
61 //! offer.write(&mut bytes).unwrap();
63 //! // Decode raw bytes into an offer.
64 //! let offer = Offer::try_from(bytes)?;
69 use bitcoin::blockdata::constants::ChainHash;
70 use bitcoin::network::constants::Network;
71 use bitcoin::secp256k1::PublicKey;
72 use core::convert::TryFrom;
73 use core::num::NonZeroU64;
74 use core::str::FromStr;
75 use core::time::Duration;
77 use crate::ln::features::OfferFeatures;
78 use crate::ln::msgs::MAX_VALUE_MSAT;
79 use crate::offers::invoice_request::InvoiceRequestBuilder;
80 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
81 use crate::onion_message::BlindedPath;
82 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
83 use crate::util::string::PrintableString;
85 use crate::prelude::*;
87 #[cfg(feature = "std")]
88 use std::time::SystemTime;
90 /// Builds an [`Offer`] for the "offer to be paid" flow.
92 /// See [module-level documentation] for usage.
94 /// [module-level documentation]: self
95 pub struct OfferBuilder {
100 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
101 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
102 /// while the offer is valid.
104 /// Use a different pubkey per offer to avoid correlating offers.
105 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
106 let offer = OfferContents {
107 chains: None, metadata: None, amount: None, description,
108 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
109 supported_quantity: Quantity::one(), signing_pubkey,
111 OfferBuilder { offer }
114 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
115 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
117 /// See [`Offer::chains`] on how this relates to the payment currency.
119 /// Successive calls to this method will add another chain hash.
120 pub fn chain(mut self, network: Network) -> Self {
121 let chains = self.offer.chains.get_or_insert_with(Vec::new);
122 let chain = ChainHash::using_genesis_block(network);
123 if !chains.contains(&chain) {
130 /// Sets the [`Offer::metadata`].
132 /// Successive calls to this method will override the previous setting.
133 pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
134 self.offer.metadata = Some(metadata);
138 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
140 /// Successive calls to this method will override the previous setting.
141 pub fn amount_msats(self, amount_msats: u64) -> Self {
142 self.amount(Amount::Bitcoin { amount_msats })
145 /// Sets the [`Offer::amount`].
147 /// Successive calls to this method will override the previous setting.
148 pub(super) fn amount(mut self, amount: Amount) -> Self {
149 self.offer.amount = Some(amount);
153 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
154 /// already passed is valid and can be checked for using [`Offer::is_expired`].
156 /// Successive calls to this method will override the previous setting.
157 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
158 self.offer.absolute_expiry = Some(absolute_expiry);
162 /// Sets the [`Offer::issuer`].
164 /// Successive calls to this method will override the previous setting.
165 pub fn issuer(mut self, issuer: String) -> Self {
166 self.offer.issuer = Some(issuer);
170 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
171 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
173 /// Successive calls to this method will add another blinded path. Caller is responsible for not
174 /// adding duplicate paths.
175 pub fn path(mut self, path: BlindedPath) -> Self {
176 self.offer.paths.get_or_insert_with(Vec::new).push(path);
180 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
181 /// [`Quantity::one`].
183 /// Successive calls to this method will override the previous setting.
184 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
185 self.offer.supported_quantity = quantity;
189 /// Builds an [`Offer`] from the builder's settings.
190 pub fn build(mut self) -> Result<Offer, SemanticError> {
191 match self.offer.amount {
192 Some(Amount::Bitcoin { amount_msats }) => {
193 if amount_msats > MAX_VALUE_MSAT {
194 return Err(SemanticError::InvalidAmount);
197 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
201 if let Some(chains) = &self.offer.chains {
202 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
203 self.offer.chains = None;
207 let mut bytes = Vec::new();
208 self.offer.write(&mut bytes).unwrap();
212 contents: self.offer,
219 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
220 self.offer.features = features;
224 pub(super) fn build_unchecked(self) -> Offer {
225 let mut bytes = Vec::new();
226 self.offer.write(&mut bytes).unwrap();
228 Offer { bytes, contents: self.offer }
232 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
234 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
235 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
236 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
238 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
241 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
243 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
244 #[derive(Clone, Debug)]
246 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
248 pub(super) bytes: Vec<u8>,
249 pub(super) contents: OfferContents,
252 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an `Invoice`.
254 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
255 #[derive(Clone, Debug)]
256 pub(super) struct OfferContents {
257 chains: Option<Vec<ChainHash>>,
258 metadata: Option<Vec<u8>>,
259 amount: Option<Amount>,
261 features: OfferFeatures,
262 absolute_expiry: Option<Duration>,
263 issuer: Option<String>,
264 paths: Option<Vec<BlindedPath>>,
265 supported_quantity: Quantity,
266 signing_pubkey: PublicKey,
270 // TODO: Return a slice once ChainHash has constants.
271 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
272 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
273 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
274 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
275 /// for the selected chain.
276 pub fn chains(&self) -> Vec<ChainHash> {
277 self.contents.chains()
280 pub(super) fn implied_chain(&self) -> ChainHash {
281 self.contents.implied_chain()
284 /// Returns whether the given chain is supported by the offer.
285 pub fn supports_chain(&self, chain: ChainHash) -> bool {
286 self.contents.supports_chain(chain)
289 // TODO: Link to corresponding method in `InvoiceRequest`.
290 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
291 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
292 pub fn metadata(&self) -> Option<&Vec<u8>> {
293 self.contents.metadata.as_ref()
296 /// The minimum amount required for a successful payment of a single item.
297 pub fn amount(&self) -> Option<&Amount> {
298 self.contents.amount()
301 /// A complete description of the purpose of the payment. Intended to be displayed to the user
302 /// but with the caveat that it has not been verified in any way.
303 pub fn description(&self) -> PrintableString {
304 PrintableString(&self.contents.description)
307 /// Features pertaining to the offer.
308 pub fn features(&self) -> &OfferFeatures {
309 &self.contents.features
312 /// Duration since the Unix epoch when an invoice should no longer be requested.
314 /// If `None`, the offer does not expire.
315 pub fn absolute_expiry(&self) -> Option<Duration> {
316 self.contents.absolute_expiry
319 /// Whether the offer has expired.
320 #[cfg(feature = "std")]
321 pub fn is_expired(&self) -> bool {
322 match self.absolute_expiry() {
323 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
324 Ok(elapsed) => elapsed > seconds_from_epoch,
331 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
332 /// displayed to the user but with the caveat that it has not been verified in any way.
333 pub fn issuer(&self) -> Option<PrintableString> {
334 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
337 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
338 /// recipient privacy by obfuscating its node id.
339 pub fn paths(&self) -> &[BlindedPath] {
340 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
343 /// The quantity of items supported.
344 pub fn supported_quantity(&self) -> Quantity {
345 self.contents.supported_quantity()
348 /// Returns whether the given quantity is valid for the offer.
349 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
350 self.contents.is_valid_quantity(quantity)
353 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
355 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
356 pub fn expects_quantity(&self) -> bool {
357 self.contents.expects_quantity()
360 /// The public key used by the recipient to sign invoices.
361 pub fn signing_pubkey(&self) -> PublicKey {
362 self.contents.signing_pubkey
365 /// Creates an [`InvoiceRequest`] for the offer with the given `metadata` and `payer_id`, which
366 /// will be reflected in the `Invoice` response.
368 /// The `metadata` is useful for including information about the derivation of `payer_id` such
369 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
370 /// hashing in the signature calculation.
372 /// This should not leak any information such as by using a simple BIP-32 derivation path.
373 /// Otherwise, payments may be correlated.
375 /// Errors if the offer contains unknown required features.
377 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
378 pub fn request_invoice(
379 &self, metadata: Vec<u8>, payer_id: PublicKey
380 ) -> Result<InvoiceRequestBuilder, SemanticError> {
381 if self.features().requires_unknown_bits() {
382 return Err(SemanticError::UnknownRequiredFeatures);
385 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
389 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
390 self.contents.as_tlv_stream()
394 impl AsRef<[u8]> for Offer {
395 fn as_ref(&self) -> &[u8] {
401 pub fn chains(&self) -> Vec<ChainHash> {
402 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
405 pub fn implied_chain(&self) -> ChainHash {
406 ChainHash::using_genesis_block(Network::Bitcoin)
409 pub fn supports_chain(&self, chain: ChainHash) -> bool {
410 self.chains().contains(&chain)
413 pub fn amount(&self) -> Option<&Amount> {
417 pub(super) fn check_amount_msats_for_quantity(
418 &self, amount_msats: Option<u64>, quantity: Option<u64>
419 ) -> Result<(), SemanticError> {
420 let offer_amount_msats = match self.amount {
422 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
423 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
426 if !self.expects_quantity() || quantity.is_some() {
427 let expected_amount_msats = offer_amount_msats * quantity.unwrap_or(1);
428 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
430 if amount_msats < expected_amount_msats {
431 return Err(SemanticError::InsufficientAmount);
434 if amount_msats > MAX_VALUE_MSAT {
435 return Err(SemanticError::InvalidAmount);
442 pub fn supported_quantity(&self) -> Quantity {
443 self.supported_quantity
446 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
447 let expects_quantity = self.expects_quantity();
449 None if expects_quantity => Err(SemanticError::MissingQuantity),
450 Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
451 Some(quantity) if !self.is_valid_quantity(quantity) => {
452 Err(SemanticError::InvalidQuantity)
458 fn is_valid_quantity(&self, quantity: u64) -> bool {
459 match self.supported_quantity {
460 Quantity::Bounded(n) => {
463 else { quantity > 0 && quantity <= n }
465 Quantity::Unbounded => quantity > 0,
469 fn expects_quantity(&self) -> bool {
470 match self.supported_quantity {
471 Quantity::Bounded(n) => n.get() != 1,
472 Quantity::Unbounded => true,
476 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
477 let (currency, amount) = match &self.amount {
478 None => (None, None),
479 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
480 Some(Amount::Currency { iso4217_code, amount }) => (
481 Some(iso4217_code), Some(*amount)
486 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
490 chains: self.chains.as_ref(),
491 metadata: self.metadata.as_ref(),
494 description: Some(&self.description),
496 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
497 paths: self.paths.as_ref(),
498 issuer: self.issuer.as_ref(),
499 quantity_max: self.supported_quantity.to_tlv_record(),
500 node_id: Some(&self.signing_pubkey),
505 impl Writeable for Offer {
506 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
507 WithoutLength(&self.bytes).write(writer)
511 impl Writeable for OfferContents {
512 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
513 self.as_tlv_stream().write(writer)
517 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
518 /// another currency.
519 #[derive(Clone, Debug, PartialEq)]
521 /// An amount of bitcoin.
523 /// The amount in millisatoshi.
526 /// An amount of currency specified using ISO 4712.
528 /// The currency that the amount is denominated in.
529 iso4217_code: CurrencyCode,
530 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
535 /// An ISO 4712 three-letter currency code (e.g., USD).
536 pub type CurrencyCode = [u8; 3];
538 /// Quantity of items supported by an [`Offer`].
539 #[derive(Clone, Copy, Debug, PartialEq)]
541 /// Up to a specific number of items (inclusive).
543 /// One or more items.
548 /// The default quantity of one.
549 pub fn one() -> Self {
550 Quantity::Bounded(NonZeroU64::new(1).unwrap())
553 fn to_tlv_record(&self) -> Option<u64> {
555 Quantity::Bounded(n) => {
557 if n == 1 { None } else { Some(n) }
559 Quantity::Unbounded => Some(0),
564 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
565 (2, chains: (Vec<ChainHash>, WithoutLength)),
566 (4, metadata: (Vec<u8>, WithoutLength)),
567 (6, currency: CurrencyCode),
568 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
569 (10, description: (String, WithoutLength)),
570 (12, features: OfferFeatures),
571 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
572 (16, paths: (Vec<BlindedPath>, WithoutLength)),
573 (18, issuer: (String, WithoutLength)),
574 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
575 (22, node_id: PublicKey),
578 impl Bech32Encode for Offer {
579 const BECH32_HRP: &'static str = "lno";
582 impl FromStr for Offer {
583 type Err = ParseError;
585 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
586 Self::from_bech32_str(s)
590 impl TryFrom<Vec<u8>> for Offer {
591 type Error = ParseError;
593 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
594 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
595 let ParsedMessage { bytes, tlv_stream } = offer;
596 let contents = OfferContents::try_from(tlv_stream)?;
597 Ok(Offer { bytes, contents })
601 impl TryFrom<OfferTlvStream> for OfferContents {
602 type Error = SemanticError;
604 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
606 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
607 issuer, quantity_max, node_id,
610 let amount = match (currency, amount) {
611 (None, None) => None,
612 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
613 return Err(SemanticError::InvalidAmount);
615 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
616 (Some(_), None) => return Err(SemanticError::MissingAmount),
617 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
620 let description = match description {
621 None => return Err(SemanticError::MissingDescription),
622 Some(description) => description,
625 let features = features.unwrap_or_else(OfferFeatures::empty);
627 let absolute_expiry = absolute_expiry
628 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
630 let supported_quantity = match quantity_max {
631 None => Quantity::one(),
632 Some(0) => Quantity::Unbounded,
633 Some(1) => return Err(SemanticError::InvalidQuantity),
634 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
637 let signing_pubkey = match node_id {
638 None => return Err(SemanticError::MissingSigningPubkey),
639 Some(node_id) => node_id,
643 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
644 supported_quantity, signing_pubkey,
649 impl core::fmt::Display for Offer {
650 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
651 self.fmt_bech32_str(f)
657 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
659 use bitcoin::blockdata::constants::ChainHash;
660 use bitcoin::network::constants::Network;
661 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
662 use core::convert::TryFrom;
663 use core::num::NonZeroU64;
664 use core::time::Duration;
665 use crate::ln::features::OfferFeatures;
666 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
667 use crate::offers::parse::{ParseError, SemanticError};
668 use crate::onion_message::{BlindedHop, BlindedPath};
669 use crate::util::ser::{BigSize, Writeable};
670 use crate::util::string::PrintableString;
672 fn pubkey(byte: u8) -> PublicKey {
673 let secp_ctx = Secp256k1::new();
674 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
677 fn privkey(byte: u8) -> SecretKey {
678 SecretKey::from_slice(&[byte; 32]).unwrap()
682 fn builds_offer_with_defaults() {
683 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
685 let mut buffer = Vec::new();
686 offer.write(&mut buffer).unwrap();
688 assert_eq!(offer.bytes, buffer.as_slice());
689 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
690 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
691 assert_eq!(offer.metadata(), None);
692 assert_eq!(offer.amount(), None);
693 assert_eq!(offer.description(), PrintableString("foo"));
694 assert_eq!(offer.features(), &OfferFeatures::empty());
695 assert_eq!(offer.absolute_expiry(), None);
696 #[cfg(feature = "std")]
697 assert!(!offer.is_expired());
698 assert_eq!(offer.paths(), &[]);
699 assert_eq!(offer.issuer(), None);
700 assert_eq!(offer.supported_quantity(), Quantity::one());
701 assert_eq!(offer.signing_pubkey(), pubkey(42));
704 offer.as_tlv_stream(),
710 description: Some(&String::from("foo")),
712 absolute_expiry: None,
716 node_id: Some(&pubkey(42)),
720 if let Err(e) = Offer::try_from(buffer) {
721 panic!("error parsing offer: {:?}", e);
726 fn builds_offer_with_chains() {
727 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
728 let testnet = ChainHash::using_genesis_block(Network::Testnet);
730 let offer = OfferBuilder::new("foo".into(), pubkey(42))
731 .chain(Network::Bitcoin)
734 assert!(offer.supports_chain(mainnet));
735 assert_eq!(offer.chains(), vec![mainnet]);
736 assert_eq!(offer.as_tlv_stream().chains, None);
738 let offer = OfferBuilder::new("foo".into(), pubkey(42))
739 .chain(Network::Testnet)
742 assert!(offer.supports_chain(testnet));
743 assert_eq!(offer.chains(), vec![testnet]);
744 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
746 let offer = OfferBuilder::new("foo".into(), pubkey(42))
747 .chain(Network::Testnet)
748 .chain(Network::Testnet)
751 assert!(offer.supports_chain(testnet));
752 assert_eq!(offer.chains(), vec![testnet]);
753 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
755 let offer = OfferBuilder::new("foo".into(), pubkey(42))
756 .chain(Network::Bitcoin)
757 .chain(Network::Testnet)
760 assert!(offer.supports_chain(mainnet));
761 assert!(offer.supports_chain(testnet));
762 assert_eq!(offer.chains(), vec![mainnet, testnet]);
763 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
767 fn builds_offer_with_metadata() {
768 let offer = OfferBuilder::new("foo".into(), pubkey(42))
769 .metadata(vec![42; 32])
772 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
773 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
775 let offer = OfferBuilder::new("foo".into(), pubkey(42))
776 .metadata(vec![42; 32])
777 .metadata(vec![43; 32])
780 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
781 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
785 fn builds_offer_with_amount() {
786 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
787 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
789 let offer = OfferBuilder::new("foo".into(), pubkey(42))
793 let tlv_stream = offer.as_tlv_stream();
794 assert_eq!(offer.amount(), Some(&bitcoin_amount));
795 assert_eq!(tlv_stream.amount, Some(1000));
796 assert_eq!(tlv_stream.currency, None);
798 let builder = OfferBuilder::new("foo".into(), pubkey(42))
799 .amount(currency_amount.clone());
800 let tlv_stream = builder.offer.as_tlv_stream();
801 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
802 assert_eq!(tlv_stream.amount, Some(10));
803 assert_eq!(tlv_stream.currency, Some(b"USD"));
804 match builder.build() {
805 Ok(_) => panic!("expected error"),
806 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
809 let offer = OfferBuilder::new("foo".into(), pubkey(42))
810 .amount(currency_amount.clone())
811 .amount(bitcoin_amount.clone())
814 let tlv_stream = offer.as_tlv_stream();
815 assert_eq!(tlv_stream.amount, Some(1000));
816 assert_eq!(tlv_stream.currency, None);
818 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
819 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
820 Ok(_) => panic!("expected error"),
821 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
826 fn builds_offer_with_features() {
827 let offer = OfferBuilder::new("foo".into(), pubkey(42))
828 .features_unchecked(OfferFeatures::unknown())
831 assert_eq!(offer.features(), &OfferFeatures::unknown());
832 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
834 let offer = OfferBuilder::new("foo".into(), pubkey(42))
835 .features_unchecked(OfferFeatures::unknown())
836 .features_unchecked(OfferFeatures::empty())
839 assert_eq!(offer.features(), &OfferFeatures::empty());
840 assert_eq!(offer.as_tlv_stream().features, None);
844 fn builds_offer_with_absolute_expiry() {
845 let future_expiry = Duration::from_secs(u64::max_value());
846 let past_expiry = Duration::from_secs(0);
848 let offer = OfferBuilder::new("foo".into(), pubkey(42))
849 .absolute_expiry(future_expiry)
852 #[cfg(feature = "std")]
853 assert!(!offer.is_expired());
854 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
855 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
857 let offer = OfferBuilder::new("foo".into(), pubkey(42))
858 .absolute_expiry(future_expiry)
859 .absolute_expiry(past_expiry)
862 #[cfg(feature = "std")]
863 assert!(offer.is_expired());
864 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
865 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
869 fn builds_offer_with_paths() {
872 introduction_node_id: pubkey(40),
873 blinding_point: pubkey(41),
875 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
876 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
880 introduction_node_id: pubkey(40),
881 blinding_point: pubkey(41),
883 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
884 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
889 let offer = OfferBuilder::new("foo".into(), pubkey(42))
890 .path(paths[0].clone())
891 .path(paths[1].clone())
894 let tlv_stream = offer.as_tlv_stream();
895 assert_eq!(offer.paths(), paths.as_slice());
896 assert_eq!(offer.signing_pubkey(), pubkey(42));
897 assert_ne!(pubkey(42), pubkey(44));
898 assert_eq!(tlv_stream.paths, Some(&paths));
899 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
903 fn builds_offer_with_issuer() {
904 let offer = OfferBuilder::new("foo".into(), pubkey(42))
905 .issuer("bar".into())
908 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
909 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
911 let offer = OfferBuilder::new("foo".into(), pubkey(42))
912 .issuer("bar".into())
913 .issuer("baz".into())
916 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
917 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
921 fn builds_offer_with_supported_quantity() {
922 let ten = NonZeroU64::new(10).unwrap();
924 let offer = OfferBuilder::new("foo".into(), pubkey(42))
925 .supported_quantity(Quantity::one())
928 let tlv_stream = offer.as_tlv_stream();
929 assert_eq!(offer.supported_quantity(), Quantity::one());
930 assert_eq!(tlv_stream.quantity_max, None);
932 let offer = OfferBuilder::new("foo".into(), pubkey(42))
933 .supported_quantity(Quantity::Unbounded)
936 let tlv_stream = offer.as_tlv_stream();
937 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
938 assert_eq!(tlv_stream.quantity_max, Some(0));
940 let offer = OfferBuilder::new("foo".into(), pubkey(42))
941 .supported_quantity(Quantity::Bounded(ten))
944 let tlv_stream = offer.as_tlv_stream();
945 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
946 assert_eq!(tlv_stream.quantity_max, Some(10));
948 let offer = OfferBuilder::new("foo".into(), pubkey(42))
949 .supported_quantity(Quantity::Bounded(ten))
950 .supported_quantity(Quantity::one())
953 let tlv_stream = offer.as_tlv_stream();
954 assert_eq!(offer.supported_quantity(), Quantity::one());
955 assert_eq!(tlv_stream.quantity_max, None);
959 fn fails_requesting_invoice_with_unknown_required_features() {
960 match OfferBuilder::new("foo".into(), pubkey(42))
961 .features_unchecked(OfferFeatures::unknown())
963 .request_invoice(vec![1; 32], pubkey(43))
965 Ok(_) => panic!("expected error"),
966 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
971 fn parses_offer_with_chains() {
972 let offer = OfferBuilder::new("foo".into(), pubkey(42))
973 .chain(Network::Bitcoin)
974 .chain(Network::Testnet)
977 if let Err(e) = offer.to_string().parse::<Offer>() {
978 panic!("error parsing offer: {:?}", e);
983 fn parses_offer_with_amount() {
984 let offer = OfferBuilder::new("foo".into(), pubkey(42))
985 .amount(Amount::Bitcoin { amount_msats: 1000 })
988 if let Err(e) = offer.to_string().parse::<Offer>() {
989 panic!("error parsing offer: {:?}", e);
992 let mut tlv_stream = offer.as_tlv_stream();
993 tlv_stream.amount = Some(1000);
994 tlv_stream.currency = Some(b"USD");
996 let mut encoded_offer = Vec::new();
997 tlv_stream.write(&mut encoded_offer).unwrap();
999 if let Err(e) = Offer::try_from(encoded_offer) {
1000 panic!("error parsing offer: {:?}", e);
1003 let mut tlv_stream = offer.as_tlv_stream();
1004 tlv_stream.amount = None;
1005 tlv_stream.currency = Some(b"USD");
1007 let mut encoded_offer = Vec::new();
1008 tlv_stream.write(&mut encoded_offer).unwrap();
1010 match Offer::try_from(encoded_offer) {
1011 Ok(_) => panic!("expected error"),
1012 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1015 let mut tlv_stream = offer.as_tlv_stream();
1016 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1017 tlv_stream.currency = None;
1019 let mut encoded_offer = Vec::new();
1020 tlv_stream.write(&mut encoded_offer).unwrap();
1022 match Offer::try_from(encoded_offer) {
1023 Ok(_) => panic!("expected error"),
1024 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1029 fn parses_offer_with_description() {
1030 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1031 if let Err(e) = offer.to_string().parse::<Offer>() {
1032 panic!("error parsing offer: {:?}", e);
1035 let mut tlv_stream = offer.as_tlv_stream();
1036 tlv_stream.description = None;
1038 let mut encoded_offer = Vec::new();
1039 tlv_stream.write(&mut encoded_offer).unwrap();
1041 match Offer::try_from(encoded_offer) {
1042 Ok(_) => panic!("expected error"),
1044 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1050 fn parses_offer_with_paths() {
1051 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1053 introduction_node_id: pubkey(40),
1054 blinding_point: pubkey(41),
1056 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1057 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1061 introduction_node_id: pubkey(40),
1062 blinding_point: pubkey(41),
1064 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1065 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1070 if let Err(e) = offer.to_string().parse::<Offer>() {
1071 panic!("error parsing offer: {:?}", e);
1074 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1075 builder.offer.paths = Some(vec![]);
1077 let offer = builder.build().unwrap();
1078 if let Err(e) = offer.to_string().parse::<Offer>() {
1079 panic!("error parsing offer: {:?}", e);
1084 fn parses_offer_with_quantity() {
1085 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1086 .supported_quantity(Quantity::one())
1089 if let Err(e) = offer.to_string().parse::<Offer>() {
1090 panic!("error parsing offer: {:?}", e);
1093 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1094 .supported_quantity(Quantity::Unbounded)
1097 if let Err(e) = offer.to_string().parse::<Offer>() {
1098 panic!("error parsing offer: {:?}", e);
1101 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1102 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1105 if let Err(e) = offer.to_string().parse::<Offer>() {
1106 panic!("error parsing offer: {:?}", e);
1109 let mut tlv_stream = offer.as_tlv_stream();
1110 tlv_stream.quantity_max = Some(1);
1112 let mut encoded_offer = Vec::new();
1113 tlv_stream.write(&mut encoded_offer).unwrap();
1115 match Offer::try_from(encoded_offer) {
1116 Ok(_) => panic!("expected error"),
1118 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
1124 fn parses_offer_with_node_id() {
1125 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1126 if let Err(e) = offer.to_string().parse::<Offer>() {
1127 panic!("error parsing offer: {:?}", e);
1130 let mut tlv_stream = offer.as_tlv_stream();
1131 tlv_stream.node_id = None;
1133 let mut encoded_offer = Vec::new();
1134 tlv_stream.write(&mut encoded_offer).unwrap();
1136 match Offer::try_from(encoded_offer) {
1137 Ok(_) => panic!("expected error"),
1139 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1145 fn fails_parsing_offer_with_extra_tlv_records() {
1146 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1148 let mut encoded_offer = Vec::new();
1149 offer.write(&mut encoded_offer).unwrap();
1150 BigSize(80).write(&mut encoded_offer).unwrap();
1151 BigSize(32).write(&mut encoded_offer).unwrap();
1152 [42u8; 32].write(&mut encoded_offer).unwrap();
1154 match Offer::try_from(encoded_offer) {
1155 Ok(_) => panic!("expected error"),
1156 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1163 use super::{Offer, ParseError};
1164 use bitcoin::bech32;
1165 use crate::ln::msgs::DecodeError;
1167 // TODO: Remove once test vectors are updated.
1170 fn encodes_offer_as_bech32_without_checksum() {
1171 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1172 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1173 let reencoded_offer = offer.to_string();
1174 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1175 assert_eq!(reencoded_offer, encoded_offer);
1178 // TODO: Remove once test vectors are updated.
1181 fn parses_bech32_encoded_offers() {
1183 // BOLT 12 test vectors
1184 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1185 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1186 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1187 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1188 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1189 // Two blinded paths
1190 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1192 for encoded_offer in &offers {
1193 if let Err(e) = encoded_offer.parse::<Offer>() {
1194 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1200 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1202 // BOLT 12 test vectors
1203 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1204 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1205 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1206 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1207 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1209 for encoded_offer in &offers {
1210 match encoded_offer.parse::<Offer>() {
1211 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1212 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1219 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1220 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1221 match encoded_offer.parse::<Offer>() {
1222 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1223 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1228 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1229 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1230 match encoded_offer.parse::<Offer>() {
1231 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1232 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1237 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1238 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1239 match encoded_offer.parse::<Offer>() {
1240 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1241 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),