Merge pull request #2075 from TheBlueMatt/2023-02-0.0.114-bindings
[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 //! ```
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, PartialEq)]
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, PartialEq)]
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.checked_mul(quantity.unwrap_or(1))
435                                 .ok_or(SemanticError::InvalidAmount)?;
436                         let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
437
438                         if amount_msats < expected_amount_msats {
439                                 return Err(SemanticError::InsufficientAmount);
440                         }
441
442                         if amount_msats > MAX_VALUE_MSAT {
443                                 return Err(SemanticError::InvalidAmount);
444                         }
445                 }
446
447                 Ok(())
448         }
449
450         pub fn supported_quantity(&self) -> Quantity {
451                 self.supported_quantity
452         }
453
454         pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
455                 let expects_quantity = self.expects_quantity();
456                 match quantity {
457                         None if expects_quantity => Err(SemanticError::MissingQuantity),
458                         Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
459                         Some(quantity) if !self.is_valid_quantity(quantity) => {
460                                 Err(SemanticError::InvalidQuantity)
461                         },
462                         _ => Ok(()),
463                 }
464         }
465
466         fn is_valid_quantity(&self, quantity: u64) -> bool {
467                 match self.supported_quantity {
468                         Quantity::Bounded(n) => quantity <= n.get(),
469                         Quantity::Unbounded => quantity > 0,
470                         Quantity::One => quantity == 1,
471                 }
472         }
473
474         fn expects_quantity(&self) -> bool {
475                 match self.supported_quantity {
476                         Quantity::Bounded(_) => true,
477                         Quantity::Unbounded => true,
478                         Quantity::One => false,
479                 }
480         }
481
482         pub(super) fn signing_pubkey(&self) -> PublicKey {
483                 self.signing_pubkey
484         }
485
486         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
487                 let (currency, amount) = match &self.amount {
488                         None => (None, None),
489                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
490                         Some(Amount::Currency { iso4217_code, amount }) => (
491                                 Some(iso4217_code), Some(*amount)
492                         ),
493                 };
494
495                 let features = {
496                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
497                 };
498
499                 OfferTlvStreamRef {
500                         chains: self.chains.as_ref(),
501                         metadata: self.metadata.as_ref(),
502                         currency,
503                         amount,
504                         description: Some(&self.description),
505                         features,
506                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
507                         paths: self.paths.as_ref(),
508                         issuer: self.issuer.as_ref(),
509                         quantity_max: self.supported_quantity.to_tlv_record(),
510                         node_id: Some(&self.signing_pubkey),
511                 }
512         }
513 }
514
515 impl Writeable for Offer {
516         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
517                 WithoutLength(&self.bytes).write(writer)
518         }
519 }
520
521 impl Writeable for OfferContents {
522         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
523                 self.as_tlv_stream().write(writer)
524         }
525 }
526
527 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
528 /// another currency.
529 #[derive(Clone, Debug, PartialEq)]
530 pub enum Amount {
531         /// An amount of bitcoin.
532         Bitcoin {
533                 /// The amount in millisatoshi.
534                 amount_msats: u64,
535         },
536         /// An amount of currency specified using ISO 4712.
537         Currency {
538                 /// The currency that the amount is denominated in.
539                 iso4217_code: [u8; 3],
540                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
541                 amount: u64,
542         },
543 }
544
545 /// Quantity of items supported by an [`Offer`].
546 #[derive(Clone, Copy, Debug, PartialEq)]
547 pub enum Quantity {
548         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
549         /// but is limited (e.g., because of per customer or inventory limits).
550         ///
551         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
552         /// is supported.
553         Bounded(NonZeroU64),
554         /// One or more items. Use when more than one item can be requested without any limit.
555         Unbounded,
556         /// Only one item. Use when only a single item can be requested.
557         One,
558 }
559
560 impl Quantity {
561         fn to_tlv_record(&self) -> Option<u64> {
562                 match self {
563                         Quantity::Bounded(n) => Some(n.get()),
564                         Quantity::Unbounded => Some(0),
565                         Quantity::One => None,
566                 }
567         }
568 }
569
570 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
571         (2, chains: (Vec<ChainHash>, WithoutLength)),
572         (4, metadata: (Vec<u8>, WithoutLength)),
573         (6, currency: [u8; 3]),
574         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
575         (10, description: (String, WithoutLength)),
576         (12, features: (OfferFeatures, WithoutLength)),
577         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
578         (16, paths: (Vec<BlindedPath>, WithoutLength)),
579         (18, issuer: (String, WithoutLength)),
580         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
581         (22, node_id: PublicKey),
582 });
583
584 impl Bech32Encode for Offer {
585         const BECH32_HRP: &'static str = "lno";
586 }
587
588 impl FromStr for Offer {
589         type Err = ParseError;
590
591         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
592                 Self::from_bech32_str(s)
593         }
594 }
595
596 impl TryFrom<Vec<u8>> for Offer {
597         type Error = ParseError;
598
599         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
600                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
601                 let ParsedMessage { bytes, tlv_stream } = offer;
602                 let contents = OfferContents::try_from(tlv_stream)?;
603                 Ok(Offer { bytes, contents })
604         }
605 }
606
607 impl TryFrom<OfferTlvStream> for OfferContents {
608         type Error = SemanticError;
609
610         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
611                 let OfferTlvStream {
612                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
613                         issuer, quantity_max, node_id,
614                 } = tlv_stream;
615
616                 let amount = match (currency, amount) {
617                         (None, None) => None,
618                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
619                                 return Err(SemanticError::InvalidAmount);
620                         },
621                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
622                         (Some(_), None) => return Err(SemanticError::MissingAmount),
623                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
624                 };
625
626                 let description = match description {
627                         None => return Err(SemanticError::MissingDescription),
628                         Some(description) => description,
629                 };
630
631                 let features = features.unwrap_or_else(OfferFeatures::empty);
632
633                 let absolute_expiry = absolute_expiry
634                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
635
636                 let supported_quantity = match quantity_max {
637                         None => Quantity::One,
638                         Some(0) => Quantity::Unbounded,
639                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
640                 };
641
642                 let signing_pubkey = match node_id {
643                         None => return Err(SemanticError::MissingSigningPubkey),
644                         Some(node_id) => node_id,
645                 };
646
647                 Ok(OfferContents {
648                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
649                         supported_quantity, signing_pubkey,
650                 })
651         }
652 }
653
654 impl core::fmt::Display for Offer {
655         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
656                 self.fmt_bech32_str(f)
657         }
658 }
659
660 #[cfg(test)]
661 mod tests {
662         use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
663
664         use bitcoin::blockdata::constants::ChainHash;
665         use bitcoin::network::constants::Network;
666         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
667         use core::convert::TryFrom;
668         use core::num::NonZeroU64;
669         use core::time::Duration;
670         use crate::ln::features::OfferFeatures;
671         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
672         use crate::offers::parse::{ParseError, SemanticError};
673         use crate::onion_message::{BlindedHop, BlindedPath};
674         use crate::util::ser::{BigSize, Writeable};
675         use crate::util::string::PrintableString;
676
677         fn pubkey(byte: u8) -> PublicKey {
678                 let secp_ctx = Secp256k1::new();
679                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
680         }
681
682         fn privkey(byte: u8) -> SecretKey {
683                 SecretKey::from_slice(&[byte; 32]).unwrap()
684         }
685
686         #[test]
687         fn builds_offer_with_defaults() {
688                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
689
690                 let mut buffer = Vec::new();
691                 offer.write(&mut buffer).unwrap();
692
693                 assert_eq!(offer.bytes, buffer.as_slice());
694                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
695                 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
696                 assert_eq!(offer.metadata(), None);
697                 assert_eq!(offer.amount(), None);
698                 assert_eq!(offer.description(), PrintableString("foo"));
699                 assert_eq!(offer.features(), &OfferFeatures::empty());
700                 assert_eq!(offer.absolute_expiry(), None);
701                 #[cfg(feature = "std")]
702                 assert!(!offer.is_expired());
703                 assert_eq!(offer.paths(), &[]);
704                 assert_eq!(offer.issuer(), None);
705                 assert_eq!(offer.supported_quantity(), Quantity::One);
706                 assert_eq!(offer.signing_pubkey(), pubkey(42));
707
708                 assert_eq!(
709                         offer.as_tlv_stream(),
710                         OfferTlvStreamRef {
711                                 chains: None,
712                                 metadata: None,
713                                 currency: None,
714                                 amount: None,
715                                 description: Some(&String::from("foo")),
716                                 features: None,
717                                 absolute_expiry: None,
718                                 paths: None,
719                                 issuer: None,
720                                 quantity_max: None,
721                                 node_id: Some(&pubkey(42)),
722                         },
723                 );
724
725                 if let Err(e) = Offer::try_from(buffer) {
726                         panic!("error parsing offer: {:?}", e);
727                 }
728         }
729
730         #[test]
731         fn builds_offer_with_chains() {
732                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
733                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
734
735                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
736                         .chain(Network::Bitcoin)
737                         .build()
738                         .unwrap();
739                 assert!(offer.supports_chain(mainnet));
740                 assert_eq!(offer.chains(), vec![mainnet]);
741                 assert_eq!(offer.as_tlv_stream().chains, None);
742
743                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
744                         .chain(Network::Testnet)
745                         .build()
746                         .unwrap();
747                 assert!(offer.supports_chain(testnet));
748                 assert_eq!(offer.chains(), vec![testnet]);
749                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
750
751                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
752                         .chain(Network::Testnet)
753                         .chain(Network::Testnet)
754                         .build()
755                         .unwrap();
756                 assert!(offer.supports_chain(testnet));
757                 assert_eq!(offer.chains(), vec![testnet]);
758                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
759
760                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
761                         .chain(Network::Bitcoin)
762                         .chain(Network::Testnet)
763                         .build()
764                         .unwrap();
765                 assert!(offer.supports_chain(mainnet));
766                 assert!(offer.supports_chain(testnet));
767                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
768                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
769         }
770
771         #[test]
772         fn builds_offer_with_metadata() {
773                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
774                         .metadata(vec![42; 32])
775                         .build()
776                         .unwrap();
777                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
778                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
779
780                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
781                         .metadata(vec![42; 32])
782                         .metadata(vec![43; 32])
783                         .build()
784                         .unwrap();
785                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
786                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
787         }
788
789         #[test]
790         fn builds_offer_with_amount() {
791                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
792                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
793
794                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
795                         .amount_msats(1000)
796                         .build()
797                         .unwrap();
798                 let tlv_stream = offer.as_tlv_stream();
799                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
800                 assert_eq!(tlv_stream.amount, Some(1000));
801                 assert_eq!(tlv_stream.currency, None);
802
803                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
804                         .amount(currency_amount.clone());
805                 let tlv_stream = builder.offer.as_tlv_stream();
806                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
807                 assert_eq!(tlv_stream.amount, Some(10));
808                 assert_eq!(tlv_stream.currency, Some(b"USD"));
809                 match builder.build() {
810                         Ok(_) => panic!("expected error"),
811                         Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
812                 }
813
814                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
815                         .amount(currency_amount.clone())
816                         .amount(bitcoin_amount.clone())
817                         .build()
818                         .unwrap();
819                 let tlv_stream = offer.as_tlv_stream();
820                 assert_eq!(tlv_stream.amount, Some(1000));
821                 assert_eq!(tlv_stream.currency, None);
822
823                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
824                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
825                         Ok(_) => panic!("expected error"),
826                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
827                 }
828         }
829
830         #[test]
831         fn builds_offer_with_features() {
832                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
833                         .features_unchecked(OfferFeatures::unknown())
834                         .build()
835                         .unwrap();
836                 assert_eq!(offer.features(), &OfferFeatures::unknown());
837                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
838
839                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
840                         .features_unchecked(OfferFeatures::unknown())
841                         .features_unchecked(OfferFeatures::empty())
842                         .build()
843                         .unwrap();
844                 assert_eq!(offer.features(), &OfferFeatures::empty());
845                 assert_eq!(offer.as_tlv_stream().features, None);
846         }
847
848         #[test]
849         fn builds_offer_with_absolute_expiry() {
850                 let future_expiry = Duration::from_secs(u64::max_value());
851                 let past_expiry = Duration::from_secs(0);
852
853                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
854                         .absolute_expiry(future_expiry)
855                         .build()
856                         .unwrap();
857                 #[cfg(feature = "std")]
858                 assert!(!offer.is_expired());
859                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
860                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
861
862                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
863                         .absolute_expiry(future_expiry)
864                         .absolute_expiry(past_expiry)
865                         .build()
866                         .unwrap();
867                 #[cfg(feature = "std")]
868                 assert!(offer.is_expired());
869                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
870                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
871         }
872
873         #[test]
874         fn builds_offer_with_paths() {
875                 let paths = vec![
876                         BlindedPath {
877                                 introduction_node_id: pubkey(40),
878                                 blinding_point: pubkey(41),
879                                 blinded_hops: vec![
880                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
881                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
882                                 ],
883                         },
884                         BlindedPath {
885                                 introduction_node_id: pubkey(40),
886                                 blinding_point: pubkey(41),
887                                 blinded_hops: vec![
888                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
889                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
890                                 ],
891                         },
892                 ];
893
894                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
895                         .path(paths[0].clone())
896                         .path(paths[1].clone())
897                         .build()
898                         .unwrap();
899                 let tlv_stream = offer.as_tlv_stream();
900                 assert_eq!(offer.paths(), paths.as_slice());
901                 assert_eq!(offer.signing_pubkey(), pubkey(42));
902                 assert_ne!(pubkey(42), pubkey(44));
903                 assert_eq!(tlv_stream.paths, Some(&paths));
904                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
905         }
906
907         #[test]
908         fn builds_offer_with_issuer() {
909                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
910                         .issuer("bar".into())
911                         .build()
912                         .unwrap();
913                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
914                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
915
916                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
917                         .issuer("bar".into())
918                         .issuer("baz".into())
919                         .build()
920                         .unwrap();
921                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
922                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
923         }
924
925         #[test]
926         fn builds_offer_with_supported_quantity() {
927                 let one = NonZeroU64::new(1).unwrap();
928                 let ten = NonZeroU64::new(10).unwrap();
929
930                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
931                         .supported_quantity(Quantity::One)
932                         .build()
933                         .unwrap();
934                 let tlv_stream = offer.as_tlv_stream();
935                 assert_eq!(offer.supported_quantity(), Quantity::One);
936                 assert_eq!(tlv_stream.quantity_max, None);
937
938                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
939                         .supported_quantity(Quantity::Unbounded)
940                         .build()
941                         .unwrap();
942                 let tlv_stream = offer.as_tlv_stream();
943                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
944                 assert_eq!(tlv_stream.quantity_max, Some(0));
945
946                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
947                         .supported_quantity(Quantity::Bounded(ten))
948                         .build()
949                         .unwrap();
950                 let tlv_stream = offer.as_tlv_stream();
951                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
952                 assert_eq!(tlv_stream.quantity_max, Some(10));
953
954                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
955                         .supported_quantity(Quantity::Bounded(one))
956                         .build()
957                         .unwrap();
958                 let tlv_stream = offer.as_tlv_stream();
959                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
960                 assert_eq!(tlv_stream.quantity_max, Some(1));
961
962                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
963                         .supported_quantity(Quantity::Bounded(ten))
964                         .supported_quantity(Quantity::One)
965                         .build()
966                         .unwrap();
967                 let tlv_stream = offer.as_tlv_stream();
968                 assert_eq!(offer.supported_quantity(), Quantity::One);
969                 assert_eq!(tlv_stream.quantity_max, None);
970         }
971
972         #[test]
973         fn fails_requesting_invoice_with_unknown_required_features() {
974                 match OfferBuilder::new("foo".into(), pubkey(42))
975                         .features_unchecked(OfferFeatures::unknown())
976                         .build().unwrap()
977                         .request_invoice(vec![1; 32], pubkey(43))
978                 {
979                         Ok(_) => panic!("expected error"),
980                         Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
981                 }
982         }
983
984         #[test]
985         fn parses_offer_with_chains() {
986                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
987                         .chain(Network::Bitcoin)
988                         .chain(Network::Testnet)
989                         .build()
990                         .unwrap();
991                 if let Err(e) = offer.to_string().parse::<Offer>() {
992                         panic!("error parsing offer: {:?}", e);
993                 }
994         }
995
996         #[test]
997         fn parses_offer_with_amount() {
998                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
999                         .amount(Amount::Bitcoin { amount_msats: 1000 })
1000                         .build()
1001                         .unwrap();
1002                 if let Err(e) = offer.to_string().parse::<Offer>() {
1003                         panic!("error parsing offer: {:?}", e);
1004                 }
1005
1006                 let mut tlv_stream = offer.as_tlv_stream();
1007                 tlv_stream.amount = Some(1000);
1008                 tlv_stream.currency = Some(b"USD");
1009
1010                 let mut encoded_offer = Vec::new();
1011                 tlv_stream.write(&mut encoded_offer).unwrap();
1012
1013                 if let Err(e) = Offer::try_from(encoded_offer) {
1014                         panic!("error parsing offer: {:?}", e);
1015                 }
1016
1017                 let mut tlv_stream = offer.as_tlv_stream();
1018                 tlv_stream.amount = None;
1019                 tlv_stream.currency = Some(b"USD");
1020
1021                 let mut encoded_offer = Vec::new();
1022                 tlv_stream.write(&mut encoded_offer).unwrap();
1023
1024                 match Offer::try_from(encoded_offer) {
1025                         Ok(_) => panic!("expected error"),
1026                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1027                 }
1028
1029                 let mut tlv_stream = offer.as_tlv_stream();
1030                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1031                 tlv_stream.currency = None;
1032
1033                 let mut encoded_offer = Vec::new();
1034                 tlv_stream.write(&mut encoded_offer).unwrap();
1035
1036                 match Offer::try_from(encoded_offer) {
1037                         Ok(_) => panic!("expected error"),
1038                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1039                 }
1040         }
1041
1042         #[test]
1043         fn parses_offer_with_description() {
1044                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1045                 if let Err(e) = offer.to_string().parse::<Offer>() {
1046                         panic!("error parsing offer: {:?}", e);
1047                 }
1048
1049                 let mut tlv_stream = offer.as_tlv_stream();
1050                 tlv_stream.description = None;
1051
1052                 let mut encoded_offer = Vec::new();
1053                 tlv_stream.write(&mut encoded_offer).unwrap();
1054
1055                 match Offer::try_from(encoded_offer) {
1056                         Ok(_) => panic!("expected error"),
1057                         Err(e) => {
1058                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1059                         },
1060                 }
1061         }
1062
1063         #[test]
1064         fn parses_offer_with_paths() {
1065                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1066                         .path(BlindedPath {
1067                                 introduction_node_id: pubkey(40),
1068                                 blinding_point: pubkey(41),
1069                                 blinded_hops: vec![
1070                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1071                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1072                                 ],
1073                         })
1074                         .path(BlindedPath {
1075                                 introduction_node_id: pubkey(40),
1076                                 blinding_point: pubkey(41),
1077                                 blinded_hops: vec![
1078                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1079                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1080                                 ],
1081                         })
1082                         .build()
1083                         .unwrap();
1084                 if let Err(e) = offer.to_string().parse::<Offer>() {
1085                         panic!("error parsing offer: {:?}", e);
1086                 }
1087
1088                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1089                 builder.offer.paths = Some(vec![]);
1090
1091                 let offer = builder.build().unwrap();
1092                 if let Err(e) = offer.to_string().parse::<Offer>() {
1093                         panic!("error parsing offer: {:?}", e);
1094                 }
1095         }
1096
1097         #[test]
1098         fn parses_offer_with_quantity() {
1099                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1100                         .supported_quantity(Quantity::One)
1101                         .build()
1102                         .unwrap();
1103                 if let Err(e) = offer.to_string().parse::<Offer>() {
1104                         panic!("error parsing offer: {:?}", e);
1105                 }
1106
1107                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1108                         .supported_quantity(Quantity::Unbounded)
1109                         .build()
1110                         .unwrap();
1111                 if let Err(e) = offer.to_string().parse::<Offer>() {
1112                         panic!("error parsing offer: {:?}", e);
1113                 }
1114
1115                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1116                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1117                         .build()
1118                         .unwrap();
1119                 if let Err(e) = offer.to_string().parse::<Offer>() {
1120                         panic!("error parsing offer: {:?}", e);
1121                 }
1122
1123                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1124                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1125                         .build()
1126                         .unwrap();
1127                 if let Err(e) = offer.to_string().parse::<Offer>() {
1128                         panic!("error parsing offer: {:?}", e);
1129                 }
1130         }
1131
1132         #[test]
1133         fn parses_offer_with_node_id() {
1134                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1135                 if let Err(e) = offer.to_string().parse::<Offer>() {
1136                         panic!("error parsing offer: {:?}", e);
1137                 }
1138
1139                 let mut tlv_stream = offer.as_tlv_stream();
1140                 tlv_stream.node_id = None;
1141
1142                 let mut encoded_offer = Vec::new();
1143                 tlv_stream.write(&mut encoded_offer).unwrap();
1144
1145                 match Offer::try_from(encoded_offer) {
1146                         Ok(_) => panic!("expected error"),
1147                         Err(e) => {
1148                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1149                         },
1150                 }
1151         }
1152
1153         #[test]
1154         fn fails_parsing_offer_with_extra_tlv_records() {
1155                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1156
1157                 let mut encoded_offer = Vec::new();
1158                 offer.write(&mut encoded_offer).unwrap();
1159                 BigSize(80).write(&mut encoded_offer).unwrap();
1160                 BigSize(32).write(&mut encoded_offer).unwrap();
1161                 [42u8; 32].write(&mut encoded_offer).unwrap();
1162
1163                 match Offer::try_from(encoded_offer) {
1164                         Ok(_) => panic!("expected error"),
1165                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1166                 }
1167         }
1168 }
1169
1170 #[cfg(test)]
1171 mod bech32_tests {
1172         use super::{Offer, ParseError};
1173         use bitcoin::bech32;
1174         use crate::ln::msgs::DecodeError;
1175
1176         // TODO: Remove once test vectors are updated.
1177         #[ignore]
1178         #[test]
1179         fn encodes_offer_as_bech32_without_checksum() {
1180                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1181                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1182                 let reencoded_offer = offer.to_string();
1183                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1184                 assert_eq!(reencoded_offer, encoded_offer);
1185         }
1186
1187         // TODO: Remove once test vectors are updated.
1188         #[ignore]
1189         #[test]
1190         fn parses_bech32_encoded_offers() {
1191                 let offers = [
1192                         // BOLT 12 test vectors
1193                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1194                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1195                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1196                         "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1197                         "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+  0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r  y",
1198                         // Two blinded paths
1199                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1200                 ];
1201                 for encoded_offer in &offers {
1202                         if let Err(e) = encoded_offer.parse::<Offer>() {
1203                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1204                         }
1205                 }
1206         }
1207
1208         #[test]
1209         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1210                 let offers = [
1211                         // BOLT 12 test vectors
1212                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1213                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1214                         "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1215                         "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1216                         "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1217                 ];
1218                 for encoded_offer in &offers {
1219                         match encoded_offer.parse::<Offer>() {
1220                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1221                                 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1222                         }
1223                 }
1224
1225         }
1226
1227         #[test]
1228         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1229                 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1230                 match encoded_offer.parse::<Offer>() {
1231                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1232                         Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1233                 }
1234         }
1235
1236         #[test]
1237         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1238                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1239                 match encoded_offer.parse::<Offer>() {
1240                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1241                         Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1242                 }
1243         }
1244
1245         #[test]
1246         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1247                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1248                 match encoded_offer.parse::<Offer>() {
1249                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1250                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1251                 }
1252         }
1253 }