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