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