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