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