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