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