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