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