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