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