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