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