Include InvoiceRequest fields in PaymentContext
[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                         amount_msats: *amount_msats,
887                         features: features.clone(),
888                         quantity: *quantity,
889                         payer_note_truncated: payer_note.clone()
890                                 .map(|mut s| { s.truncate(PAYER_NOTE_LIMIT); UntrustedString(s) }),
891                 }
892         }
893 }
894
895 impl InvoiceRequestContents {
896         pub(super) fn metadata(&self) -> &[u8] {
897                 self.inner.metadata()
898         }
899
900         pub(super) fn derives_keys(&self) -> bool {
901                 self.inner.payer.0.derives_payer_keys()
902         }
903
904         pub(super) fn chain(&self) -> ChainHash {
905                 self.inner.chain()
906         }
907
908         pub(super) fn amount_msats(&self) -> Option<u64> {
909                 self.inner.amount_msats
910         }
911
912         pub(super) fn features(&self) -> &InvoiceRequestFeatures {
913                 &self.inner.features
914         }
915
916         pub(super) fn quantity(&self) -> Option<u64> {
917                 self.inner.quantity
918         }
919
920         pub(super) fn payer_id(&self) -> PublicKey {
921                 self.payer_id
922         }
923
924         pub(super) fn payer_note(&self) -> Option<PrintableString> {
925                 self.inner.payer_note.as_ref()
926                         .map(|payer_note| PrintableString(payer_note.as_str()))
927         }
928
929         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
930                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
931                 invoice_request.payer_id = Some(&self.payer_id);
932                 (payer, offer, invoice_request)
933         }
934 }
935
936 impl InvoiceRequestContentsWithoutPayerId {
937         pub(super) fn metadata(&self) -> &[u8] {
938                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
939         }
940
941         pub(super) fn chain(&self) -> ChainHash {
942                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
943         }
944
945         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
946                 let payer = PayerTlvStreamRef {
947                         metadata: self.payer.0.as_bytes(),
948                 };
949
950                 let offer = self.offer.as_tlv_stream();
951
952                 let features = {
953                         if self.features == InvoiceRequestFeatures::empty() { None }
954                         else { Some(&self.features) }
955                 };
956
957                 let invoice_request = InvoiceRequestTlvStreamRef {
958                         chain: self.chain.as_ref(),
959                         amount: self.amount_msats,
960                         features,
961                         quantity: self.quantity,
962                         payer_id: None,
963                         payer_note: self.payer_note.as_ref(),
964                 };
965
966                 (payer, offer, invoice_request)
967         }
968 }
969
970 impl Writeable for UnsignedInvoiceRequest {
971         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
972                 WithoutLength(&self.bytes).write(writer)
973         }
974 }
975
976 impl Writeable for InvoiceRequest {
977         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
978                 WithoutLength(&self.bytes).write(writer)
979         }
980 }
981
982 impl Writeable for InvoiceRequestContents {
983         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
984                 self.as_tlv_stream().write(writer)
985         }
986 }
987
988 /// Valid type range for invoice_request TLV records.
989 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
990
991 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
992 ///
993 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
994 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
995
996 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
997         (80, chain: ChainHash),
998         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
999         (84, features: (InvoiceRequestFeatures, WithoutLength)),
1000         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
1001         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
1002         (89, payer_note: (String, WithoutLength)),
1003 });
1004
1005 type FullInvoiceRequestTlvStream =
1006         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
1007
1008 type FullInvoiceRequestTlvStreamRef<'a> = (
1009         PayerTlvStreamRef<'a>,
1010         OfferTlvStreamRef<'a>,
1011         InvoiceRequestTlvStreamRef<'a>,
1012         SignatureTlvStreamRef<'a>,
1013 );
1014
1015 impl SeekReadable for FullInvoiceRequestTlvStream {
1016         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1017                 let payer = SeekReadable::read(r)?;
1018                 let offer = SeekReadable::read(r)?;
1019                 let invoice_request = SeekReadable::read(r)?;
1020                 let signature = SeekReadable::read(r)?;
1021
1022                 Ok((payer, offer, invoice_request, signature))
1023         }
1024 }
1025
1026 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1027
1028 type PartialInvoiceRequestTlvStreamRef<'a> = (
1029         PayerTlvStreamRef<'a>,
1030         OfferTlvStreamRef<'a>,
1031         InvoiceRequestTlvStreamRef<'a>,
1032 );
1033
1034 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1035         type Error = Bolt12ParseError;
1036
1037         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1038                 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1039                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1040                 let (
1041                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1042                 ) = tlv_stream;
1043                 let contents = InvoiceRequestContents::try_from(
1044                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1045                 )?;
1046
1047                 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1048
1049                 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1050         }
1051 }
1052
1053 impl TryFrom<Vec<u8>> for InvoiceRequest {
1054         type Error = Bolt12ParseError;
1055
1056         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1057                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1058                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1059                 let (
1060                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1061                         SignatureTlvStream { signature },
1062                 ) = tlv_stream;
1063                 let contents = InvoiceRequestContents::try_from(
1064                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1065                 )?;
1066
1067                 let signature = match signature {
1068                         None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1069                         Some(signature) => signature,
1070                 };
1071                 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1072                 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1073
1074                 Ok(InvoiceRequest { bytes, contents, signature })
1075         }
1076 }
1077
1078 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1079         type Error = Bolt12SemanticError;
1080
1081         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1082                 let (
1083                         PayerTlvStream { metadata },
1084                         offer_tlv_stream,
1085                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1086                 ) = tlv_stream;
1087
1088                 let payer = match metadata {
1089                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1090                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1091                 };
1092                 let offer = OfferContents::try_from(offer_tlv_stream)?;
1093
1094                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1095                         return Err(Bolt12SemanticError::UnsupportedChain);
1096                 }
1097
1098                 if offer.amount().is_none() && amount.is_none() {
1099                         return Err(Bolt12SemanticError::MissingAmount);
1100                 }
1101
1102                 offer.check_quantity(quantity)?;
1103                 offer.check_amount_msats_for_quantity(amount, quantity)?;
1104
1105                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1106
1107                 let payer_id = match payer_id {
1108                         None => return Err(Bolt12SemanticError::MissingPayerId),
1109                         Some(payer_id) => payer_id,
1110                 };
1111
1112                 Ok(InvoiceRequestContents {
1113                         inner: InvoiceRequestContentsWithoutPayerId {
1114                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1115                         },
1116                         payer_id,
1117                 })
1118         }
1119 }
1120
1121 /// Fields sent in an [`InvoiceRequest`] message to include in [`PaymentContext::Bolt12Offer`].
1122 ///
1123 /// [`PaymentContext::Bolt12Offer`]: crate::blinded_path::payment::PaymentContext::Bolt12Offer
1124 #[derive(Clone, Debug, Eq, PartialEq)]
1125 pub struct InvoiceRequestFields {
1126         /// A possibly transient pubkey used to sign the invoice request.
1127         pub payer_id: PublicKey,
1128
1129         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
1130         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
1131         ///
1132         /// [`chain`]: InvoiceRequest::chain
1133         pub amount_msats: Option<u64>,
1134
1135         /// Features pertaining to requesting an invoice.
1136         pub features: InvoiceRequestFeatures,
1137
1138         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
1139         pub quantity: Option<u64>,
1140
1141         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
1142         /// response. Truncated to [`PAYER_NOTE_LIMIT`] characters.
1143         pub payer_note_truncated: Option<UntrustedString>,
1144 }
1145
1146 /// The maximum number of characters included in [`InvoiceRequestFields::payer_note_truncated`].
1147 pub const PAYER_NOTE_LIMIT: usize = 512;
1148
1149 impl Writeable for InvoiceRequestFields {
1150         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1151                 write_tlv_fields!(writer, {
1152                         (0, self.payer_id, required),
1153                         (2, self.amount_msats.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1154                         (4, WithoutLength(&self.features), required),
1155                         (6, self.quantity.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1156                         (8, self.payer_note_truncated.as_ref().map(|s| WithoutLength(&s.0)), option),
1157                 });
1158                 Ok(())
1159         }
1160 }
1161
1162 impl Readable for InvoiceRequestFields {
1163         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1164                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1165                         (0, payer_id, required),
1166                         (2, amount_msats, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1167                         (4, features, (option, encoding: (InvoiceRequestFeatures, WithoutLength))),
1168                         (6, quantity, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1169                         (8, payer_note_truncated, (option, encoding: (String, WithoutLength))),
1170                 });
1171                 let features = features.unwrap_or(InvoiceRequestFeatures::empty());
1172
1173                 Ok(InvoiceRequestFields {
1174                         payer_id: payer_id.0.unwrap(), amount_msats, features, quantity,
1175                         payer_note_truncated: payer_note_truncated.map(|s| UntrustedString(s)),
1176                 })
1177         }
1178 }
1179
1180 #[cfg(test)]
1181 mod tests {
1182         use super::{InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest};
1183
1184         use bitcoin::blockdata::constants::ChainHash;
1185         use bitcoin::network::constants::Network;
1186         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1187         use core::num::NonZeroU64;
1188         #[cfg(feature = "std")]
1189         use core::time::Duration;
1190         use crate::sign::KeyMaterial;
1191         use crate::ln::channelmanager::PaymentId;
1192         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1193         use crate::ln::inbound_payment::ExpandedKey;
1194         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1195         use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1196         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1197         use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1198         #[cfg(not(c_bindings))]
1199         use {
1200                 crate::offers::offer::OfferBuilder,
1201         };
1202         #[cfg(c_bindings)]
1203         use {
1204                 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1205         };
1206         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1207         use crate::offers::payer::PayerTlvStreamRef;
1208         use crate::offers::test_utils::*;
1209         use crate::util::ser::{BigSize, Readable, Writeable};
1210         use crate::util::string::{PrintableString, UntrustedString};
1211
1212         #[test]
1213         fn builds_invoice_request_with_defaults() {
1214                 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1215                         .amount_msats(1000)
1216                         .build().unwrap()
1217                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1218                         .build().unwrap();
1219                 #[cfg(c_bindings)]
1220                 let mut unsigned_invoice_request = unsigned_invoice_request;
1221
1222                 let mut buffer = Vec::new();
1223                 unsigned_invoice_request.write(&mut buffer).unwrap();
1224
1225                 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1226                 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1227                 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1228                 assert_eq!(unsigned_invoice_request.metadata(), None);
1229                 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1230                 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1231                 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1232                 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1233                 assert_eq!(unsigned_invoice_request.paths(), &[]);
1234                 assert_eq!(unsigned_invoice_request.issuer(), None);
1235                 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1236                 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1237                 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1238                 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1239                 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1240                 assert_eq!(unsigned_invoice_request.quantity(), None);
1241                 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1242                 assert_eq!(unsigned_invoice_request.payer_note(), None);
1243
1244                 match UnsignedInvoiceRequest::try_from(buffer) {
1245                         Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1246                         Ok(parsed) => {
1247                                 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1248                                 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1249                         },
1250                 }
1251
1252                 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1253
1254                 let mut buffer = Vec::new();
1255                 invoice_request.write(&mut buffer).unwrap();
1256
1257                 assert_eq!(invoice_request.bytes, buffer.as_slice());
1258                 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1259                 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1260                 assert_eq!(invoice_request.metadata(), None);
1261                 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1262                 assert_eq!(invoice_request.description(), PrintableString("foo"));
1263                 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1264                 assert_eq!(invoice_request.absolute_expiry(), None);
1265                 assert_eq!(invoice_request.paths(), &[]);
1266                 assert_eq!(invoice_request.issuer(), None);
1267                 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1268                 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1269                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1270                 assert_eq!(invoice_request.amount_msats(), None);
1271                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1272                 assert_eq!(invoice_request.quantity(), None);
1273                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1274                 assert_eq!(invoice_request.payer_note(), None);
1275
1276                 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1277                 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1278
1279                 assert_eq!(
1280                         invoice_request.as_tlv_stream(),
1281                         (
1282                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1283                                 OfferTlvStreamRef {
1284                                         chains: None,
1285                                         metadata: None,
1286                                         currency: None,
1287                                         amount: Some(1000),
1288                                         description: Some(&String::from("foo")),
1289                                         features: None,
1290                                         absolute_expiry: None,
1291                                         paths: None,
1292                                         issuer: None,
1293                                         quantity_max: None,
1294                                         node_id: Some(&recipient_pubkey()),
1295                                 },
1296                                 InvoiceRequestTlvStreamRef {
1297                                         chain: None,
1298                                         amount: None,
1299                                         features: None,
1300                                         quantity: None,
1301                                         payer_id: Some(&payer_pubkey()),
1302                                         payer_note: None,
1303                                 },
1304                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1305                         ),
1306                 );
1307
1308                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1309                         panic!("error parsing invoice request: {:?}", e);
1310                 }
1311         }
1312
1313         #[cfg(feature = "std")]
1314         #[test]
1315         fn builds_invoice_request_from_offer_with_expiration() {
1316                 let future_expiry = Duration::from_secs(u64::max_value());
1317                 let past_expiry = Duration::from_secs(0);
1318
1319                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1320                         .amount_msats(1000)
1321                         .absolute_expiry(future_expiry)
1322                         .build().unwrap()
1323                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1324                         .build()
1325                 {
1326                         panic!("error building invoice_request: {:?}", e);
1327                 }
1328
1329                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1330                         .amount_msats(1000)
1331                         .absolute_expiry(past_expiry)
1332                         .build().unwrap()
1333                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1334                         .build()
1335                 {
1336                         Ok(_) => panic!("expected error"),
1337                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1338                 }
1339         }
1340
1341         #[test]
1342         fn builds_invoice_request_with_derived_metadata() {
1343                 let payer_id = payer_pubkey();
1344                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1345                 let entropy = FixedEntropy {};
1346                 let secp_ctx = Secp256k1::new();
1347                 let payment_id = PaymentId([1; 32]);
1348
1349                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1350                         .amount_msats(1000)
1351                         .build().unwrap();
1352                 let invoice_request = offer
1353                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1354                         .unwrap()
1355                         .build().unwrap()
1356                         .sign(payer_sign).unwrap();
1357                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1358
1359                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1360                         .unwrap()
1361                         .build().unwrap()
1362                         .sign(recipient_sign).unwrap();
1363                 match invoice.verify(&expanded_key, &secp_ctx) {
1364                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1365                         Err(()) => panic!("verification failed"),
1366                 }
1367
1368                 // Fails verification with altered fields
1369                 let (
1370                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1371                         mut invoice_tlv_stream, mut signature_tlv_stream
1372                 ) = invoice.as_tlv_stream();
1373                 invoice_request_tlv_stream.amount = Some(2000);
1374                 invoice_tlv_stream.amount = Some(2000);
1375
1376                 let tlv_stream =
1377                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1378                 let mut bytes = Vec::new();
1379                 tlv_stream.write(&mut bytes).unwrap();
1380
1381                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1382                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1383                 signature_tlv_stream.signature = Some(&signature);
1384
1385                 let mut encoded_invoice = bytes;
1386                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1387
1388                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1389                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1390
1391                 // Fails verification with altered metadata
1392                 let (
1393                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1394                         mut signature_tlv_stream
1395                 ) = invoice.as_tlv_stream();
1396                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1397                 payer_tlv_stream.metadata = Some(&metadata);
1398
1399                 let tlv_stream =
1400                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1401                 let mut bytes = Vec::new();
1402                 tlv_stream.write(&mut bytes).unwrap();
1403
1404                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1405                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1406                 signature_tlv_stream.signature = Some(&signature);
1407
1408                 let mut encoded_invoice = bytes;
1409                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1410
1411                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1412                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1413         }
1414
1415         #[test]
1416         fn builds_invoice_request_with_derived_payer_id() {
1417                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1418                 let entropy = FixedEntropy {};
1419                 let secp_ctx = Secp256k1::new();
1420                 let payment_id = PaymentId([1; 32]);
1421
1422                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1423                         .amount_msats(1000)
1424                         .build().unwrap();
1425                 let invoice_request = offer
1426                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1427                         .unwrap()
1428                         .build_and_sign()
1429                         .unwrap();
1430
1431                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1432                         .unwrap()
1433                         .build().unwrap()
1434                         .sign(recipient_sign).unwrap();
1435                 match invoice.verify(&expanded_key, &secp_ctx) {
1436                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1437                         Err(()) => panic!("verification failed"),
1438                 }
1439
1440                 // Fails verification with altered fields
1441                 let (
1442                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1443                         mut invoice_tlv_stream, mut signature_tlv_stream
1444                 ) = invoice.as_tlv_stream();
1445                 invoice_request_tlv_stream.amount = Some(2000);
1446                 invoice_tlv_stream.amount = Some(2000);
1447
1448                 let tlv_stream =
1449                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1450                 let mut bytes = Vec::new();
1451                 tlv_stream.write(&mut bytes).unwrap();
1452
1453                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1454                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1455                 signature_tlv_stream.signature = Some(&signature);
1456
1457                 let mut encoded_invoice = bytes;
1458                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1459
1460                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1461                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1462
1463                 // Fails verification with altered payer id
1464                 let (
1465                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1466                         mut signature_tlv_stream
1467                 ) = invoice.as_tlv_stream();
1468                 let payer_id = pubkey(1);
1469                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1470
1471                 let tlv_stream =
1472                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1473                 let mut bytes = Vec::new();
1474                 tlv_stream.write(&mut bytes).unwrap();
1475
1476                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1477                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1478                 signature_tlv_stream.signature = Some(&signature);
1479
1480                 let mut encoded_invoice = bytes;
1481                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1482
1483                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1484                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1485         }
1486
1487         #[test]
1488         fn builds_invoice_request_with_chain() {
1489                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1490                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1491
1492                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1493                         .amount_msats(1000)
1494                         .build().unwrap()
1495                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1496                         .chain(Network::Bitcoin).unwrap()
1497                         .build().unwrap()
1498                         .sign(payer_sign).unwrap();
1499                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1500                 assert_eq!(invoice_request.chain(), mainnet);
1501                 assert_eq!(tlv_stream.chain, None);
1502
1503                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1504                         .amount_msats(1000)
1505                         .chain(Network::Testnet)
1506                         .build().unwrap()
1507                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1508                         .chain(Network::Testnet).unwrap()
1509                         .build().unwrap()
1510                         .sign(payer_sign).unwrap();
1511                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1512                 assert_eq!(invoice_request.chain(), testnet);
1513                 assert_eq!(tlv_stream.chain, Some(&testnet));
1514
1515                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1516                         .amount_msats(1000)
1517                         .chain(Network::Bitcoin)
1518                         .chain(Network::Testnet)
1519                         .build().unwrap()
1520                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1521                         .chain(Network::Bitcoin).unwrap()
1522                         .build().unwrap()
1523                         .sign(payer_sign).unwrap();
1524                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1525                 assert_eq!(invoice_request.chain(), mainnet);
1526                 assert_eq!(tlv_stream.chain, None);
1527
1528                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1529                         .amount_msats(1000)
1530                         .chain(Network::Bitcoin)
1531                         .chain(Network::Testnet)
1532                         .build().unwrap()
1533                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534                         .chain(Network::Bitcoin).unwrap()
1535                         .chain(Network::Testnet).unwrap()
1536                         .build().unwrap()
1537                         .sign(payer_sign).unwrap();
1538                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1539                 assert_eq!(invoice_request.chain(), testnet);
1540                 assert_eq!(tlv_stream.chain, Some(&testnet));
1541
1542                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1543                         .amount_msats(1000)
1544                         .chain(Network::Testnet)
1545                         .build().unwrap()
1546                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1547                         .chain(Network::Bitcoin)
1548                 {
1549                         Ok(_) => panic!("expected error"),
1550                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1551                 }
1552
1553                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1554                         .amount_msats(1000)
1555                         .chain(Network::Testnet)
1556                         .build().unwrap()
1557                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1558                         .build()
1559                 {
1560                         Ok(_) => panic!("expected error"),
1561                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1562                 }
1563         }
1564
1565         #[test]
1566         fn builds_invoice_request_with_amount() {
1567                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1568                         .amount_msats(1000)
1569                         .build().unwrap()
1570                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1571                         .amount_msats(1000).unwrap()
1572                         .build().unwrap()
1573                         .sign(payer_sign).unwrap();
1574                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1575                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1576                 assert_eq!(tlv_stream.amount, Some(1000));
1577
1578                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1579                         .amount_msats(1000)
1580                         .build().unwrap()
1581                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1582                         .amount_msats(1001).unwrap()
1583                         .amount_msats(1000).unwrap()
1584                         .build().unwrap()
1585                         .sign(payer_sign).unwrap();
1586                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1587                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1588                 assert_eq!(tlv_stream.amount, Some(1000));
1589
1590                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1591                         .amount_msats(1000)
1592                         .build().unwrap()
1593                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594                         .amount_msats(1001).unwrap()
1595                         .build().unwrap()
1596                         .sign(payer_sign).unwrap();
1597                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1598                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1599                 assert_eq!(tlv_stream.amount, Some(1001));
1600
1601                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1602                         .amount_msats(1000)
1603                         .build().unwrap()
1604                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1605                         .amount_msats(999)
1606                 {
1607                         Ok(_) => panic!("expected error"),
1608                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1609                 }
1610
1611                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1612                         .amount_msats(1000)
1613                         .supported_quantity(Quantity::Unbounded)
1614                         .build().unwrap()
1615                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1616                         .quantity(2).unwrap()
1617                         .amount_msats(1000)
1618                 {
1619                         Ok(_) => panic!("expected error"),
1620                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1621                 }
1622
1623                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1624                         .amount_msats(1000)
1625                         .build().unwrap()
1626                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1627                         .amount_msats(MAX_VALUE_MSAT + 1)
1628                 {
1629                         Ok(_) => panic!("expected error"),
1630                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1631                 }
1632
1633                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1634                         .amount_msats(1000)
1635                         .supported_quantity(Quantity::Unbounded)
1636                         .build().unwrap()
1637                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1638                         .amount_msats(1000).unwrap()
1639                         .quantity(2).unwrap()
1640                         .build()
1641                 {
1642                         Ok(_) => panic!("expected error"),
1643                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1644                 }
1645
1646                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1647                         .build().unwrap()
1648                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1649                         .build()
1650                 {
1651                         Ok(_) => panic!("expected error"),
1652                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1653                 }
1654
1655                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1656                         .amount_msats(1000)
1657                         .supported_quantity(Quantity::Unbounded)
1658                         .build().unwrap()
1659                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1660                         .quantity(u64::max_value()).unwrap()
1661                         .build()
1662                 {
1663                         Ok(_) => panic!("expected error"),
1664                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1665                 }
1666         }
1667
1668         #[test]
1669         fn builds_invoice_request_with_features() {
1670                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1671                         .amount_msats(1000)
1672                         .build().unwrap()
1673                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1674                         .features_unchecked(InvoiceRequestFeatures::unknown())
1675                         .build().unwrap()
1676                         .sign(payer_sign).unwrap();
1677                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1678                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1679                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1680
1681                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1682                         .amount_msats(1000)
1683                         .build().unwrap()
1684                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1685                         .features_unchecked(InvoiceRequestFeatures::unknown())
1686                         .features_unchecked(InvoiceRequestFeatures::empty())
1687                         .build().unwrap()
1688                         .sign(payer_sign).unwrap();
1689                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1690                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1691                 assert_eq!(tlv_stream.features, None);
1692         }
1693
1694         #[test]
1695         fn builds_invoice_request_with_quantity() {
1696                 let one = NonZeroU64::new(1).unwrap();
1697                 let ten = NonZeroU64::new(10).unwrap();
1698
1699                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1700                         .amount_msats(1000)
1701                         .supported_quantity(Quantity::One)
1702                         .build().unwrap()
1703                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1704                         .build().unwrap()
1705                         .sign(payer_sign).unwrap();
1706                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1707                 assert_eq!(invoice_request.quantity(), None);
1708                 assert_eq!(tlv_stream.quantity, None);
1709
1710                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1711                         .amount_msats(1000)
1712                         .supported_quantity(Quantity::One)
1713                         .build().unwrap()
1714                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715                         .amount_msats(2_000).unwrap()
1716                         .quantity(2)
1717                 {
1718                         Ok(_) => panic!("expected error"),
1719                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1720                 }
1721
1722                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1723                         .amount_msats(1000)
1724                         .supported_quantity(Quantity::Bounded(ten))
1725                         .build().unwrap()
1726                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1727                         .amount_msats(10_000).unwrap()
1728                         .quantity(10).unwrap()
1729                         .build().unwrap()
1730                         .sign(payer_sign).unwrap();
1731                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1732                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1733                 assert_eq!(tlv_stream.amount, Some(10_000));
1734
1735                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1736                         .amount_msats(1000)
1737                         .supported_quantity(Quantity::Bounded(ten))
1738                         .build().unwrap()
1739                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1740                         .amount_msats(11_000).unwrap()
1741                         .quantity(11)
1742                 {
1743                         Ok(_) => panic!("expected error"),
1744                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1745                 }
1746
1747                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1748                         .amount_msats(1000)
1749                         .supported_quantity(Quantity::Unbounded)
1750                         .build().unwrap()
1751                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1752                         .amount_msats(2_000).unwrap()
1753                         .quantity(2).unwrap()
1754                         .build().unwrap()
1755                         .sign(payer_sign).unwrap();
1756                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1757                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1758                 assert_eq!(tlv_stream.amount, Some(2_000));
1759
1760                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1761                         .amount_msats(1000)
1762                         .supported_quantity(Quantity::Unbounded)
1763                         .build().unwrap()
1764                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1765                         .build()
1766                 {
1767                         Ok(_) => panic!("expected error"),
1768                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1769                 }
1770
1771                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1772                         .amount_msats(1000)
1773                         .supported_quantity(Quantity::Bounded(one))
1774                         .build().unwrap()
1775                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1776                         .build()
1777                 {
1778                         Ok(_) => panic!("expected error"),
1779                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1780                 }
1781         }
1782
1783         #[test]
1784         fn builds_invoice_request_with_payer_note() {
1785                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1786                         .amount_msats(1000)
1787                         .build().unwrap()
1788                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1789                         .payer_note("bar".into())
1790                         .build().unwrap()
1791                         .sign(payer_sign).unwrap();
1792                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1793                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1794                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1795
1796                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1797                         .amount_msats(1000)
1798                         .build().unwrap()
1799                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1800                         .payer_note("bar".into())
1801                         .payer_note("baz".into())
1802                         .build().unwrap()
1803                         .sign(payer_sign).unwrap();
1804                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1805                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1806                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1807         }
1808
1809         #[test]
1810         fn fails_signing_invoice_request() {
1811                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1812                         .amount_msats(1000)
1813                         .build().unwrap()
1814                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1815                         .build().unwrap()
1816                         .sign(fail_sign)
1817                 {
1818                         Ok(_) => panic!("expected error"),
1819                         Err(e) => assert_eq!(e, SignError::Signing),
1820                 }
1821
1822                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1823                         .amount_msats(1000)
1824                         .build().unwrap()
1825                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1826                         .build().unwrap()
1827                         .sign(recipient_sign)
1828                 {
1829                         Ok(_) => panic!("expected error"),
1830                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1831                 }
1832         }
1833
1834         #[test]
1835         fn fails_responding_with_unknown_required_features() {
1836                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1837                         .amount_msats(1000)
1838                         .build().unwrap()
1839                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1840                         .features_unchecked(InvoiceRequestFeatures::unknown())
1841                         .build().unwrap()
1842                         .sign(payer_sign).unwrap()
1843                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1844                 {
1845                         Ok(_) => panic!("expected error"),
1846                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1847                 }
1848         }
1849
1850         #[test]
1851         fn parses_invoice_request_with_metadata() {
1852                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1853                         .amount_msats(1000)
1854                         .build().unwrap()
1855                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1856                         .build().unwrap()
1857                         .sign(payer_sign).unwrap();
1858
1859                 let mut buffer = Vec::new();
1860                 invoice_request.write(&mut buffer).unwrap();
1861
1862                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1863                         panic!("error parsing invoice_request: {:?}", e);
1864                 }
1865         }
1866
1867         #[test]
1868         fn parses_invoice_request_with_chain() {
1869                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1870                         .amount_msats(1000)
1871                         .build().unwrap()
1872                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1873                         .chain(Network::Bitcoin).unwrap()
1874                         .build().unwrap()
1875                         .sign(payer_sign).unwrap();
1876
1877                 let mut buffer = Vec::new();
1878                 invoice_request.write(&mut buffer).unwrap();
1879
1880                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1881                         panic!("error parsing invoice_request: {:?}", e);
1882                 }
1883
1884                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1885                         .amount_msats(1000)
1886                         .build().unwrap()
1887                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1888                         .chain_unchecked(Network::Testnet)
1889                         .build_unchecked()
1890                         .sign(payer_sign).unwrap();
1891
1892                 let mut buffer = Vec::new();
1893                 invoice_request.write(&mut buffer).unwrap();
1894
1895                 match InvoiceRequest::try_from(buffer) {
1896                         Ok(_) => panic!("expected error"),
1897                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1898                 }
1899         }
1900
1901         #[test]
1902         fn parses_invoice_request_with_amount() {
1903                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1904                         .amount_msats(1000)
1905                         .build().unwrap()
1906                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1907                         .build().unwrap()
1908                         .sign(payer_sign).unwrap();
1909
1910                 let mut buffer = Vec::new();
1911                 invoice_request.write(&mut buffer).unwrap();
1912
1913                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1914                         panic!("error parsing invoice_request: {:?}", e);
1915                 }
1916
1917                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1918                         .build().unwrap()
1919                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1920                         .amount_msats(1000).unwrap()
1921                         .build().unwrap()
1922                         .sign(payer_sign).unwrap();
1923
1924                 let mut buffer = Vec::new();
1925                 invoice_request.write(&mut buffer).unwrap();
1926
1927                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1928                         panic!("error parsing invoice_request: {:?}", e);
1929                 }
1930
1931                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1932                         .build().unwrap()
1933                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1934                         .build_unchecked()
1935                         .sign(payer_sign).unwrap();
1936
1937                 let mut buffer = Vec::new();
1938                 invoice_request.write(&mut buffer).unwrap();
1939
1940                 match InvoiceRequest::try_from(buffer) {
1941                         Ok(_) => panic!("expected error"),
1942                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1943                 }
1944
1945                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1946                         .amount_msats(1000)
1947                         .build().unwrap()
1948                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1949                         .amount_msats_unchecked(999)
1950                         .build_unchecked()
1951                         .sign(payer_sign).unwrap();
1952
1953                 let mut buffer = Vec::new();
1954                 invoice_request.write(&mut buffer).unwrap();
1955
1956                 match InvoiceRequest::try_from(buffer) {
1957                         Ok(_) => panic!("expected error"),
1958                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1959                 }
1960
1961                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1962                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1963                         .build_unchecked()
1964                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1965                         .build_unchecked()
1966                         .sign(payer_sign).unwrap();
1967
1968                 let mut buffer = Vec::new();
1969                 invoice_request.write(&mut buffer).unwrap();
1970
1971                 match InvoiceRequest::try_from(buffer) {
1972                         Ok(_) => panic!("expected error"),
1973                         Err(e) => {
1974                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1975                         },
1976                 }
1977
1978                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1979                         .amount_msats(1000)
1980                         .supported_quantity(Quantity::Unbounded)
1981                         .build().unwrap()
1982                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1983                         .quantity(u64::max_value()).unwrap()
1984                         .build_unchecked()
1985                         .sign(payer_sign).unwrap();
1986
1987                 let mut buffer = Vec::new();
1988                 invoice_request.write(&mut buffer).unwrap();
1989
1990                 match InvoiceRequest::try_from(buffer) {
1991                         Ok(_) => panic!("expected error"),
1992                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1993                 }
1994         }
1995
1996         #[test]
1997         fn parses_invoice_request_with_quantity() {
1998                 let one = NonZeroU64::new(1).unwrap();
1999                 let ten = NonZeroU64::new(10).unwrap();
2000
2001                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2002                         .amount_msats(1000)
2003                         .supported_quantity(Quantity::One)
2004                         .build().unwrap()
2005                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2006                         .build().unwrap()
2007                         .sign(payer_sign).unwrap();
2008
2009                 let mut buffer = Vec::new();
2010                 invoice_request.write(&mut buffer).unwrap();
2011
2012                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2013                         panic!("error parsing invoice_request: {:?}", e);
2014                 }
2015
2016                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2017                         .amount_msats(1000)
2018                         .supported_quantity(Quantity::One)
2019                         .build().unwrap()
2020                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2021                         .amount_msats(2_000).unwrap()
2022                         .quantity_unchecked(2)
2023                         .build_unchecked()
2024                         .sign(payer_sign).unwrap();
2025
2026                 let mut buffer = Vec::new();
2027                 invoice_request.write(&mut buffer).unwrap();
2028
2029                 match InvoiceRequest::try_from(buffer) {
2030                         Ok(_) => panic!("expected error"),
2031                         Err(e) => {
2032                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
2033                         },
2034                 }
2035
2036                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2037                         .amount_msats(1000)
2038                         .supported_quantity(Quantity::Bounded(ten))
2039                         .build().unwrap()
2040                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2041                         .amount_msats(10_000).unwrap()
2042                         .quantity(10).unwrap()
2043                         .build().unwrap()
2044                         .sign(payer_sign).unwrap();
2045
2046                 let mut buffer = Vec::new();
2047                 invoice_request.write(&mut buffer).unwrap();
2048
2049                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2050                         panic!("error parsing invoice_request: {:?}", e);
2051                 }
2052
2053                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2054                         .amount_msats(1000)
2055                         .supported_quantity(Quantity::Bounded(ten))
2056                         .build().unwrap()
2057                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2058                         .amount_msats(11_000).unwrap()
2059                         .quantity_unchecked(11)
2060                         .build_unchecked()
2061                         .sign(payer_sign).unwrap();
2062
2063                 let mut buffer = Vec::new();
2064                 invoice_request.write(&mut buffer).unwrap();
2065
2066                 match InvoiceRequest::try_from(buffer) {
2067                         Ok(_) => panic!("expected error"),
2068                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
2069                 }
2070
2071                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2072                         .amount_msats(1000)
2073                         .supported_quantity(Quantity::Unbounded)
2074                         .build().unwrap()
2075                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2076                         .amount_msats(2_000).unwrap()
2077                         .quantity(2).unwrap()
2078                         .build().unwrap()
2079                         .sign(payer_sign).unwrap();
2080
2081                 let mut buffer = Vec::new();
2082                 invoice_request.write(&mut buffer).unwrap();
2083
2084                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2085                         panic!("error parsing invoice_request: {:?}", e);
2086                 }
2087
2088                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2089                         .amount_msats(1000)
2090                         .supported_quantity(Quantity::Unbounded)
2091                         .build().unwrap()
2092                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2093                         .build_unchecked()
2094                         .sign(payer_sign).unwrap();
2095
2096                 let mut buffer = Vec::new();
2097                 invoice_request.write(&mut buffer).unwrap();
2098
2099                 match InvoiceRequest::try_from(buffer) {
2100                         Ok(_) => panic!("expected error"),
2101                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2102                 }
2103
2104                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2105                         .amount_msats(1000)
2106                         .supported_quantity(Quantity::Bounded(one))
2107                         .build().unwrap()
2108                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2109                         .build_unchecked()
2110                         .sign(payer_sign).unwrap();
2111
2112                 let mut buffer = Vec::new();
2113                 invoice_request.write(&mut buffer).unwrap();
2114
2115                 match InvoiceRequest::try_from(buffer) {
2116                         Ok(_) => panic!("expected error"),
2117                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2118                 }
2119         }
2120
2121         #[test]
2122         fn fails_parsing_invoice_request_without_metadata() {
2123                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2124                         .amount_msats(1000)
2125                         .build().unwrap();
2126                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2127                         .build().unwrap();
2128                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2129                 tlv_stream.0.metadata = None;
2130
2131                 let mut buffer = Vec::new();
2132                 tlv_stream.write(&mut buffer).unwrap();
2133
2134                 match InvoiceRequest::try_from(buffer) {
2135                         Ok(_) => panic!("expected error"),
2136                         Err(e) => {
2137                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2138                         },
2139                 }
2140         }
2141
2142         #[test]
2143         fn fails_parsing_invoice_request_without_payer_id() {
2144                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2145                         .amount_msats(1000)
2146                         .build().unwrap();
2147                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2148                         .build().unwrap();
2149                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2150                 tlv_stream.2.payer_id = None;
2151
2152                 let mut buffer = Vec::new();
2153                 tlv_stream.write(&mut buffer).unwrap();
2154
2155                 match InvoiceRequest::try_from(buffer) {
2156                         Ok(_) => panic!("expected error"),
2157                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2158                 }
2159         }
2160
2161         #[test]
2162         fn fails_parsing_invoice_request_without_node_id() {
2163                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2164                         .amount_msats(1000)
2165                         .build().unwrap();
2166                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2167                         .build().unwrap();
2168                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2169                 tlv_stream.1.node_id = None;
2170
2171                 let mut buffer = Vec::new();
2172                 tlv_stream.write(&mut buffer).unwrap();
2173
2174                 match InvoiceRequest::try_from(buffer) {
2175                         Ok(_) => panic!("expected error"),
2176                         Err(e) => {
2177                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2178                         },
2179                 }
2180         }
2181
2182         #[test]
2183         fn fails_parsing_invoice_request_without_signature() {
2184                 let mut buffer = Vec::new();
2185                 OfferBuilder::new("foo".into(), recipient_pubkey())
2186                         .amount_msats(1000)
2187                         .build().unwrap()
2188                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2189                         .build().unwrap()
2190                         .contents
2191                         .write(&mut buffer).unwrap();
2192
2193                 match InvoiceRequest::try_from(buffer) {
2194                         Ok(_) => panic!("expected error"),
2195                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2196                 }
2197         }
2198
2199         #[test]
2200         fn fails_parsing_invoice_request_with_invalid_signature() {
2201                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2202                         .amount_msats(1000)
2203                         .build().unwrap()
2204                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2205                         .build().unwrap()
2206                         .sign(payer_sign).unwrap();
2207                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2208                 *last_signature_byte = last_signature_byte.wrapping_add(1);
2209
2210                 let mut buffer = Vec::new();
2211                 invoice_request.write(&mut buffer).unwrap();
2212
2213                 match InvoiceRequest::try_from(buffer) {
2214                         Ok(_) => panic!("expected error"),
2215                         Err(e) => {
2216                                 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2217                         },
2218                 }
2219         }
2220
2221         #[test]
2222         fn fails_parsing_invoice_request_with_extra_tlv_records() {
2223                 let secp_ctx = Secp256k1::new();
2224                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2225                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2226                         .amount_msats(1000)
2227                         .build().unwrap()
2228                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2229                         .build().unwrap()
2230                         .sign(|message: &UnsignedInvoiceRequest|
2231                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2232                         )
2233                         .unwrap();
2234
2235                 let mut encoded_invoice_request = Vec::new();
2236                 invoice_request.write(&mut encoded_invoice_request).unwrap();
2237                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2238                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2239                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2240
2241                 match InvoiceRequest::try_from(encoded_invoice_request) {
2242                         Ok(_) => panic!("expected error"),
2243                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2244                 }
2245         }
2246
2247         #[test]
2248         fn copies_verified_invoice_request_fields() {
2249                 let desc = "foo".to_string();
2250                 let node_id = recipient_pubkey();
2251                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
2252                 let entropy = FixedEntropy {};
2253                 let secp_ctx = Secp256k1::new();
2254
2255                 #[cfg(c_bindings)]
2256                 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
2257                 let offer = OfferBuilder
2258                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
2259                         .chain(Network::Testnet)
2260                         .amount_msats(1000)
2261                         .supported_quantity(Quantity::Unbounded)
2262                         .build().unwrap();
2263                 assert_eq!(offer.signing_pubkey(), node_id);
2264
2265                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2266                         .chain(Network::Testnet).unwrap()
2267                         .amount_msats(1001).unwrap()
2268                         .quantity(1).unwrap()
2269                         .payer_note("0".repeat(PAYER_NOTE_LIMIT * 2))
2270                         .build().unwrap()
2271                         .sign(payer_sign).unwrap();
2272                 match invoice_request.verify(&expanded_key, &secp_ctx) {
2273                         Ok(invoice_request) => {
2274                                 let fields = invoice_request.fields();
2275                                 assert_eq!(invoice_request.offer_id, offer.id());
2276                                 assert_eq!(
2277                                         fields,
2278                                         InvoiceRequestFields {
2279                                                 payer_id: payer_pubkey(),
2280                                                 amount_msats: Some(1001),
2281                                                 features: InvoiceRequestFeatures::empty(),
2282                                                 quantity: Some(1),
2283                                                 payer_note_truncated: Some(UntrustedString("0".repeat(PAYER_NOTE_LIMIT))),
2284                                         }
2285                                 );
2286
2287                                 let mut buffer = Vec::new();
2288                                 fields.write(&mut buffer).unwrap();
2289
2290                                 let deserialized_fields: InvoiceRequestFields =
2291                                         Readable::read(&mut buffer.as_slice()).unwrap();
2292                                 assert_eq!(deserialized_fields, fields);
2293                         },
2294                         Err(_) => panic!("unexpected error"),
2295                 }
2296         }
2297 }