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