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