e57334f316c02745f2d53127ef3c548b3383af47
[rust-lightning] / lightning / src / offers / offer.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Data structures and encoding for `offer` messages.
11 //!
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.
15 //!
16 //! ```ignore
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
20 //!
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
24 //!
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};
29 //!
30 //! # use lightning::onion_message::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
33 //! #
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
36 //! #
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);
42 //!
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())
51 //!     .build()?;
52 //!
53 //! // Encode as a bech32 string for use in a QR code.
54 //! let encoded_offer = offer.to_string();
55 //!
56 //! // Parse from a bech32 string after scanning from a QR code.
57 //! let offer = encoded_offer.parse::<Offer>()?;
58 //!
59 //! // Encode offer as raw bytes.
60 //! let mut bytes = Vec::new();
61 //! offer.write(&mut bytes).unwrap();
62 //!
63 //! // Decode raw bytes into an offer.
64 //! let offer = Offer::try_from(bytes)?;
65 //! # Ok(())
66 //! # }
67 //! ```
68
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;
76 use crate::io;
77 use crate::ln::features::OfferFeatures;
78 use crate::ln::msgs::MAX_VALUE_MSAT;
79 use crate::offers::parse::{Bech32Encode, ParseError, SemanticError};
80 use crate::onion_message::BlindedPath;
81 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
82 use crate::util::string::PrintableString;
83
84 use crate::prelude::*;
85
86 #[cfg(feature = "std")]
87 use std::time::SystemTime;
88
89 /// Builds an [`Offer`] for the "offer to be paid" flow.
90 ///
91 /// See [module-level documentation] for usage.
92 ///
93 /// [module-level documentation]: self
94 pub struct OfferBuilder {
95         offer: OfferContents,
96 }
97
98 impl OfferBuilder {
99         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
100         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
101         /// while the offer is valid.
102         ///
103         /// Use a different pubkey per offer to avoid correlating offers.
104         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
105                 let offer = OfferContents {
106                         chains: None, metadata: None, amount: None, description,
107                         features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
108                         supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
109                 };
110                 OfferBuilder { offer }
111         }
112
113         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
114         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
115         ///
116         /// See [`Offer::chains`] on how this relates to the payment currency.
117         ///
118         /// Successive calls to this method will add another chain hash.
119         pub fn chain(mut self, network: Network) -> Self {
120                 let chains = self.offer.chains.get_or_insert_with(Vec::new);
121                 let chain = ChainHash::using_genesis_block(network);
122                 if !chains.contains(&chain) {
123                         chains.push(chain);
124                 }
125
126                 self
127         }
128
129         /// Sets the [`Offer::metadata`].
130         ///
131         /// Successive calls to this method will override the previous setting.
132         pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
133                 self.offer.metadata = Some(metadata);
134                 self
135         }
136
137         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
138         ///
139         /// Successive calls to this method will override the previous setting.
140         pub fn amount_msats(mut self, amount_msats: u64) -> Self {
141                 self.amount(Amount::Bitcoin { amount_msats })
142         }
143
144         /// Sets the [`Offer::amount`].
145         ///
146         /// Successive calls to this method will override the previous setting.
147         fn amount(mut self, amount: Amount) -> Self {
148                 self.offer.amount = Some(amount);
149                 self
150         }
151
152         /// Sets the [`Offer::features`].
153         ///
154         /// Successive calls to this method will override the previous setting.
155         #[cfg(test)]
156         pub fn features(mut self, features: OfferFeatures) -> Self {
157                 self.offer.features = features;
158                 self
159         }
160
161         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
162         /// already passed is valid and can be checked for using [`Offer::is_expired`].
163         ///
164         /// Successive calls to this method will override the previous setting.
165         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
166                 self.offer.absolute_expiry = Some(absolute_expiry);
167                 self
168         }
169
170         /// Sets the [`Offer::issuer`].
171         ///
172         /// Successive calls to this method will override the previous setting.
173         pub fn issuer(mut self, issuer: String) -> Self {
174                 self.offer.issuer = Some(issuer);
175                 self
176         }
177
178         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
179         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
180         ///
181         /// Successive calls to this method will add another blinded path. Caller is responsible for not
182         /// adding duplicate paths.
183         pub fn path(mut self, path: BlindedPath) -> Self {
184                 self.offer.paths.get_or_insert_with(Vec::new).push(path);
185                 self
186         }
187
188         /// Sets the quantity of items for [`Offer::supported_quantity`].
189         ///
190         /// Successive calls to this method will override the previous setting.
191         pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
192                 self.offer.supported_quantity = quantity;
193                 self
194         }
195
196         /// Builds an [`Offer`] from the builder's settings.
197         pub fn build(mut self) -> Result<Offer, SemanticError> {
198                 match self.offer.amount {
199                         Some(Amount::Bitcoin { amount_msats }) => {
200                                 if amount_msats > MAX_VALUE_MSAT {
201                                         return Err(SemanticError::InvalidAmount);
202                                 }
203                         },
204                         Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
205                         None => {},
206                 }
207
208                 if let Some(chains) = &self.offer.chains {
209                         if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
210                                 self.offer.chains = None;
211                         }
212                 }
213
214                 let mut bytes = Vec::new();
215                 self.offer.write(&mut bytes).unwrap();
216
217                 Ok(Offer {
218                         bytes,
219                         contents: self.offer,
220                 })
221         }
222 }
223
224 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
225 ///
226 /// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
227 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
228 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
229 ///
230 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
231 /// latter.
232 ///
233 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
234 #[derive(Clone, Debug)]
235 pub struct Offer {
236         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
237         // fields.
238         bytes: Vec<u8>,
239         contents: OfferContents,
240 }
241
242 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
243 #[derive(Clone, Debug)]
244 pub(crate) struct OfferContents {
245         chains: Option<Vec<ChainHash>>,
246         metadata: Option<Vec<u8>>,
247         amount: Option<Amount>,
248         description: String,
249         features: OfferFeatures,
250         absolute_expiry: Option<Duration>,
251         issuer: Option<String>,
252         paths: Option<Vec<BlindedPath>>,
253         supported_quantity: Quantity,
254         signing_pubkey: Option<PublicKey>,
255 }
256
257 impl Offer {
258         // TODO: Return a slice once ChainHash has constants.
259         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
260         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
261         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
262         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
263         /// for the selected chain.
264         pub fn chains(&self) -> Vec<ChainHash> {
265                 self.contents.chains
266                         .as_ref()
267                         .cloned()
268                         .unwrap_or_else(|| vec![self.contents.implied_chain()])
269         }
270
271         // TODO: Link to corresponding method in `InvoiceRequest`.
272         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
273         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
274         pub fn metadata(&self) -> Option<&Vec<u8>> {
275                 self.contents.metadata.as_ref()
276         }
277
278         /// The minimum amount required for a successful payment of a single item.
279         pub fn amount(&self) -> Option<&Amount> {
280                 self.contents.amount.as_ref()
281         }
282
283         /// A complete description of the purpose of the payment. Intended to be displayed to the user
284         /// but with the caveat that it has not been verified in any way.
285         pub fn description(&self) -> PrintableString {
286                 PrintableString(&self.contents.description)
287         }
288
289         /// Features pertaining to the offer.
290         pub fn features(&self) -> &OfferFeatures {
291                 &self.contents.features
292         }
293
294         /// Duration since the Unix epoch when an invoice should no longer be requested.
295         ///
296         /// If `None`, the offer does not expire.
297         pub fn absolute_expiry(&self) -> Option<Duration> {
298                 self.contents.absolute_expiry
299         }
300
301         /// Whether the offer has expired.
302         #[cfg(feature = "std")]
303         pub fn is_expired(&self) -> bool {
304                 match self.absolute_expiry() {
305                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
306                                 Ok(elapsed) => elapsed > seconds_from_epoch,
307                                 Err(_) => false,
308                         },
309                         None => false,
310                 }
311         }
312
313         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
314         /// displayed to the user but with the caveat that it has not been verified in any way.
315         pub fn issuer(&self) -> Option<PrintableString> {
316                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
317         }
318
319         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
320         /// recipient privacy by obfuscating its node id.
321         pub fn paths(&self) -> &[BlindedPath] {
322                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
323         }
324
325         /// The quantity of items supported.
326         pub fn supported_quantity(&self) -> Quantity {
327                 self.contents.supported_quantity()
328         }
329
330         /// The public key used by the recipient to sign invoices.
331         pub fn signing_pubkey(&self) -> PublicKey {
332                 self.contents.signing_pubkey.unwrap()
333         }
334
335         #[cfg(test)]
336         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
337                 self.contents.as_tlv_stream()
338         }
339 }
340
341 impl AsRef<[u8]> for Offer {
342         fn as_ref(&self) -> &[u8] {
343                 &self.bytes
344         }
345 }
346
347 impl OfferContents {
348         pub fn implied_chain(&self) -> ChainHash {
349                 ChainHash::using_genesis_block(Network::Bitcoin)
350         }
351
352         pub fn supported_quantity(&self) -> Quantity {
353                 self.supported_quantity
354         }
355
356         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
357                 let (currency, amount) = match &self.amount {
358                         None => (None, None),
359                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
360                         Some(Amount::Currency { iso4217_code, amount }) => (
361                                 Some(iso4217_code), Some(*amount)
362                         ),
363                 };
364
365                 let features = {
366                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
367                 };
368
369                 OfferTlvStreamRef {
370                         chains: self.chains.as_ref(),
371                         metadata: self.metadata.as_ref(),
372                         currency,
373                         amount,
374                         description: Some(&self.description),
375                         features,
376                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
377                         paths: self.paths.as_ref(),
378                         issuer: self.issuer.as_ref(),
379                         quantity_max: self.supported_quantity.to_tlv_record(),
380                         node_id: self.signing_pubkey.as_ref(),
381                 }
382         }
383 }
384
385 impl Writeable for Offer {
386         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
387                 WithoutLength(&self.bytes).write(writer)
388         }
389 }
390
391 impl Writeable for OfferContents {
392         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
393                 self.as_tlv_stream().write(writer)
394         }
395 }
396
397 impl TryFrom<Vec<u8>> for Offer {
398         type Error = ParseError;
399
400         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
401                 let tlv_stream: OfferTlvStream = Readable::read(&mut &bytes[..])?;
402                 Offer::try_from((bytes, tlv_stream))
403         }
404 }
405
406 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
407 /// another currency.
408 #[derive(Clone, Debug, PartialEq)]
409 pub enum Amount {
410         /// An amount of bitcoin.
411         Bitcoin {
412                 /// The amount in millisatoshi.
413                 amount_msats: u64,
414         },
415         /// An amount of currency specified using ISO 4712.
416         Currency {
417                 /// The currency that the amount is denominated in.
418                 iso4217_code: CurrencyCode,
419                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
420                 amount: u64,
421         },
422 }
423
424 /// An ISO 4712 three-letter currency code (e.g., USD).
425 pub type CurrencyCode = [u8; 3];
426
427 /// Quantity of items supported by an [`Offer`].
428 #[derive(Clone, Copy, Debug, PartialEq)]
429 pub enum Quantity {
430         /// Up to a specific number of items (inclusive).
431         Bounded(NonZeroU64),
432         /// One or more items.
433         Unbounded,
434 }
435
436 impl Quantity {
437         fn one() -> Self {
438                 Quantity::Bounded(NonZeroU64::new(1).unwrap())
439         }
440
441         fn to_tlv_record(&self) -> Option<u64> {
442                 match self {
443                         Quantity::Bounded(n) => {
444                                 let n = n.get();
445                                 if n == 1 { None } else { Some(n) }
446                         },
447                         Quantity::Unbounded => Some(0),
448                 }
449         }
450 }
451
452 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
453         (2, chains: (Vec<ChainHash>, WithoutLength)),
454         (4, metadata: (Vec<u8>, WithoutLength)),
455         (6, currency: CurrencyCode),
456         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
457         (10, description: (String, WithoutLength)),
458         (12, features: OfferFeatures),
459         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
460         (16, paths: (Vec<BlindedPath>, WithoutLength)),
461         (18, issuer: (String, WithoutLength)),
462         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
463         (22, node_id: PublicKey),
464 });
465
466 impl Bech32Encode for Offer {
467         const BECH32_HRP: &'static str = "lno";
468 }
469
470 type ParsedOffer = (Vec<u8>, OfferTlvStream);
471
472 impl FromStr for Offer {
473         type Err = ParseError;
474
475         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
476                 Self::from_bech32_str(s)
477         }
478 }
479
480 impl TryFrom<ParsedOffer> for Offer {
481         type Error = ParseError;
482
483         fn try_from(offer: ParsedOffer) -> Result<Self, Self::Error> {
484                 let (bytes, tlv_stream) = offer;
485                 let contents = OfferContents::try_from(tlv_stream)?;
486                 Ok(Offer { bytes, contents })
487         }
488 }
489
490 impl TryFrom<OfferTlvStream> for OfferContents {
491         type Error = SemanticError;
492
493         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
494                 let OfferTlvStream {
495                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
496                         issuer, quantity_max, node_id,
497                 } = tlv_stream;
498
499                 let amount = match (currency, amount) {
500                         (None, None) => None,
501                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
502                                 return Err(SemanticError::InvalidAmount);
503                         },
504                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
505                         (Some(_), None) => return Err(SemanticError::MissingAmount),
506                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
507                 };
508
509                 let description = match description {
510                         None => return Err(SemanticError::MissingDescription),
511                         Some(description) => description,
512                 };
513
514                 let features = features.unwrap_or_else(OfferFeatures::empty);
515
516                 let absolute_expiry = absolute_expiry
517                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
518
519                 let supported_quantity = match quantity_max {
520                         None => Quantity::one(),
521                         Some(0) => Quantity::Unbounded,
522                         Some(1) => return Err(SemanticError::InvalidQuantity),
523                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
524                 };
525
526                 if node_id.is_none() {
527                         return Err(SemanticError::MissingSigningPubkey);
528                 }
529
530                 Ok(OfferContents {
531                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
532                         supported_quantity, signing_pubkey: node_id,
533                 })
534         }
535 }
536
537 impl core::fmt::Display for Offer {
538         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
539                 self.fmt_bech32_str(f)
540         }
541 }
542
543 #[cfg(test)]
544 mod tests {
545         use super::{Amount, Offer, OfferBuilder, Quantity};
546
547         use bitcoin::blockdata::constants::ChainHash;
548         use bitcoin::network::constants::Network;
549         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
550         use core::convert::TryFrom;
551         use core::num::NonZeroU64;
552         use core::time::Duration;
553         use crate::ln::features::OfferFeatures;
554         use crate::ln::msgs::MAX_VALUE_MSAT;
555         use crate::offers::parse::{ParseError, SemanticError};
556         use crate::onion_message::{BlindedHop, BlindedPath};
557         use crate::util::ser::Writeable;
558         use crate::util::string::PrintableString;
559
560         fn pubkey(byte: u8) -> PublicKey {
561                 let secp_ctx = Secp256k1::new();
562                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
563         }
564
565         fn privkey(byte: u8) -> SecretKey {
566                 SecretKey::from_slice(&[byte; 32]).unwrap()
567         }
568
569         #[test]
570         fn builds_offer_with_defaults() {
571                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
572                 let tlv_stream = offer.as_tlv_stream();
573                 let mut buffer = Vec::new();
574                 offer.write(&mut buffer).unwrap();
575
576                 assert_eq!(offer.bytes, buffer.as_slice());
577                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
578                 assert_eq!(offer.metadata(), None);
579                 assert_eq!(offer.amount(), None);
580                 assert_eq!(offer.description(), PrintableString("foo"));
581                 assert_eq!(offer.features(), &OfferFeatures::empty());
582                 assert_eq!(offer.absolute_expiry(), None);
583                 #[cfg(feature = "std")]
584                 assert!(!offer.is_expired());
585                 assert_eq!(offer.paths(), &[]);
586                 assert_eq!(offer.issuer(), None);
587                 assert_eq!(offer.supported_quantity(), Quantity::one());
588                 assert_eq!(offer.signing_pubkey(), pubkey(42));
589
590                 assert_eq!(tlv_stream.chains, None);
591                 assert_eq!(tlv_stream.metadata, None);
592                 assert_eq!(tlv_stream.currency, None);
593                 assert_eq!(tlv_stream.amount, None);
594                 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
595                 assert_eq!(tlv_stream.features, None);
596                 assert_eq!(tlv_stream.absolute_expiry, None);
597                 assert_eq!(tlv_stream.paths, None);
598                 assert_eq!(tlv_stream.issuer, None);
599                 assert_eq!(tlv_stream.quantity_max, None);
600                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
601
602                 if let Err(e) = Offer::try_from(buffer) {
603                         panic!("error parsing offer: {:?}", e);
604                 }
605         }
606
607         #[test]
608         fn builds_offer_with_chains() {
609                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
610                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
611
612                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
613                         .chain(Network::Bitcoin)
614                         .build()
615                         .unwrap();
616                 assert_eq!(offer.chains(), vec![mainnet]);
617                 assert_eq!(offer.as_tlv_stream().chains, None);
618
619                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
620                         .chain(Network::Testnet)
621                         .build()
622                         .unwrap();
623                 assert_eq!(offer.chains(), vec![testnet]);
624                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
625
626                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
627                         .chain(Network::Testnet)
628                         .chain(Network::Testnet)
629                         .build()
630                         .unwrap();
631                 assert_eq!(offer.chains(), vec![testnet]);
632                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
633
634                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
635                         .chain(Network::Bitcoin)
636                         .chain(Network::Testnet)
637                         .build()
638                         .unwrap();
639                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
640                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
641         }
642
643         #[test]
644         fn builds_offer_with_metadata() {
645                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
646                         .metadata(vec![42; 32])
647                         .build()
648                         .unwrap();
649                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
650                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
651
652                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
653                         .metadata(vec![42; 32])
654                         .metadata(vec![43; 32])
655                         .build()
656                         .unwrap();
657                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
658                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
659         }
660
661         #[test]
662         fn builds_offer_with_amount() {
663                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
664                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
665
666                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
667                         .amount_msats(1000)
668                         .build()
669                         .unwrap();
670                 let tlv_stream = offer.as_tlv_stream();
671                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
672                 assert_eq!(tlv_stream.amount, Some(1000));
673                 assert_eq!(tlv_stream.currency, None);
674
675                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
676                         .amount(currency_amount.clone());
677                 let tlv_stream = builder.offer.as_tlv_stream();
678                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
679                 assert_eq!(tlv_stream.amount, Some(10));
680                 assert_eq!(tlv_stream.currency, Some(b"USD"));
681                 match builder.build() {
682                         Ok(_) => panic!("expected error"),
683                         Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
684                 }
685
686                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
687                         .amount(currency_amount.clone())
688                         .amount(bitcoin_amount.clone())
689                         .build()
690                         .unwrap();
691                 let tlv_stream = offer.as_tlv_stream();
692                 assert_eq!(tlv_stream.amount, Some(1000));
693                 assert_eq!(tlv_stream.currency, None);
694
695                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
696                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
697                         Ok(_) => panic!("expected error"),
698                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
699                 }
700         }
701
702         #[test]
703         fn builds_offer_with_features() {
704                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
705                         .features(OfferFeatures::unknown())
706                         .build()
707                         .unwrap();
708                 assert_eq!(offer.features(), &OfferFeatures::unknown());
709                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
710
711                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
712                         .features(OfferFeatures::unknown())
713                         .features(OfferFeatures::empty())
714                         .build()
715                         .unwrap();
716                 assert_eq!(offer.features(), &OfferFeatures::empty());
717                 assert_eq!(offer.as_tlv_stream().features, None);
718         }
719
720         #[test]
721         fn builds_offer_with_absolute_expiry() {
722                 let future_expiry = Duration::from_secs(u64::max_value());
723                 let past_expiry = Duration::from_secs(0);
724
725                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
726                         .absolute_expiry(future_expiry)
727                         .build()
728                         .unwrap();
729                 #[cfg(feature = "std")]
730                 assert!(!offer.is_expired());
731                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
732                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
733
734                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
735                         .absolute_expiry(future_expiry)
736                         .absolute_expiry(past_expiry)
737                         .build()
738                         .unwrap();
739                 #[cfg(feature = "std")]
740                 assert!(offer.is_expired());
741                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
742                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
743         }
744
745         #[test]
746         fn builds_offer_with_paths() {
747                 let paths = vec![
748                         BlindedPath {
749                                 introduction_node_id: pubkey(40),
750                                 blinding_point: pubkey(41),
751                                 blinded_hops: vec![
752                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
753                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
754                                 ],
755                         },
756                         BlindedPath {
757                                 introduction_node_id: pubkey(40),
758                                 blinding_point: pubkey(41),
759                                 blinded_hops: vec![
760                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
761                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
762                                 ],
763                         },
764                 ];
765
766                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
767                         .path(paths[0].clone())
768                         .path(paths[1].clone())
769                         .build()
770                         .unwrap();
771                 let tlv_stream = offer.as_tlv_stream();
772                 assert_eq!(offer.paths(), paths.as_slice());
773                 assert_eq!(offer.signing_pubkey(), pubkey(42));
774                 assert_ne!(pubkey(42), pubkey(44));
775                 assert_eq!(tlv_stream.paths, Some(&paths));
776                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
777         }
778
779         #[test]
780         fn builds_offer_with_issuer() {
781                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
782                         .issuer("bar".into())
783                         .build()
784                         .unwrap();
785                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
786                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
787
788                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
789                         .issuer("bar".into())
790                         .issuer("baz".into())
791                         .build()
792                         .unwrap();
793                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
794                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
795         }
796
797         #[test]
798         fn builds_offer_with_supported_quantity() {
799                 let ten = NonZeroU64::new(10).unwrap();
800
801                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
802                         .supported_quantity(Quantity::one())
803                         .build()
804                         .unwrap();
805                 let tlv_stream = offer.as_tlv_stream();
806                 assert_eq!(offer.supported_quantity(), Quantity::one());
807                 assert_eq!(tlv_stream.quantity_max, None);
808
809                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
810                         .supported_quantity(Quantity::Unbounded)
811                         .build()
812                         .unwrap();
813                 let tlv_stream = offer.as_tlv_stream();
814                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
815                 assert_eq!(tlv_stream.quantity_max, Some(0));
816
817                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
818                         .supported_quantity(Quantity::Bounded(ten))
819                         .build()
820                         .unwrap();
821                 let tlv_stream = offer.as_tlv_stream();
822                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
823                 assert_eq!(tlv_stream.quantity_max, Some(10));
824
825                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
826                         .supported_quantity(Quantity::Bounded(ten))
827                         .supported_quantity(Quantity::one())
828                         .build()
829                         .unwrap();
830                 let tlv_stream = offer.as_tlv_stream();
831                 assert_eq!(offer.supported_quantity(), Quantity::one());
832                 assert_eq!(tlv_stream.quantity_max, None);
833         }
834
835         #[test]
836         fn parses_offer_with_chains() {
837                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
838                         .chain(Network::Bitcoin)
839                         .chain(Network::Testnet)
840                         .build()
841                         .unwrap();
842                 if let Err(e) = offer.to_string().parse::<Offer>() {
843                         panic!("error parsing offer: {:?}", e);
844                 }
845         }
846
847         #[test]
848         fn parses_offer_with_amount() {
849                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
850                         .amount(Amount::Bitcoin { amount_msats: 1000 })
851                         .build()
852                         .unwrap();
853                 if let Err(e) = offer.to_string().parse::<Offer>() {
854                         panic!("error parsing offer: {:?}", e);
855                 }
856
857                 let mut tlv_stream = offer.as_tlv_stream();
858                 tlv_stream.amount = Some(1000);
859                 tlv_stream.currency = Some(b"USD");
860
861                 let mut encoded_offer = Vec::new();
862                 tlv_stream.write(&mut encoded_offer).unwrap();
863
864                 if let Err(e) = Offer::try_from(encoded_offer) {
865                         panic!("error parsing offer: {:?}", e);
866                 }
867
868                 let mut tlv_stream = offer.as_tlv_stream();
869                 tlv_stream.amount = None;
870                 tlv_stream.currency = Some(b"USD");
871
872                 let mut encoded_offer = Vec::new();
873                 tlv_stream.write(&mut encoded_offer).unwrap();
874
875                 match Offer::try_from(encoded_offer) {
876                         Ok(_) => panic!("expected error"),
877                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
878                 }
879
880                 let mut tlv_stream = offer.as_tlv_stream();
881                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
882                 tlv_stream.currency = None;
883
884                 let mut encoded_offer = Vec::new();
885                 tlv_stream.write(&mut encoded_offer).unwrap();
886
887                 match Offer::try_from(encoded_offer) {
888                         Ok(_) => panic!("expected error"),
889                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
890                 }
891         }
892
893         #[test]
894         fn parses_offer_with_description() {
895                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
896                 if let Err(e) = offer.to_string().parse::<Offer>() {
897                         panic!("error parsing offer: {:?}", e);
898                 }
899
900                 let mut tlv_stream = offer.as_tlv_stream();
901                 tlv_stream.description = None;
902
903                 let mut encoded_offer = Vec::new();
904                 tlv_stream.write(&mut encoded_offer).unwrap();
905
906                 match Offer::try_from(encoded_offer) {
907                         Ok(_) => panic!("expected error"),
908                         Err(e) => {
909                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
910                         },
911                 }
912         }
913
914         #[test]
915         fn parses_offer_with_paths() {
916                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
917                         .path(BlindedPath {
918                                 introduction_node_id: pubkey(40),
919                                 blinding_point: pubkey(41),
920                                 blinded_hops: vec![
921                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
922                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
923                                 ],
924                         })
925                         .path(BlindedPath {
926                                 introduction_node_id: pubkey(40),
927                                 blinding_point: pubkey(41),
928                                 blinded_hops: vec![
929                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
930                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
931                                 ],
932                         })
933                         .build()
934                         .unwrap();
935                 if let Err(e) = offer.to_string().parse::<Offer>() {
936                         panic!("error parsing offer: {:?}", e);
937                 }
938
939                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
940                 builder.offer.paths = Some(vec![]);
941
942                 let offer = builder.build().unwrap();
943                 if let Err(e) = offer.to_string().parse::<Offer>() {
944                         panic!("error parsing offer: {:?}", e);
945                 }
946         }
947
948         #[test]
949         fn parses_offer_with_quantity() {
950                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
951                         .supported_quantity(Quantity::one())
952                         .build()
953                         .unwrap();
954                 if let Err(e) = offer.to_string().parse::<Offer>() {
955                         panic!("error parsing offer: {:?}", e);
956                 }
957
958                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
959                         .supported_quantity(Quantity::Unbounded)
960                         .build()
961                         .unwrap();
962                 if let Err(e) = offer.to_string().parse::<Offer>() {
963                         panic!("error parsing offer: {:?}", e);
964                 }
965
966                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
967                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
968                         .build()
969                         .unwrap();
970                 if let Err(e) = offer.to_string().parse::<Offer>() {
971                         panic!("error parsing offer: {:?}", e);
972                 }
973
974                 let mut tlv_stream = offer.as_tlv_stream();
975                 tlv_stream.quantity_max = Some(1);
976
977                 let mut encoded_offer = Vec::new();
978                 tlv_stream.write(&mut encoded_offer).unwrap();
979
980                 match Offer::try_from(encoded_offer) {
981                         Ok(_) => panic!("expected error"),
982                         Err(e) => {
983                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
984                         },
985                 }
986         }
987
988         #[test]
989         fn parses_offer_with_node_id() {
990                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
991                 if let Err(e) = offer.to_string().parse::<Offer>() {
992                         panic!("error parsing offer: {:?}", e);
993                 }
994
995                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
996                 builder.offer.signing_pubkey = None;
997
998                 let offer = builder.build().unwrap();
999                 match offer.to_string().parse::<Offer>() {
1000                         Ok(_) => panic!("expected error"),
1001                         Err(e) => {
1002                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1003                         },
1004                 }
1005         }
1006 }
1007
1008 #[cfg(test)]
1009 mod bech32_tests {
1010         use super::{Offer, ParseError};
1011         use bitcoin::bech32;
1012         use crate::ln::msgs::DecodeError;
1013
1014         // TODO: Remove once test vectors are updated.
1015         #[ignore]
1016         #[test]
1017         fn encodes_offer_as_bech32_without_checksum() {
1018                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1019                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1020                 let reencoded_offer = offer.to_string();
1021                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1022                 assert_eq!(reencoded_offer, encoded_offer);
1023         }
1024
1025         // TODO: Remove once test vectors are updated.
1026         #[ignore]
1027         #[test]
1028         fn parses_bech32_encoded_offers() {
1029                 let offers = [
1030                         // BOLT 12 test vectors
1031                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1032                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1033                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1034                         "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1035                         "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+  0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r  y",
1036                         // Two blinded paths
1037                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1038                 ];
1039                 for encoded_offer in &offers {
1040                         if let Err(e) = encoded_offer.parse::<Offer>() {
1041                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1042                         }
1043                 }
1044         }
1045
1046         #[test]
1047         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1048                 let offers = [
1049                         // BOLT 12 test vectors
1050                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1051                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1052                         "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1053                         "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1054                         "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1055                 ];
1056                 for encoded_offer in &offers {
1057                         match encoded_offer.parse::<Offer>() {
1058                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1059                                 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1060                         }
1061                 }
1062
1063         }
1064
1065         #[test]
1066         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1067                 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1068                 match encoded_offer.parse::<Offer>() {
1069                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1070                         Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1071                 }
1072         }
1073
1074         #[test]
1075         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1076                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1077                 match encoded_offer.parse::<Offer>() {
1078                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1079                         Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1080                 }
1081         }
1082
1083         #[test]
1084         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1085                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1086                 match encoded_offer.parse::<Offer>() {
1087                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1088                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1089                 }
1090         }
1091 }