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