f243ea693f2f019be1e0dddf214a599751213e1a
[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::types::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 #[derive(Clone)]
491 pub struct UnsignedInvoiceRequest {
492         bytes: Vec<u8>,
493         contents: InvoiceRequestContents,
494         tagged_hash: TaggedHash,
495 }
496
497 /// A function for signing an [`UnsignedInvoiceRequest`].
498 pub trait SignInvoiceRequestFn {
499         /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
500         fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()>;
501 }
502
503 impl<F> SignInvoiceRequestFn for F
504 where
505         F: Fn(&UnsignedInvoiceRequest) -> Result<Signature, ()>,
506 {
507         fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
508                 self(message)
509         }
510 }
511
512 impl<F> SignFn<UnsignedInvoiceRequest> for F
513 where
514         F: SignInvoiceRequestFn,
515 {
516         fn sign(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
517                 self.sign_invoice_request(message)
518         }
519 }
520
521 impl UnsignedInvoiceRequest {
522         fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
523                 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
524                 // unknown TLV records, which are not stored in `OfferContents`.
525                 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
526                         contents.as_tlv_stream();
527                 let offer_bytes = WithoutLength(&offer.bytes);
528                 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
529
530                 let mut bytes = Vec::new();
531                 unsigned_tlv_stream.write(&mut bytes).unwrap();
532
533                 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
534
535                 Self { bytes, contents, tagged_hash }
536         }
537
538         /// Returns the [`TaggedHash`] of the invoice to sign.
539         pub fn tagged_hash(&self) -> &TaggedHash {
540                 &self.tagged_hash
541         }
542 }
543
544 macro_rules! unsigned_invoice_request_sign_method { (
545         $self: ident, $self_type: ty $(, $self_mut: tt)?
546 ) => {
547         /// Signs the [`TaggedHash`] of the invoice request using the given function.
548         ///
549         /// Note: The hash computation may have included unknown, odd TLV records.
550         pub fn sign<F: SignInvoiceRequestFn>(
551                 $($self_mut)* $self: $self_type, sign: F
552         ) -> Result<InvoiceRequest, SignError> {
553                 let pubkey = $self.contents.payer_id;
554                 let signature = merkle::sign_message(sign, &$self, pubkey)?;
555
556                 // Append the signature TLV record to the bytes.
557                 let signature_tlv_stream = SignatureTlvStreamRef {
558                         signature: Some(&signature),
559                 };
560                 signature_tlv_stream.write(&mut $self.bytes).unwrap();
561
562                 Ok(InvoiceRequest {
563                         #[cfg(not(c_bindings))]
564                         bytes: $self.bytes,
565                         #[cfg(c_bindings)]
566                         bytes: $self.bytes.clone(),
567                         #[cfg(not(c_bindings))]
568                         contents: $self.contents,
569                         #[cfg(c_bindings)]
570                         contents: $self.contents.clone(),
571                         signature,
572                 })
573         }
574 } }
575
576 #[cfg(not(c_bindings))]
577 impl UnsignedInvoiceRequest {
578         unsigned_invoice_request_sign_method!(self, Self, mut);
579 }
580
581 #[cfg(c_bindings)]
582 impl UnsignedInvoiceRequest {
583         unsigned_invoice_request_sign_method!(self, &mut Self);
584 }
585
586 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
587         fn as_ref(&self) -> &TaggedHash {
588                 &self.tagged_hash
589         }
590 }
591
592 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
593 ///
594 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
595 /// specifies these such that its recipient can send an invoice for payment.
596 ///
597 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
598 /// [`Offer`]: crate::offers::offer::Offer
599 #[derive(Clone, Debug)]
600 #[cfg_attr(test, derive(PartialEq))]
601 pub struct InvoiceRequest {
602         pub(super) bytes: Vec<u8>,
603         pub(super) contents: InvoiceRequestContents,
604         signature: Signature,
605 }
606
607 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
608 /// ways to respond depending on whether the signing keys were derived.
609 #[derive(Clone, Debug)]
610 pub struct VerifiedInvoiceRequest {
611         /// The identifier of the [`Offer`] for which the [`InvoiceRequest`] was made.
612         pub offer_id: OfferId,
613
614         /// The verified request.
615         inner: InvoiceRequest,
616
617         /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
618         ///
619         /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
620         /// [`respond_with`].
621         ///
622         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
623         /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
624         /// [`respond_with`]: Self::respond_with
625         pub keys: Option<KeyPair>,
626 }
627
628 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
629 ///
630 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
631 #[derive(Clone, Debug)]
632 #[cfg_attr(test, derive(PartialEq))]
633 pub(super) struct InvoiceRequestContents {
634         pub(super) inner: InvoiceRequestContentsWithoutPayerId,
635         payer_id: PublicKey,
636 }
637
638 #[derive(Clone, Debug)]
639 #[cfg_attr(test, derive(PartialEq))]
640 pub(super) struct InvoiceRequestContentsWithoutPayerId {
641         payer: PayerContents,
642         pub(super) offer: OfferContents,
643         chain: Option<ChainHash>,
644         amount_msats: Option<u64>,
645         features: InvoiceRequestFeatures,
646         quantity: Option<u64>,
647         payer_note: Option<String>,
648 }
649
650 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
651         /// An unpredictable series of bytes, typically containing information about the derivation of
652         /// [`payer_id`].
653         ///
654         /// [`payer_id`]: Self::payer_id
655         pub fn payer_metadata(&$self) -> &[u8] {
656                 $contents.metadata()
657         }
658
659         /// A chain from [`Offer::chains`] that the offer is valid for.
660         pub fn chain(&$self) -> ChainHash {
661                 $contents.chain()
662         }
663
664         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
665         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
666         ///
667         /// [`chain`]: Self::chain
668         pub fn amount_msats(&$self) -> Option<u64> {
669                 $contents.amount_msats()
670         }
671
672         /// Features pertaining to requesting an invoice.
673         pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
674                 &$contents.features()
675         }
676
677         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
678         pub fn quantity(&$self) -> Option<u64> {
679                 $contents.quantity()
680         }
681
682         /// A possibly transient pubkey used to sign the invoice request.
683         pub fn payer_id(&$self) -> PublicKey {
684                 $contents.payer_id()
685         }
686
687         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
688         /// response.
689         pub fn payer_note(&$self) -> Option<PrintableString> {
690                 $contents.payer_note()
691         }
692 } }
693
694 impl UnsignedInvoiceRequest {
695         offer_accessors!(self, self.contents.inner.offer);
696         invoice_request_accessors!(self, self.contents);
697 }
698
699 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
700         $self: ident, $contents: expr, $builder: ty
701 ) => {
702         /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
703         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
704         ///
705         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
706         /// creation time is used for the `created_at` parameter.
707         ///
708         /// [`Duration`]: core::time::Duration
709         #[cfg(feature = "std")]
710         pub fn respond_with(
711                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
712         ) -> Result<$builder, Bolt12SemanticError> {
713                 let created_at = std::time::SystemTime::now()
714                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
715                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
716
717                 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
718         }
719
720         /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
721         ///
722         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
723         /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
724         /// where [`std::time::SystemTime`] is not available.
725         ///
726         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
727         /// for the invoice.
728         ///
729         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
730         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
731         /// a preference. Note, however, that any privacy is lost if a public node id was used for
732         /// [`Offer::signing_pubkey`].
733         ///
734         /// Errors if the request contains unknown required features.
735         ///
736         /// # Note
737         ///
738         /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
739         /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
740         ///
741         /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
742         /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
743         pub fn respond_with_no_std(
744                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
745                 created_at: core::time::Duration
746         ) -> Result<$builder, Bolt12SemanticError> {
747                 if $contents.invoice_request_features().requires_unknown_bits() {
748                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
749                 }
750
751                 let signing_pubkey = match $contents.contents.inner.offer.signing_pubkey() {
752                         Some(signing_pubkey) => signing_pubkey,
753                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
754                 };
755
756                 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
757         }
758
759         #[cfg(test)]
760         #[allow(dead_code)]
761         pub(super) fn respond_with_no_std_using_signing_pubkey(
762                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
763                 created_at: core::time::Duration, signing_pubkey: PublicKey
764         ) -> Result<$builder, Bolt12SemanticError> {
765                 debug_assert!($contents.contents.inner.offer.signing_pubkey().is_none());
766
767                 if $contents.invoice_request_features().requires_unknown_bits() {
768                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
769                 }
770
771                 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
772         }
773 } }
774
775 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
776         /// Verifies that the request was for an offer created using the given key. Returns the verified
777         /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
778         /// if they could be extracted from the metadata.
779         ///
780         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
781         pub fn verify<
782                 #[cfg(not(c_bindings))]
783                 T: secp256k1::Signing
784         >(
785                 $self: $self_type, key: &ExpandedKey,
786                 #[cfg(not(c_bindings))]
787                 secp_ctx: &Secp256k1<T>,
788                 #[cfg(c_bindings)]
789                 secp_ctx: &Secp256k1<secp256k1::All>,
790         ) -> Result<VerifiedInvoiceRequest, ()> {
791                 let (offer_id, keys) = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
792                 Ok(VerifiedInvoiceRequest {
793                         offer_id,
794                         #[cfg(not(c_bindings))]
795                         inner: $self,
796                         #[cfg(c_bindings)]
797                         inner: $self.clone(),
798                         keys,
799                 })
800         }
801
802 } }
803
804 #[cfg(not(c_bindings))]
805 impl InvoiceRequest {
806         offer_accessors!(self, self.contents.inner.offer);
807         invoice_request_accessors!(self, self.contents);
808         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
809         invoice_request_verify_method!(self, Self);
810 }
811
812 #[cfg(c_bindings)]
813 impl InvoiceRequest {
814         offer_accessors!(self, self.contents.inner.offer);
815         invoice_request_accessors!(self, self.contents);
816         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
817         invoice_request_verify_method!(self, &Self);
818 }
819
820 impl InvoiceRequest {
821         /// Signature of the invoice request using [`payer_id`].
822         ///
823         /// [`payer_id`]: Self::payer_id
824         pub fn signature(&self) -> Signature {
825                 self.signature
826         }
827
828         pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
829                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
830                         self.contents.as_tlv_stream();
831                 let signature_tlv_stream = SignatureTlvStreamRef {
832                         signature: Some(&self.signature),
833                 };
834                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
835         }
836 }
837
838 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
839         $self: ident, $contents: expr, $builder: ty
840 ) => {
841         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
842         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
843         /// the same [`ExpandedKey`] as the one used to create the offer.
844         ///
845         /// See [`InvoiceRequest::respond_with`] for further details.
846         ///
847         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
848         #[cfg(feature = "std")]
849         pub fn respond_using_derived_keys(
850                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
851         ) -> Result<$builder, Bolt12SemanticError> {
852                 let created_at = std::time::SystemTime::now()
853                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
854                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
855
856                 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
857         }
858
859         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
860         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
861         /// the same [`ExpandedKey`] as the one used to create the offer.
862         ///
863         /// See [`InvoiceRequest::respond_with_no_std`] for further details.
864         ///
865         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
866         pub fn respond_using_derived_keys_no_std(
867                 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
868                 created_at: core::time::Duration
869         ) -> Result<$builder, Bolt12SemanticError> {
870                 if $self.inner.invoice_request_features().requires_unknown_bits() {
871                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
872                 }
873
874                 let keys = match $self.keys {
875                         None => return Err(Bolt12SemanticError::InvalidMetadata),
876                         Some(keys) => keys,
877                 };
878
879                 match $contents.contents.inner.offer.signing_pubkey() {
880                         Some(signing_pubkey) => debug_assert_eq!(signing_pubkey, keys.public_key()),
881                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
882                 }
883
884                 <$builder>::for_offer_using_keys(
885                         &$self.inner, payment_paths, created_at, payment_hash, keys
886                 )
887         }
888 } }
889
890 impl VerifiedInvoiceRequest {
891         offer_accessors!(self, self.inner.contents.inner.offer);
892         invoice_request_accessors!(self, self.inner.contents);
893         #[cfg(not(c_bindings))]
894         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
895         #[cfg(c_bindings)]
896         invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
897         #[cfg(not(c_bindings))]
898         invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
899         #[cfg(c_bindings)]
900         invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
901
902         pub(crate) fn fields(&self) -> InvoiceRequestFields {
903                 let InvoiceRequestContents {
904                         payer_id,
905                         inner: InvoiceRequestContentsWithoutPayerId {
906                                 payer: _, offer: _, chain: _, amount_msats: _, features: _, quantity, payer_note
907                         },
908                 } = &self.inner.contents;
909
910                 InvoiceRequestFields {
911                         payer_id: *payer_id,
912                         quantity: *quantity,
913                         payer_note_truncated: payer_note.clone()
914                                 .map(|mut s| { s.truncate(PAYER_NOTE_LIMIT); UntrustedString(s) }),
915                 }
916         }
917 }
918
919 impl InvoiceRequestContents {
920         pub(super) fn metadata(&self) -> &[u8] {
921                 self.inner.metadata()
922         }
923
924         pub(super) fn derives_keys(&self) -> bool {
925                 self.inner.payer.0.derives_payer_keys()
926         }
927
928         pub(super) fn chain(&self) -> ChainHash {
929                 self.inner.chain()
930         }
931
932         pub(super) fn amount_msats(&self) -> Option<u64> {
933                 self.inner.amount_msats
934         }
935
936         pub(super) fn features(&self) -> &InvoiceRequestFeatures {
937                 &self.inner.features
938         }
939
940         pub(super) fn quantity(&self) -> Option<u64> {
941                 self.inner.quantity
942         }
943
944         pub(super) fn payer_id(&self) -> PublicKey {
945                 self.payer_id
946         }
947
948         pub(super) fn payer_note(&self) -> Option<PrintableString> {
949                 self.inner.payer_note.as_ref()
950                         .map(|payer_note| PrintableString(payer_note.as_str()))
951         }
952
953         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
954                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
955                 invoice_request.payer_id = Some(&self.payer_id);
956                 (payer, offer, invoice_request)
957         }
958 }
959
960 impl InvoiceRequestContentsWithoutPayerId {
961         pub(super) fn metadata(&self) -> &[u8] {
962                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
963         }
964
965         pub(super) fn chain(&self) -> ChainHash {
966                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
967         }
968
969         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
970                 let payer = PayerTlvStreamRef {
971                         metadata: self.payer.0.as_bytes(),
972                 };
973
974                 let offer = self.offer.as_tlv_stream();
975
976                 let features = {
977                         if self.features == InvoiceRequestFeatures::empty() { None }
978                         else { Some(&self.features) }
979                 };
980
981                 let invoice_request = InvoiceRequestTlvStreamRef {
982                         chain: self.chain.as_ref(),
983                         amount: self.amount_msats,
984                         features,
985                         quantity: self.quantity,
986                         payer_id: None,
987                         payer_note: self.payer_note.as_ref(),
988                         paths: None,
989                 };
990
991                 (payer, offer, invoice_request)
992         }
993 }
994
995 impl Writeable for UnsignedInvoiceRequest {
996         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
997                 WithoutLength(&self.bytes).write(writer)
998         }
999 }
1000
1001 impl Writeable for InvoiceRequest {
1002         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1003                 WithoutLength(&self.bytes).write(writer)
1004         }
1005 }
1006
1007 impl Writeable for InvoiceRequestContents {
1008         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1009                 self.as_tlv_stream().write(writer)
1010         }
1011 }
1012
1013 /// Valid type range for invoice_request TLV records.
1014 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
1015
1016 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
1017 ///
1018 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
1019 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
1020
1021 // This TLV stream is used for both InvoiceRequest and Refund, but not all TLV records are valid for
1022 // InvoiceRequest as noted below.
1023 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
1024         (80, chain: ChainHash),
1025         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
1026         (84, features: (InvoiceRequestFeatures, WithoutLength)),
1027         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
1028         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
1029         (89, payer_note: (String, WithoutLength)),
1030         // Only used for Refund since the onion message of an InvoiceRequest has a reply path.
1031         (90, paths: (Vec<BlindedPath>, WithoutLength)),
1032 });
1033
1034 type FullInvoiceRequestTlvStream =
1035         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
1036
1037 type FullInvoiceRequestTlvStreamRef<'a> = (
1038         PayerTlvStreamRef<'a>,
1039         OfferTlvStreamRef<'a>,
1040         InvoiceRequestTlvStreamRef<'a>,
1041         SignatureTlvStreamRef<'a>,
1042 );
1043
1044 impl SeekReadable for FullInvoiceRequestTlvStream {
1045         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1046                 let payer = SeekReadable::read(r)?;
1047                 let offer = SeekReadable::read(r)?;
1048                 let invoice_request = SeekReadable::read(r)?;
1049                 let signature = SeekReadable::read(r)?;
1050
1051                 Ok((payer, offer, invoice_request, signature))
1052         }
1053 }
1054
1055 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1056
1057 type PartialInvoiceRequestTlvStreamRef<'a> = (
1058         PayerTlvStreamRef<'a>,
1059         OfferTlvStreamRef<'a>,
1060         InvoiceRequestTlvStreamRef<'a>,
1061 );
1062
1063 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1064         type Error = Bolt12ParseError;
1065
1066         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1067                 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1068                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1069                 let (
1070                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1071                 ) = tlv_stream;
1072                 let contents = InvoiceRequestContents::try_from(
1073                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1074                 )?;
1075
1076                 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1077
1078                 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1079         }
1080 }
1081
1082 impl TryFrom<Vec<u8>> for InvoiceRequest {
1083         type Error = Bolt12ParseError;
1084
1085         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1086                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1087                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1088                 let (
1089                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1090                         SignatureTlvStream { signature },
1091                 ) = tlv_stream;
1092                 let contents = InvoiceRequestContents::try_from(
1093                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1094                 )?;
1095
1096                 let signature = match signature {
1097                         None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1098                         Some(signature) => signature,
1099                 };
1100                 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1101                 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1102
1103                 Ok(InvoiceRequest { bytes, contents, signature })
1104         }
1105 }
1106
1107 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1108         type Error = Bolt12SemanticError;
1109
1110         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1111                 let (
1112                         PayerTlvStream { metadata },
1113                         offer_tlv_stream,
1114                         InvoiceRequestTlvStream {
1115                                 chain, amount, features, quantity, payer_id, payer_note, paths,
1116                         },
1117                 ) = tlv_stream;
1118
1119                 let payer = match metadata {
1120                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1121                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1122                 };
1123                 let offer = OfferContents::try_from(offer_tlv_stream)?;
1124
1125                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1126                         return Err(Bolt12SemanticError::UnsupportedChain);
1127                 }
1128
1129                 if offer.amount().is_none() && amount.is_none() {
1130                         return Err(Bolt12SemanticError::MissingAmount);
1131                 }
1132
1133                 offer.check_quantity(quantity)?;
1134                 offer.check_amount_msats_for_quantity(amount, quantity)?;
1135
1136                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1137
1138                 let payer_id = match payer_id {
1139                         None => return Err(Bolt12SemanticError::MissingPayerId),
1140                         Some(payer_id) => payer_id,
1141                 };
1142
1143                 if paths.is_some() {
1144                         return Err(Bolt12SemanticError::UnexpectedPaths);
1145                 }
1146
1147                 Ok(InvoiceRequestContents {
1148                         inner: InvoiceRequestContentsWithoutPayerId {
1149                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1150                         },
1151                         payer_id,
1152                 })
1153         }
1154 }
1155
1156 /// Fields sent in an [`InvoiceRequest`] message to include in [`PaymentContext::Bolt12Offer`].
1157 ///
1158 /// [`PaymentContext::Bolt12Offer`]: crate::blinded_path::payment::PaymentContext::Bolt12Offer
1159 #[derive(Clone, Debug, Eq, PartialEq)]
1160 pub struct InvoiceRequestFields {
1161         /// A possibly transient pubkey used to sign the invoice request.
1162         pub payer_id: PublicKey,
1163
1164         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
1165         pub quantity: Option<u64>,
1166
1167         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
1168         /// response. Truncated to [`PAYER_NOTE_LIMIT`] characters.
1169         pub payer_note_truncated: Option<UntrustedString>,
1170 }
1171
1172 /// The maximum number of characters included in [`InvoiceRequestFields::payer_note_truncated`].
1173 pub const PAYER_NOTE_LIMIT: usize = 512;
1174
1175 impl Writeable for InvoiceRequestFields {
1176         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1177                 write_tlv_fields!(writer, {
1178                         (0, self.payer_id, required),
1179                         (2, self.quantity.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1180                         (4, self.payer_note_truncated.as_ref().map(|s| WithoutLength(&s.0)), option),
1181                 });
1182                 Ok(())
1183         }
1184 }
1185
1186 impl Readable for InvoiceRequestFields {
1187         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1188                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1189                         (0, payer_id, required),
1190                         (2, quantity, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1191                         (4, payer_note_truncated, (option, encoding: (String, WithoutLength))),
1192                 });
1193
1194                 Ok(InvoiceRequestFields {
1195                         payer_id: payer_id.0.unwrap(),
1196                         quantity,
1197                         payer_note_truncated: payer_note_truncated.map(|s| UntrustedString(s)),
1198                 })
1199         }
1200 }
1201
1202 #[cfg(test)]
1203 mod tests {
1204         use super::{InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest};
1205
1206         use bitcoin::blockdata::constants::ChainHash;
1207         use bitcoin::network::constants::Network;
1208         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1209         use core::num::NonZeroU64;
1210         #[cfg(feature = "std")]
1211         use core::time::Duration;
1212         use crate::sign::KeyMaterial;
1213         use crate::ln::channelmanager::PaymentId;
1214         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1215         use crate::ln::inbound_payment::ExpandedKey;
1216         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1217         use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1218         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1219         use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1220         #[cfg(not(c_bindings))]
1221         use {
1222                 crate::offers::offer::OfferBuilder,
1223         };
1224         #[cfg(c_bindings)]
1225         use {
1226                 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1227         };
1228         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1229         use crate::offers::payer::PayerTlvStreamRef;
1230         use crate::offers::test_utils::*;
1231         use crate::util::ser::{BigSize, Readable, Writeable};
1232         use crate::util::string::{PrintableString, UntrustedString};
1233
1234         #[test]
1235         fn builds_invoice_request_with_defaults() {
1236                 let unsigned_invoice_request = OfferBuilder::new(recipient_pubkey())
1237                         .amount_msats(1000)
1238                         .build().unwrap()
1239                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1240                         .build().unwrap();
1241                 #[cfg(c_bindings)]
1242                 let mut unsigned_invoice_request = unsigned_invoice_request;
1243
1244                 let mut buffer = Vec::new();
1245                 unsigned_invoice_request.write(&mut buffer).unwrap();
1246
1247                 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1248                 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1249                 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1250                 assert_eq!(unsigned_invoice_request.metadata(), None);
1251                 assert_eq!(unsigned_invoice_request.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1252                 assert_eq!(unsigned_invoice_request.description(), Some(PrintableString("")));
1253                 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1254                 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1255                 assert_eq!(unsigned_invoice_request.paths(), &[]);
1256                 assert_eq!(unsigned_invoice_request.issuer(), None);
1257                 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1258                 assert_eq!(unsigned_invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1259                 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1260                 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1261                 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1262                 assert_eq!(unsigned_invoice_request.quantity(), None);
1263                 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1264                 assert_eq!(unsigned_invoice_request.payer_note(), None);
1265
1266                 match UnsignedInvoiceRequest::try_from(buffer) {
1267                         Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1268                         Ok(parsed) => {
1269                                 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1270                                 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1271                         },
1272                 }
1273
1274                 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1275
1276                 let mut buffer = Vec::new();
1277                 invoice_request.write(&mut buffer).unwrap();
1278
1279                 assert_eq!(invoice_request.bytes, buffer.as_slice());
1280                 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1281                 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1282                 assert_eq!(invoice_request.metadata(), None);
1283                 assert_eq!(invoice_request.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1284                 assert_eq!(invoice_request.description(), Some(PrintableString("")));
1285                 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1286                 assert_eq!(invoice_request.absolute_expiry(), None);
1287                 assert_eq!(invoice_request.paths(), &[]);
1288                 assert_eq!(invoice_request.issuer(), None);
1289                 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1290                 assert_eq!(invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1291                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1292                 assert_eq!(invoice_request.amount_msats(), None);
1293                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1294                 assert_eq!(invoice_request.quantity(), None);
1295                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1296                 assert_eq!(invoice_request.payer_note(), None);
1297
1298                 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1299                 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1300
1301                 assert_eq!(
1302                         invoice_request.as_tlv_stream(),
1303                         (
1304                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1305                                 OfferTlvStreamRef {
1306                                         chains: None,
1307                                         metadata: None,
1308                                         currency: None,
1309                                         amount: Some(1000),
1310                                         description: Some(&String::from("")),
1311                                         features: None,
1312                                         absolute_expiry: None,
1313                                         paths: None,
1314                                         issuer: None,
1315                                         quantity_max: None,
1316                                         node_id: Some(&recipient_pubkey()),
1317                                 },
1318                                 InvoiceRequestTlvStreamRef {
1319                                         chain: None,
1320                                         amount: None,
1321                                         features: None,
1322                                         quantity: None,
1323                                         payer_id: Some(&payer_pubkey()),
1324                                         payer_note: None,
1325                                         paths: None,
1326                                 },
1327                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1328                         ),
1329                 );
1330
1331                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1332                         panic!("error parsing invoice request: {:?}", e);
1333                 }
1334         }
1335
1336         #[cfg(feature = "std")]
1337         #[test]
1338         fn builds_invoice_request_from_offer_with_expiration() {
1339                 let future_expiry = Duration::from_secs(u64::max_value());
1340                 let past_expiry = Duration::from_secs(0);
1341
1342                 if let Err(e) = OfferBuilder::new(recipient_pubkey())
1343                         .amount_msats(1000)
1344                         .absolute_expiry(future_expiry)
1345                         .build().unwrap()
1346                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347                         .build()
1348                 {
1349                         panic!("error building invoice_request: {:?}", e);
1350                 }
1351
1352                 match OfferBuilder::new(recipient_pubkey())
1353                         .amount_msats(1000)
1354                         .absolute_expiry(past_expiry)
1355                         .build().unwrap()
1356                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1357                         .build()
1358                 {
1359                         Ok(_) => panic!("expected error"),
1360                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1361                 }
1362         }
1363
1364         #[test]
1365         fn builds_invoice_request_with_derived_metadata() {
1366                 let payer_id = payer_pubkey();
1367                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1368                 let entropy = FixedEntropy {};
1369                 let secp_ctx = Secp256k1::new();
1370                 let payment_id = PaymentId([1; 32]);
1371
1372                 let offer = OfferBuilder::new(recipient_pubkey())
1373                         .amount_msats(1000)
1374                         .build().unwrap();
1375                 let invoice_request = offer
1376                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1377                         .unwrap()
1378                         .build().unwrap()
1379                         .sign(payer_sign).unwrap();
1380                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1381
1382                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1383                         .unwrap()
1384                         .build().unwrap()
1385                         .sign(recipient_sign).unwrap();
1386                 match invoice.verify(&expanded_key, &secp_ctx) {
1387                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1388                         Err(()) => panic!("verification failed"),
1389                 }
1390
1391                 // Fails verification with altered fields
1392                 let (
1393                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1394                         mut invoice_tlv_stream, mut signature_tlv_stream
1395                 ) = invoice.as_tlv_stream();
1396                 invoice_request_tlv_stream.amount = Some(2000);
1397                 invoice_tlv_stream.amount = Some(2000);
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                 // Fails verification with altered metadata
1415                 let (
1416                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1417                         mut signature_tlv_stream
1418                 ) = invoice.as_tlv_stream();
1419                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1420                 payer_tlv_stream.metadata = Some(&metadata);
1421
1422                 let tlv_stream =
1423                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1424                 let mut bytes = Vec::new();
1425                 tlv_stream.write(&mut bytes).unwrap();
1426
1427                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1428                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1429                 signature_tlv_stream.signature = Some(&signature);
1430
1431                 let mut encoded_invoice = bytes;
1432                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1433
1434                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1435                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1436         }
1437
1438         #[test]
1439         fn builds_invoice_request_with_derived_payer_id() {
1440                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1441                 let entropy = FixedEntropy {};
1442                 let secp_ctx = Secp256k1::new();
1443                 let payment_id = PaymentId([1; 32]);
1444
1445                 let offer = OfferBuilder::new(recipient_pubkey())
1446                         .amount_msats(1000)
1447                         .build().unwrap();
1448                 let invoice_request = offer
1449                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1450                         .unwrap()
1451                         .build_and_sign()
1452                         .unwrap();
1453
1454                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1455                         .unwrap()
1456                         .build().unwrap()
1457                         .sign(recipient_sign).unwrap();
1458                 match invoice.verify(&expanded_key, &secp_ctx) {
1459                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1460                         Err(()) => panic!("verification failed"),
1461                 }
1462
1463                 // Fails verification with altered fields
1464                 let (
1465                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1466                         mut invoice_tlv_stream, mut signature_tlv_stream
1467                 ) = invoice.as_tlv_stream();
1468                 invoice_request_tlv_stream.amount = Some(2000);
1469                 invoice_tlv_stream.amount = Some(2000);
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                 // Fails verification with altered payer id
1487                 let (
1488                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1489                         mut signature_tlv_stream
1490                 ) = invoice.as_tlv_stream();
1491                 let payer_id = pubkey(1);
1492                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1493
1494                 let tlv_stream =
1495                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1496                 let mut bytes = Vec::new();
1497                 tlv_stream.write(&mut bytes).unwrap();
1498
1499                 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1500                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1501                 signature_tlv_stream.signature = Some(&signature);
1502
1503                 let mut encoded_invoice = bytes;
1504                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1505
1506                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1507                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1508         }
1509
1510         #[test]
1511         fn builds_invoice_request_with_chain() {
1512                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1513                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1514
1515                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1516                         .amount_msats(1000)
1517                         .build().unwrap()
1518                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1519                         .chain(Network::Bitcoin).unwrap()
1520                         .build().unwrap()
1521                         .sign(payer_sign).unwrap();
1522                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1523                 assert_eq!(invoice_request.chain(), mainnet);
1524                 assert_eq!(tlv_stream.chain, None);
1525
1526                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1527                         .amount_msats(1000)
1528                         .chain(Network::Testnet)
1529                         .build().unwrap()
1530                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531                         .chain(Network::Testnet).unwrap()
1532                         .build().unwrap()
1533                         .sign(payer_sign).unwrap();
1534                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1535                 assert_eq!(invoice_request.chain(), testnet);
1536                 assert_eq!(tlv_stream.chain, Some(&testnet));
1537
1538                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1539                         .amount_msats(1000)
1540                         .chain(Network::Bitcoin)
1541                         .chain(Network::Testnet)
1542                         .build().unwrap()
1543                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1544                         .chain(Network::Bitcoin).unwrap()
1545                         .build().unwrap()
1546                         .sign(payer_sign).unwrap();
1547                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1548                 assert_eq!(invoice_request.chain(), mainnet);
1549                 assert_eq!(tlv_stream.chain, None);
1550
1551                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1552                         .amount_msats(1000)
1553                         .chain(Network::Bitcoin)
1554                         .chain(Network::Testnet)
1555                         .build().unwrap()
1556                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1557                         .chain(Network::Bitcoin).unwrap()
1558                         .chain(Network::Testnet).unwrap()
1559                         .build().unwrap()
1560                         .sign(payer_sign).unwrap();
1561                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1562                 assert_eq!(invoice_request.chain(), testnet);
1563                 assert_eq!(tlv_stream.chain, Some(&testnet));
1564
1565                 match OfferBuilder::new(recipient_pubkey())
1566                         .amount_msats(1000)
1567                         .chain(Network::Testnet)
1568                         .build().unwrap()
1569                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1570                         .chain(Network::Bitcoin)
1571                 {
1572                         Ok(_) => panic!("expected error"),
1573                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1574                 }
1575
1576                 match OfferBuilder::new(recipient_pubkey())
1577                         .amount_msats(1000)
1578                         .chain(Network::Testnet)
1579                         .build().unwrap()
1580                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1581                         .build()
1582                 {
1583                         Ok(_) => panic!("expected error"),
1584                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1585                 }
1586         }
1587
1588         #[test]
1589         fn builds_invoice_request_with_amount() {
1590                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1591                         .amount_msats(1000)
1592                         .build().unwrap()
1593                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594                         .amount_msats(1000).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(1000));
1599                 assert_eq!(tlv_stream.amount, Some(1000));
1600
1601                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1602                         .amount_msats(1000)
1603                         .build().unwrap()
1604                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1605                         .amount_msats(1001).unwrap()
1606                         .amount_msats(1000).unwrap()
1607                         .build().unwrap()
1608                         .sign(payer_sign).unwrap();
1609                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1610                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1611                 assert_eq!(tlv_stream.amount, Some(1000));
1612
1613                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1614                         .amount_msats(1000)
1615                         .build().unwrap()
1616                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1617                         .amount_msats(1001).unwrap()
1618                         .build().unwrap()
1619                         .sign(payer_sign).unwrap();
1620                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1621                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1622                 assert_eq!(tlv_stream.amount, Some(1001));
1623
1624                 match OfferBuilder::new(recipient_pubkey())
1625                         .amount_msats(1000)
1626                         .build().unwrap()
1627                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1628                         .amount_msats(999)
1629                 {
1630                         Ok(_) => panic!("expected error"),
1631                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1632                 }
1633
1634                 match OfferBuilder::new(recipient_pubkey())
1635                         .amount_msats(1000)
1636                         .supported_quantity(Quantity::Unbounded)
1637                         .build().unwrap()
1638                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1639                         .quantity(2).unwrap()
1640                         .amount_msats(1000)
1641                 {
1642                         Ok(_) => panic!("expected error"),
1643                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1644                 }
1645
1646                 match OfferBuilder::new(recipient_pubkey())
1647                         .amount_msats(1000)
1648                         .build().unwrap()
1649                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1650                         .amount_msats(MAX_VALUE_MSAT + 1)
1651                 {
1652                         Ok(_) => panic!("expected error"),
1653                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1654                 }
1655
1656                 match OfferBuilder::new(recipient_pubkey())
1657                         .amount_msats(1000)
1658                         .supported_quantity(Quantity::Unbounded)
1659                         .build().unwrap()
1660                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661                         .amount_msats(1000).unwrap()
1662                         .quantity(2).unwrap()
1663                         .build()
1664                 {
1665                         Ok(_) => panic!("expected error"),
1666                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1667                 }
1668
1669                 match OfferBuilder::new(recipient_pubkey())
1670                         .build().unwrap()
1671                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1672                         .build()
1673                 {
1674                         Ok(_) => panic!("expected error"),
1675                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1676                 }
1677
1678                 match OfferBuilder::new(recipient_pubkey())
1679                         .amount_msats(1000)
1680                         .supported_quantity(Quantity::Unbounded)
1681                         .build().unwrap()
1682                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1683                         .quantity(u64::max_value()).unwrap()
1684                         .build()
1685                 {
1686                         Ok(_) => panic!("expected error"),
1687                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1688                 }
1689         }
1690
1691         #[test]
1692         fn builds_invoice_request_with_features() {
1693                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1694                         .amount_msats(1000)
1695                         .build().unwrap()
1696                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1697                         .features_unchecked(InvoiceRequestFeatures::unknown())
1698                         .build().unwrap()
1699                         .sign(payer_sign).unwrap();
1700                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1701                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1702                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1703
1704                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1705                         .amount_msats(1000)
1706                         .build().unwrap()
1707                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1708                         .features_unchecked(InvoiceRequestFeatures::unknown())
1709                         .features_unchecked(InvoiceRequestFeatures::empty())
1710                         .build().unwrap()
1711                         .sign(payer_sign).unwrap();
1712                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1713                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1714                 assert_eq!(tlv_stream.features, None);
1715         }
1716
1717         #[test]
1718         fn builds_invoice_request_with_quantity() {
1719                 let one = NonZeroU64::new(1).unwrap();
1720                 let ten = NonZeroU64::new(10).unwrap();
1721
1722                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1723                         .amount_msats(1000)
1724                         .supported_quantity(Quantity::One)
1725                         .build().unwrap()
1726                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1727                         .build().unwrap()
1728                         .sign(payer_sign).unwrap();
1729                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1730                 assert_eq!(invoice_request.quantity(), None);
1731                 assert_eq!(tlv_stream.quantity, None);
1732
1733                 match OfferBuilder::new(recipient_pubkey())
1734                         .amount_msats(1000)
1735                         .supported_quantity(Quantity::One)
1736                         .build().unwrap()
1737                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1738                         .amount_msats(2_000).unwrap()
1739                         .quantity(2)
1740                 {
1741                         Ok(_) => panic!("expected error"),
1742                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1743                 }
1744
1745                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1746                         .amount_msats(1000)
1747                         .supported_quantity(Quantity::Bounded(ten))
1748                         .build().unwrap()
1749                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750                         .amount_msats(10_000).unwrap()
1751                         .quantity(10).unwrap()
1752                         .build().unwrap()
1753                         .sign(payer_sign).unwrap();
1754                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1755                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1756                 assert_eq!(tlv_stream.amount, Some(10_000));
1757
1758                 match OfferBuilder::new(recipient_pubkey())
1759                         .amount_msats(1000)
1760                         .supported_quantity(Quantity::Bounded(ten))
1761                         .build().unwrap()
1762                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1763                         .amount_msats(11_000).unwrap()
1764                         .quantity(11)
1765                 {
1766                         Ok(_) => panic!("expected error"),
1767                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1768                 }
1769
1770                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1771                         .amount_msats(1000)
1772                         .supported_quantity(Quantity::Unbounded)
1773                         .build().unwrap()
1774                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1775                         .amount_msats(2_000).unwrap()
1776                         .quantity(2).unwrap()
1777                         .build().unwrap()
1778                         .sign(payer_sign).unwrap();
1779                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1780                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1781                 assert_eq!(tlv_stream.amount, Some(2_000));
1782
1783                 match OfferBuilder::new(recipient_pubkey())
1784                         .amount_msats(1000)
1785                         .supported_quantity(Quantity::Unbounded)
1786                         .build().unwrap()
1787                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1788                         .build()
1789                 {
1790                         Ok(_) => panic!("expected error"),
1791                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1792                 }
1793
1794                 match OfferBuilder::new(recipient_pubkey())
1795                         .amount_msats(1000)
1796                         .supported_quantity(Quantity::Bounded(one))
1797                         .build().unwrap()
1798                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1799                         .build()
1800                 {
1801                         Ok(_) => panic!("expected error"),
1802                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1803                 }
1804         }
1805
1806         #[test]
1807         fn builds_invoice_request_with_payer_note() {
1808                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1809                         .amount_msats(1000)
1810                         .build().unwrap()
1811                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1812                         .payer_note("bar".into())
1813                         .build().unwrap()
1814                         .sign(payer_sign).unwrap();
1815                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1816                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1817                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1818
1819                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1820                         .amount_msats(1000)
1821                         .build().unwrap()
1822                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1823                         .payer_note("bar".into())
1824                         .payer_note("baz".into())
1825                         .build().unwrap()
1826                         .sign(payer_sign).unwrap();
1827                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1828                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1829                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1830         }
1831
1832         #[test]
1833         fn fails_signing_invoice_request() {
1834                 match OfferBuilder::new(recipient_pubkey())
1835                         .amount_msats(1000)
1836                         .build().unwrap()
1837                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1838                         .build().unwrap()
1839                         .sign(fail_sign)
1840                 {
1841                         Ok(_) => panic!("expected error"),
1842                         Err(e) => assert_eq!(e, SignError::Signing),
1843                 }
1844
1845                 match OfferBuilder::new(recipient_pubkey())
1846                         .amount_msats(1000)
1847                         .build().unwrap()
1848                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1849                         .build().unwrap()
1850                         .sign(recipient_sign)
1851                 {
1852                         Ok(_) => panic!("expected error"),
1853                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1854                 }
1855         }
1856
1857         #[test]
1858         fn fails_responding_with_unknown_required_features() {
1859                 match OfferBuilder::new(recipient_pubkey())
1860                         .amount_msats(1000)
1861                         .build().unwrap()
1862                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1863                         .features_unchecked(InvoiceRequestFeatures::unknown())
1864                         .build().unwrap()
1865                         .sign(payer_sign).unwrap()
1866                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1867                 {
1868                         Ok(_) => panic!("expected error"),
1869                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1870                 }
1871         }
1872
1873         #[test]
1874         fn parses_invoice_request_with_metadata() {
1875                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1876                         .amount_msats(1000)
1877                         .build().unwrap()
1878                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1879                         .build().unwrap()
1880                         .sign(payer_sign).unwrap();
1881
1882                 let mut buffer = Vec::new();
1883                 invoice_request.write(&mut buffer).unwrap();
1884
1885                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1886                         panic!("error parsing invoice_request: {:?}", e);
1887                 }
1888         }
1889
1890         #[test]
1891         fn parses_invoice_request_with_chain() {
1892                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1893                         .amount_msats(1000)
1894                         .build().unwrap()
1895                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1896                         .chain(Network::Bitcoin).unwrap()
1897                         .build().unwrap()
1898                         .sign(payer_sign).unwrap();
1899
1900                 let mut buffer = Vec::new();
1901                 invoice_request.write(&mut buffer).unwrap();
1902
1903                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1904                         panic!("error parsing invoice_request: {:?}", e);
1905                 }
1906
1907                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1908                         .amount_msats(1000)
1909                         .build().unwrap()
1910                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1911                         .chain_unchecked(Network::Testnet)
1912                         .build_unchecked()
1913                         .sign(payer_sign).unwrap();
1914
1915                 let mut buffer = Vec::new();
1916                 invoice_request.write(&mut buffer).unwrap();
1917
1918                 match InvoiceRequest::try_from(buffer) {
1919                         Ok(_) => panic!("expected error"),
1920                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1921                 }
1922         }
1923
1924         #[test]
1925         fn parses_invoice_request_with_amount() {
1926                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1927                         .amount_msats(1000)
1928                         .build().unwrap()
1929                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1930                         .build().unwrap()
1931                         .sign(payer_sign).unwrap();
1932
1933                 let mut buffer = Vec::new();
1934                 invoice_request.write(&mut buffer).unwrap();
1935
1936                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1937                         panic!("error parsing invoice_request: {:?}", e);
1938                 }
1939
1940                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1941                         .build().unwrap()
1942                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1943                         .amount_msats(1000).unwrap()
1944                         .build().unwrap()
1945                         .sign(payer_sign).unwrap();
1946
1947                 let mut buffer = Vec::new();
1948                 invoice_request.write(&mut buffer).unwrap();
1949
1950                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1951                         panic!("error parsing invoice_request: {:?}", e);
1952                 }
1953
1954                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1955                         .build().unwrap()
1956                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1957                         .build_unchecked()
1958                         .sign(payer_sign).unwrap();
1959
1960                 let mut buffer = Vec::new();
1961                 invoice_request.write(&mut buffer).unwrap();
1962
1963                 match InvoiceRequest::try_from(buffer) {
1964                         Ok(_) => panic!("expected error"),
1965                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1966                 }
1967
1968                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1969                         .amount_msats(1000)
1970                         .build().unwrap()
1971                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1972                         .amount_msats_unchecked(999)
1973                         .build_unchecked()
1974                         .sign(payer_sign).unwrap();
1975
1976                 let mut buffer = Vec::new();
1977                 invoice_request.write(&mut buffer).unwrap();
1978
1979                 match InvoiceRequest::try_from(buffer) {
1980                         Ok(_) => panic!("expected error"),
1981                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1982                 }
1983
1984                 let invoice_request = OfferBuilder::new(recipient_pubkey())
1985                         .description("foo".to_string())
1986                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1987                         .build_unchecked()
1988                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1989                         .build_unchecked()
1990                         .sign(payer_sign).unwrap();
1991
1992                 let mut buffer = Vec::new();
1993                 invoice_request.write(&mut buffer).unwrap();
1994
1995                 match InvoiceRequest::try_from(buffer) {
1996                         Ok(_) => panic!("expected error"),
1997                         Err(e) => {
1998                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1999                         },
2000                 }
2001
2002                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2003                         .amount_msats(1000)
2004                         .supported_quantity(Quantity::Unbounded)
2005                         .build().unwrap()
2006                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2007                         .quantity(u64::max_value()).unwrap()
2008                         .build_unchecked()
2009                         .sign(payer_sign).unwrap();
2010
2011                 let mut buffer = Vec::new();
2012                 invoice_request.write(&mut buffer).unwrap();
2013
2014                 match InvoiceRequest::try_from(buffer) {
2015                         Ok(_) => panic!("expected error"),
2016                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
2017                 }
2018         }
2019
2020         #[test]
2021         fn parses_invoice_request_with_quantity() {
2022                 let one = NonZeroU64::new(1).unwrap();
2023                 let ten = NonZeroU64::new(10).unwrap();
2024
2025                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2026                         .amount_msats(1000)
2027                         .supported_quantity(Quantity::One)
2028                         .build().unwrap()
2029                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2030                         .build().unwrap()
2031                         .sign(payer_sign).unwrap();
2032
2033                 let mut buffer = Vec::new();
2034                 invoice_request.write(&mut buffer).unwrap();
2035
2036                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2037                         panic!("error parsing invoice_request: {:?}", e);
2038                 }
2039
2040                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2041                         .amount_msats(1000)
2042                         .supported_quantity(Quantity::One)
2043                         .build().unwrap()
2044                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2045                         .amount_msats(2_000).unwrap()
2046                         .quantity_unchecked(2)
2047                         .build_unchecked()
2048                         .sign(payer_sign).unwrap();
2049
2050                 let mut buffer = Vec::new();
2051                 invoice_request.write(&mut buffer).unwrap();
2052
2053                 match InvoiceRequest::try_from(buffer) {
2054                         Ok(_) => panic!("expected error"),
2055                         Err(e) => {
2056                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
2057                         },
2058                 }
2059
2060                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2061                         .amount_msats(1000)
2062                         .supported_quantity(Quantity::Bounded(ten))
2063                         .build().unwrap()
2064                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2065                         .amount_msats(10_000).unwrap()
2066                         .quantity(10).unwrap()
2067                         .build().unwrap()
2068                         .sign(payer_sign).unwrap();
2069
2070                 let mut buffer = Vec::new();
2071                 invoice_request.write(&mut buffer).unwrap();
2072
2073                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2074                         panic!("error parsing invoice_request: {:?}", e);
2075                 }
2076
2077                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2078                         .amount_msats(1000)
2079                         .supported_quantity(Quantity::Bounded(ten))
2080                         .build().unwrap()
2081                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2082                         .amount_msats(11_000).unwrap()
2083                         .quantity_unchecked(11)
2084                         .build_unchecked()
2085                         .sign(payer_sign).unwrap();
2086
2087                 let mut buffer = Vec::new();
2088                 invoice_request.write(&mut buffer).unwrap();
2089
2090                 match InvoiceRequest::try_from(buffer) {
2091                         Ok(_) => panic!("expected error"),
2092                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
2093                 }
2094
2095                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2096                         .amount_msats(1000)
2097                         .supported_quantity(Quantity::Unbounded)
2098                         .build().unwrap()
2099                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2100                         .amount_msats(2_000).unwrap()
2101                         .quantity(2).unwrap()
2102                         .build().unwrap()
2103                         .sign(payer_sign).unwrap();
2104
2105                 let mut buffer = Vec::new();
2106                 invoice_request.write(&mut buffer).unwrap();
2107
2108                 if let Err(e) = InvoiceRequest::try_from(buffer) {
2109                         panic!("error parsing invoice_request: {:?}", e);
2110                 }
2111
2112                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2113                         .amount_msats(1000)
2114                         .supported_quantity(Quantity::Unbounded)
2115                         .build().unwrap()
2116                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2117                         .build_unchecked()
2118                         .sign(payer_sign).unwrap();
2119
2120                 let mut buffer = Vec::new();
2121                 invoice_request.write(&mut buffer).unwrap();
2122
2123                 match InvoiceRequest::try_from(buffer) {
2124                         Ok(_) => panic!("expected error"),
2125                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2126                 }
2127
2128                 let invoice_request = OfferBuilder::new(recipient_pubkey())
2129                         .amount_msats(1000)
2130                         .supported_quantity(Quantity::Bounded(one))
2131                         .build().unwrap()
2132                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2133                         .build_unchecked()
2134                         .sign(payer_sign).unwrap();
2135
2136                 let mut buffer = Vec::new();
2137                 invoice_request.write(&mut buffer).unwrap();
2138
2139                 match InvoiceRequest::try_from(buffer) {
2140                         Ok(_) => panic!("expected error"),
2141                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2142                 }
2143         }
2144
2145         #[test]
2146         fn fails_parsing_invoice_request_without_metadata() {
2147                 let offer = OfferBuilder::new(recipient_pubkey())
2148                         .amount_msats(1000)
2149                         .build().unwrap();
2150                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2151                         .build().unwrap();
2152                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2153                 tlv_stream.0.metadata = None;
2154
2155                 let mut buffer = Vec::new();
2156                 tlv_stream.write(&mut buffer).unwrap();
2157
2158                 match InvoiceRequest::try_from(buffer) {
2159                         Ok(_) => panic!("expected error"),
2160                         Err(e) => {
2161                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2162                         },
2163                 }
2164         }
2165
2166         #[test]
2167         fn fails_parsing_invoice_request_without_payer_id() {
2168                 let offer = OfferBuilder::new(recipient_pubkey())
2169                         .amount_msats(1000)
2170                         .build().unwrap();
2171                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2172                         .build().unwrap();
2173                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2174                 tlv_stream.2.payer_id = None;
2175
2176                 let mut buffer = Vec::new();
2177                 tlv_stream.write(&mut buffer).unwrap();
2178
2179                 match InvoiceRequest::try_from(buffer) {
2180                         Ok(_) => panic!("expected error"),
2181                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2182                 }
2183         }
2184
2185         #[test]
2186         fn fails_parsing_invoice_request_without_node_id() {
2187                 let offer = OfferBuilder::new(recipient_pubkey())
2188                         .amount_msats(1000)
2189                         .build().unwrap();
2190                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2191                         .build().unwrap();
2192                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2193                 tlv_stream.1.node_id = None;
2194
2195                 let mut buffer = Vec::new();
2196                 tlv_stream.write(&mut buffer).unwrap();
2197
2198                 match InvoiceRequest::try_from(buffer) {
2199                         Ok(_) => panic!("expected error"),
2200                         Err(e) => {
2201                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2202                         },
2203                 }
2204         }
2205
2206         #[test]
2207         fn fails_parsing_invoice_request_without_signature() {
2208                 let mut buffer = Vec::new();
2209                 OfferBuilder::new(recipient_pubkey())
2210                         .amount_msats(1000)
2211                         .build().unwrap()
2212                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2213                         .build().unwrap()
2214                         .contents
2215                         .write(&mut buffer).unwrap();
2216
2217                 match InvoiceRequest::try_from(buffer) {
2218                         Ok(_) => panic!("expected error"),
2219                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2220                 }
2221         }
2222
2223         #[test]
2224         fn fails_parsing_invoice_request_with_invalid_signature() {
2225                 let mut invoice_request = OfferBuilder::new(recipient_pubkey())
2226                         .amount_msats(1000)
2227                         .build().unwrap()
2228                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2229                         .build().unwrap()
2230                         .sign(payer_sign).unwrap();
2231                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2232                 *last_signature_byte = last_signature_byte.wrapping_add(1);
2233
2234                 let mut buffer = Vec::new();
2235                 invoice_request.write(&mut buffer).unwrap();
2236
2237                 match InvoiceRequest::try_from(buffer) {
2238                         Ok(_) => panic!("expected error"),
2239                         Err(e) => {
2240                                 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2241                         },
2242                 }
2243         }
2244
2245         #[test]
2246         fn fails_parsing_invoice_request_with_extra_tlv_records() {
2247                 let secp_ctx = Secp256k1::new();
2248                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2249                 let invoice_request = OfferBuilder::new(keys.public_key())
2250                         .amount_msats(1000)
2251                         .build().unwrap()
2252                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2253                         .build().unwrap()
2254                         .sign(|message: &UnsignedInvoiceRequest|
2255                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2256                         )
2257                         .unwrap();
2258
2259                 let mut encoded_invoice_request = Vec::new();
2260                 invoice_request.write(&mut encoded_invoice_request).unwrap();
2261                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2262                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2263                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2264
2265                 match InvoiceRequest::try_from(encoded_invoice_request) {
2266                         Ok(_) => panic!("expected error"),
2267                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2268                 }
2269         }
2270
2271         #[test]
2272         fn copies_verified_invoice_request_fields() {
2273                 let node_id = recipient_pubkey();
2274                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
2275                 let entropy = FixedEntropy {};
2276                 let secp_ctx = Secp256k1::new();
2277
2278                 #[cfg(c_bindings)]
2279                 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
2280                 let offer = OfferBuilder
2281                         ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
2282                         .chain(Network::Testnet)
2283                         .amount_msats(1000)
2284                         .supported_quantity(Quantity::Unbounded)
2285                         .build().unwrap();
2286                 assert_eq!(offer.signing_pubkey(), Some(node_id));
2287
2288                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2289                         .chain(Network::Testnet).unwrap()
2290                         .quantity(1).unwrap()
2291                         .payer_note("0".repeat(PAYER_NOTE_LIMIT * 2))
2292                         .build().unwrap()
2293                         .sign(payer_sign).unwrap();
2294                 match invoice_request.verify(&expanded_key, &secp_ctx) {
2295                         Ok(invoice_request) => {
2296                                 let fields = invoice_request.fields();
2297                                 assert_eq!(invoice_request.offer_id, offer.id());
2298                                 assert_eq!(
2299                                         fields,
2300                                         InvoiceRequestFields {
2301                                                 payer_id: payer_pubkey(),
2302                                                 quantity: Some(1),
2303                                                 payer_note_truncated: Some(UntrustedString("0".repeat(PAYER_NOTE_LIMIT))),
2304                                         }
2305                                 );
2306
2307                                 let mut buffer = Vec::new();
2308                                 fields.write(&mut buffer).unwrap();
2309
2310                                 let deserialized_fields: InvoiceRequestFields =
2311                                         Readable::read(&mut buffer.as_slice()).unwrap();
2312                                 assert_eq!(deserialized_fields, fields);
2313                         },
2314                         Err(_) => panic!("unexpected error"),
2315                 }
2316         }
2317 }