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