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