Implement `Hash` for `Offer` and `Refund`
[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 //! # Example
17 //!
18 //! ```
19 //! extern crate bitcoin;
20 //! extern crate core;
21 //! extern crate lightning;
22 //!
23 //! use core::convert::TryFrom;
24 //! use core::num::NonZeroU64;
25 //! use core::time::Duration;
26 //!
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
29 //! use lightning::offers::parse::Bolt12ParseError;
30 //! use lightning::util::ser::{Readable, Writeable};
31 //!
32 //! # use lightning::blinded_path::BlindedPath;
33 //! # #[cfg(feature = "std")]
34 //! # use std::time::SystemTime;
35 //! #
36 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
38 //! #
39 //! # #[cfg(feature = "std")]
40 //! # fn build() -> Result<(), Bolt12ParseError> {
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
43 //! let pubkey = PublicKey::from(keys);
44 //!
45 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
46 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
47 //!     .amount_msats(20_000)
48 //!     .supported_quantity(Quantity::Unbounded)
49 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //!     .issuer("Foo Bar".to_string())
51 //!     .path(create_blinded_path())
52 //!     .path(create_another_blinded_path())
53 //!     .build()?;
54 //!
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
57 //!
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
60 //!
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
64 //!
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
67 //! # Ok(())
68 //! # }
69 //! ```
70 //!
71 //! # Note
72 //!
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
75 //!
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
78
79 use bitcoin::blockdata::constants::ChainHash;
80 use bitcoin::network::constants::Network;
81 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
82 use core::convert::TryFrom;
83 use core::hash::{Hash, Hasher};
84 use core::num::NonZeroU64;
85 use core::ops::Deref;
86 use core::str::FromStr;
87 use core::time::Duration;
88 use crate::sign::EntropySource;
89 use crate::io;
90 use crate::blinded_path::BlindedPath;
91 use crate::ln::channelmanager::PaymentId;
92 use crate::ln::features::OfferFeatures;
93 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
94 use crate::ln::msgs::MAX_VALUE_MSAT;
95 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
96 use crate::offers::merkle::TlvStream;
97 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
98 use crate::offers::signer::{Metadata, MetadataMaterial, self};
99 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
100 use crate::util::string::PrintableString;
101
102 use crate::prelude::*;
103
104 #[cfg(feature = "std")]
105 use std::time::SystemTime;
106
107 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
108
109 /// Builds an [`Offer`] for the "offer to be paid" flow.
110 ///
111 /// See [module-level documentation] for usage.
112 ///
113 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
114 ///
115 /// [module-level documentation]: self
116 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
117         offer: OfferContents,
118         metadata_strategy: core::marker::PhantomData<M>,
119         secp_ctx: Option<&'a Secp256k1<T>>,
120 }
121
122 /// Indicates how [`Offer::metadata`] may be set.
123 ///
124 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
125 pub trait MetadataStrategy {}
126
127 /// [`Offer::metadata`] may be explicitly set or left empty.
128 ///
129 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
130 pub struct ExplicitMetadata {}
131
132 /// [`Offer::metadata`] will be derived.
133 ///
134 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
135 pub struct DerivedMetadata {}
136
137 impl MetadataStrategy for ExplicitMetadata {}
138 impl MetadataStrategy for DerivedMetadata {}
139
140 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
141         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
142         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
143         /// while the offer is valid.
144         ///
145         /// Use a different pubkey per offer to avoid correlating offers.
146         ///
147         /// # Note
148         ///
149         /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
150         /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
151         ///
152         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
153         /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
154         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
155                 OfferBuilder {
156                         offer: OfferContents {
157                                 chains: None, metadata: None, amount: None, description,
158                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
159                                 supported_quantity: Quantity::One, signing_pubkey,
160                         },
161                         metadata_strategy: core::marker::PhantomData,
162                         secp_ctx: None,
163                 }
164         }
165
166         /// Sets the [`Offer::metadata`] to the given bytes.
167         ///
168         /// Successive calls to this method will override the previous setting.
169         pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, Bolt12SemanticError> {
170                 self.offer.metadata = Some(Metadata::Bytes(metadata));
171                 Ok(self)
172         }
173 }
174
175 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
176         /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
177         /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
178         /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
179         /// provided `node_id` is used for the signing pubkey.
180         ///
181         /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
182         /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
183         /// [`ExpandedKey`].
184         ///
185         /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
186         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
187         pub fn deriving_signing_pubkey<ES: Deref>(
188                 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
189                 secp_ctx: &'a Secp256k1<T>
190         ) -> Self where ES::Target: EntropySource {
191                 let nonce = Nonce::from_entropy_source(entropy_source);
192                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
193                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
194                 OfferBuilder {
195                         offer: OfferContents {
196                                 chains: None, metadata: Some(metadata), amount: None, description,
197                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
198                                 supported_quantity: Quantity::One, signing_pubkey: node_id,
199                         },
200                         metadata_strategy: core::marker::PhantomData,
201                         secp_ctx: Some(secp_ctx),
202                 }
203         }
204 }
205
206 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
207         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
208         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
209         ///
210         /// See [`Offer::chains`] on how this relates to the payment currency.
211         ///
212         /// Successive calls to this method will add another chain hash.
213         pub fn chain(self, network: Network) -> Self {
214                 self.chain_hash(ChainHash::using_genesis_block(network))
215         }
216
217         /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
218         /// [`Network::Bitcoin`] is assumed to be the only one supported.
219         ///
220         /// See [`Offer::chains`] on how this relates to the payment currency.
221         ///
222         /// Successive calls to this method will add another chain hash.
223         pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Self {
224                 let chains = self.offer.chains.get_or_insert_with(Vec::new);
225                 if !chains.contains(&chain) {
226                         chains.push(chain);
227                 }
228
229                 self
230         }
231
232         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
233         ///
234         /// Successive calls to this method will override the previous setting.
235         pub fn amount_msats(self, amount_msats: u64) -> Self {
236                 self.amount(Amount::Bitcoin { amount_msats })
237         }
238
239         /// Sets the [`Offer::amount`].
240         ///
241         /// Successive calls to this method will override the previous setting.
242         pub(super) fn amount(mut self, amount: Amount) -> Self {
243                 self.offer.amount = Some(amount);
244                 self
245         }
246
247         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
248         /// already passed is valid and can be checked for using [`Offer::is_expired`].
249         ///
250         /// Successive calls to this method will override the previous setting.
251         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
252                 self.offer.absolute_expiry = Some(absolute_expiry);
253                 self
254         }
255
256         /// Sets the [`Offer::issuer`].
257         ///
258         /// Successive calls to this method will override the previous setting.
259         pub fn issuer(mut self, issuer: String) -> Self {
260                 self.offer.issuer = Some(issuer);
261                 self
262         }
263
264         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
265         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
266         ///
267         /// Successive calls to this method will add another blinded path. Caller is responsible for not
268         /// adding duplicate paths.
269         pub fn path(mut self, path: BlindedPath) -> Self {
270                 self.offer.paths.get_or_insert_with(Vec::new).push(path);
271                 self
272         }
273
274         /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
275         /// [`Quantity::One`].
276         ///
277         /// Successive calls to this method will override the previous setting.
278         pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
279                 self.offer.supported_quantity = quantity;
280                 self
281         }
282
283         /// Builds an [`Offer`] from the builder's settings.
284         pub fn build(mut self) -> Result<Offer, Bolt12SemanticError> {
285                 match self.offer.amount {
286                         Some(Amount::Bitcoin { amount_msats }) => {
287                                 if amount_msats > MAX_VALUE_MSAT {
288                                         return Err(Bolt12SemanticError::InvalidAmount);
289                                 }
290                         },
291                         Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
292                         None => {},
293                 }
294
295                 if let Some(chains) = &self.offer.chains {
296                         if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
297                                 self.offer.chains = None;
298                         }
299                 }
300
301                 Ok(self.build_without_checks())
302         }
303
304         fn build_without_checks(mut self) -> Offer {
305                 // Create the metadata for stateless verification of an InvoiceRequest.
306                 if let Some(mut metadata) = self.offer.metadata.take() {
307                         if metadata.has_derivation_material() {
308                                 if self.offer.paths.is_none() {
309                                         metadata = metadata.without_keys();
310                                 }
311
312                                 let mut tlv_stream = self.offer.as_tlv_stream();
313                                 debug_assert_eq!(tlv_stream.metadata, None);
314                                 tlv_stream.metadata = None;
315                                 if metadata.derives_recipient_keys() {
316                                         tlv_stream.node_id = None;
317                                 }
318
319                                 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
320                                 metadata = derived_metadata;
321                                 if let Some(keys) = keys {
322                                         self.offer.signing_pubkey = keys.public_key();
323                                 }
324                         }
325
326                         self.offer.metadata = Some(metadata);
327                 }
328
329                 let mut bytes = Vec::new();
330                 self.offer.write(&mut bytes).unwrap();
331
332                 Offer { bytes, contents: self.offer }
333         }
334 }
335
336 #[cfg(test)]
337 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
338         fn features_unchecked(mut self, features: OfferFeatures) -> Self {
339                 self.offer.features = features;
340                 self
341         }
342
343         pub(crate) fn clear_paths(mut self) -> Self {
344                 self.offer.paths = None;
345                 self
346         }
347
348         pub(super) fn build_unchecked(self) -> Offer {
349                 self.build_without_checks()
350         }
351 }
352
353 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
354 ///
355 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
356 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
357 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
358 ///
359 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
360 /// latter.
361 ///
362 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
363 ///
364 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
365 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
366 #[derive(Clone, Debug)]
367 pub struct Offer {
368         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
369         // fields.
370         pub(super) bytes: Vec<u8>,
371         pub(super) contents: OfferContents,
372 }
373
374 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
375 /// [`Bolt12Invoice`].
376 ///
377 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
378 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
379 #[derive(Clone, Debug)]
380 #[cfg_attr(test, derive(PartialEq))]
381 pub(super) struct OfferContents {
382         chains: Option<Vec<ChainHash>>,
383         metadata: Option<Metadata>,
384         amount: Option<Amount>,
385         description: String,
386         features: OfferFeatures,
387         absolute_expiry: Option<Duration>,
388         issuer: Option<String>,
389         paths: Option<Vec<BlindedPath>>,
390         supported_quantity: Quantity,
391         signing_pubkey: PublicKey,
392 }
393
394 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
395         // TODO: Return a slice once ChainHash has constants.
396         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
397         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
398         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
399         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
400         /// for the selected chain.
401         pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
402                 $contents.chains()
403         }
404
405         // TODO: Link to corresponding method in `InvoiceRequest`.
406         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
407         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
408         pub fn metadata(&$self) -> Option<&Vec<u8>> {
409                 $contents.metadata()
410         }
411
412         /// The minimum amount required for a successful payment of a single item.
413         pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
414                 $contents.amount()
415         }
416
417         /// A complete description of the purpose of the payment. Intended to be displayed to the user
418         /// but with the caveat that it has not been verified in any way.
419         pub fn description(&$self) -> $crate::util::string::PrintableString {
420                 $contents.description()
421         }
422
423         /// Features pertaining to the offer.
424         pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
425                 &$contents.features()
426         }
427
428         /// Duration since the Unix epoch when an invoice should no longer be requested.
429         ///
430         /// If `None`, the offer does not expire.
431         pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
432                 $contents.absolute_expiry()
433         }
434
435         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
436         /// displayed to the user but with the caveat that it has not been verified in any way.
437         pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
438                 $contents.issuer()
439         }
440
441         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
442         /// recipient privacy by obfuscating its node id.
443         pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
444                 $contents.paths()
445         }
446
447         /// The quantity of items supported.
448         pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
449                 $contents.supported_quantity()
450         }
451
452         /// The public key used by the recipient to sign invoices.
453         pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
454                 $contents.signing_pubkey()
455         }
456 } }
457
458 impl Offer {
459         offer_accessors!(self, self.contents);
460
461         pub(super) fn implied_chain(&self) -> ChainHash {
462                 self.contents.implied_chain()
463         }
464
465         /// Returns whether the given chain is supported by the offer.
466         pub fn supports_chain(&self, chain: ChainHash) -> bool {
467                 self.contents.supports_chain(chain)
468         }
469
470         /// Whether the offer has expired.
471         #[cfg(feature = "std")]
472         pub fn is_expired(&self) -> bool {
473                 self.contents.is_expired()
474         }
475
476         /// Whether the offer has expired given the duration since the Unix epoch.
477         pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
478                 self.contents.is_expired_no_std(duration_since_epoch)
479         }
480
481         /// Returns whether the given quantity is valid for the offer.
482         pub fn is_valid_quantity(&self, quantity: u64) -> bool {
483                 self.contents.is_valid_quantity(quantity)
484         }
485
486         /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
487         ///
488         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
489         pub fn expects_quantity(&self) -> bool {
490                 self.contents.expects_quantity()
491         }
492
493         /// Similar to [`Offer::request_invoice`] except it:
494         /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
495         ///   request,
496         /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
497         ///   such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
498         ///   requested using a base [`ExpandedKey`] from which the payer id was derived, and
499         /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
500         ///   be used when sending the payment for the requested invoice.
501         ///
502         /// Useful to protect the sender's privacy.
503         ///
504         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
505         ///
506         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
507         /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
508         /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
509         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
510         pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
511                 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>,
512                 payment_id: PaymentId
513         ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, Bolt12SemanticError>
514         where
515                 ES::Target: EntropySource,
516         {
517                 if self.offer_features().requires_unknown_bits() {
518                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
519                 }
520
521                 Ok(InvoiceRequestBuilder::deriving_payer_id(
522                         self, expanded_key, entropy_source, secp_ctx, payment_id
523                 ))
524         }
525
526         /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
527         /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
528         ///
529         /// Useful for recurring payments using the same `payer_id` with different invoices.
530         ///
531         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
532         ///
533         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
534         pub fn request_invoice_deriving_metadata<ES: Deref>(
535                 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
536                 payment_id: PaymentId
537         ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError>
538         where
539                 ES::Target: EntropySource,
540         {
541                 if self.offer_features().requires_unknown_bits() {
542                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
543                 }
544
545                 Ok(InvoiceRequestBuilder::deriving_metadata(
546                         self, payer_id, expanded_key, entropy_source, payment_id
547                 ))
548         }
549
550         /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
551         /// which will be reflected in the `Bolt12Invoice` response.
552         ///
553         /// The `metadata` is useful for including information about the derivation of `payer_id` such
554         /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
555         /// hashing in the signature calculation.
556         ///
557         /// This should not leak any information such as by using a simple BIP-32 derivation path.
558         /// Otherwise, payments may be correlated.
559         ///
560         /// Errors if the offer contains unknown required features.
561         ///
562         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
563         ///
564         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
565         pub fn request_invoice(
566                 &self, metadata: Vec<u8>, payer_id: PublicKey
567         ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError> {
568                 if self.offer_features().requires_unknown_bits() {
569                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
570                 }
571
572                 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
573         }
574
575         #[cfg(test)]
576         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
577                 self.contents.as_tlv_stream()
578         }
579 }
580
581 impl AsRef<[u8]> for Offer {
582         fn as_ref(&self) -> &[u8] {
583                 &self.bytes
584         }
585 }
586
587 impl PartialEq for Offer {
588         fn eq(&self, other: &Self) -> bool {
589                 self.bytes.eq(&other.bytes)
590         }
591 }
592
593 impl Eq for Offer {}
594
595 impl Hash for Offer {
596         fn hash<H: Hasher>(&self, state: &mut H) {
597                 self.bytes.hash(state);
598         }
599 }
600
601 impl OfferContents {
602         pub fn chains(&self) -> Vec<ChainHash> {
603                 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
604         }
605
606         pub fn implied_chain(&self) -> ChainHash {
607                 ChainHash::using_genesis_block(Network::Bitcoin)
608         }
609
610         pub fn supports_chain(&self, chain: ChainHash) -> bool {
611                 self.chains().contains(&chain)
612         }
613
614         pub fn metadata(&self) -> Option<&Vec<u8>> {
615                 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
616         }
617
618         pub fn amount(&self) -> Option<&Amount> {
619                 self.amount.as_ref()
620         }
621
622         pub fn description(&self) -> PrintableString {
623                 PrintableString(&self.description)
624         }
625
626         pub fn features(&self) -> &OfferFeatures {
627                 &self.features
628         }
629
630         pub fn absolute_expiry(&self) -> Option<Duration> {
631                 self.absolute_expiry
632         }
633
634         #[cfg(feature = "std")]
635         pub(super) fn is_expired(&self) -> bool {
636                 SystemTime::UNIX_EPOCH
637                         .elapsed()
638                         .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
639                         .unwrap_or(false)
640         }
641
642         pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
643                 self.absolute_expiry
644                         .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
645                         .unwrap_or(false)
646         }
647
648         pub fn issuer(&self) -> Option<PrintableString> {
649                 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
650         }
651
652         pub fn paths(&self) -> &[BlindedPath] {
653                 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
654         }
655
656         pub(super) fn check_amount_msats_for_quantity(
657                 &self, amount_msats: Option<u64>, quantity: Option<u64>
658         ) -> Result<(), Bolt12SemanticError> {
659                 let offer_amount_msats = match self.amount {
660                         None => 0,
661                         Some(Amount::Bitcoin { amount_msats }) => amount_msats,
662                         Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
663                 };
664
665                 if !self.expects_quantity() || quantity.is_some() {
666                         let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
667                                 .ok_or(Bolt12SemanticError::InvalidAmount)?;
668                         let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
669
670                         if amount_msats < expected_amount_msats {
671                                 return Err(Bolt12SemanticError::InsufficientAmount);
672                         }
673
674                         if amount_msats > MAX_VALUE_MSAT {
675                                 return Err(Bolt12SemanticError::InvalidAmount);
676                         }
677                 }
678
679                 Ok(())
680         }
681
682         pub fn supported_quantity(&self) -> Quantity {
683                 self.supported_quantity
684         }
685
686         pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
687                 let expects_quantity = self.expects_quantity();
688                 match quantity {
689                         None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
690                         Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
691                         Some(quantity) if !self.is_valid_quantity(quantity) => {
692                                 Err(Bolt12SemanticError::InvalidQuantity)
693                         },
694                         _ => Ok(()),
695                 }
696         }
697
698         fn is_valid_quantity(&self, quantity: u64) -> bool {
699                 match self.supported_quantity {
700                         Quantity::Bounded(n) => quantity <= n.get(),
701                         Quantity::Unbounded => quantity > 0,
702                         Quantity::One => quantity == 1,
703                 }
704         }
705
706         fn expects_quantity(&self) -> bool {
707                 match self.supported_quantity {
708                         Quantity::Bounded(_) => true,
709                         Quantity::Unbounded => true,
710                         Quantity::One => false,
711                 }
712         }
713
714         pub(super) fn signing_pubkey(&self) -> PublicKey {
715                 self.signing_pubkey
716         }
717
718         /// Verifies that the offer metadata was produced from the offer in the TLV stream.
719         pub(super) fn verify<T: secp256k1::Signing>(
720                 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
721         ) -> Result<Option<KeyPair>, ()> {
722                 match self.metadata() {
723                         Some(metadata) => {
724                                 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
725                                         match record.r#type {
726                                                 OFFER_METADATA_TYPE => false,
727                                                 OFFER_NODE_ID_TYPE => {
728                                                         !self.metadata.as_ref().unwrap().derives_recipient_keys()
729                                                 },
730                                                 _ => true,
731                                         }
732                                 });
733                                 signer::verify_recipient_metadata(
734                                         metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
735                                 )
736                         },
737                         None => Err(()),
738                 }
739         }
740
741         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
742                 let (currency, amount) = match &self.amount {
743                         None => (None, None),
744                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
745                         Some(Amount::Currency { iso4217_code, amount }) => (
746                                 Some(iso4217_code), Some(*amount)
747                         ),
748                 };
749
750                 let features = {
751                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
752                 };
753
754                 OfferTlvStreamRef {
755                         chains: self.chains.as_ref(),
756                         metadata: self.metadata(),
757                         currency,
758                         amount,
759                         description: Some(&self.description),
760                         features,
761                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
762                         paths: self.paths.as_ref(),
763                         issuer: self.issuer.as_ref(),
764                         quantity_max: self.supported_quantity.to_tlv_record(),
765                         node_id: Some(&self.signing_pubkey),
766                 }
767         }
768 }
769
770 impl Writeable for Offer {
771         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
772                 WithoutLength(&self.bytes).write(writer)
773         }
774 }
775
776 impl Writeable for OfferContents {
777         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
778                 self.as_tlv_stream().write(writer)
779         }
780 }
781
782 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
783 /// another currency.
784 #[derive(Clone, Debug, PartialEq)]
785 pub enum Amount {
786         /// An amount of bitcoin.
787         Bitcoin {
788                 /// The amount in millisatoshi.
789                 amount_msats: u64,
790         },
791         /// An amount of currency specified using ISO 4712.
792         Currency {
793                 /// The currency that the amount is denominated in.
794                 iso4217_code: CurrencyCode,
795                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
796                 amount: u64,
797         },
798 }
799
800 /// An ISO 4712 three-letter currency code (e.g., USD).
801 pub type CurrencyCode = [u8; 3];
802
803 /// Quantity of items supported by an [`Offer`].
804 #[derive(Clone, Copy, Debug, PartialEq)]
805 pub enum Quantity {
806         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
807         /// but is limited (e.g., because of per customer or inventory limits).
808         ///
809         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
810         /// is supported.
811         Bounded(NonZeroU64),
812         /// One or more items. Use when more than one item can be requested without any limit.
813         Unbounded,
814         /// Only one item. Use when only a single item can be requested.
815         One,
816 }
817
818 impl Quantity {
819         fn to_tlv_record(&self) -> Option<u64> {
820                 match self {
821                         Quantity::Bounded(n) => Some(n.get()),
822                         Quantity::Unbounded => Some(0),
823                         Quantity::One => None,
824                 }
825         }
826 }
827
828 /// Valid type range for offer TLV records.
829 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
830
831 /// TLV record type for [`Offer::metadata`].
832 const OFFER_METADATA_TYPE: u64 = 4;
833
834 /// TLV record type for [`Offer::signing_pubkey`].
835 const OFFER_NODE_ID_TYPE: u64 = 22;
836
837 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
838         (2, chains: (Vec<ChainHash>, WithoutLength)),
839         (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
840         (6, currency: CurrencyCode),
841         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
842         (10, description: (String, WithoutLength)),
843         (12, features: (OfferFeatures, WithoutLength)),
844         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
845         (16, paths: (Vec<BlindedPath>, WithoutLength)),
846         (18, issuer: (String, WithoutLength)),
847         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
848         (OFFER_NODE_ID_TYPE, node_id: PublicKey),
849 });
850
851 impl Bech32Encode for Offer {
852         const BECH32_HRP: &'static str = "lno";
853 }
854
855 impl FromStr for Offer {
856         type Err = Bolt12ParseError;
857
858         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
859                 Self::from_bech32_str(s)
860         }
861 }
862
863 impl TryFrom<Vec<u8>> for Offer {
864         type Error = Bolt12ParseError;
865
866         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
867                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
868                 let ParsedMessage { bytes, tlv_stream } = offer;
869                 let contents = OfferContents::try_from(tlv_stream)?;
870                 Ok(Offer { bytes, contents })
871         }
872 }
873
874 impl TryFrom<OfferTlvStream> for OfferContents {
875         type Error = Bolt12SemanticError;
876
877         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
878                 let OfferTlvStream {
879                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
880                         issuer, quantity_max, node_id,
881                 } = tlv_stream;
882
883                 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
884
885                 let amount = match (currency, amount) {
886                         (None, None) => None,
887                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
888                                 return Err(Bolt12SemanticError::InvalidAmount);
889                         },
890                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
891                         (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
892                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
893                 };
894
895                 let description = match description {
896                         None => return Err(Bolt12SemanticError::MissingDescription),
897                         Some(description) => description,
898                 };
899
900                 let features = features.unwrap_or_else(OfferFeatures::empty);
901
902                 let absolute_expiry = absolute_expiry
903                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
904
905                 let supported_quantity = match quantity_max {
906                         None => Quantity::One,
907                         Some(0) => Quantity::Unbounded,
908                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
909                 };
910
911                 let signing_pubkey = match node_id {
912                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
913                         Some(node_id) => node_id,
914                 };
915
916                 Ok(OfferContents {
917                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
918                         supported_quantity, signing_pubkey,
919                 })
920         }
921 }
922
923 impl core::fmt::Display for Offer {
924         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
925                 self.fmt_bech32_str(f)
926         }
927 }
928
929 #[cfg(test)]
930 mod tests {
931         use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
932
933         use bitcoin::blockdata::constants::ChainHash;
934         use bitcoin::network::constants::Network;
935         use bitcoin::secp256k1::Secp256k1;
936         use core::convert::TryFrom;
937         use core::num::NonZeroU64;
938         use core::time::Duration;
939         use crate::blinded_path::{BlindedHop, BlindedPath};
940         use crate::sign::KeyMaterial;
941         use crate::ln::features::OfferFeatures;
942         use crate::ln::inbound_payment::ExpandedKey;
943         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
944         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
945         use crate::offers::test_utils::*;
946         use crate::util::ser::{BigSize, Writeable};
947         use crate::util::string::PrintableString;
948
949         #[test]
950         fn builds_offer_with_defaults() {
951                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
952
953                 let mut buffer = Vec::new();
954                 offer.write(&mut buffer).unwrap();
955
956                 assert_eq!(offer.bytes, buffer.as_slice());
957                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
958                 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
959                 assert_eq!(offer.metadata(), None);
960                 assert_eq!(offer.amount(), None);
961                 assert_eq!(offer.description(), PrintableString("foo"));
962                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
963                 assert_eq!(offer.absolute_expiry(), None);
964                 #[cfg(feature = "std")]
965                 assert!(!offer.is_expired());
966                 assert_eq!(offer.paths(), &[]);
967                 assert_eq!(offer.issuer(), None);
968                 assert_eq!(offer.supported_quantity(), Quantity::One);
969                 assert_eq!(offer.signing_pubkey(), pubkey(42));
970
971                 assert_eq!(
972                         offer.as_tlv_stream(),
973                         OfferTlvStreamRef {
974                                 chains: None,
975                                 metadata: None,
976                                 currency: None,
977                                 amount: None,
978                                 description: Some(&String::from("foo")),
979                                 features: None,
980                                 absolute_expiry: None,
981                                 paths: None,
982                                 issuer: None,
983                                 quantity_max: None,
984                                 node_id: Some(&pubkey(42)),
985                         },
986                 );
987
988                 if let Err(e) = Offer::try_from(buffer) {
989                         panic!("error parsing offer: {:?}", e);
990                 }
991         }
992
993         #[test]
994         fn builds_offer_with_chains() {
995                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
996                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
997
998                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
999                         .chain(Network::Bitcoin)
1000                         .build()
1001                         .unwrap();
1002                 assert!(offer.supports_chain(mainnet));
1003                 assert_eq!(offer.chains(), vec![mainnet]);
1004                 assert_eq!(offer.as_tlv_stream().chains, None);
1005
1006                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1007                         .chain(Network::Testnet)
1008                         .build()
1009                         .unwrap();
1010                 assert!(offer.supports_chain(testnet));
1011                 assert_eq!(offer.chains(), vec![testnet]);
1012                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1013
1014                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1015                         .chain(Network::Testnet)
1016                         .chain(Network::Testnet)
1017                         .build()
1018                         .unwrap();
1019                 assert!(offer.supports_chain(testnet));
1020                 assert_eq!(offer.chains(), vec![testnet]);
1021                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1022
1023                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1024                         .chain(Network::Bitcoin)
1025                         .chain(Network::Testnet)
1026                         .build()
1027                         .unwrap();
1028                 assert!(offer.supports_chain(mainnet));
1029                 assert!(offer.supports_chain(testnet));
1030                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1031                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1032         }
1033
1034         #[test]
1035         fn builds_offer_with_metadata() {
1036                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1037                         .metadata(vec![42; 32]).unwrap()
1038                         .build()
1039                         .unwrap();
1040                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1041                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1042
1043                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1044                         .metadata(vec![42; 32]).unwrap()
1045                         .metadata(vec![43; 32]).unwrap()
1046                         .build()
1047                         .unwrap();
1048                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1049                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1050         }
1051
1052         #[test]
1053         fn builds_offer_with_metadata_derived() {
1054                 let desc = "foo".to_string();
1055                 let node_id = recipient_pubkey();
1056                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1057                 let entropy = FixedEntropy {};
1058                 let secp_ctx = Secp256k1::new();
1059
1060                 let offer = OfferBuilder
1061                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1062                         .amount_msats(1000)
1063                         .build().unwrap();
1064                 assert_eq!(offer.signing_pubkey(), node_id);
1065
1066                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1067                         .build().unwrap()
1068                         .sign(payer_sign).unwrap();
1069                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1070
1071                 // Fails verification with altered offer field
1072                 let mut tlv_stream = offer.as_tlv_stream();
1073                 tlv_stream.amount = Some(100);
1074
1075                 let mut encoded_offer = Vec::new();
1076                 tlv_stream.write(&mut encoded_offer).unwrap();
1077
1078                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1079                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1080                         .build().unwrap()
1081                         .sign(payer_sign).unwrap();
1082                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1083
1084                 // Fails verification with altered metadata
1085                 let mut tlv_stream = offer.as_tlv_stream();
1086                 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1087                 tlv_stream.metadata = Some(&metadata);
1088
1089                 let mut encoded_offer = Vec::new();
1090                 tlv_stream.write(&mut encoded_offer).unwrap();
1091
1092                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1093                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1094                         .build().unwrap()
1095                         .sign(payer_sign).unwrap();
1096                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1097         }
1098
1099         #[test]
1100         fn builds_offer_with_derived_signing_pubkey() {
1101                 let desc = "foo".to_string();
1102                 let node_id = recipient_pubkey();
1103                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1104                 let entropy = FixedEntropy {};
1105                 let secp_ctx = Secp256k1::new();
1106
1107                 let blinded_path = BlindedPath {
1108                         introduction_node_id: pubkey(40),
1109                         blinding_point: pubkey(41),
1110                         blinded_hops: vec![
1111                                 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1112                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1113                         ],
1114                 };
1115
1116                 let offer = OfferBuilder
1117                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1118                         .amount_msats(1000)
1119                         .path(blinded_path)
1120                         .build().unwrap();
1121                 assert_ne!(offer.signing_pubkey(), node_id);
1122
1123                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1124                         .build().unwrap()
1125                         .sign(payer_sign).unwrap();
1126                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1127
1128                 // Fails verification with altered offer field
1129                 let mut tlv_stream = offer.as_tlv_stream();
1130                 tlv_stream.amount = Some(100);
1131
1132                 let mut encoded_offer = Vec::new();
1133                 tlv_stream.write(&mut encoded_offer).unwrap();
1134
1135                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1136                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1137                         .build().unwrap()
1138                         .sign(payer_sign).unwrap();
1139                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1140
1141                 // Fails verification with altered signing pubkey
1142                 let mut tlv_stream = offer.as_tlv_stream();
1143                 let signing_pubkey = pubkey(1);
1144                 tlv_stream.node_id = Some(&signing_pubkey);
1145
1146                 let mut encoded_offer = Vec::new();
1147                 tlv_stream.write(&mut encoded_offer).unwrap();
1148
1149                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1150                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151                         .build().unwrap()
1152                         .sign(payer_sign).unwrap();
1153                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1154         }
1155
1156         #[test]
1157         fn builds_offer_with_amount() {
1158                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1159                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1160
1161                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1162                         .amount_msats(1000)
1163                         .build()
1164                         .unwrap();
1165                 let tlv_stream = offer.as_tlv_stream();
1166                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1167                 assert_eq!(tlv_stream.amount, Some(1000));
1168                 assert_eq!(tlv_stream.currency, None);
1169
1170                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1171                         .amount(currency_amount.clone());
1172                 let tlv_stream = builder.offer.as_tlv_stream();
1173                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1174                 assert_eq!(tlv_stream.amount, Some(10));
1175                 assert_eq!(tlv_stream.currency, Some(b"USD"));
1176                 match builder.build() {
1177                         Ok(_) => panic!("expected error"),
1178                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1179                 }
1180
1181                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1182                         .amount(currency_amount.clone())
1183                         .amount(bitcoin_amount.clone())
1184                         .build()
1185                         .unwrap();
1186                 let tlv_stream = offer.as_tlv_stream();
1187                 assert_eq!(tlv_stream.amount, Some(1000));
1188                 assert_eq!(tlv_stream.currency, None);
1189
1190                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1191                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1192                         Ok(_) => panic!("expected error"),
1193                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1194                 }
1195         }
1196
1197         #[test]
1198         fn builds_offer_with_features() {
1199                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1200                         .features_unchecked(OfferFeatures::unknown())
1201                         .build()
1202                         .unwrap();
1203                 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1204                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1205
1206                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1207                         .features_unchecked(OfferFeatures::unknown())
1208                         .features_unchecked(OfferFeatures::empty())
1209                         .build()
1210                         .unwrap();
1211                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1212                 assert_eq!(offer.as_tlv_stream().features, None);
1213         }
1214
1215         #[test]
1216         fn builds_offer_with_absolute_expiry() {
1217                 let future_expiry = Duration::from_secs(u64::max_value());
1218                 let past_expiry = Duration::from_secs(0);
1219                 let now = future_expiry - Duration::from_secs(1_000);
1220
1221                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1222                         .absolute_expiry(future_expiry)
1223                         .build()
1224                         .unwrap();
1225                 #[cfg(feature = "std")]
1226                 assert!(!offer.is_expired());
1227                 assert!(!offer.is_expired_no_std(now));
1228                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1229                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1230
1231                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1232                         .absolute_expiry(future_expiry)
1233                         .absolute_expiry(past_expiry)
1234                         .build()
1235                         .unwrap();
1236                 #[cfg(feature = "std")]
1237                 assert!(offer.is_expired());
1238                 assert!(offer.is_expired_no_std(now));
1239                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1240                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1241         }
1242
1243         #[test]
1244         fn builds_offer_with_paths() {
1245                 let paths = vec![
1246                         BlindedPath {
1247                                 introduction_node_id: pubkey(40),
1248                                 blinding_point: pubkey(41),
1249                                 blinded_hops: vec![
1250                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1251                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1252                                 ],
1253                         },
1254                         BlindedPath {
1255                                 introduction_node_id: pubkey(40),
1256                                 blinding_point: pubkey(41),
1257                                 blinded_hops: vec![
1258                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1259                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1260                                 ],
1261                         },
1262                 ];
1263
1264                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1265                         .path(paths[0].clone())
1266                         .path(paths[1].clone())
1267                         .build()
1268                         .unwrap();
1269                 let tlv_stream = offer.as_tlv_stream();
1270                 assert_eq!(offer.paths(), paths.as_slice());
1271                 assert_eq!(offer.signing_pubkey(), pubkey(42));
1272                 assert_ne!(pubkey(42), pubkey(44));
1273                 assert_eq!(tlv_stream.paths, Some(&paths));
1274                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1275         }
1276
1277         #[test]
1278         fn builds_offer_with_issuer() {
1279                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1280                         .issuer("bar".into())
1281                         .build()
1282                         .unwrap();
1283                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1284                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1285
1286                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1287                         .issuer("bar".into())
1288                         .issuer("baz".into())
1289                         .build()
1290                         .unwrap();
1291                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1292                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1293         }
1294
1295         #[test]
1296         fn builds_offer_with_supported_quantity() {
1297                 let one = NonZeroU64::new(1).unwrap();
1298                 let ten = NonZeroU64::new(10).unwrap();
1299
1300                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1301                         .supported_quantity(Quantity::One)
1302                         .build()
1303                         .unwrap();
1304                 let tlv_stream = offer.as_tlv_stream();
1305                 assert_eq!(offer.supported_quantity(), Quantity::One);
1306                 assert_eq!(tlv_stream.quantity_max, None);
1307
1308                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1309                         .supported_quantity(Quantity::Unbounded)
1310                         .build()
1311                         .unwrap();
1312                 let tlv_stream = offer.as_tlv_stream();
1313                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1314                 assert_eq!(tlv_stream.quantity_max, Some(0));
1315
1316                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1317                         .supported_quantity(Quantity::Bounded(ten))
1318                         .build()
1319                         .unwrap();
1320                 let tlv_stream = offer.as_tlv_stream();
1321                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1322                 assert_eq!(tlv_stream.quantity_max, Some(10));
1323
1324                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1325                         .supported_quantity(Quantity::Bounded(one))
1326                         .build()
1327                         .unwrap();
1328                 let tlv_stream = offer.as_tlv_stream();
1329                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1330                 assert_eq!(tlv_stream.quantity_max, Some(1));
1331
1332                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1333                         .supported_quantity(Quantity::Bounded(ten))
1334                         .supported_quantity(Quantity::One)
1335                         .build()
1336                         .unwrap();
1337                 let tlv_stream = offer.as_tlv_stream();
1338                 assert_eq!(offer.supported_quantity(), Quantity::One);
1339                 assert_eq!(tlv_stream.quantity_max, None);
1340         }
1341
1342         #[test]
1343         fn fails_requesting_invoice_with_unknown_required_features() {
1344                 match OfferBuilder::new("foo".into(), pubkey(42))
1345                         .features_unchecked(OfferFeatures::unknown())
1346                         .build().unwrap()
1347                         .request_invoice(vec![1; 32], pubkey(43))
1348                 {
1349                         Ok(_) => panic!("expected error"),
1350                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1351                 }
1352         }
1353
1354         #[test]
1355         fn parses_offer_with_chains() {
1356                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1357                         .chain(Network::Bitcoin)
1358                         .chain(Network::Testnet)
1359                         .build()
1360                         .unwrap();
1361                 if let Err(e) = offer.to_string().parse::<Offer>() {
1362                         panic!("error parsing offer: {:?}", e);
1363                 }
1364         }
1365
1366         #[test]
1367         fn parses_offer_with_amount() {
1368                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1369                         .amount(Amount::Bitcoin { amount_msats: 1000 })
1370                         .build()
1371                         .unwrap();
1372                 if let Err(e) = offer.to_string().parse::<Offer>() {
1373                         panic!("error parsing offer: {:?}", e);
1374                 }
1375
1376                 let mut tlv_stream = offer.as_tlv_stream();
1377                 tlv_stream.amount = Some(1000);
1378                 tlv_stream.currency = Some(b"USD");
1379
1380                 let mut encoded_offer = Vec::new();
1381                 tlv_stream.write(&mut encoded_offer).unwrap();
1382
1383                 if let Err(e) = Offer::try_from(encoded_offer) {
1384                         panic!("error parsing offer: {:?}", e);
1385                 }
1386
1387                 let mut tlv_stream = offer.as_tlv_stream();
1388                 tlv_stream.amount = None;
1389                 tlv_stream.currency = Some(b"USD");
1390
1391                 let mut encoded_offer = Vec::new();
1392                 tlv_stream.write(&mut encoded_offer).unwrap();
1393
1394                 match Offer::try_from(encoded_offer) {
1395                         Ok(_) => panic!("expected error"),
1396                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1397                 }
1398
1399                 let mut tlv_stream = offer.as_tlv_stream();
1400                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1401                 tlv_stream.currency = None;
1402
1403                 let mut encoded_offer = Vec::new();
1404                 tlv_stream.write(&mut encoded_offer).unwrap();
1405
1406                 match Offer::try_from(encoded_offer) {
1407                         Ok(_) => panic!("expected error"),
1408                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1409                 }
1410         }
1411
1412         #[test]
1413         fn parses_offer_with_description() {
1414                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1415                 if let Err(e) = offer.to_string().parse::<Offer>() {
1416                         panic!("error parsing offer: {:?}", e);
1417                 }
1418
1419                 let mut tlv_stream = offer.as_tlv_stream();
1420                 tlv_stream.description = None;
1421
1422                 let mut encoded_offer = Vec::new();
1423                 tlv_stream.write(&mut encoded_offer).unwrap();
1424
1425                 match Offer::try_from(encoded_offer) {
1426                         Ok(_) => panic!("expected error"),
1427                         Err(e) => {
1428                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1429                         },
1430                 }
1431         }
1432
1433         #[test]
1434         fn parses_offer_with_paths() {
1435                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1436                         .path(BlindedPath {
1437                                 introduction_node_id: pubkey(40),
1438                                 blinding_point: pubkey(41),
1439                                 blinded_hops: vec![
1440                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1441                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1442                                 ],
1443                         })
1444                         .path(BlindedPath {
1445                                 introduction_node_id: pubkey(40),
1446                                 blinding_point: pubkey(41),
1447                                 blinded_hops: vec![
1448                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1449                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1450                                 ],
1451                         })
1452                         .build()
1453                         .unwrap();
1454                 if let Err(e) = offer.to_string().parse::<Offer>() {
1455                         panic!("error parsing offer: {:?}", e);
1456                 }
1457
1458                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1459                 builder.offer.paths = Some(vec![]);
1460
1461                 let offer = builder.build().unwrap();
1462                 if let Err(e) = offer.to_string().parse::<Offer>() {
1463                         panic!("error parsing offer: {:?}", e);
1464                 }
1465         }
1466
1467         #[test]
1468         fn parses_offer_with_quantity() {
1469                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1470                         .supported_quantity(Quantity::One)
1471                         .build()
1472                         .unwrap();
1473                 if let Err(e) = offer.to_string().parse::<Offer>() {
1474                         panic!("error parsing offer: {:?}", e);
1475                 }
1476
1477                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1478                         .supported_quantity(Quantity::Unbounded)
1479                         .build()
1480                         .unwrap();
1481                 if let Err(e) = offer.to_string().parse::<Offer>() {
1482                         panic!("error parsing offer: {:?}", e);
1483                 }
1484
1485                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1486                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1487                         .build()
1488                         .unwrap();
1489                 if let Err(e) = offer.to_string().parse::<Offer>() {
1490                         panic!("error parsing offer: {:?}", e);
1491                 }
1492
1493                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1494                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1495                         .build()
1496                         .unwrap();
1497                 if let Err(e) = offer.to_string().parse::<Offer>() {
1498                         panic!("error parsing offer: {:?}", e);
1499                 }
1500         }
1501
1502         #[test]
1503         fn parses_offer_with_node_id() {
1504                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1505                 if let Err(e) = offer.to_string().parse::<Offer>() {
1506                         panic!("error parsing offer: {:?}", e);
1507                 }
1508
1509                 let mut tlv_stream = offer.as_tlv_stream();
1510                 tlv_stream.node_id = None;
1511
1512                 let mut encoded_offer = Vec::new();
1513                 tlv_stream.write(&mut encoded_offer).unwrap();
1514
1515                 match Offer::try_from(encoded_offer) {
1516                         Ok(_) => panic!("expected error"),
1517                         Err(e) => {
1518                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1519                         },
1520                 }
1521         }
1522
1523         #[test]
1524         fn fails_parsing_offer_with_extra_tlv_records() {
1525                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1526
1527                 let mut encoded_offer = Vec::new();
1528                 offer.write(&mut encoded_offer).unwrap();
1529                 BigSize(80).write(&mut encoded_offer).unwrap();
1530                 BigSize(32).write(&mut encoded_offer).unwrap();
1531                 [42u8; 32].write(&mut encoded_offer).unwrap();
1532
1533                 match Offer::try_from(encoded_offer) {
1534                         Ok(_) => panic!("expected error"),
1535                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1536                 }
1537         }
1538 }
1539
1540 #[cfg(test)]
1541 mod bolt12_tests {
1542         use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1543         use crate::ln::msgs::DecodeError;
1544
1545         #[test]
1546         fn parses_bech32_encoded_offers() {
1547                 let offers = [
1548                         // Minimal bolt12 offer
1549                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1550
1551                         // for testnet
1552                         "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1553
1554                         // for bitcoin (redundant)
1555                         "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1556
1557                         // for bitcoin or liquidv1
1558                         "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1559
1560                         // with metadata
1561                         "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1562
1563                         // with amount
1564                         "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1565
1566                         // with currency
1567                         "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1568
1569                         // with expiry
1570                         "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1571
1572                         // with issuer
1573                         "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1574
1575                         // with quantity
1576                         "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1577
1578                         // with unlimited (or unknown) quantity
1579                         "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1580
1581                         // with single quantity (weird but valid)
1582                         "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1583
1584                         // with feature
1585                         "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1586
1587                         // with blinded path via Bob (0x424242...), blinding 020202...
1588                         "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1589
1590                         // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1591                         "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1592
1593                         // unknown odd field
1594                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1595                 ];
1596                 for encoded_offer in &offers {
1597                         if let Err(e) = encoded_offer.parse::<Offer>() {
1598                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1599                         }
1600                 }
1601         }
1602
1603         #[test]
1604         fn fails_parsing_bech32_encoded_offers() {
1605                 // Malformed: fields out of order
1606                 assert_eq!(
1607                         "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1608                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1609                 );
1610
1611                 // Malformed: unknown even TLV type 78
1612                 assert_eq!(
1613                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1614                         Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1615                 );
1616
1617                 // Malformed: empty
1618                 assert_eq!(
1619                         "lno1".parse::<Offer>(),
1620                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1621                 );
1622
1623                 // Malformed: truncated at type
1624                 assert_eq!(
1625                         "lno1pg".parse::<Offer>(),
1626                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1627                 );
1628
1629                 // Malformed: truncated in length
1630                 assert_eq!(
1631                         "lno1pt7s".parse::<Offer>(),
1632                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1633                 );
1634
1635                 // Malformed: truncated after length
1636                 assert_eq!(
1637                         "lno1pgpq".parse::<Offer>(),
1638                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1639                 );
1640
1641                 // Malformed: truncated in description
1642                 assert_eq!(
1643                         "lno1pgpyz".parse::<Offer>(),
1644                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1645                 );
1646
1647                 // Malformed: invalid offer_chains length
1648                 assert_eq!(
1649                         "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1650                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1651                 );
1652
1653                 // Malformed: truncated currency UTF-8
1654                 assert_eq!(
1655                         "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1656                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1657                 );
1658
1659                 // Malformed: invalid currency UTF-8
1660                 assert_eq!(
1661                         "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1662                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1663                 );
1664
1665                 // Malformed: truncated description UTF-8
1666                 assert_eq!(
1667                         "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1668                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1669                 );
1670
1671                 // Malformed: invalid description UTF-8
1672                 assert_eq!(
1673                         "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1674                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1675                 );
1676
1677                 // Malformed: truncated offer_paths
1678                 assert_eq!(
1679                         "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1680                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1681                 );
1682
1683                 // Malformed: zero num_hops in blinded_path
1684                 assert_eq!(
1685                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1686                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1687                 );
1688
1689                 // Malformed: truncated onionmsg_hop in blinded_path
1690                 assert_eq!(
1691                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1692                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1693                 );
1694
1695                 // Malformed: bad first_node_id in blinded_path
1696                 assert_eq!(
1697                         "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1698                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1699                 );
1700
1701                 // Malformed: bad blinding in blinded_path
1702                 assert_eq!(
1703                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1704                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1705                 );
1706
1707                 // Malformed: bad blinded_node_id in onionmsg_hop
1708                 assert_eq!(
1709                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1710                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1711                 );
1712
1713                 // Malformed: truncated issuer UTF-8
1714                 assert_eq!(
1715                         "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1716                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1717                 );
1718
1719                 // Malformed: invalid issuer UTF-8
1720                 assert_eq!(
1721                         "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1722                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1723                 );
1724
1725                 // Malformed: invalid offer_node_id
1726                 assert_eq!(
1727                         "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1728                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1729                 );
1730
1731                 // Contains type >= 80
1732                 assert_eq!(
1733                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1734                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1735                 );
1736
1737                 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1738                 // Contains unknown feature 22
1739                 assert!(
1740                         "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1741                 );
1742
1743                 // Missing offer_description
1744                 assert_eq!(
1745                         "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1746                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1747                 );
1748
1749                 // Missing offer_node_id"
1750                 assert_eq!(
1751                         "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1752                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),
1753                 );
1754         }
1755 }