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