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