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