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