6b2dfe2aa5359770f18da167732a013a64857d3c
[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, ParsedMessage, SemanticError};
80 use crate::onion_message::BlindedPath;
81 use crate::util::ser::{HighZeroBytesDroppedBigSize, 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 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
398 /// another currency.
399 #[derive(Clone, Debug, PartialEq)]
400 pub enum Amount {
401         /// An amount of bitcoin.
402         Bitcoin {
403                 /// The amount in millisatoshi.
404                 amount_msats: u64,
405         },
406         /// An amount of currency specified using ISO 4712.
407         Currency {
408                 /// The currency that the amount is denominated in.
409                 iso4217_code: CurrencyCode,
410                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
411                 amount: u64,
412         },
413 }
414
415 /// An ISO 4712 three-letter currency code (e.g., USD).
416 pub type CurrencyCode = [u8; 3];
417
418 /// Quantity of items supported by an [`Offer`].
419 #[derive(Clone, Copy, Debug, PartialEq)]
420 pub enum Quantity {
421         /// Up to a specific number of items (inclusive).
422         Bounded(NonZeroU64),
423         /// One or more items.
424         Unbounded,
425 }
426
427 impl Quantity {
428         fn one() -> Self {
429                 Quantity::Bounded(NonZeroU64::new(1).unwrap())
430         }
431
432         fn to_tlv_record(&self) -> Option<u64> {
433                 match self {
434                         Quantity::Bounded(n) => {
435                                 let n = n.get();
436                                 if n == 1 { None } else { Some(n) }
437                         },
438                         Quantity::Unbounded => Some(0),
439                 }
440         }
441 }
442
443 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
444         (2, chains: (Vec<ChainHash>, WithoutLength)),
445         (4, metadata: (Vec<u8>, WithoutLength)),
446         (6, currency: CurrencyCode),
447         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
448         (10, description: (String, WithoutLength)),
449         (12, features: OfferFeatures),
450         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
451         (16, paths: (Vec<BlindedPath>, WithoutLength)),
452         (18, issuer: (String, WithoutLength)),
453         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
454         (22, node_id: PublicKey),
455 });
456
457 impl Bech32Encode for Offer {
458         const BECH32_HRP: &'static str = "lno";
459 }
460
461 impl FromStr for Offer {
462         type Err = ParseError;
463
464         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
465                 Self::from_bech32_str(s)
466         }
467 }
468
469 impl TryFrom<Vec<u8>> for Offer {
470         type Error = ParseError;
471
472         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
473                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
474                 let ParsedMessage { bytes, tlv_stream } = offer;
475                 let contents = OfferContents::try_from(tlv_stream)?;
476                 Ok(Offer { bytes, contents })
477         }
478 }
479
480 impl TryFrom<OfferTlvStream> for OfferContents {
481         type Error = SemanticError;
482
483         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
484                 let OfferTlvStream {
485                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
486                         issuer, quantity_max, node_id,
487                 } = tlv_stream;
488
489                 let amount = match (currency, amount) {
490                         (None, None) => None,
491                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
492                                 return Err(SemanticError::InvalidAmount);
493                         },
494                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
495                         (Some(_), None) => return Err(SemanticError::MissingAmount),
496                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
497                 };
498
499                 let description = match description {
500                         None => return Err(SemanticError::MissingDescription),
501                         Some(description) => description,
502                 };
503
504                 let features = features.unwrap_or_else(OfferFeatures::empty);
505
506                 let absolute_expiry = absolute_expiry
507                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
508
509                 let supported_quantity = match quantity_max {
510                         None => Quantity::one(),
511                         Some(0) => Quantity::Unbounded,
512                         Some(1) => return Err(SemanticError::InvalidQuantity),
513                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
514                 };
515
516                 if node_id.is_none() {
517                         return Err(SemanticError::MissingSigningPubkey);
518                 }
519
520                 Ok(OfferContents {
521                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
522                         supported_quantity, signing_pubkey: node_id,
523                 })
524         }
525 }
526
527 impl core::fmt::Display for Offer {
528         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
529                 self.fmt_bech32_str(f)
530         }
531 }
532
533 #[cfg(test)]
534 mod tests {
535         use super::{Amount, Offer, OfferBuilder, Quantity};
536
537         use bitcoin::blockdata::constants::ChainHash;
538         use bitcoin::network::constants::Network;
539         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
540         use core::convert::TryFrom;
541         use core::num::NonZeroU64;
542         use core::time::Duration;
543         use crate::ln::features::OfferFeatures;
544         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
545         use crate::offers::parse::{ParseError, SemanticError};
546         use crate::onion_message::{BlindedHop, BlindedPath};
547         use crate::util::ser::{BigSize, Writeable};
548         use crate::util::string::PrintableString;
549
550         fn pubkey(byte: u8) -> PublicKey {
551                 let secp_ctx = Secp256k1::new();
552                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
553         }
554
555         fn privkey(byte: u8) -> SecretKey {
556                 SecretKey::from_slice(&[byte; 32]).unwrap()
557         }
558
559         #[test]
560         fn builds_offer_with_defaults() {
561                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
562                 let tlv_stream = offer.as_tlv_stream();
563                 let mut buffer = Vec::new();
564                 offer.write(&mut buffer).unwrap();
565
566                 assert_eq!(offer.bytes, buffer.as_slice());
567                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
568                 assert_eq!(offer.metadata(), None);
569                 assert_eq!(offer.amount(), None);
570                 assert_eq!(offer.description(), PrintableString("foo"));
571                 assert_eq!(offer.features(), &OfferFeatures::empty());
572                 assert_eq!(offer.absolute_expiry(), None);
573                 #[cfg(feature = "std")]
574                 assert!(!offer.is_expired());
575                 assert_eq!(offer.paths(), &[]);
576                 assert_eq!(offer.issuer(), None);
577                 assert_eq!(offer.supported_quantity(), Quantity::one());
578                 assert_eq!(offer.signing_pubkey(), pubkey(42));
579
580                 assert_eq!(tlv_stream.chains, None);
581                 assert_eq!(tlv_stream.metadata, None);
582                 assert_eq!(tlv_stream.currency, None);
583                 assert_eq!(tlv_stream.amount, None);
584                 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
585                 assert_eq!(tlv_stream.features, None);
586                 assert_eq!(tlv_stream.absolute_expiry, None);
587                 assert_eq!(tlv_stream.paths, None);
588                 assert_eq!(tlv_stream.issuer, None);
589                 assert_eq!(tlv_stream.quantity_max, None);
590                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
591
592                 if let Err(e) = Offer::try_from(buffer) {
593                         panic!("error parsing offer: {:?}", e);
594                 }
595         }
596
597         #[test]
598         fn builds_offer_with_chains() {
599                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
600                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
601
602                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
603                         .chain(Network::Bitcoin)
604                         .build()
605                         .unwrap();
606                 assert_eq!(offer.chains(), vec![mainnet]);
607                 assert_eq!(offer.as_tlv_stream().chains, None);
608
609                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
610                         .chain(Network::Testnet)
611                         .build()
612                         .unwrap();
613                 assert_eq!(offer.chains(), vec![testnet]);
614                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
615
616                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
617                         .chain(Network::Testnet)
618                         .chain(Network::Testnet)
619                         .build()
620                         .unwrap();
621                 assert_eq!(offer.chains(), vec![testnet]);
622                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
623
624                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
625                         .chain(Network::Bitcoin)
626                         .chain(Network::Testnet)
627                         .build()
628                         .unwrap();
629                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
630                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
631         }
632
633         #[test]
634         fn builds_offer_with_metadata() {
635                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
636                         .metadata(vec![42; 32])
637                         .build()
638                         .unwrap();
639                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
640                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
641
642                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
643                         .metadata(vec![42; 32])
644                         .metadata(vec![43; 32])
645                         .build()
646                         .unwrap();
647                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
648                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
649         }
650
651         #[test]
652         fn builds_offer_with_amount() {
653                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
654                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
655
656                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
657                         .amount_msats(1000)
658                         .build()
659                         .unwrap();
660                 let tlv_stream = offer.as_tlv_stream();
661                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
662                 assert_eq!(tlv_stream.amount, Some(1000));
663                 assert_eq!(tlv_stream.currency, None);
664
665                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
666                         .amount(currency_amount.clone());
667                 let tlv_stream = builder.offer.as_tlv_stream();
668                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
669                 assert_eq!(tlv_stream.amount, Some(10));
670                 assert_eq!(tlv_stream.currency, Some(b"USD"));
671                 match builder.build() {
672                         Ok(_) => panic!("expected error"),
673                         Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
674                 }
675
676                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
677                         .amount(currency_amount.clone())
678                         .amount(bitcoin_amount.clone())
679                         .build()
680                         .unwrap();
681                 let tlv_stream = offer.as_tlv_stream();
682                 assert_eq!(tlv_stream.amount, Some(1000));
683                 assert_eq!(tlv_stream.currency, None);
684
685                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
686                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
687                         Ok(_) => panic!("expected error"),
688                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
689                 }
690         }
691
692         #[test]
693         fn builds_offer_with_features() {
694                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
695                         .features(OfferFeatures::unknown())
696                         .build()
697                         .unwrap();
698                 assert_eq!(offer.features(), &OfferFeatures::unknown());
699                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
700
701                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
702                         .features(OfferFeatures::unknown())
703                         .features(OfferFeatures::empty())
704                         .build()
705                         .unwrap();
706                 assert_eq!(offer.features(), &OfferFeatures::empty());
707                 assert_eq!(offer.as_tlv_stream().features, None);
708         }
709
710         #[test]
711         fn builds_offer_with_absolute_expiry() {
712                 let future_expiry = Duration::from_secs(u64::max_value());
713                 let past_expiry = Duration::from_secs(0);
714
715                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
716                         .absolute_expiry(future_expiry)
717                         .build()
718                         .unwrap();
719                 #[cfg(feature = "std")]
720                 assert!(!offer.is_expired());
721                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
722                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
723
724                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
725                         .absolute_expiry(future_expiry)
726                         .absolute_expiry(past_expiry)
727                         .build()
728                         .unwrap();
729                 #[cfg(feature = "std")]
730                 assert!(offer.is_expired());
731                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
732                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
733         }
734
735         #[test]
736         fn builds_offer_with_paths() {
737                 let paths = vec![
738                         BlindedPath {
739                                 introduction_node_id: pubkey(40),
740                                 blinding_point: pubkey(41),
741                                 blinded_hops: vec![
742                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
743                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
744                                 ],
745                         },
746                         BlindedPath {
747                                 introduction_node_id: pubkey(40),
748                                 blinding_point: pubkey(41),
749                                 blinded_hops: vec![
750                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
751                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
752                                 ],
753                         },
754                 ];
755
756                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
757                         .path(paths[0].clone())
758                         .path(paths[1].clone())
759                         .build()
760                         .unwrap();
761                 let tlv_stream = offer.as_tlv_stream();
762                 assert_eq!(offer.paths(), paths.as_slice());
763                 assert_eq!(offer.signing_pubkey(), pubkey(42));
764                 assert_ne!(pubkey(42), pubkey(44));
765                 assert_eq!(tlv_stream.paths, Some(&paths));
766                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
767         }
768
769         #[test]
770         fn builds_offer_with_issuer() {
771                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
772                         .issuer("bar".into())
773                         .build()
774                         .unwrap();
775                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
776                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
777
778                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
779                         .issuer("bar".into())
780                         .issuer("baz".into())
781                         .build()
782                         .unwrap();
783                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
784                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
785         }
786
787         #[test]
788         fn builds_offer_with_supported_quantity() {
789                 let ten = NonZeroU64::new(10).unwrap();
790
791                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
792                         .supported_quantity(Quantity::one())
793                         .build()
794                         .unwrap();
795                 let tlv_stream = offer.as_tlv_stream();
796                 assert_eq!(offer.supported_quantity(), Quantity::one());
797                 assert_eq!(tlv_stream.quantity_max, None);
798
799                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
800                         .supported_quantity(Quantity::Unbounded)
801                         .build()
802                         .unwrap();
803                 let tlv_stream = offer.as_tlv_stream();
804                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
805                 assert_eq!(tlv_stream.quantity_max, Some(0));
806
807                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
808                         .supported_quantity(Quantity::Bounded(ten))
809                         .build()
810                         .unwrap();
811                 let tlv_stream = offer.as_tlv_stream();
812                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
813                 assert_eq!(tlv_stream.quantity_max, Some(10));
814
815                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
816                         .supported_quantity(Quantity::Bounded(ten))
817                         .supported_quantity(Quantity::one())
818                         .build()
819                         .unwrap();
820                 let tlv_stream = offer.as_tlv_stream();
821                 assert_eq!(offer.supported_quantity(), Quantity::one());
822                 assert_eq!(tlv_stream.quantity_max, None);
823         }
824
825         #[test]
826         fn parses_offer_with_chains() {
827                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
828                         .chain(Network::Bitcoin)
829                         .chain(Network::Testnet)
830                         .build()
831                         .unwrap();
832                 if let Err(e) = offer.to_string().parse::<Offer>() {
833                         panic!("error parsing offer: {:?}", e);
834                 }
835         }
836
837         #[test]
838         fn parses_offer_with_amount() {
839                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
840                         .amount(Amount::Bitcoin { amount_msats: 1000 })
841                         .build()
842                         .unwrap();
843                 if let Err(e) = offer.to_string().parse::<Offer>() {
844                         panic!("error parsing offer: {:?}", e);
845                 }
846
847                 let mut tlv_stream = offer.as_tlv_stream();
848                 tlv_stream.amount = Some(1000);
849                 tlv_stream.currency = Some(b"USD");
850
851                 let mut encoded_offer = Vec::new();
852                 tlv_stream.write(&mut encoded_offer).unwrap();
853
854                 if let Err(e) = Offer::try_from(encoded_offer) {
855                         panic!("error parsing offer: {:?}", e);
856                 }
857
858                 let mut tlv_stream = offer.as_tlv_stream();
859                 tlv_stream.amount = None;
860                 tlv_stream.currency = Some(b"USD");
861
862                 let mut encoded_offer = Vec::new();
863                 tlv_stream.write(&mut encoded_offer).unwrap();
864
865                 match Offer::try_from(encoded_offer) {
866                         Ok(_) => panic!("expected error"),
867                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
868                 }
869
870                 let mut tlv_stream = offer.as_tlv_stream();
871                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
872                 tlv_stream.currency = None;
873
874                 let mut encoded_offer = Vec::new();
875                 tlv_stream.write(&mut encoded_offer).unwrap();
876
877                 match Offer::try_from(encoded_offer) {
878                         Ok(_) => panic!("expected error"),
879                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
880                 }
881         }
882
883         #[test]
884         fn parses_offer_with_description() {
885                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
886                 if let Err(e) = offer.to_string().parse::<Offer>() {
887                         panic!("error parsing offer: {:?}", e);
888                 }
889
890                 let mut tlv_stream = offer.as_tlv_stream();
891                 tlv_stream.description = None;
892
893                 let mut encoded_offer = Vec::new();
894                 tlv_stream.write(&mut encoded_offer).unwrap();
895
896                 match Offer::try_from(encoded_offer) {
897                         Ok(_) => panic!("expected error"),
898                         Err(e) => {
899                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
900                         },
901                 }
902         }
903
904         #[test]
905         fn parses_offer_with_paths() {
906                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
907                         .path(BlindedPath {
908                                 introduction_node_id: pubkey(40),
909                                 blinding_point: pubkey(41),
910                                 blinded_hops: vec![
911                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
912                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
913                                 ],
914                         })
915                         .path(BlindedPath {
916                                 introduction_node_id: pubkey(40),
917                                 blinding_point: pubkey(41),
918                                 blinded_hops: vec![
919                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
920                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
921                                 ],
922                         })
923                         .build()
924                         .unwrap();
925                 if let Err(e) = offer.to_string().parse::<Offer>() {
926                         panic!("error parsing offer: {:?}", e);
927                 }
928
929                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
930                 builder.offer.paths = Some(vec![]);
931
932                 let offer = builder.build().unwrap();
933                 if let Err(e) = offer.to_string().parse::<Offer>() {
934                         panic!("error parsing offer: {:?}", e);
935                 }
936         }
937
938         #[test]
939         fn parses_offer_with_quantity() {
940                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
941                         .supported_quantity(Quantity::one())
942                         .build()
943                         .unwrap();
944                 if let Err(e) = offer.to_string().parse::<Offer>() {
945                         panic!("error parsing offer: {:?}", e);
946                 }
947
948                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
949                         .supported_quantity(Quantity::Unbounded)
950                         .build()
951                         .unwrap();
952                 if let Err(e) = offer.to_string().parse::<Offer>() {
953                         panic!("error parsing offer: {:?}", e);
954                 }
955
956                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
957                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
958                         .build()
959                         .unwrap();
960                 if let Err(e) = offer.to_string().parse::<Offer>() {
961                         panic!("error parsing offer: {:?}", e);
962                 }
963
964                 let mut tlv_stream = offer.as_tlv_stream();
965                 tlv_stream.quantity_max = Some(1);
966
967                 let mut encoded_offer = Vec::new();
968                 tlv_stream.write(&mut encoded_offer).unwrap();
969
970                 match Offer::try_from(encoded_offer) {
971                         Ok(_) => panic!("expected error"),
972                         Err(e) => {
973                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
974                         },
975                 }
976         }
977
978         #[test]
979         fn parses_offer_with_node_id() {
980                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
981                 if let Err(e) = offer.to_string().parse::<Offer>() {
982                         panic!("error parsing offer: {:?}", e);
983                 }
984
985                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
986                 builder.offer.signing_pubkey = None;
987
988                 let offer = builder.build().unwrap();
989                 match offer.to_string().parse::<Offer>() {
990                         Ok(_) => panic!("expected error"),
991                         Err(e) => {
992                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
993                         },
994                 }
995         }
996
997         #[test]
998         fn fails_parsing_offer_with_extra_tlv_records() {
999                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1000
1001                 let mut encoded_offer = Vec::new();
1002                 offer.write(&mut encoded_offer).unwrap();
1003                 BigSize(80).write(&mut encoded_offer).unwrap();
1004                 BigSize(32).write(&mut encoded_offer).unwrap();
1005                 [42u8; 32].write(&mut encoded_offer).unwrap();
1006
1007                 match Offer::try_from(encoded_offer) {
1008                         Ok(_) => panic!("expected error"),
1009                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1010                 }
1011         }
1012 }
1013
1014 #[cfg(test)]
1015 mod bech32_tests {
1016         use super::{Offer, ParseError};
1017         use bitcoin::bech32;
1018         use crate::ln::msgs::DecodeError;
1019
1020         // TODO: Remove once test vectors are updated.
1021         #[ignore]
1022         #[test]
1023         fn encodes_offer_as_bech32_without_checksum() {
1024                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1025                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1026                 let reencoded_offer = offer.to_string();
1027                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1028                 assert_eq!(reencoded_offer, encoded_offer);
1029         }
1030
1031         // TODO: Remove once test vectors are updated.
1032         #[ignore]
1033         #[test]
1034         fn parses_bech32_encoded_offers() {
1035                 let offers = [
1036                         // BOLT 12 test vectors
1037                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1038                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1039                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1040                         "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1041                         "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+  0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r  y",
1042                         // Two blinded paths
1043                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1044                 ];
1045                 for encoded_offer in &offers {
1046                         if let Err(e) = encoded_offer.parse::<Offer>() {
1047                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1048                         }
1049                 }
1050         }
1051
1052         #[test]
1053         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1054                 let offers = [
1055                         // BOLT 12 test vectors
1056                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1057                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1058                         "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1059                         "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1060                         "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1061                 ];
1062                 for encoded_offer in &offers {
1063                         match encoded_offer.parse::<Offer>() {
1064                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1065                                 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1066                         }
1067                 }
1068
1069         }
1070
1071         #[test]
1072         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1073                 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1074                 match encoded_offer.parse::<Offer>() {
1075                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1076                         Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1077                 }
1078         }
1079
1080         #[test]
1081         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1082                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1083                 match encoded_offer.parse::<Offer>() {
1084                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1085                         Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1086                 }
1087         }
1088
1089         #[test]
1090         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1091                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1092                 match encoded_offer.parse::<Offer>() {
1093                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1094                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1095                 }
1096         }
1097 }