967db3cdd884d17d9f51b2bbb8f9fe079ca920b3
[rust-lightning] / lightning / src / offers / invoice_request.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 `invoice_request` messages.
11 //!
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with a [`Bolt12Invoice`].
15 //!
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
18 //!
19 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
21 //!
22 //! ```
23 //! extern crate bitcoin;
24 //! extern crate lightning;
25 //!
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
32 //!
33 //! # fn parse() -> Result<(), lightning::offers::parse::Bolt12ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
38 //!
39 //! # use lightning::offers::invoice_request::{ExplicitPayerId, InvoiceRequestBuilder};
40 //! # <InvoiceRequestBuilder<ExplicitPayerId, _>>::from(
41 //! "lno1qcp4256ypq"
42 //!     .parse::<Offer>()?
43 //!     .request_invoice(vec![42; 64], pubkey)?
44 //! # )
45 //!     .chain(Network::Testnet)?
46 //!     .amount_msats(1000)?
47 //!     .quantity(5)?
48 //!     .payer_note("foo".to_string())
49 //!     .build()?
50 //!     .sign::<_, Infallible>(
51 //!         |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
52 //!     )
53 //!     .expect("failed verifying signature")
54 //!     .write(&mut buffer)
55 //!     .unwrap();
56 //! # Ok(())
57 //! # }
58 //! ```
59
60 use bitcoin::blockdata::constants::ChainHash;
61 use bitcoin::network::constants::Network;
62 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
63 use bitcoin::secp256k1::schnorr::Signature;
64 use core::convert::{AsRef, Infallible, TryFrom};
65 use core::ops::Deref;
66 use crate::sign::EntropySource;
67 use crate::io;
68 use crate::blinded_path::BlindedPath;
69 use crate::ln::PaymentHash;
70 use crate::ln::channelmanager::PaymentId;
71 use crate::ln::features::InvoiceRequestFeatures;
72 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
73 use crate::ln::msgs::DecodeError;
74 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
75 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
76 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
77 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
78 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
79 use crate::offers::signer::{Metadata, MetadataMaterial};
80 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
81 use crate::util::string::PrintableString;
82
83 use crate::prelude::*;
84
85 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
86 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
87
88 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
89
90 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
91 ///
92 /// See [module-level documentation] for usage.
93 ///
94 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
95 ///
96 /// [module-level documentation]: self
97 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
98         offer: &'a Offer,
99         invoice_request: InvoiceRequestContentsWithoutPayerId,
100         payer_id: Option<PublicKey>,
101         payer_id_strategy: core::marker::PhantomData<P>,
102         secp_ctx: Option<&'b Secp256k1<T>>,
103 }
104
105 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
106 ///
107 /// See [module-level documentation] for usage.
108 ///
109 /// [module-level documentation]: self
110 #[cfg(c_bindings)]
111 pub struct InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
112         offer: &'a Offer,
113         invoice_request: InvoiceRequestContentsWithoutPayerId,
114         payer_id: Option<PublicKey>,
115         payer_id_strategy: core::marker::PhantomData<ExplicitPayerId>,
116         secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
117 }
118
119 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
120 ///
121 /// See [module-level documentation] for usage.
122 ///
123 /// [module-level documentation]: self
124 #[cfg(c_bindings)]
125 pub struct InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
126         offer: &'a Offer,
127         invoice_request: InvoiceRequestContentsWithoutPayerId,
128         payer_id: Option<PublicKey>,
129         payer_id_strategy: core::marker::PhantomData<DerivedPayerId>,
130         secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
131 }
132
133 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
134 ///
135 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
136 pub trait PayerIdStrategy {}
137
138 /// [`InvoiceRequest::payer_id`] will be explicitly set.
139 ///
140 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
141 pub struct ExplicitPayerId {}
142
143 /// [`InvoiceRequest::payer_id`] will be derived.
144 ///
145 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
146 pub struct DerivedPayerId {}
147
148 impl PayerIdStrategy for ExplicitPayerId {}
149 impl PayerIdStrategy for DerivedPayerId {}
150
151 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
152         #[cfg_attr(c_bindings, allow(dead_code))]
153         pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
154                 Self {
155                         offer,
156                         invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
157                         payer_id: Some(payer_id),
158                         payer_id_strategy: core::marker::PhantomData,
159                         secp_ctx: None,
160                 }
161         }
162
163         #[cfg_attr(c_bindings, allow(dead_code))]
164         pub(super) fn deriving_metadata<ES: Deref>(
165                 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
166                 payment_id: PaymentId,
167         ) -> Self where ES::Target: EntropySource {
168                 let nonce = Nonce::from_entropy_source(entropy_source);
169                 let payment_id = Some(payment_id);
170                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
171                 let metadata = Metadata::Derived(derivation_material);
172                 Self {
173                         offer,
174                         invoice_request: Self::create_contents(offer, metadata),
175                         payer_id: Some(payer_id),
176                         payer_id_strategy: core::marker::PhantomData,
177                         secp_ctx: None,
178                 }
179         }
180
181         /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
182         /// by [`UnsignedInvoiceRequest::sign`].
183         pub fn build($self: $self_type) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
184                 let (unsigned_invoice_request, keys, _) = $self.build_with_checks()?;
185                 debug_assert!(keys.is_none());
186                 Ok(unsigned_invoice_request)
187         }
188 } }
189
190 macro_rules! invoice_request_derived_payer_id_builder_methods { (
191         $self: ident, $self_type: ty, $secp_context: ty
192 ) => {
193         #[cfg_attr(c_bindings, allow(dead_code))]
194         pub(super) fn deriving_payer_id<ES: Deref>(
195                 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
196                 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
197         ) -> Self where ES::Target: EntropySource {
198                 let nonce = Nonce::from_entropy_source(entropy_source);
199                 let payment_id = Some(payment_id);
200                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
201                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
202                 Self {
203                         offer,
204                         invoice_request: Self::create_contents(offer, metadata),
205                         payer_id: None,
206                         payer_id_strategy: core::marker::PhantomData,
207                         secp_ctx: Some(secp_ctx),
208                 }
209         }
210
211         /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
212         pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
213                 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
214                 #[cfg(c_bindings)]
215                 let mut unsigned_invoice_request = unsigned_invoice_request;
216                 debug_assert!(keys.is_some());
217
218                 let secp_ctx = secp_ctx.unwrap();
219                 let keys = keys.unwrap();
220                 let invoice_request = unsigned_invoice_request
221                         .sign::<_, Infallible>(
222                                 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
223                         )
224                         .unwrap();
225                 Ok(invoice_request)
226         }
227 } }
228
229 macro_rules! invoice_request_builder_methods { (
230         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
231 ) => {
232         #[cfg_attr(c_bindings, allow(dead_code))]
233         fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
234                 let offer = offer.contents.clone();
235                 InvoiceRequestContentsWithoutPayerId {
236                         payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
237                         features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
238                 }
239         }
240
241         /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
242         /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
243         /// by the offer.
244         ///
245         /// Successive calls to this method will override the previous setting.
246         pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
247                 $self.chain_hash(ChainHash::using_genesis_block(network))
248         }
249
250         /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
251         /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
252         /// offer.
253         ///
254         /// Successive calls to this method will override the previous setting.
255         pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
256                 if !$self.offer.supports_chain(chain) {
257                         return Err(Bolt12SemanticError::UnsupportedChain);
258                 }
259
260                 $self.invoice_request.chain = Some(chain);
261                 Ok($return_value)
262         }
263
264         /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
265         /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
266         ///
267         /// Successive calls to this method will override the previous setting.
268         ///
269         /// [`quantity`]: Self::quantity
270         pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
271                 $self.invoice_request.offer.check_amount_msats_for_quantity(
272                         Some(amount_msats), $self.invoice_request.quantity
273                 )?;
274                 $self.invoice_request.amount_msats = Some(amount_msats);
275                 Ok($return_value)
276         }
277
278         /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
279         /// does not conform to [`Offer::is_valid_quantity`].
280         ///
281         /// Successive calls to this method will override the previous setting.
282         pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
283                 $self.invoice_request.offer.check_quantity(Some(quantity))?;
284                 $self.invoice_request.quantity = Some(quantity);
285                 Ok($return_value)
286         }
287
288         /// Sets the [`InvoiceRequest::payer_note`].
289         ///
290         /// Successive calls to this method will override the previous setting.
291         pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
292                 $self.invoice_request.payer_note = Some(payer_note);
293                 $return_value
294         }
295
296         fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
297                 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>),
298                 Bolt12SemanticError
299         > {
300                 #[cfg(feature = "std")] {
301                         if $self.offer.is_expired() {
302                                 return Err(Bolt12SemanticError::AlreadyExpired);
303                         }
304                 }
305
306                 let chain = $self.invoice_request.chain();
307                 if !$self.offer.supports_chain(chain) {
308                         return Err(Bolt12SemanticError::UnsupportedChain);
309                 }
310
311                 if chain == $self.offer.implied_chain() {
312                         $self.invoice_request.chain = None;
313                 }
314
315                 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
316                         return Err(Bolt12SemanticError::MissingAmount);
317                 }
318
319                 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
320                 $self.invoice_request.offer.check_amount_msats_for_quantity(
321                         $self.invoice_request.amount_msats, $self.invoice_request.quantity
322                 )?;
323
324                 Ok($self.build_without_checks())
325         }
326
327         fn build_without_checks($($self_mut)* $self: $self_type) ->
328                 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>)
329         {
330                 // Create the metadata for stateless verification of a Bolt12Invoice.
331                 let mut keys = None;
332                 let secp_ctx = $self.secp_ctx.clone();
333                 if $self.invoice_request.payer.0.has_derivation_material() {
334                         let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
335
336                         let mut tlv_stream = $self.invoice_request.as_tlv_stream();
337                         debug_assert!(tlv_stream.2.payer_id.is_none());
338                         tlv_stream.0.metadata = None;
339                         if !metadata.derives_payer_keys() {
340                                 tlv_stream.2.payer_id = $self.payer_id.as_ref();
341                         }
342
343                         let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
344                         metadata = derived_metadata;
345                         keys = derived_keys;
346                         if let Some(keys) = keys {
347                                 debug_assert!($self.payer_id.is_none());
348                                 $self.payer_id = Some(keys.public_key());
349                         }
350
351                         $self.invoice_request.payer.0 = metadata;
352                 }
353
354                 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
355                 debug_assert!($self.payer_id.is_some());
356                 let payer_id = $self.payer_id.unwrap();
357
358                 let invoice_request = InvoiceRequestContents {
359                         #[cfg(not(c_bindings))]
360                         inner: $self.invoice_request,
361                         #[cfg(c_bindings)]
362                         inner: $self.invoice_request.clone(),
363                         payer_id,
364                 };
365                 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
366
367                 (unsigned_invoice_request, keys, secp_ctx)
368         }
369 } }
370
371 #[cfg(test)]
372 macro_rules! invoice_request_builder_test_methods { (
373         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
374 ) => {
375         #[cfg_attr(c_bindings, allow(dead_code))]
376         fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
377                 let chain = ChainHash::using_genesis_block(network);
378                 $self.invoice_request.chain = Some(chain);
379                 $return_value
380         }
381
382         #[cfg_attr(c_bindings, allow(dead_code))]
383         fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
384                 $self.invoice_request.amount_msats = Some(amount_msats);
385                 $return_value
386         }
387
388         #[cfg_attr(c_bindings, allow(dead_code))]
389         fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
390                 $self.invoice_request.features = features;
391                 $return_value
392         }
393
394         #[cfg_attr(c_bindings, allow(dead_code))]
395         fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
396                 $self.invoice_request.quantity = Some(quantity);
397                 $return_value
398         }
399
400         #[cfg_attr(c_bindings, allow(dead_code))]
401         pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
402                 $self.build_without_checks().0
403         }
404 } }
405
406 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
407         invoice_request_explicit_payer_id_builder_methods!(self, Self);
408 }
409
410 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
411         invoice_request_derived_payer_id_builder_methods!(self, Self, T);
412 }
413
414 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
415         invoice_request_builder_methods!(self, Self, Self, self, T, mut);
416
417         #[cfg(test)]
418         invoice_request_builder_test_methods!(self, Self, Self, self, mut);
419 }
420
421 #[cfg(all(c_bindings, not(test)))]
422 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
423         invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
424         invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
425 }
426
427 #[cfg(all(c_bindings, test))]
428 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
429         invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
430         invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
431         invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
432 }
433
434 #[cfg(all(c_bindings, not(test)))]
435 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
436         invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
437         invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
438 }
439
440 #[cfg(all(c_bindings, test))]
441 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
442         invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
443         invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
444         invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
445 }
446
447 #[cfg(c_bindings)]
448 impl<'a, 'b> From<InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>>
449 for InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, secp256k1::All> {
450         fn from(builder: InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>) -> Self {
451                 let InvoiceRequestWithExplicitPayerIdBuilder {
452                         offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
453                 } = builder;
454
455                 Self {
456                         offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
457                 }
458         }
459 }
460
461 #[cfg(c_bindings)]
462 impl<'a, 'b> From<InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>>
463 for InvoiceRequestBuilder<'a, 'b, DerivedPayerId, secp256k1::All> {
464         fn from(builder: InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>) -> Self {
465                 let InvoiceRequestWithDerivedPayerIdBuilder {
466                         offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
467                 } = builder;
468
469                 Self {
470                         offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
471                 }
472         }
473 }
474
475 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
476 ///
477 /// # Serialization
478 ///
479 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
480 /// such, it may include unknown, odd TLV records.
481 pub struct UnsignedInvoiceRequest {
482         bytes: Vec<u8>,
483         contents: InvoiceRequestContents,
484         tagged_hash: TaggedHash,
485 }
486
487 impl UnsignedInvoiceRequest {
488         fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
489                 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
490                 // unknown TLV records, which are not stored in `OfferContents`.
491                 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
492                         contents.as_tlv_stream();
493                 let offer_bytes = WithoutLength(&offer.bytes);
494                 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
495
496                 let mut bytes = Vec::new();
497                 unsigned_tlv_stream.write(&mut bytes).unwrap();
498
499                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
500
501                 Self { bytes, contents, tagged_hash }
502         }
503
504         /// Returns the [`TaggedHash`] of the invoice to sign.
505         pub fn tagged_hash(&self) -> &TaggedHash {
506                 &self.tagged_hash
507         }
508 }
509
510 macro_rules! unsigned_invoice_request_sign_method { (
511         $self: ident, $self_type: ty $(, $self_mut: tt)?
512 ) => {
513         /// Signs the [`TaggedHash`] of the invoice request using the given function.
514         ///
515         /// Note: The hash computation may have included unknown, odd TLV records.
516         ///
517         /// This is not exported to bindings users as functions are not yet mapped.
518         pub fn sign<F, E>($($self_mut)* $self: $self_type, sign: F) -> Result<InvoiceRequest, SignError<E>>
519         where
520                 F: FnOnce(&Self) -> Result<Signature, E>
521         {
522                 let pubkey = $self.contents.payer_id;
523                 let signature = merkle::sign_message(sign, &$self, pubkey)?;
524
525                 // Append the signature TLV record to the bytes.
526                 let signature_tlv_stream = SignatureTlvStreamRef {
527                         signature: Some(&signature),
528                 };
529                 signature_tlv_stream.write(&mut $self.bytes).unwrap();
530
531                 Ok(InvoiceRequest {
532                         #[cfg(not(c_bindings))]
533                         bytes: $self.bytes,
534                         #[cfg(c_bindings)]
535                         bytes: $self.bytes.clone(),
536                         #[cfg(not(c_bindings))]
537                         contents: $self.contents,
538                         #[cfg(c_bindings)]
539                         contents: $self.contents.clone(),
540                         signature,
541                 })
542         }
543 } }
544
545 #[cfg(not(c_bindings))]
546 impl UnsignedInvoiceRequest {
547         unsigned_invoice_request_sign_method!(self, Self, mut);
548 }
549
550 #[cfg(c_bindings)]
551 impl UnsignedInvoiceRequest {
552         unsigned_invoice_request_sign_method!(self, &mut Self);
553 }
554
555 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
556         fn as_ref(&self) -> &TaggedHash {
557                 &self.tagged_hash
558         }
559 }
560
561 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
562 ///
563 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
564 /// specifies these such that its recipient can send an invoice for payment.
565 ///
566 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
567 /// [`Offer`]: crate::offers::offer::Offer
568 #[derive(Clone, Debug)]
569 #[cfg_attr(test, derive(PartialEq))]
570 pub struct InvoiceRequest {
571         pub(super) bytes: Vec<u8>,
572         pub(super) contents: InvoiceRequestContents,
573         signature: Signature,
574 }
575
576 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
577 /// ways to respond depending on whether the signing keys were derived.
578 #[derive(Clone, Debug)]
579 pub struct VerifiedInvoiceRequest {
580         /// The verified request.
581         inner: InvoiceRequest,
582
583         /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
584         ///
585         /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
586         /// [`respond_with`].
587         ///
588         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
589         /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
590         /// [`respond_with`]: Self::respond_with
591         pub keys: Option<KeyPair>,
592 }
593
594 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
595 ///
596 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
597 #[derive(Clone, Debug)]
598 #[cfg_attr(test, derive(PartialEq))]
599 pub(super) struct InvoiceRequestContents {
600         pub(super) inner: InvoiceRequestContentsWithoutPayerId,
601         payer_id: PublicKey,
602 }
603
604 #[derive(Clone, Debug)]
605 #[cfg_attr(test, derive(PartialEq))]
606 pub(super) struct InvoiceRequestContentsWithoutPayerId {
607         payer: PayerContents,
608         pub(super) offer: OfferContents,
609         chain: Option<ChainHash>,
610         amount_msats: Option<u64>,
611         features: InvoiceRequestFeatures,
612         quantity: Option<u64>,
613         payer_note: Option<String>,
614 }
615
616 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
617         /// An unpredictable series of bytes, typically containing information about the derivation of
618         /// [`payer_id`].
619         ///
620         /// [`payer_id`]: Self::payer_id
621         pub fn payer_metadata(&$self) -> &[u8] {
622                 $contents.metadata()
623         }
624
625         /// A chain from [`Offer::chains`] that the offer is valid for.
626         pub fn chain(&$self) -> ChainHash {
627                 $contents.chain()
628         }
629
630         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
631         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
632         ///
633         /// [`chain`]: Self::chain
634         pub fn amount_msats(&$self) -> Option<u64> {
635                 $contents.amount_msats()
636         }
637
638         /// Features pertaining to requesting an invoice.
639         pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
640                 &$contents.features()
641         }
642
643         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
644         pub fn quantity(&$self) -> Option<u64> {
645                 $contents.quantity()
646         }
647
648         /// A possibly transient pubkey used to sign the invoice request.
649         pub fn payer_id(&$self) -> PublicKey {
650                 $contents.payer_id()
651         }
652
653         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
654         /// response.
655         pub fn payer_note(&$self) -> Option<PrintableString> {
656                 $contents.payer_note()
657         }
658 } }
659
660 impl UnsignedInvoiceRequest {
661         offer_accessors!(self, self.contents.inner.offer);
662         invoice_request_accessors!(self, self.contents);
663 }
664
665 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
666         $self: ident, $contents: expr, $builder: ty
667 ) => {
668         /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
669         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
670         ///
671         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
672         /// creation time is used for the `created_at` parameter.
673         ///
674         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
675         ///
676         /// [`Duration`]: core::time::Duration
677         #[cfg(feature = "std")]
678         pub fn respond_with(
679                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
680         ) -> Result<$builder, Bolt12SemanticError> {
681                 let created_at = std::time::SystemTime::now()
682                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
683                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
684
685                 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
686         }
687
688         /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
689         ///
690         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
691         /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
692         /// where [`std::time::SystemTime`] is not available.
693         ///
694         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
695         /// for the invoice.
696         ///
697         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
698         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
699         /// a preference. Note, however, that any privacy is lost if a public node id was used for
700         /// [`Offer::signing_pubkey`].
701         ///
702         /// Errors if the request contains unknown required features.
703         ///
704         /// # Note
705         ///
706         /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
707         /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
708         ///
709         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
710         ///
711         /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
712         /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
713         pub fn respond_with_no_std(
714                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
715                 created_at: core::time::Duration
716         ) -> Result<$builder, Bolt12SemanticError> {
717                 if $contents.invoice_request_features().requires_unknown_bits() {
718                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
719                 }
720
721                 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash)
722         }
723 } }
724
725 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
726         /// Verifies that the request was for an offer created using the given key. Returns the verified
727         /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
728         /// if they could be extracted from the metadata.
729         ///
730         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
731         pub fn verify<T: secp256k1::Signing>(
732                 $self: $self_type, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
733         ) -> Result<VerifiedInvoiceRequest, ()> {
734                 let keys = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
735                 Ok(VerifiedInvoiceRequest {
736                         inner: $self,
737                         keys,
738                 })
739         }
740
741 } }
742
743 impl InvoiceRequest {
744         offer_accessors!(self, self.contents.inner.offer);
745         invoice_request_accessors!(self, self.contents);
746         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
747         invoice_request_verify_method!(self, Self);
748
749         /// Signature of the invoice request using [`payer_id`].
750         ///
751         /// [`payer_id`]: Self::payer_id
752         pub fn signature(&self) -> Signature {
753                 self.signature
754         }
755
756         pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
757                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
758                         self.contents.as_tlv_stream();
759                 let signature_tlv_stream = SignatureTlvStreamRef {
760                         signature: Some(&self.signature),
761                 };
762                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
763         }
764 }
765
766 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
767         $self: ident, $contents: expr, $builder: ty
768 ) => {
769         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
770         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
771         /// the same [`ExpandedKey`] as the one used to create the offer.
772         ///
773         /// See [`InvoiceRequest::respond_with`] for further details.
774         ///
775         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
776         ///
777         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
778         #[cfg(feature = "std")]
779         pub fn respond_using_derived_keys(
780                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
781         ) -> Result<$builder, Bolt12SemanticError> {
782                 let created_at = std::time::SystemTime::now()
783                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
784                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
785
786                 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
787         }
788
789         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
790         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
791         /// the same [`ExpandedKey`] as the one used to create the offer.
792         ///
793         /// See [`InvoiceRequest::respond_with_no_std`] for further details.
794         ///
795         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
796         ///
797         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
798         pub fn respond_using_derived_keys_no_std(
799                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
800                 created_at: core::time::Duration
801         ) -> Result<$builder, Bolt12SemanticError> {
802                 if $self.inner.invoice_request_features().requires_unknown_bits() {
803                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
804                 }
805
806                 let keys = match $self.keys {
807                         None => return Err(Bolt12SemanticError::InvalidMetadata),
808                         Some(keys) => keys,
809                 };
810
811                 <$builder>::for_offer_using_keys(
812                         &$self.inner, payment_paths, created_at, payment_hash, keys
813                 )
814         }
815 } }
816
817 impl VerifiedInvoiceRequest {
818         offer_accessors!(self, self.inner.contents.inner.offer);
819         invoice_request_accessors!(self, self.inner.contents);
820         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
821         invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
822 }
823
824 impl InvoiceRequestContents {
825         pub(super) fn metadata(&self) -> &[u8] {
826                 self.inner.metadata()
827         }
828
829         pub(super) fn derives_keys(&self) -> bool {
830                 self.inner.payer.0.derives_payer_keys()
831         }
832
833         pub(super) fn chain(&self) -> ChainHash {
834                 self.inner.chain()
835         }
836
837         pub(super) fn amount_msats(&self) -> Option<u64> {
838                 self.inner.amount_msats
839         }
840
841         pub(super) fn features(&self) -> &InvoiceRequestFeatures {
842                 &self.inner.features
843         }
844
845         pub(super) fn quantity(&self) -> Option<u64> {
846                 self.inner.quantity
847         }
848
849         pub(super) fn payer_id(&self) -> PublicKey {
850                 self.payer_id
851         }
852
853         pub(super) fn payer_note(&self) -> Option<PrintableString> {
854                 self.inner.payer_note.as_ref()
855                         .map(|payer_note| PrintableString(payer_note.as_str()))
856         }
857
858         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
859                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
860                 invoice_request.payer_id = Some(&self.payer_id);
861                 (payer, offer, invoice_request)
862         }
863 }
864
865 impl InvoiceRequestContentsWithoutPayerId {
866         pub(super) fn metadata(&self) -> &[u8] {
867                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
868         }
869
870         pub(super) fn chain(&self) -> ChainHash {
871                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
872         }
873
874         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
875                 let payer = PayerTlvStreamRef {
876                         metadata: self.payer.0.as_bytes(),
877                 };
878
879                 let offer = self.offer.as_tlv_stream();
880
881                 let features = {
882                         if self.features == InvoiceRequestFeatures::empty() { None }
883                         else { Some(&self.features) }
884                 };
885
886                 let invoice_request = InvoiceRequestTlvStreamRef {
887                         chain: self.chain.as_ref(),
888                         amount: self.amount_msats,
889                         features,
890                         quantity: self.quantity,
891                         payer_id: None,
892                         payer_note: self.payer_note.as_ref(),
893                 };
894
895                 (payer, offer, invoice_request)
896         }
897 }
898
899 impl Writeable for UnsignedInvoiceRequest {
900         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
901                 WithoutLength(&self.bytes).write(writer)
902         }
903 }
904
905 impl Writeable for InvoiceRequest {
906         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
907                 WithoutLength(&self.bytes).write(writer)
908         }
909 }
910
911 impl Writeable for InvoiceRequestContents {
912         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
913                 self.as_tlv_stream().write(writer)
914         }
915 }
916
917 /// Valid type range for invoice_request TLV records.
918 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
919
920 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
921 ///
922 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
923 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
924
925 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
926         (80, chain: ChainHash),
927         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
928         (84, features: (InvoiceRequestFeatures, WithoutLength)),
929         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
930         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
931         (89, payer_note: (String, WithoutLength)),
932 });
933
934 type FullInvoiceRequestTlvStream =
935         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
936
937 type FullInvoiceRequestTlvStreamRef<'a> = (
938         PayerTlvStreamRef<'a>,
939         OfferTlvStreamRef<'a>,
940         InvoiceRequestTlvStreamRef<'a>,
941         SignatureTlvStreamRef<'a>,
942 );
943
944 impl SeekReadable for FullInvoiceRequestTlvStream {
945         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
946                 let payer = SeekReadable::read(r)?;
947                 let offer = SeekReadable::read(r)?;
948                 let invoice_request = SeekReadable::read(r)?;
949                 let signature = SeekReadable::read(r)?;
950
951                 Ok((payer, offer, invoice_request, signature))
952         }
953 }
954
955 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
956
957 type PartialInvoiceRequestTlvStreamRef<'a> = (
958         PayerTlvStreamRef<'a>,
959         OfferTlvStreamRef<'a>,
960         InvoiceRequestTlvStreamRef<'a>,
961 );
962
963 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
964         type Error = Bolt12ParseError;
965
966         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
967                 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
968                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
969                 let (
970                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
971                 ) = tlv_stream;
972                 let contents = InvoiceRequestContents::try_from(
973                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
974                 )?;
975
976                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
977
978                 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
979         }
980 }
981
982 impl TryFrom<Vec<u8>> for InvoiceRequest {
983         type Error = Bolt12ParseError;
984
985         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
986                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
987                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
988                 let (
989                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
990                         SignatureTlvStream { signature },
991                 ) = tlv_stream;
992                 let contents = InvoiceRequestContents::try_from(
993                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
994                 )?;
995
996                 let signature = match signature {
997                         None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
998                         Some(signature) => signature,
999                 };
1000                 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
1001                 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1002
1003                 Ok(InvoiceRequest { bytes, contents, signature })
1004         }
1005 }
1006
1007 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1008         type Error = Bolt12SemanticError;
1009
1010         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1011                 let (
1012                         PayerTlvStream { metadata },
1013                         offer_tlv_stream,
1014                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1015                 ) = tlv_stream;
1016
1017                 let payer = match metadata {
1018                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1019                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1020                 };
1021                 let offer = OfferContents::try_from(offer_tlv_stream)?;
1022
1023                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1024                         return Err(Bolt12SemanticError::UnsupportedChain);
1025                 }
1026
1027                 if offer.amount().is_none() && amount.is_none() {
1028                         return Err(Bolt12SemanticError::MissingAmount);
1029                 }
1030
1031                 offer.check_quantity(quantity)?;
1032                 offer.check_amount_msats_for_quantity(amount, quantity)?;
1033
1034                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1035
1036                 let payer_id = match payer_id {
1037                         None => return Err(Bolt12SemanticError::MissingPayerId),
1038                         Some(payer_id) => payer_id,
1039                 };
1040
1041                 Ok(InvoiceRequestContents {
1042                         inner: InvoiceRequestContentsWithoutPayerId {
1043                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1044                         },
1045                         payer_id,
1046                 })
1047         }
1048 }
1049
1050 #[cfg(test)]
1051 mod tests {
1052         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1053
1054         use bitcoin::blockdata::constants::ChainHash;
1055         use bitcoin::network::constants::Network;
1056         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1057         use core::convert::{Infallible, TryFrom};
1058         use core::num::NonZeroU64;
1059         #[cfg(feature = "std")]
1060         use core::time::Duration;
1061         use crate::sign::KeyMaterial;
1062         use crate::ln::channelmanager::PaymentId;
1063         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1064         use crate::ln::inbound_payment::ExpandedKey;
1065         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1066         use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1067         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1068         use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1069         #[cfg(not(c_bindings))]
1070         use {
1071                 crate::offers::offer::OfferBuilder,
1072         };
1073         #[cfg(c_bindings)]
1074         use {
1075                 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1076         };
1077         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1078         use crate::offers::payer::PayerTlvStreamRef;
1079         use crate::offers::test_utils::*;
1080         use crate::util::ser::{BigSize, Writeable};
1081         use crate::util::string::PrintableString;
1082
1083         #[test]
1084         fn builds_invoice_request_with_defaults() {
1085                 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1086                         .amount_msats(1000)
1087                         .build().unwrap()
1088                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1089                         .build().unwrap();
1090                 #[cfg(c_bindings)]
1091                 let mut unsigned_invoice_request = unsigned_invoice_request;
1092
1093                 let mut buffer = Vec::new();
1094                 unsigned_invoice_request.write(&mut buffer).unwrap();
1095
1096                 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1097                 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1098                 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1099                 assert_eq!(unsigned_invoice_request.metadata(), None);
1100                 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1101                 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1102                 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1103                 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1104                 assert_eq!(unsigned_invoice_request.paths(), &[]);
1105                 assert_eq!(unsigned_invoice_request.issuer(), None);
1106                 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1107                 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1108                 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1109                 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1110                 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1111                 assert_eq!(unsigned_invoice_request.quantity(), None);
1112                 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1113                 assert_eq!(unsigned_invoice_request.payer_note(), None);
1114
1115                 match UnsignedInvoiceRequest::try_from(buffer) {
1116                         Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1117                         Ok(parsed) => {
1118                                 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1119                                 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1120                         },
1121                 }
1122
1123                 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1124
1125                 let mut buffer = Vec::new();
1126                 invoice_request.write(&mut buffer).unwrap();
1127
1128                 assert_eq!(invoice_request.bytes, buffer.as_slice());
1129                 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1130                 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1131                 assert_eq!(invoice_request.metadata(), None);
1132                 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1133                 assert_eq!(invoice_request.description(), PrintableString("foo"));
1134                 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1135                 assert_eq!(invoice_request.absolute_expiry(), None);
1136                 assert_eq!(invoice_request.paths(), &[]);
1137                 assert_eq!(invoice_request.issuer(), None);
1138                 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1139                 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1140                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1141                 assert_eq!(invoice_request.amount_msats(), None);
1142                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1143                 assert_eq!(invoice_request.quantity(), None);
1144                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1145                 assert_eq!(invoice_request.payer_note(), None);
1146
1147                 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1148                 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1149
1150                 assert_eq!(
1151                         invoice_request.as_tlv_stream(),
1152                         (
1153                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1154                                 OfferTlvStreamRef {
1155                                         chains: None,
1156                                         metadata: None,
1157                                         currency: None,
1158                                         amount: Some(1000),
1159                                         description: Some(&String::from("foo")),
1160                                         features: None,
1161                                         absolute_expiry: None,
1162                                         paths: None,
1163                                         issuer: None,
1164                                         quantity_max: None,
1165                                         node_id: Some(&recipient_pubkey()),
1166                                 },
1167                                 InvoiceRequestTlvStreamRef {
1168                                         chain: None,
1169                                         amount: None,
1170                                         features: None,
1171                                         quantity: None,
1172                                         payer_id: Some(&payer_pubkey()),
1173                                         payer_note: None,
1174                                 },
1175                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1176                         ),
1177                 );
1178
1179                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1180                         panic!("error parsing invoice request: {:?}", e);
1181                 }
1182         }
1183
1184         #[cfg(feature = "std")]
1185         #[test]
1186         fn builds_invoice_request_from_offer_with_expiration() {
1187                 let future_expiry = Duration::from_secs(u64::max_value());
1188                 let past_expiry = Duration::from_secs(0);
1189
1190                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1191                         .amount_msats(1000)
1192                         .absolute_expiry(future_expiry)
1193                         .build().unwrap()
1194                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1195                         .build()
1196                 {
1197                         panic!("error building invoice_request: {:?}", e);
1198                 }
1199
1200                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1201                         .amount_msats(1000)
1202                         .absolute_expiry(past_expiry)
1203                         .build().unwrap()
1204                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1205                         .build()
1206                 {
1207                         Ok(_) => panic!("expected error"),
1208                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1209                 }
1210         }
1211
1212         #[test]
1213         fn builds_invoice_request_with_derived_metadata() {
1214                 let payer_id = payer_pubkey();
1215                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1216                 let entropy = FixedEntropy {};
1217                 let secp_ctx = Secp256k1::new();
1218                 let payment_id = PaymentId([1; 32]);
1219
1220                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1221                         .amount_msats(1000)
1222                         .build().unwrap();
1223                 let invoice_request = offer
1224                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1225                         .unwrap()
1226                         .build().unwrap()
1227                         .sign(payer_sign).unwrap();
1228                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1229
1230                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1231                         .unwrap()
1232                         .build().unwrap()
1233                         .sign(recipient_sign).unwrap();
1234                 match invoice.verify(&expanded_key, &secp_ctx) {
1235                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1236                         Err(()) => panic!("verification failed"),
1237                 }
1238
1239                 // Fails verification with altered fields
1240                 let (
1241                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1242                         mut invoice_tlv_stream, mut signature_tlv_stream
1243                 ) = invoice.as_tlv_stream();
1244                 invoice_request_tlv_stream.amount = Some(2000);
1245                 invoice_tlv_stream.amount = Some(2000);
1246
1247                 let tlv_stream =
1248                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1249                 let mut bytes = Vec::new();
1250                 tlv_stream.write(&mut bytes).unwrap();
1251
1252                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1253                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1254                 signature_tlv_stream.signature = Some(&signature);
1255
1256                 let mut encoded_invoice = bytes;
1257                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1258
1259                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1260                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1261
1262                 // Fails verification with altered metadata
1263                 let (
1264                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1265                         mut signature_tlv_stream
1266                 ) = invoice.as_tlv_stream();
1267                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1268                 payer_tlv_stream.metadata = Some(&metadata);
1269
1270                 let tlv_stream =
1271                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1272                 let mut bytes = Vec::new();
1273                 tlv_stream.write(&mut bytes).unwrap();
1274
1275                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1276                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1277                 signature_tlv_stream.signature = Some(&signature);
1278
1279                 let mut encoded_invoice = bytes;
1280                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1281
1282                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1283                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1284         }
1285
1286         #[test]
1287         fn builds_invoice_request_with_derived_payer_id() {
1288                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1289                 let entropy = FixedEntropy {};
1290                 let secp_ctx = Secp256k1::new();
1291                 let payment_id = PaymentId([1; 32]);
1292
1293                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1294                         .amount_msats(1000)
1295                         .build().unwrap();
1296                 let invoice_request = offer
1297                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1298                         .unwrap()
1299                         .build_and_sign()
1300                         .unwrap();
1301
1302                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1303                         .unwrap()
1304                         .build().unwrap()
1305                         .sign(recipient_sign).unwrap();
1306                 match invoice.verify(&expanded_key, &secp_ctx) {
1307                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1308                         Err(()) => panic!("verification failed"),
1309                 }
1310
1311                 // Fails verification with altered fields
1312                 let (
1313                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1314                         mut invoice_tlv_stream, mut signature_tlv_stream
1315                 ) = invoice.as_tlv_stream();
1316                 invoice_request_tlv_stream.amount = Some(2000);
1317                 invoice_tlv_stream.amount = Some(2000);
1318
1319                 let tlv_stream =
1320                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1321                 let mut bytes = Vec::new();
1322                 tlv_stream.write(&mut bytes).unwrap();
1323
1324                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1325                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1326                 signature_tlv_stream.signature = Some(&signature);
1327
1328                 let mut encoded_invoice = bytes;
1329                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1330
1331                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1332                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1333
1334                 // Fails verification with altered payer id
1335                 let (
1336                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1337                         mut signature_tlv_stream
1338                 ) = invoice.as_tlv_stream();
1339                 let payer_id = pubkey(1);
1340                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1341
1342                 let tlv_stream =
1343                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1344                 let mut bytes = Vec::new();
1345                 tlv_stream.write(&mut bytes).unwrap();
1346
1347                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1348                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1349                 signature_tlv_stream.signature = Some(&signature);
1350
1351                 let mut encoded_invoice = bytes;
1352                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1353
1354                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1355                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1356         }
1357
1358         #[test]
1359         fn builds_invoice_request_with_chain() {
1360                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1361                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1362
1363                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1364                         .amount_msats(1000)
1365                         .build().unwrap()
1366                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1367                         .chain(Network::Bitcoin).unwrap()
1368                         .build().unwrap()
1369                         .sign(payer_sign).unwrap();
1370                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1371                 assert_eq!(invoice_request.chain(), mainnet);
1372                 assert_eq!(tlv_stream.chain, None);
1373
1374                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1375                         .amount_msats(1000)
1376                         .chain(Network::Testnet)
1377                         .build().unwrap()
1378                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1379                         .chain(Network::Testnet).unwrap()
1380                         .build().unwrap()
1381                         .sign(payer_sign).unwrap();
1382                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1383                 assert_eq!(invoice_request.chain(), testnet);
1384                 assert_eq!(tlv_stream.chain, Some(&testnet));
1385
1386                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1387                         .amount_msats(1000)
1388                         .chain(Network::Bitcoin)
1389                         .chain(Network::Testnet)
1390                         .build().unwrap()
1391                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1392                         .chain(Network::Bitcoin).unwrap()
1393                         .build().unwrap()
1394                         .sign(payer_sign).unwrap();
1395                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1396                 assert_eq!(invoice_request.chain(), mainnet);
1397                 assert_eq!(tlv_stream.chain, None);
1398
1399                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1400                         .amount_msats(1000)
1401                         .chain(Network::Bitcoin)
1402                         .chain(Network::Testnet)
1403                         .build().unwrap()
1404                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405                         .chain(Network::Bitcoin).unwrap()
1406                         .chain(Network::Testnet).unwrap()
1407                         .build().unwrap()
1408                         .sign(payer_sign).unwrap();
1409                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1410                 assert_eq!(invoice_request.chain(), testnet);
1411                 assert_eq!(tlv_stream.chain, Some(&testnet));
1412
1413                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1414                         .amount_msats(1000)
1415                         .chain(Network::Testnet)
1416                         .build().unwrap()
1417                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1418                         .chain(Network::Bitcoin)
1419                 {
1420                         Ok(_) => panic!("expected error"),
1421                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1422                 }
1423
1424                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1425                         .amount_msats(1000)
1426                         .chain(Network::Testnet)
1427                         .build().unwrap()
1428                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1429                         .build()
1430                 {
1431                         Ok(_) => panic!("expected error"),
1432                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1433                 }
1434         }
1435
1436         #[test]
1437         fn builds_invoice_request_with_amount() {
1438                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1439                         .amount_msats(1000)
1440                         .build().unwrap()
1441                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442                         .amount_msats(1000).unwrap()
1443                         .build().unwrap()
1444                         .sign(payer_sign).unwrap();
1445                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1446                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1447                 assert_eq!(tlv_stream.amount, Some(1000));
1448
1449                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1450                         .amount_msats(1000)
1451                         .build().unwrap()
1452                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1453                         .amount_msats(1001).unwrap()
1454                         .amount_msats(1000).unwrap()
1455                         .build().unwrap()
1456                         .sign(payer_sign).unwrap();
1457                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1458                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1459                 assert_eq!(tlv_stream.amount, Some(1000));
1460
1461                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1462                         .amount_msats(1000)
1463                         .build().unwrap()
1464                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1465                         .amount_msats(1001).unwrap()
1466                         .build().unwrap()
1467                         .sign(payer_sign).unwrap();
1468                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1469                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1470                 assert_eq!(tlv_stream.amount, Some(1001));
1471
1472                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1473                         .amount_msats(1000)
1474                         .build().unwrap()
1475                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1476                         .amount_msats(999)
1477                 {
1478                         Ok(_) => panic!("expected error"),
1479                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1480                 }
1481
1482                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1483                         .amount_msats(1000)
1484                         .supported_quantity(Quantity::Unbounded)
1485                         .build().unwrap()
1486                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1487                         .quantity(2).unwrap()
1488                         .amount_msats(1000)
1489                 {
1490                         Ok(_) => panic!("expected error"),
1491                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1492                 }
1493
1494                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1495                         .amount_msats(1000)
1496                         .build().unwrap()
1497                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1498                         .amount_msats(MAX_VALUE_MSAT + 1)
1499                 {
1500                         Ok(_) => panic!("expected error"),
1501                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1502                 }
1503
1504                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1505                         .amount_msats(1000)
1506                         .supported_quantity(Quantity::Unbounded)
1507                         .build().unwrap()
1508                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1509                         .amount_msats(1000).unwrap()
1510                         .quantity(2).unwrap()
1511                         .build()
1512                 {
1513                         Ok(_) => panic!("expected error"),
1514                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1515                 }
1516
1517                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1518                         .build().unwrap()
1519                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1520                         .build()
1521                 {
1522                         Ok(_) => panic!("expected error"),
1523                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1524                 }
1525
1526                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1527                         .amount_msats(1000)
1528                         .supported_quantity(Quantity::Unbounded)
1529                         .build().unwrap()
1530                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531                         .quantity(u64::max_value()).unwrap()
1532                         .build()
1533                 {
1534                         Ok(_) => panic!("expected error"),
1535                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1536                 }
1537         }
1538
1539         #[test]
1540         fn builds_invoice_request_with_features() {
1541                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1542                         .amount_msats(1000)
1543                         .build().unwrap()
1544                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1545                         .features_unchecked(InvoiceRequestFeatures::unknown())
1546                         .build().unwrap()
1547                         .sign(payer_sign).unwrap();
1548                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1549                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1550                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1551
1552                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1553                         .amount_msats(1000)
1554                         .build().unwrap()
1555                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1556                         .features_unchecked(InvoiceRequestFeatures::unknown())
1557                         .features_unchecked(InvoiceRequestFeatures::empty())
1558                         .build().unwrap()
1559                         .sign(payer_sign).unwrap();
1560                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1561                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1562                 assert_eq!(tlv_stream.features, None);
1563         }
1564
1565         #[test]
1566         fn builds_invoice_request_with_quantity() {
1567                 let one = NonZeroU64::new(1).unwrap();
1568                 let ten = NonZeroU64::new(10).unwrap();
1569
1570                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1571                         .amount_msats(1000)
1572                         .supported_quantity(Quantity::One)
1573                         .build().unwrap()
1574                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1575                         .build().unwrap()
1576                         .sign(payer_sign).unwrap();
1577                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1578                 assert_eq!(invoice_request.quantity(), None);
1579                 assert_eq!(tlv_stream.quantity, None);
1580
1581                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1582                         .amount_msats(1000)
1583                         .supported_quantity(Quantity::One)
1584                         .build().unwrap()
1585                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1586                         .amount_msats(2_000).unwrap()
1587                         .quantity(2)
1588                 {
1589                         Ok(_) => panic!("expected error"),
1590                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1591                 }
1592
1593                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1594                         .amount_msats(1000)
1595                         .supported_quantity(Quantity::Bounded(ten))
1596                         .build().unwrap()
1597                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598                         .amount_msats(10_000).unwrap()
1599                         .quantity(10).unwrap()
1600                         .build().unwrap()
1601                         .sign(payer_sign).unwrap();
1602                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1603                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1604                 assert_eq!(tlv_stream.amount, Some(10_000));
1605
1606                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1607                         .amount_msats(1000)
1608                         .supported_quantity(Quantity::Bounded(ten))
1609                         .build().unwrap()
1610                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1611                         .amount_msats(11_000).unwrap()
1612                         .quantity(11)
1613                 {
1614                         Ok(_) => panic!("expected error"),
1615                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1616                 }
1617
1618                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1619                         .amount_msats(1000)
1620                         .supported_quantity(Quantity::Unbounded)
1621                         .build().unwrap()
1622                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623                         .amount_msats(2_000).unwrap()
1624                         .quantity(2).unwrap()
1625                         .build().unwrap()
1626                         .sign(payer_sign).unwrap();
1627                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1628                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1629                 assert_eq!(tlv_stream.amount, Some(2_000));
1630
1631                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1632                         .amount_msats(1000)
1633                         .supported_quantity(Quantity::Unbounded)
1634                         .build().unwrap()
1635                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1636                         .build()
1637                 {
1638                         Ok(_) => panic!("expected error"),
1639                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1640                 }
1641
1642                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1643                         .amount_msats(1000)
1644                         .supported_quantity(Quantity::Bounded(one))
1645                         .build().unwrap()
1646                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1647                         .build()
1648                 {
1649                         Ok(_) => panic!("expected error"),
1650                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1651                 }
1652         }
1653
1654         #[test]
1655         fn builds_invoice_request_with_payer_note() {
1656                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1657                         .amount_msats(1000)
1658                         .build().unwrap()
1659                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1660                         .payer_note("bar".into())
1661                         .build().unwrap()
1662                         .sign(payer_sign).unwrap();
1663                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1664                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1665                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1666
1667                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1668                         .amount_msats(1000)
1669                         .build().unwrap()
1670                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1671                         .payer_note("bar".into())
1672                         .payer_note("baz".into())
1673                         .build().unwrap()
1674                         .sign(payer_sign).unwrap();
1675                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1676                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1677                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1678         }
1679
1680         #[test]
1681         fn fails_signing_invoice_request() {
1682                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1683                         .amount_msats(1000)
1684                         .build().unwrap()
1685                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1686                         .build().unwrap()
1687                         .sign(|_| Err(()))
1688                 {
1689                         Ok(_) => panic!("expected error"),
1690                         Err(e) => assert_eq!(e, SignError::Signing(())),
1691                 }
1692
1693                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1694                         .amount_msats(1000)
1695                         .build().unwrap()
1696                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1697                         .build().unwrap()
1698                         .sign(recipient_sign)
1699                 {
1700                         Ok(_) => panic!("expected error"),
1701                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1702                 }
1703         }
1704
1705         #[test]
1706         fn fails_responding_with_unknown_required_features() {
1707                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1708                         .amount_msats(1000)
1709                         .build().unwrap()
1710                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1711                         .features_unchecked(InvoiceRequestFeatures::unknown())
1712                         .build().unwrap()
1713                         .sign(payer_sign).unwrap()
1714                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1715                 {
1716                         Ok(_) => panic!("expected error"),
1717                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1718                 }
1719         }
1720
1721         #[test]
1722         fn parses_invoice_request_with_metadata() {
1723                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1724                         .amount_msats(1000)
1725                         .build().unwrap()
1726                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1727                         .build().unwrap()
1728                         .sign(payer_sign).unwrap();
1729
1730                 let mut buffer = Vec::new();
1731                 invoice_request.write(&mut buffer).unwrap();
1732
1733                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1734                         panic!("error parsing invoice_request: {:?}", e);
1735                 }
1736         }
1737
1738         #[test]
1739         fn parses_invoice_request_with_chain() {
1740                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1741                         .amount_msats(1000)
1742                         .build().unwrap()
1743                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1744                         .chain(Network::Bitcoin).unwrap()
1745                         .build().unwrap()
1746                         .sign(payer_sign).unwrap();
1747
1748                 let mut buffer = Vec::new();
1749                 invoice_request.write(&mut buffer).unwrap();
1750
1751                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1752                         panic!("error parsing invoice_request: {:?}", e);
1753                 }
1754
1755                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1756                         .amount_msats(1000)
1757                         .build().unwrap()
1758                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1759                         .chain_unchecked(Network::Testnet)
1760                         .build_unchecked()
1761                         .sign(payer_sign).unwrap();
1762
1763                 let mut buffer = Vec::new();
1764                 invoice_request.write(&mut buffer).unwrap();
1765
1766                 match InvoiceRequest::try_from(buffer) {
1767                         Ok(_) => panic!("expected error"),
1768                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1769                 }
1770         }
1771
1772         #[test]
1773         fn parses_invoice_request_with_amount() {
1774                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1775                         .amount_msats(1000)
1776                         .build().unwrap()
1777                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1778                         .build().unwrap()
1779                         .sign(payer_sign).unwrap();
1780
1781                 let mut buffer = Vec::new();
1782                 invoice_request.write(&mut buffer).unwrap();
1783
1784                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1785                         panic!("error parsing invoice_request: {:?}", e);
1786                 }
1787
1788                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1789                         .build().unwrap()
1790                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1791                         .amount_msats(1000).unwrap()
1792                         .build().unwrap()
1793                         .sign(payer_sign).unwrap();
1794
1795                 let mut buffer = Vec::new();
1796                 invoice_request.write(&mut buffer).unwrap();
1797
1798                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1799                         panic!("error parsing invoice_request: {:?}", e);
1800                 }
1801
1802                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1803                         .build().unwrap()
1804                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1805                         .build_unchecked()
1806                         .sign(payer_sign).unwrap();
1807
1808                 let mut buffer = Vec::new();
1809                 invoice_request.write(&mut buffer).unwrap();
1810
1811                 match InvoiceRequest::try_from(buffer) {
1812                         Ok(_) => panic!("expected error"),
1813                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1814                 }
1815
1816                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1817                         .amount_msats(1000)
1818                         .build().unwrap()
1819                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1820                         .amount_msats_unchecked(999)
1821                         .build_unchecked()
1822                         .sign(payer_sign).unwrap();
1823
1824                 let mut buffer = Vec::new();
1825                 invoice_request.write(&mut buffer).unwrap();
1826
1827                 match InvoiceRequest::try_from(buffer) {
1828                         Ok(_) => panic!("expected error"),
1829                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1830                 }
1831
1832                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1833                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1834                         .build_unchecked()
1835                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1836                         .build_unchecked()
1837                         .sign(payer_sign).unwrap();
1838
1839                 let mut buffer = Vec::new();
1840                 invoice_request.write(&mut buffer).unwrap();
1841
1842                 match InvoiceRequest::try_from(buffer) {
1843                         Ok(_) => panic!("expected error"),
1844                         Err(e) => {
1845                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1846                         },
1847                 }
1848
1849                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1850                         .amount_msats(1000)
1851                         .supported_quantity(Quantity::Unbounded)
1852                         .build().unwrap()
1853                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1854                         .quantity(u64::max_value()).unwrap()
1855                         .build_unchecked()
1856                         .sign(payer_sign).unwrap();
1857
1858                 let mut buffer = Vec::new();
1859                 invoice_request.write(&mut buffer).unwrap();
1860
1861                 match InvoiceRequest::try_from(buffer) {
1862                         Ok(_) => panic!("expected error"),
1863                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1864                 }
1865         }
1866
1867         #[test]
1868         fn parses_invoice_request_with_quantity() {
1869                 let one = NonZeroU64::new(1).unwrap();
1870                 let ten = NonZeroU64::new(10).unwrap();
1871
1872                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1873                         .amount_msats(1000)
1874                         .supported_quantity(Quantity::One)
1875                         .build().unwrap()
1876                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1877                         .build().unwrap()
1878                         .sign(payer_sign).unwrap();
1879
1880                 let mut buffer = Vec::new();
1881                 invoice_request.write(&mut buffer).unwrap();
1882
1883                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1884                         panic!("error parsing invoice_request: {:?}", e);
1885                 }
1886
1887                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1888                         .amount_msats(1000)
1889                         .supported_quantity(Quantity::One)
1890                         .build().unwrap()
1891                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1892                         .amount_msats(2_000).unwrap()
1893                         .quantity_unchecked(2)
1894                         .build_unchecked()
1895                         .sign(payer_sign).unwrap();
1896
1897                 let mut buffer = Vec::new();
1898                 invoice_request.write(&mut buffer).unwrap();
1899
1900                 match InvoiceRequest::try_from(buffer) {
1901                         Ok(_) => panic!("expected error"),
1902                         Err(e) => {
1903                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1904                         },
1905                 }
1906
1907                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1908                         .amount_msats(1000)
1909                         .supported_quantity(Quantity::Bounded(ten))
1910                         .build().unwrap()
1911                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1912                         .amount_msats(10_000).unwrap()
1913                         .quantity(10).unwrap()
1914                         .build().unwrap()
1915                         .sign(payer_sign).unwrap();
1916
1917                 let mut buffer = Vec::new();
1918                 invoice_request.write(&mut buffer).unwrap();
1919
1920                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1921                         panic!("error parsing invoice_request: {:?}", e);
1922                 }
1923
1924                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1925                         .amount_msats(1000)
1926                         .supported_quantity(Quantity::Bounded(ten))
1927                         .build().unwrap()
1928                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1929                         .amount_msats(11_000).unwrap()
1930                         .quantity_unchecked(11)
1931                         .build_unchecked()
1932                         .sign(payer_sign).unwrap();
1933
1934                 let mut buffer = Vec::new();
1935                 invoice_request.write(&mut buffer).unwrap();
1936
1937                 match InvoiceRequest::try_from(buffer) {
1938                         Ok(_) => panic!("expected error"),
1939                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1940                 }
1941
1942                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1943                         .amount_msats(1000)
1944                         .supported_quantity(Quantity::Unbounded)
1945                         .build().unwrap()
1946                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1947                         .amount_msats(2_000).unwrap()
1948                         .quantity(2).unwrap()
1949                         .build().unwrap()
1950                         .sign(payer_sign).unwrap();
1951
1952                 let mut buffer = Vec::new();
1953                 invoice_request.write(&mut buffer).unwrap();
1954
1955                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1956                         panic!("error parsing invoice_request: {:?}", e);
1957                 }
1958
1959                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1960                         .amount_msats(1000)
1961                         .supported_quantity(Quantity::Unbounded)
1962                         .build().unwrap()
1963                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1964                         .build_unchecked()
1965                         .sign(payer_sign).unwrap();
1966
1967                 let mut buffer = Vec::new();
1968                 invoice_request.write(&mut buffer).unwrap();
1969
1970                 match InvoiceRequest::try_from(buffer) {
1971                         Ok(_) => panic!("expected error"),
1972                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1973                 }
1974
1975                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1976                         .amount_msats(1000)
1977                         .supported_quantity(Quantity::Bounded(one))
1978                         .build().unwrap()
1979                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1980                         .build_unchecked()
1981                         .sign(payer_sign).unwrap();
1982
1983                 let mut buffer = Vec::new();
1984                 invoice_request.write(&mut buffer).unwrap();
1985
1986                 match InvoiceRequest::try_from(buffer) {
1987                         Ok(_) => panic!("expected error"),
1988                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1989                 }
1990         }
1991
1992         #[test]
1993         fn fails_parsing_invoice_request_without_metadata() {
1994                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1995                         .amount_msats(1000)
1996                         .build().unwrap();
1997                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1998                         .build().unwrap();
1999                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2000                 tlv_stream.0.metadata = None;
2001
2002                 let mut buffer = Vec::new();
2003                 tlv_stream.write(&mut buffer).unwrap();
2004
2005                 match InvoiceRequest::try_from(buffer) {
2006                         Ok(_) => panic!("expected error"),
2007                         Err(e) => {
2008                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2009                         },
2010                 }
2011         }
2012
2013         #[test]
2014         fn fails_parsing_invoice_request_without_payer_id() {
2015                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2016                         .amount_msats(1000)
2017                         .build().unwrap();
2018                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2019                         .build().unwrap();
2020                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2021                 tlv_stream.2.payer_id = None;
2022
2023                 let mut buffer = Vec::new();
2024                 tlv_stream.write(&mut buffer).unwrap();
2025
2026                 match InvoiceRequest::try_from(buffer) {
2027                         Ok(_) => panic!("expected error"),
2028                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2029                 }
2030         }
2031
2032         #[test]
2033         fn fails_parsing_invoice_request_without_node_id() {
2034                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2035                         .amount_msats(1000)
2036                         .build().unwrap();
2037                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2038                         .build().unwrap();
2039                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2040                 tlv_stream.1.node_id = None;
2041
2042                 let mut buffer = Vec::new();
2043                 tlv_stream.write(&mut buffer).unwrap();
2044
2045                 match InvoiceRequest::try_from(buffer) {
2046                         Ok(_) => panic!("expected error"),
2047                         Err(e) => {
2048                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2049                         },
2050                 }
2051         }
2052
2053         #[test]
2054         fn fails_parsing_invoice_request_without_signature() {
2055                 let mut buffer = Vec::new();
2056                 OfferBuilder::new("foo".into(), recipient_pubkey())
2057                         .amount_msats(1000)
2058                         .build().unwrap()
2059                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2060                         .build().unwrap()
2061                         .contents
2062                         .write(&mut buffer).unwrap();
2063
2064                 match InvoiceRequest::try_from(buffer) {
2065                         Ok(_) => panic!("expected error"),
2066                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2067                 }
2068         }
2069
2070         #[test]
2071         fn fails_parsing_invoice_request_with_invalid_signature() {
2072                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2073                         .amount_msats(1000)
2074                         .build().unwrap()
2075                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2076                         .build().unwrap()
2077                         .sign(payer_sign).unwrap();
2078                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2079                 *last_signature_byte = last_signature_byte.wrapping_add(1);
2080
2081                 let mut buffer = Vec::new();
2082                 invoice_request.write(&mut buffer).unwrap();
2083
2084                 match InvoiceRequest::try_from(buffer) {
2085                         Ok(_) => panic!("expected error"),
2086                         Err(e) => {
2087                                 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2088                         },
2089                 }
2090         }
2091
2092         #[test]
2093         fn fails_parsing_invoice_request_with_extra_tlv_records() {
2094                 let secp_ctx = Secp256k1::new();
2095                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2096                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2097                         .amount_msats(1000)
2098                         .build().unwrap()
2099                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2100                         .build().unwrap()
2101                         .sign::<_, Infallible>(
2102                                 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2103                         )
2104                         .unwrap();
2105
2106                 let mut encoded_invoice_request = Vec::new();
2107                 invoice_request.write(&mut encoded_invoice_request).unwrap();
2108                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2109                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2110                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2111
2112                 match InvoiceRequest::try_from(encoded_invoice_request) {
2113                         Ok(_) => panic!("expected error"),
2114                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2115                 }
2116         }
2117 }