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