Merge pull request #2697 from jkczyz/2023-10-offer-functional-tests
[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 #[cfg_attr(test, derive(PartialEq))]
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 OfferContents {
588         pub fn chains(&self) -> Vec<ChainHash> {
589                 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
590         }
591
592         pub fn implied_chain(&self) -> ChainHash {
593                 ChainHash::using_genesis_block(Network::Bitcoin)
594         }
595
596         pub fn supports_chain(&self, chain: ChainHash) -> bool {
597                 self.chains().contains(&chain)
598         }
599
600         pub fn metadata(&self) -> Option<&Vec<u8>> {
601                 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
602         }
603
604         pub fn amount(&self) -> Option<&Amount> {
605                 self.amount.as_ref()
606         }
607
608         pub fn description(&self) -> PrintableString {
609                 PrintableString(&self.description)
610         }
611
612         pub fn features(&self) -> &OfferFeatures {
613                 &self.features
614         }
615
616         pub fn absolute_expiry(&self) -> Option<Duration> {
617                 self.absolute_expiry
618         }
619
620         #[cfg(feature = "std")]
621         pub(super) fn is_expired(&self) -> bool {
622                 SystemTime::UNIX_EPOCH
623                         .elapsed()
624                         .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
625                         .unwrap_or(false)
626         }
627
628         pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
629                 self.absolute_expiry
630                         .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
631                         .unwrap_or(false)
632         }
633
634         pub fn issuer(&self) -> Option<PrintableString> {
635                 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
636         }
637
638         pub fn paths(&self) -> &[BlindedPath] {
639                 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
640         }
641
642         pub(super) fn check_amount_msats_for_quantity(
643                 &self, amount_msats: Option<u64>, quantity: Option<u64>
644         ) -> Result<(), Bolt12SemanticError> {
645                 let offer_amount_msats = match self.amount {
646                         None => 0,
647                         Some(Amount::Bitcoin { amount_msats }) => amount_msats,
648                         Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
649                 };
650
651                 if !self.expects_quantity() || quantity.is_some() {
652                         let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
653                                 .ok_or(Bolt12SemanticError::InvalidAmount)?;
654                         let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
655
656                         if amount_msats < expected_amount_msats {
657                                 return Err(Bolt12SemanticError::InsufficientAmount);
658                         }
659
660                         if amount_msats > MAX_VALUE_MSAT {
661                                 return Err(Bolt12SemanticError::InvalidAmount);
662                         }
663                 }
664
665                 Ok(())
666         }
667
668         pub fn supported_quantity(&self) -> Quantity {
669                 self.supported_quantity
670         }
671
672         pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
673                 let expects_quantity = self.expects_quantity();
674                 match quantity {
675                         None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
676                         Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
677                         Some(quantity) if !self.is_valid_quantity(quantity) => {
678                                 Err(Bolt12SemanticError::InvalidQuantity)
679                         },
680                         _ => Ok(()),
681                 }
682         }
683
684         fn is_valid_quantity(&self, quantity: u64) -> bool {
685                 match self.supported_quantity {
686                         Quantity::Bounded(n) => quantity <= n.get(),
687                         Quantity::Unbounded => quantity > 0,
688                         Quantity::One => quantity == 1,
689                 }
690         }
691
692         fn expects_quantity(&self) -> bool {
693                 match self.supported_quantity {
694                         Quantity::Bounded(_) => true,
695                         Quantity::Unbounded => true,
696                         Quantity::One => false,
697                 }
698         }
699
700         pub(super) fn signing_pubkey(&self) -> PublicKey {
701                 self.signing_pubkey
702         }
703
704         /// Verifies that the offer metadata was produced from the offer in the TLV stream.
705         pub(super) fn verify<T: secp256k1::Signing>(
706                 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
707         ) -> Result<Option<KeyPair>, ()> {
708                 match self.metadata() {
709                         Some(metadata) => {
710                                 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
711                                         match record.r#type {
712                                                 OFFER_METADATA_TYPE => false,
713                                                 OFFER_NODE_ID_TYPE => {
714                                                         !self.metadata.as_ref().unwrap().derives_recipient_keys()
715                                                 },
716                                                 _ => true,
717                                         }
718                                 });
719                                 signer::verify_recipient_metadata(
720                                         metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
721                                 )
722                         },
723                         None => Err(()),
724                 }
725         }
726
727         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
728                 let (currency, amount) = match &self.amount {
729                         None => (None, None),
730                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
731                         Some(Amount::Currency { iso4217_code, amount }) => (
732                                 Some(iso4217_code), Some(*amount)
733                         ),
734                 };
735
736                 let features = {
737                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
738                 };
739
740                 OfferTlvStreamRef {
741                         chains: self.chains.as_ref(),
742                         metadata: self.metadata(),
743                         currency,
744                         amount,
745                         description: Some(&self.description),
746                         features,
747                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
748                         paths: self.paths.as_ref(),
749                         issuer: self.issuer.as_ref(),
750                         quantity_max: self.supported_quantity.to_tlv_record(),
751                         node_id: Some(&self.signing_pubkey),
752                 }
753         }
754 }
755
756 impl Writeable for Offer {
757         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
758                 WithoutLength(&self.bytes).write(writer)
759         }
760 }
761
762 impl Writeable for OfferContents {
763         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
764                 self.as_tlv_stream().write(writer)
765         }
766 }
767
768 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
769 /// another currency.
770 #[derive(Clone, Debug, PartialEq)]
771 pub enum Amount {
772         /// An amount of bitcoin.
773         Bitcoin {
774                 /// The amount in millisatoshi.
775                 amount_msats: u64,
776         },
777         /// An amount of currency specified using ISO 4712.
778         Currency {
779                 /// The currency that the amount is denominated in.
780                 iso4217_code: CurrencyCode,
781                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
782                 amount: u64,
783         },
784 }
785
786 /// An ISO 4712 three-letter currency code (e.g., USD).
787 pub type CurrencyCode = [u8; 3];
788
789 /// Quantity of items supported by an [`Offer`].
790 #[derive(Clone, Copy, Debug, PartialEq)]
791 pub enum Quantity {
792         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
793         /// but is limited (e.g., because of per customer or inventory limits).
794         ///
795         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
796         /// is supported.
797         Bounded(NonZeroU64),
798         /// One or more items. Use when more than one item can be requested without any limit.
799         Unbounded,
800         /// Only one item. Use when only a single item can be requested.
801         One,
802 }
803
804 impl Quantity {
805         fn to_tlv_record(&self) -> Option<u64> {
806                 match self {
807                         Quantity::Bounded(n) => Some(n.get()),
808                         Quantity::Unbounded => Some(0),
809                         Quantity::One => None,
810                 }
811         }
812 }
813
814 /// Valid type range for offer TLV records.
815 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
816
817 /// TLV record type for [`Offer::metadata`].
818 const OFFER_METADATA_TYPE: u64 = 4;
819
820 /// TLV record type for [`Offer::signing_pubkey`].
821 const OFFER_NODE_ID_TYPE: u64 = 22;
822
823 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
824         (2, chains: (Vec<ChainHash>, WithoutLength)),
825         (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
826         (6, currency: CurrencyCode),
827         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
828         (10, description: (String, WithoutLength)),
829         (12, features: (OfferFeatures, WithoutLength)),
830         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
831         (16, paths: (Vec<BlindedPath>, WithoutLength)),
832         (18, issuer: (String, WithoutLength)),
833         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
834         (OFFER_NODE_ID_TYPE, node_id: PublicKey),
835 });
836
837 impl Bech32Encode for Offer {
838         const BECH32_HRP: &'static str = "lno";
839 }
840
841 impl FromStr for Offer {
842         type Err = Bolt12ParseError;
843
844         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
845                 Self::from_bech32_str(s)
846         }
847 }
848
849 impl TryFrom<Vec<u8>> for Offer {
850         type Error = Bolt12ParseError;
851
852         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
853                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
854                 let ParsedMessage { bytes, tlv_stream } = offer;
855                 let contents = OfferContents::try_from(tlv_stream)?;
856                 Ok(Offer { bytes, contents })
857         }
858 }
859
860 impl TryFrom<OfferTlvStream> for OfferContents {
861         type Error = Bolt12SemanticError;
862
863         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
864                 let OfferTlvStream {
865                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
866                         issuer, quantity_max, node_id,
867                 } = tlv_stream;
868
869                 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
870
871                 let amount = match (currency, amount) {
872                         (None, None) => None,
873                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
874                                 return Err(Bolt12SemanticError::InvalidAmount);
875                         },
876                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
877                         (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
878                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
879                 };
880
881                 let description = match description {
882                         None => return Err(Bolt12SemanticError::MissingDescription),
883                         Some(description) => description,
884                 };
885
886                 let features = features.unwrap_or_else(OfferFeatures::empty);
887
888                 let absolute_expiry = absolute_expiry
889                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
890
891                 let supported_quantity = match quantity_max {
892                         None => Quantity::One,
893                         Some(0) => Quantity::Unbounded,
894                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
895                 };
896
897                 let signing_pubkey = match node_id {
898                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
899                         Some(node_id) => node_id,
900                 };
901
902                 Ok(OfferContents {
903                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
904                         supported_quantity, signing_pubkey,
905                 })
906         }
907 }
908
909 impl core::fmt::Display for Offer {
910         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
911                 self.fmt_bech32_str(f)
912         }
913 }
914
915 #[cfg(test)]
916 mod tests {
917         use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
918
919         use bitcoin::blockdata::constants::ChainHash;
920         use bitcoin::network::constants::Network;
921         use bitcoin::secp256k1::Secp256k1;
922         use core::convert::TryFrom;
923         use core::num::NonZeroU64;
924         use core::time::Duration;
925         use crate::blinded_path::{BlindedHop, BlindedPath};
926         use crate::sign::KeyMaterial;
927         use crate::ln::features::OfferFeatures;
928         use crate::ln::inbound_payment::ExpandedKey;
929         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
930         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
931         use crate::offers::test_utils::*;
932         use crate::util::ser::{BigSize, Writeable};
933         use crate::util::string::PrintableString;
934
935         #[test]
936         fn builds_offer_with_defaults() {
937                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
938
939                 let mut buffer = Vec::new();
940                 offer.write(&mut buffer).unwrap();
941
942                 assert_eq!(offer.bytes, buffer.as_slice());
943                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
944                 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
945                 assert_eq!(offer.metadata(), None);
946                 assert_eq!(offer.amount(), None);
947                 assert_eq!(offer.description(), PrintableString("foo"));
948                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
949                 assert_eq!(offer.absolute_expiry(), None);
950                 #[cfg(feature = "std")]
951                 assert!(!offer.is_expired());
952                 assert_eq!(offer.paths(), &[]);
953                 assert_eq!(offer.issuer(), None);
954                 assert_eq!(offer.supported_quantity(), Quantity::One);
955                 assert_eq!(offer.signing_pubkey(), pubkey(42));
956
957                 assert_eq!(
958                         offer.as_tlv_stream(),
959                         OfferTlvStreamRef {
960                                 chains: None,
961                                 metadata: None,
962                                 currency: None,
963                                 amount: None,
964                                 description: Some(&String::from("foo")),
965                                 features: None,
966                                 absolute_expiry: None,
967                                 paths: None,
968                                 issuer: None,
969                                 quantity_max: None,
970                                 node_id: Some(&pubkey(42)),
971                         },
972                 );
973
974                 if let Err(e) = Offer::try_from(buffer) {
975                         panic!("error parsing offer: {:?}", e);
976                 }
977         }
978
979         #[test]
980         fn builds_offer_with_chains() {
981                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
982                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
983
984                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
985                         .chain(Network::Bitcoin)
986                         .build()
987                         .unwrap();
988                 assert!(offer.supports_chain(mainnet));
989                 assert_eq!(offer.chains(), vec![mainnet]);
990                 assert_eq!(offer.as_tlv_stream().chains, None);
991
992                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
993                         .chain(Network::Testnet)
994                         .build()
995                         .unwrap();
996                 assert!(offer.supports_chain(testnet));
997                 assert_eq!(offer.chains(), vec![testnet]);
998                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
999
1000                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1001                         .chain(Network::Testnet)
1002                         .chain(Network::Testnet)
1003                         .build()
1004                         .unwrap();
1005                 assert!(offer.supports_chain(testnet));
1006                 assert_eq!(offer.chains(), vec![testnet]);
1007                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1008
1009                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1010                         .chain(Network::Bitcoin)
1011                         .chain(Network::Testnet)
1012                         .build()
1013                         .unwrap();
1014                 assert!(offer.supports_chain(mainnet));
1015                 assert!(offer.supports_chain(testnet));
1016                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1017                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1018         }
1019
1020         #[test]
1021         fn builds_offer_with_metadata() {
1022                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1023                         .metadata(vec![42; 32]).unwrap()
1024                         .build()
1025                         .unwrap();
1026                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1027                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1028
1029                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1030                         .metadata(vec![42; 32]).unwrap()
1031                         .metadata(vec![43; 32]).unwrap()
1032                         .build()
1033                         .unwrap();
1034                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1035                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1036         }
1037
1038         #[test]
1039         fn builds_offer_with_metadata_derived() {
1040                 let desc = "foo".to_string();
1041                 let node_id = recipient_pubkey();
1042                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1043                 let entropy = FixedEntropy {};
1044                 let secp_ctx = Secp256k1::new();
1045
1046                 let offer = OfferBuilder
1047                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1048                         .amount_msats(1000)
1049                         .build().unwrap();
1050                 assert_eq!(offer.signing_pubkey(), node_id);
1051
1052                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1053                         .build().unwrap()
1054                         .sign(payer_sign).unwrap();
1055                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1056
1057                 // Fails verification with altered offer field
1058                 let mut tlv_stream = offer.as_tlv_stream();
1059                 tlv_stream.amount = Some(100);
1060
1061                 let mut encoded_offer = Vec::new();
1062                 tlv_stream.write(&mut encoded_offer).unwrap();
1063
1064                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1065                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1066                         .build().unwrap()
1067                         .sign(payer_sign).unwrap();
1068                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1069
1070                 // Fails verification with altered metadata
1071                 let mut tlv_stream = offer.as_tlv_stream();
1072                 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1073                 tlv_stream.metadata = Some(&metadata);
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
1085         #[test]
1086         fn builds_offer_with_derived_signing_pubkey() {
1087                 let desc = "foo".to_string();
1088                 let node_id = recipient_pubkey();
1089                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1090                 let entropy = FixedEntropy {};
1091                 let secp_ctx = Secp256k1::new();
1092
1093                 let blinded_path = BlindedPath {
1094                         introduction_node_id: pubkey(40),
1095                         blinding_point: pubkey(41),
1096                         blinded_hops: vec![
1097                                 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1098                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1099                         ],
1100                 };
1101
1102                 let offer = OfferBuilder
1103                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1104                         .amount_msats(1000)
1105                         .path(blinded_path)
1106                         .build().unwrap();
1107                 assert_ne!(offer.signing_pubkey(), node_id);
1108
1109                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1110                         .build().unwrap()
1111                         .sign(payer_sign).unwrap();
1112                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1113
1114                 // Fails verification with altered offer field
1115                 let mut tlv_stream = offer.as_tlv_stream();
1116                 tlv_stream.amount = Some(100);
1117
1118                 let mut encoded_offer = Vec::new();
1119                 tlv_stream.write(&mut encoded_offer).unwrap();
1120
1121                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1122                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1123                         .build().unwrap()
1124                         .sign(payer_sign).unwrap();
1125                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1126
1127                 // Fails verification with altered signing pubkey
1128                 let mut tlv_stream = offer.as_tlv_stream();
1129                 let signing_pubkey = pubkey(1);
1130                 tlv_stream.node_id = Some(&signing_pubkey);
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
1142         #[test]
1143         fn builds_offer_with_amount() {
1144                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1145                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1146
1147                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1148                         .amount_msats(1000)
1149                         .build()
1150                         .unwrap();
1151                 let tlv_stream = offer.as_tlv_stream();
1152                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1153                 assert_eq!(tlv_stream.amount, Some(1000));
1154                 assert_eq!(tlv_stream.currency, None);
1155
1156                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1157                         .amount(currency_amount.clone());
1158                 let tlv_stream = builder.offer.as_tlv_stream();
1159                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1160                 assert_eq!(tlv_stream.amount, Some(10));
1161                 assert_eq!(tlv_stream.currency, Some(b"USD"));
1162                 match builder.build() {
1163                         Ok(_) => panic!("expected error"),
1164                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1165                 }
1166
1167                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1168                         .amount(currency_amount.clone())
1169                         .amount(bitcoin_amount.clone())
1170                         .build()
1171                         .unwrap();
1172                 let tlv_stream = offer.as_tlv_stream();
1173                 assert_eq!(tlv_stream.amount, Some(1000));
1174                 assert_eq!(tlv_stream.currency, None);
1175
1176                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1177                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1178                         Ok(_) => panic!("expected error"),
1179                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1180                 }
1181         }
1182
1183         #[test]
1184         fn builds_offer_with_features() {
1185                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1186                         .features_unchecked(OfferFeatures::unknown())
1187                         .build()
1188                         .unwrap();
1189                 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1190                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1191
1192                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1193                         .features_unchecked(OfferFeatures::unknown())
1194                         .features_unchecked(OfferFeatures::empty())
1195                         .build()
1196                         .unwrap();
1197                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1198                 assert_eq!(offer.as_tlv_stream().features, None);
1199         }
1200
1201         #[test]
1202         fn builds_offer_with_absolute_expiry() {
1203                 let future_expiry = Duration::from_secs(u64::max_value());
1204                 let past_expiry = Duration::from_secs(0);
1205                 let now = future_expiry - Duration::from_secs(1_000);
1206
1207                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1208                         .absolute_expiry(future_expiry)
1209                         .build()
1210                         .unwrap();
1211                 #[cfg(feature = "std")]
1212                 assert!(!offer.is_expired());
1213                 assert!(!offer.is_expired_no_std(now));
1214                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1215                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1216
1217                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1218                         .absolute_expiry(future_expiry)
1219                         .absolute_expiry(past_expiry)
1220                         .build()
1221                         .unwrap();
1222                 #[cfg(feature = "std")]
1223                 assert!(offer.is_expired());
1224                 assert!(offer.is_expired_no_std(now));
1225                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1226                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1227         }
1228
1229         #[test]
1230         fn builds_offer_with_paths() {
1231                 let paths = vec![
1232                         BlindedPath {
1233                                 introduction_node_id: pubkey(40),
1234                                 blinding_point: pubkey(41),
1235                                 blinded_hops: vec![
1236                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1237                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1238                                 ],
1239                         },
1240                         BlindedPath {
1241                                 introduction_node_id: pubkey(40),
1242                                 blinding_point: pubkey(41),
1243                                 blinded_hops: vec![
1244                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1245                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1246                                 ],
1247                         },
1248                 ];
1249
1250                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1251                         .path(paths[0].clone())
1252                         .path(paths[1].clone())
1253                         .build()
1254                         .unwrap();
1255                 let tlv_stream = offer.as_tlv_stream();
1256                 assert_eq!(offer.paths(), paths.as_slice());
1257                 assert_eq!(offer.signing_pubkey(), pubkey(42));
1258                 assert_ne!(pubkey(42), pubkey(44));
1259                 assert_eq!(tlv_stream.paths, Some(&paths));
1260                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1261         }
1262
1263         #[test]
1264         fn builds_offer_with_issuer() {
1265                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1266                         .issuer("bar".into())
1267                         .build()
1268                         .unwrap();
1269                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1270                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1271
1272                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1273                         .issuer("bar".into())
1274                         .issuer("baz".into())
1275                         .build()
1276                         .unwrap();
1277                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1278                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1279         }
1280
1281         #[test]
1282         fn builds_offer_with_supported_quantity() {
1283                 let one = NonZeroU64::new(1).unwrap();
1284                 let ten = NonZeroU64::new(10).unwrap();
1285
1286                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1287                         .supported_quantity(Quantity::One)
1288                         .build()
1289                         .unwrap();
1290                 let tlv_stream = offer.as_tlv_stream();
1291                 assert_eq!(offer.supported_quantity(), Quantity::One);
1292                 assert_eq!(tlv_stream.quantity_max, None);
1293
1294                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1295                         .supported_quantity(Quantity::Unbounded)
1296                         .build()
1297                         .unwrap();
1298                 let tlv_stream = offer.as_tlv_stream();
1299                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1300                 assert_eq!(tlv_stream.quantity_max, Some(0));
1301
1302                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1303                         .supported_quantity(Quantity::Bounded(ten))
1304                         .build()
1305                         .unwrap();
1306                 let tlv_stream = offer.as_tlv_stream();
1307                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1308                 assert_eq!(tlv_stream.quantity_max, Some(10));
1309
1310                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1311                         .supported_quantity(Quantity::Bounded(one))
1312                         .build()
1313                         .unwrap();
1314                 let tlv_stream = offer.as_tlv_stream();
1315                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1316                 assert_eq!(tlv_stream.quantity_max, Some(1));
1317
1318                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1319                         .supported_quantity(Quantity::Bounded(ten))
1320                         .supported_quantity(Quantity::One)
1321                         .build()
1322                         .unwrap();
1323                 let tlv_stream = offer.as_tlv_stream();
1324                 assert_eq!(offer.supported_quantity(), Quantity::One);
1325                 assert_eq!(tlv_stream.quantity_max, None);
1326         }
1327
1328         #[test]
1329         fn fails_requesting_invoice_with_unknown_required_features() {
1330                 match OfferBuilder::new("foo".into(), pubkey(42))
1331                         .features_unchecked(OfferFeatures::unknown())
1332                         .build().unwrap()
1333                         .request_invoice(vec![1; 32], pubkey(43))
1334                 {
1335                         Ok(_) => panic!("expected error"),
1336                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1337                 }
1338         }
1339
1340         #[test]
1341         fn parses_offer_with_chains() {
1342                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1343                         .chain(Network::Bitcoin)
1344                         .chain(Network::Testnet)
1345                         .build()
1346                         .unwrap();
1347                 if let Err(e) = offer.to_string().parse::<Offer>() {
1348                         panic!("error parsing offer: {:?}", e);
1349                 }
1350         }
1351
1352         #[test]
1353         fn parses_offer_with_amount() {
1354                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1355                         .amount(Amount::Bitcoin { amount_msats: 1000 })
1356                         .build()
1357                         .unwrap();
1358                 if let Err(e) = offer.to_string().parse::<Offer>() {
1359                         panic!("error parsing offer: {:?}", e);
1360                 }
1361
1362                 let mut tlv_stream = offer.as_tlv_stream();
1363                 tlv_stream.amount = Some(1000);
1364                 tlv_stream.currency = Some(b"USD");
1365
1366                 let mut encoded_offer = Vec::new();
1367                 tlv_stream.write(&mut encoded_offer).unwrap();
1368
1369                 if let Err(e) = Offer::try_from(encoded_offer) {
1370                         panic!("error parsing offer: {:?}", e);
1371                 }
1372
1373                 let mut tlv_stream = offer.as_tlv_stream();
1374                 tlv_stream.amount = None;
1375                 tlv_stream.currency = Some(b"USD");
1376
1377                 let mut encoded_offer = Vec::new();
1378                 tlv_stream.write(&mut encoded_offer).unwrap();
1379
1380                 match Offer::try_from(encoded_offer) {
1381                         Ok(_) => panic!("expected error"),
1382                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1383                 }
1384
1385                 let mut tlv_stream = offer.as_tlv_stream();
1386                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1387                 tlv_stream.currency = None;
1388
1389                 let mut encoded_offer = Vec::new();
1390                 tlv_stream.write(&mut encoded_offer).unwrap();
1391
1392                 match Offer::try_from(encoded_offer) {
1393                         Ok(_) => panic!("expected error"),
1394                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1395                 }
1396         }
1397
1398         #[test]
1399         fn parses_offer_with_description() {
1400                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1401                 if let Err(e) = offer.to_string().parse::<Offer>() {
1402                         panic!("error parsing offer: {:?}", e);
1403                 }
1404
1405                 let mut tlv_stream = offer.as_tlv_stream();
1406                 tlv_stream.description = None;
1407
1408                 let mut encoded_offer = Vec::new();
1409                 tlv_stream.write(&mut encoded_offer).unwrap();
1410
1411                 match Offer::try_from(encoded_offer) {
1412                         Ok(_) => panic!("expected error"),
1413                         Err(e) => {
1414                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1415                         },
1416                 }
1417         }
1418
1419         #[test]
1420         fn parses_offer_with_paths() {
1421                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1422                         .path(BlindedPath {
1423                                 introduction_node_id: pubkey(40),
1424                                 blinding_point: pubkey(41),
1425                                 blinded_hops: vec![
1426                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1427                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1428                                 ],
1429                         })
1430                         .path(BlindedPath {
1431                                 introduction_node_id: pubkey(40),
1432                                 blinding_point: pubkey(41),
1433                                 blinded_hops: vec![
1434                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1435                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1436                                 ],
1437                         })
1438                         .build()
1439                         .unwrap();
1440                 if let Err(e) = offer.to_string().parse::<Offer>() {
1441                         panic!("error parsing offer: {:?}", e);
1442                 }
1443
1444                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1445                 builder.offer.paths = Some(vec![]);
1446
1447                 let offer = builder.build().unwrap();
1448                 if let Err(e) = offer.to_string().parse::<Offer>() {
1449                         panic!("error parsing offer: {:?}", e);
1450                 }
1451         }
1452
1453         #[test]
1454         fn parses_offer_with_quantity() {
1455                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1456                         .supported_quantity(Quantity::One)
1457                         .build()
1458                         .unwrap();
1459                 if let Err(e) = offer.to_string().parse::<Offer>() {
1460                         panic!("error parsing offer: {:?}", e);
1461                 }
1462
1463                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1464                         .supported_quantity(Quantity::Unbounded)
1465                         .build()
1466                         .unwrap();
1467                 if let Err(e) = offer.to_string().parse::<Offer>() {
1468                         panic!("error parsing offer: {:?}", e);
1469                 }
1470
1471                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1472                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1473                         .build()
1474                         .unwrap();
1475                 if let Err(e) = offer.to_string().parse::<Offer>() {
1476                         panic!("error parsing offer: {:?}", e);
1477                 }
1478
1479                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1480                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1481                         .build()
1482                         .unwrap();
1483                 if let Err(e) = offer.to_string().parse::<Offer>() {
1484                         panic!("error parsing offer: {:?}", e);
1485                 }
1486         }
1487
1488         #[test]
1489         fn parses_offer_with_node_id() {
1490                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1491                 if let Err(e) = offer.to_string().parse::<Offer>() {
1492                         panic!("error parsing offer: {:?}", e);
1493                 }
1494
1495                 let mut tlv_stream = offer.as_tlv_stream();
1496                 tlv_stream.node_id = None;
1497
1498                 let mut encoded_offer = Vec::new();
1499                 tlv_stream.write(&mut encoded_offer).unwrap();
1500
1501                 match Offer::try_from(encoded_offer) {
1502                         Ok(_) => panic!("expected error"),
1503                         Err(e) => {
1504                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1505                         },
1506                 }
1507         }
1508
1509         #[test]
1510         fn fails_parsing_offer_with_extra_tlv_records() {
1511                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1512
1513                 let mut encoded_offer = Vec::new();
1514                 offer.write(&mut encoded_offer).unwrap();
1515                 BigSize(80).write(&mut encoded_offer).unwrap();
1516                 BigSize(32).write(&mut encoded_offer).unwrap();
1517                 [42u8; 32].write(&mut encoded_offer).unwrap();
1518
1519                 match Offer::try_from(encoded_offer) {
1520                         Ok(_) => panic!("expected error"),
1521                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1522                 }
1523         }
1524 }
1525
1526 #[cfg(test)]
1527 mod bolt12_tests {
1528         use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1529         use crate::ln::msgs::DecodeError;
1530
1531         #[test]
1532         fn parses_bech32_encoded_offers() {
1533                 let offers = [
1534                         // Minimal bolt12 offer
1535                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1536
1537                         // for testnet
1538                         "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1539
1540                         // for bitcoin (redundant)
1541                         "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1542
1543                         // for bitcoin or liquidv1
1544                         "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1545
1546                         // with metadata
1547                         "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1548
1549                         // with amount
1550                         "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1551
1552                         // with currency
1553                         "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1554
1555                         // with expiry
1556                         "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1557
1558                         // with issuer
1559                         "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1560
1561                         // with quantity
1562                         "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1563
1564                         // with unlimited (or unknown) quantity
1565                         "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1566
1567                         // with single quantity (weird but valid)
1568                         "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1569
1570                         // with feature
1571                         "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1572
1573                         // with blinded path via Bob (0x424242...), blinding 020202...
1574                         "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1575
1576                         // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1577                         "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1578
1579                         // unknown odd field
1580                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1581                 ];
1582                 for encoded_offer in &offers {
1583                         if let Err(e) = encoded_offer.parse::<Offer>() {
1584                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1585                         }
1586                 }
1587         }
1588
1589         #[test]
1590         fn fails_parsing_bech32_encoded_offers() {
1591                 // Malformed: fields out of order
1592                 assert_eq!(
1593                         "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1594                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1595                 );
1596
1597                 // Malformed: unknown even TLV type 78
1598                 assert_eq!(
1599                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1600                         Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1601                 );
1602
1603                 // Malformed: empty
1604                 assert_eq!(
1605                         "lno1".parse::<Offer>(),
1606                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1607                 );
1608
1609                 // Malformed: truncated at type
1610                 assert_eq!(
1611                         "lno1pg".parse::<Offer>(),
1612                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1613                 );
1614
1615                 // Malformed: truncated in length
1616                 assert_eq!(
1617                         "lno1pt7s".parse::<Offer>(),
1618                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1619                 );
1620
1621                 // Malformed: truncated after length
1622                 assert_eq!(
1623                         "lno1pgpq".parse::<Offer>(),
1624                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1625                 );
1626
1627                 // Malformed: truncated in description
1628                 assert_eq!(
1629                         "lno1pgpyz".parse::<Offer>(),
1630                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1631                 );
1632
1633                 // Malformed: invalid offer_chains length
1634                 assert_eq!(
1635                         "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1636                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1637                 );
1638
1639                 // Malformed: truncated currency UTF-8
1640                 assert_eq!(
1641                         "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1642                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1643                 );
1644
1645                 // Malformed: invalid currency UTF-8
1646                 assert_eq!(
1647                         "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1648                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1649                 );
1650
1651                 // Malformed: truncated description UTF-8
1652                 assert_eq!(
1653                         "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1654                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1655                 );
1656
1657                 // Malformed: invalid description UTF-8
1658                 assert_eq!(
1659                         "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1660                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1661                 );
1662
1663                 // Malformed: truncated offer_paths
1664                 assert_eq!(
1665                         "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1666                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1667                 );
1668
1669                 // Malformed: zero num_hops in blinded_path
1670                 assert_eq!(
1671                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1672                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1673                 );
1674
1675                 // Malformed: truncated onionmsg_hop in blinded_path
1676                 assert_eq!(
1677                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1678                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1679                 );
1680
1681                 // Malformed: bad first_node_id in blinded_path
1682                 assert_eq!(
1683                         "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1684                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1685                 );
1686
1687                 // Malformed: bad blinding in blinded_path
1688                 assert_eq!(
1689                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1690                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1691                 );
1692
1693                 // Malformed: bad blinded_node_id in onionmsg_hop
1694                 assert_eq!(
1695                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1696                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1697                 );
1698
1699                 // Malformed: truncated issuer UTF-8
1700                 assert_eq!(
1701                         "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1702                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1703                 );
1704
1705                 // Malformed: invalid issuer UTF-8
1706                 assert_eq!(
1707                         "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1708                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1709                 );
1710
1711                 // Malformed: invalid offer_node_id
1712                 assert_eq!(
1713                         "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1714                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1715                 );
1716
1717                 // Contains type >= 80
1718                 assert_eq!(
1719                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1720                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1721                 );
1722
1723                 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1724                 // Contains unknown feature 22
1725                 assert!(
1726                         "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1727                 );
1728
1729                 // Missing offer_description
1730                 assert_eq!(
1731                         "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1732                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1733                 );
1734
1735                 // Missing offer_node_id"
1736                 assert_eq!(
1737                         "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1738                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),
1739                 );
1740         }
1741 }