]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/offers/invoice_request.rs
Add some no-exporting of more offers code
[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 an [`Invoice`].
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 //! [`Invoice`]: crate::offers::invoice::Invoice
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 core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
32 //!
33 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
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 //! "lno1qcp4256ypq"
40 //!     .parse::<Offer>()?
41 //!     .request_invoice(vec![42; 64], pubkey)?
42 //!     .chain(Network::Testnet)?
43 //!     .amount_msats(1000)?
44 //!     .quantity(5)?
45 //!     .payer_note("foo".to_string())
46 //!     .build()?
47 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
48 //!     .expect("failed verifying signature")
49 //!     .write(&mut buffer)
50 //!     .unwrap();
51 //! # Ok(())
52 //! # }
53 //! ```
54
55 use bitcoin::blockdata::constants::ChainHash;
56 use bitcoin::network::constants::Network;
57 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, self};
58 use bitcoin::secp256k1::schnorr::Signature;
59 use core::convert::{Infallible, TryFrom};
60 use core::ops::Deref;
61 use crate::chain::keysinterface::EntropySource;
62 use crate::io;
63 use crate::blinded_path::BlindedPath;
64 use crate::ln::PaymentHash;
65 use crate::ln::features::InvoiceRequestFeatures;
66 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
67 use crate::ln::msgs::DecodeError;
68 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
69 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
70 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
71 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
72 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
73 use crate::offers::signer::{Metadata, MetadataMaterial};
74 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
75 use crate::util::string::PrintableString;
76
77 use crate::prelude::*;
78
79 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
80
81 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
82
83 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
84 ///
85 /// See [module-level documentation] for usage.
86 ///
87 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
88 ///
89 /// [module-level documentation]: self
90 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
91         offer: &'a Offer,
92         invoice_request: InvoiceRequestContentsWithoutPayerId,
93         payer_id: Option<PublicKey>,
94         payer_id_strategy: core::marker::PhantomData<P>,
95         secp_ctx: Option<&'b Secp256k1<T>>,
96 }
97
98 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
99 ///
100 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
101 pub trait PayerIdStrategy {}
102
103 /// [`InvoiceRequest::payer_id`] will be explicitly set.
104 ///
105 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
106 pub struct ExplicitPayerId {}
107
108 /// [`InvoiceRequest::payer_id`] will be derived.
109 ///
110 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
111 pub struct DerivedPayerId {}
112
113 impl PayerIdStrategy for ExplicitPayerId {}
114 impl PayerIdStrategy for DerivedPayerId {}
115
116 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
117         pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
118                 Self {
119                         offer,
120                         invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
121                         payer_id: Some(payer_id),
122                         payer_id_strategy: core::marker::PhantomData,
123                         secp_ctx: None,
124                 }
125         }
126
127         pub(super) fn deriving_metadata<ES: Deref>(
128                 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
129         ) -> Self where ES::Target: EntropySource {
130                 let nonce = Nonce::from_entropy_source(entropy_source);
131                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
132                 let metadata = Metadata::Derived(derivation_material);
133                 Self {
134                         offer,
135                         invoice_request: Self::create_contents(offer, metadata),
136                         payer_id: Some(payer_id),
137                         payer_id_strategy: core::marker::PhantomData,
138                         secp_ctx: None,
139                 }
140         }
141 }
142
143 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
144         pub(super) fn deriving_payer_id<ES: Deref>(
145                 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
146         ) -> Self where ES::Target: EntropySource {
147                 let nonce = Nonce::from_entropy_source(entropy_source);
148                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
149                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
150                 Self {
151                         offer,
152                         invoice_request: Self::create_contents(offer, metadata),
153                         payer_id: None,
154                         payer_id_strategy: core::marker::PhantomData,
155                         secp_ctx: Some(secp_ctx),
156                 }
157         }
158 }
159
160 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
161         fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
162                 let offer = offer.contents.clone();
163                 InvoiceRequestContentsWithoutPayerId {
164                         payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
165                         features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
166                 }
167         }
168
169         /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
170         /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
171         /// by the offer.
172         ///
173         /// Successive calls to this method will override the previous setting.
174         pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
175                 let chain = ChainHash::using_genesis_block(network);
176                 if !self.offer.supports_chain(chain) {
177                         return Err(SemanticError::UnsupportedChain);
178                 }
179
180                 self.invoice_request.chain = Some(chain);
181                 Ok(self)
182         }
183
184         /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
185         /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
186         ///
187         /// Successive calls to this method will override the previous setting.
188         ///
189         /// [`quantity`]: Self::quantity
190         pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
191                 self.invoice_request.offer.check_amount_msats_for_quantity(
192                         Some(amount_msats), self.invoice_request.quantity
193                 )?;
194                 self.invoice_request.amount_msats = Some(amount_msats);
195                 Ok(self)
196         }
197
198         /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
199         /// does not conform to [`Offer::is_valid_quantity`].
200         ///
201         /// Successive calls to this method will override the previous setting.
202         pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
203                 self.invoice_request.offer.check_quantity(Some(quantity))?;
204                 self.invoice_request.quantity = Some(quantity);
205                 Ok(self)
206         }
207
208         /// Sets the [`InvoiceRequest::payer_note`].
209         ///
210         /// Successive calls to this method will override the previous setting.
211         pub fn payer_note(mut self, payer_note: String) -> Self {
212                 self.invoice_request.payer_note = Some(payer_note);
213                 self
214         }
215
216         fn build_with_checks(mut self) -> Result<
217                 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>),
218                 SemanticError
219         > {
220                 #[cfg(feature = "std")] {
221                         if self.offer.is_expired() {
222                                 return Err(SemanticError::AlreadyExpired);
223                         }
224                 }
225
226                 let chain = self.invoice_request.chain();
227                 if !self.offer.supports_chain(chain) {
228                         return Err(SemanticError::UnsupportedChain);
229                 }
230
231                 if chain == self.offer.implied_chain() {
232                         self.invoice_request.chain = None;
233                 }
234
235                 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
236                         return Err(SemanticError::MissingAmount);
237                 }
238
239                 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
240                 self.invoice_request.offer.check_amount_msats_for_quantity(
241                         self.invoice_request.amount_msats, self.invoice_request.quantity
242                 )?;
243
244                 Ok(self.build_without_checks())
245         }
246
247         fn build_without_checks(mut self) ->
248                 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>)
249         {
250                 // Create the metadata for stateless verification of an Invoice.
251                 let mut keys = None;
252                 let secp_ctx = self.secp_ctx.clone();
253                 if self.invoice_request.payer.0.has_derivation_material() {
254                         let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
255
256                         let mut tlv_stream = self.invoice_request.as_tlv_stream();
257                         debug_assert!(tlv_stream.2.payer_id.is_none());
258                         tlv_stream.0.metadata = None;
259                         if !metadata.derives_keys() {
260                                 tlv_stream.2.payer_id = self.payer_id.as_ref();
261                         }
262
263                         let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
264                         metadata = derived_metadata;
265                         keys = derived_keys;
266                         if let Some(keys) = keys {
267                                 debug_assert!(self.payer_id.is_none());
268                                 self.payer_id = Some(keys.public_key());
269                         }
270
271                         self.invoice_request.payer.0 = metadata;
272                 }
273
274                 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
275                 debug_assert!(self.payer_id.is_some());
276                 let payer_id = self.payer_id.unwrap();
277
278                 let unsigned_invoice = UnsignedInvoiceRequest {
279                         offer: self.offer,
280                         invoice_request: InvoiceRequestContents {
281                                 inner: self.invoice_request,
282                                 payer_id,
283                         },
284                 };
285
286                 (unsigned_invoice, keys, secp_ctx)
287         }
288 }
289
290 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
291         /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
292         /// by [`UnsignedInvoiceRequest::sign`].
293         pub fn build(self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
294                 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
295                 debug_assert!(keys.is_none());
296                 Ok(unsigned_invoice_request)
297         }
298 }
299
300 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
301         /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
302         pub fn build_and_sign(self) -> Result<InvoiceRequest, SemanticError> {
303                 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
304                 debug_assert!(keys.is_some());
305
306                 let secp_ctx = secp_ctx.unwrap();
307                 let keys = keys.unwrap();
308                 let invoice_request = unsigned_invoice_request
309                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
310                         .unwrap();
311                 Ok(invoice_request)
312         }
313 }
314
315 #[cfg(test)]
316 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
317         fn chain_unchecked(mut self, network: Network) -> Self {
318                 let chain = ChainHash::using_genesis_block(network);
319                 self.invoice_request.chain = Some(chain);
320                 self
321         }
322
323         fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
324                 self.invoice_request.amount_msats = Some(amount_msats);
325                 self
326         }
327
328         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
329                 self.invoice_request.features = features;
330                 self
331         }
332
333         fn quantity_unchecked(mut self, quantity: u64) -> Self {
334                 self.invoice_request.quantity = Some(quantity);
335                 self
336         }
337
338         pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
339                 self.build_without_checks().0
340         }
341 }
342
343 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
344 pub struct UnsignedInvoiceRequest<'a> {
345         offer: &'a Offer,
346         invoice_request: InvoiceRequestContents,
347 }
348
349 impl<'a> UnsignedInvoiceRequest<'a> {
350         /// Signs the invoice request using the given function.
351         ///
352         /// This is not exported to bindings users as functions are not yet mapped.
353         pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
354         where
355                 F: FnOnce(&Message) -> Result<Signature, E>
356         {
357                 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
358                 // unknown TLV records, which are not stored in `OfferContents`.
359                 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
360                         self.invoice_request.as_tlv_stream();
361                 let offer_bytes = WithoutLength(&self.offer.bytes);
362                 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
363
364                 let mut bytes = Vec::new();
365                 unsigned_tlv_stream.write(&mut bytes).unwrap();
366
367                 let pubkey = self.invoice_request.payer_id;
368                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
369
370                 // Append the signature TLV record to the bytes.
371                 let signature_tlv_stream = SignatureTlvStreamRef {
372                         signature: Some(&signature),
373                 };
374                 signature_tlv_stream.write(&mut bytes).unwrap();
375
376                 Ok(InvoiceRequest {
377                         bytes,
378                         contents: self.invoice_request,
379                         signature,
380                 })
381         }
382 }
383
384 /// An `InvoiceRequest` is a request for an [`Invoice`] formulated from an [`Offer`].
385 ///
386 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
387 /// specifies these such that its recipient can send an invoice for payment.
388 ///
389 /// [`Invoice`]: crate::offers::invoice::Invoice
390 /// [`Offer`]: crate::offers::offer::Offer
391 #[derive(Clone, Debug)]
392 #[cfg_attr(test, derive(PartialEq))]
393 pub struct InvoiceRequest {
394         pub(super) bytes: Vec<u8>,
395         pub(super) contents: InvoiceRequestContents,
396         signature: Signature,
397 }
398
399 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Invoice`].
400 ///
401 /// [`Invoice`]: crate::offers::invoice::Invoice
402 #[derive(Clone, Debug)]
403 #[cfg_attr(test, derive(PartialEq))]
404 pub(super) struct InvoiceRequestContents {
405         pub(super) inner: InvoiceRequestContentsWithoutPayerId,
406         payer_id: PublicKey,
407 }
408
409 #[derive(Clone, Debug)]
410 #[cfg_attr(test, derive(PartialEq))]
411 pub(super) struct InvoiceRequestContentsWithoutPayerId {
412         payer: PayerContents,
413         pub(super) offer: OfferContents,
414         chain: Option<ChainHash>,
415         amount_msats: Option<u64>,
416         features: InvoiceRequestFeatures,
417         quantity: Option<u64>,
418         payer_note: Option<String>,
419 }
420
421 impl InvoiceRequest {
422         /// An unpredictable series of bytes, typically containing information about the derivation of
423         /// [`payer_id`].
424         ///
425         /// [`payer_id`]: Self::payer_id
426         pub fn metadata(&self) -> &[u8] {
427                 self.contents.metadata()
428         }
429
430         /// A chain from [`Offer::chains`] that the offer is valid for.
431         pub fn chain(&self) -> ChainHash {
432                 self.contents.chain()
433         }
434
435         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
436         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
437         ///
438         /// [`chain`]: Self::chain
439         pub fn amount_msats(&self) -> Option<u64> {
440                 self.contents.inner.amount_msats
441         }
442
443         /// Features pertaining to requesting an invoice.
444         pub fn features(&self) -> &InvoiceRequestFeatures {
445                 &self.contents.inner.features
446         }
447
448         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
449         pub fn quantity(&self) -> Option<u64> {
450                 self.contents.inner.quantity
451         }
452
453         /// A possibly transient pubkey used to sign the invoice request.
454         pub fn payer_id(&self) -> PublicKey {
455                 self.contents.payer_id
456         }
457
458         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
459         /// response.
460         pub fn payer_note(&self) -> Option<PrintableString> {
461                 self.contents.inner.payer_note.as_ref()
462                         .map(|payer_note| PrintableString(payer_note.as_str()))
463         }
464
465         /// Signature of the invoice request using [`payer_id`].
466         ///
467         /// This is not exported to bindings users as Signature is not yet mapped.
468         ///
469         /// [`payer_id`]: Self::payer_id
470         pub fn signature(&self) -> Signature {
471                 self.signature
472         }
473
474         /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
475         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
476         ///
477         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
478         /// creation time is used for the `created_at` parameter.
479         ///
480         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
481         ///
482         /// [`Duration`]: core::time::Duration
483         #[cfg(feature = "std")]
484         pub fn respond_with(
485                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
486         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
487                 let created_at = std::time::SystemTime::now()
488                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
489                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
490
491                 self.respond_with_no_std(payment_paths, payment_hash, created_at)
492         }
493
494         /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
495         ///
496         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
497         /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
498         /// [`std::time::SystemTime`] is not available.
499         ///
500         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
501         /// for the invoice.
502         ///
503         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
504         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
505         /// a preference. Note, however, that any privacy is lost if a public node id was used for
506         /// [`Offer::signing_pubkey`].
507         ///
508         /// Errors if the request contains unknown required features.
509         ///
510         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
511         ///
512         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
513         pub fn respond_with_no_std(
514                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
515                 created_at: core::time::Duration
516         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
517                 if self.features().requires_unknown_bits() {
518                         return Err(SemanticError::UnknownRequiredFeatures);
519                 }
520
521                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
522         }
523
524         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
525         /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
526         /// same [`ExpandedKey`] as the one used to create the offer.
527         ///
528         /// See [`InvoiceRequest::respond_with`] for further details.
529         ///
530         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
531         ///
532         /// [`Invoice`]: crate::offers::invoice::Invoice
533         #[cfg(feature = "std")]
534         pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
535                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
536                 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
537         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
538                 let created_at = std::time::SystemTime::now()
539                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
540                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
541
542                 self.verify_and_respond_using_derived_keys_no_std(
543                         payment_paths, payment_hash, created_at, expanded_key, secp_ctx
544                 )
545         }
546
547         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
548         /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
549         /// same [`ExpandedKey`] as the one used to create the offer.
550         ///
551         /// See [`InvoiceRequest::respond_with_no_std`] for further details.
552         ///
553         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
554         ///
555         /// [`Invoice`]: crate::offers::invoice::Invoice
556         pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
557                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
558                 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
559         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
560                 if self.features().requires_unknown_bits() {
561                         return Err(SemanticError::UnknownRequiredFeatures);
562                 }
563
564                 let keys = match self.verify(expanded_key, secp_ctx) {
565                         Err(()) => return Err(SemanticError::InvalidMetadata),
566                         Ok(None) => return Err(SemanticError::InvalidMetadata),
567                         Ok(Some(keys)) => keys,
568                 };
569
570                 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
571         }
572
573         /// Verifies that the request was for an offer created using the given key. Returns the derived
574         /// keys need to sign an [`Invoice`] for the request if they could be extracted from the
575         /// metadata.
576         ///
577         /// This is not exported to bindings users as KeyPair is not yet mapped.
578         ///
579         /// [`Invoice`]: crate::offers::invoice::Invoice
580         pub fn verify<T: secp256k1::Signing>(
581                 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
582         ) -> Result<Option<KeyPair>, ()> {
583                 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
584         }
585
586         #[cfg(test)]
587         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
588                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
589                         self.contents.as_tlv_stream();
590                 let signature_tlv_stream = SignatureTlvStreamRef {
591                         signature: Some(&self.signature),
592                 };
593                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
594         }
595 }
596
597 impl InvoiceRequestContents {
598         pub fn metadata(&self) -> &[u8] {
599                 self.inner.metadata()
600         }
601
602         pub(super) fn derives_keys(&self) -> bool {
603                 self.inner.payer.0.derives_keys()
604         }
605
606         pub(super) fn chain(&self) -> ChainHash {
607                 self.inner.chain()
608         }
609
610         pub(super) fn payer_id(&self) -> PublicKey {
611                 self.payer_id
612         }
613
614         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
615                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
616                 invoice_request.payer_id = Some(&self.payer_id);
617                 (payer, offer, invoice_request)
618         }
619 }
620
621 impl InvoiceRequestContentsWithoutPayerId {
622         pub(super) fn metadata(&self) -> &[u8] {
623                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
624         }
625
626         pub(super) fn chain(&self) -> ChainHash {
627                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
628         }
629
630         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
631                 let payer = PayerTlvStreamRef {
632                         metadata: self.payer.0.as_bytes(),
633                 };
634
635                 let offer = self.offer.as_tlv_stream();
636
637                 let features = {
638                         if self.features == InvoiceRequestFeatures::empty() { None }
639                         else { Some(&self.features) }
640                 };
641
642                 let invoice_request = InvoiceRequestTlvStreamRef {
643                         chain: self.chain.as_ref(),
644                         amount: self.amount_msats,
645                         features,
646                         quantity: self.quantity,
647                         payer_id: None,
648                         payer_note: self.payer_note.as_ref(),
649                 };
650
651                 (payer, offer, invoice_request)
652         }
653 }
654
655 impl Writeable for InvoiceRequest {
656         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
657                 WithoutLength(&self.bytes).write(writer)
658         }
659 }
660
661 impl Writeable for InvoiceRequestContents {
662         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
663                 self.as_tlv_stream().write(writer)
664         }
665 }
666
667 /// Valid type range for invoice_request TLV records.
668 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
669
670 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
671 ///
672 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
673 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
674
675 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
676         (80, chain: ChainHash),
677         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
678         (84, features: (InvoiceRequestFeatures, WithoutLength)),
679         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
680         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
681         (89, payer_note: (String, WithoutLength)),
682 });
683
684 type FullInvoiceRequestTlvStream =
685         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
686
687 #[cfg(test)]
688 type FullInvoiceRequestTlvStreamRef<'a> = (
689         PayerTlvStreamRef<'a>,
690         OfferTlvStreamRef<'a>,
691         InvoiceRequestTlvStreamRef<'a>,
692         SignatureTlvStreamRef<'a>,
693 );
694
695 impl SeekReadable for FullInvoiceRequestTlvStream {
696         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
697                 let payer = SeekReadable::read(r)?;
698                 let offer = SeekReadable::read(r)?;
699                 let invoice_request = SeekReadable::read(r)?;
700                 let signature = SeekReadable::read(r)?;
701
702                 Ok((payer, offer, invoice_request, signature))
703         }
704 }
705
706 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
707
708 type PartialInvoiceRequestTlvStreamRef<'a> = (
709         PayerTlvStreamRef<'a>,
710         OfferTlvStreamRef<'a>,
711         InvoiceRequestTlvStreamRef<'a>,
712 );
713
714 impl TryFrom<Vec<u8>> for InvoiceRequest {
715         type Error = ParseError;
716
717         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
718                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
719                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
720                 let (
721                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
722                         SignatureTlvStream { signature },
723                 ) = tlv_stream;
724                 let contents = InvoiceRequestContents::try_from(
725                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
726                 )?;
727
728                 let signature = match signature {
729                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
730                         Some(signature) => signature,
731                 };
732                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
733
734                 Ok(InvoiceRequest { bytes, contents, signature })
735         }
736 }
737
738 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
739         type Error = SemanticError;
740
741         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
742                 let (
743                         PayerTlvStream { metadata },
744                         offer_tlv_stream,
745                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
746                 ) = tlv_stream;
747
748                 let payer = match metadata {
749                         None => return Err(SemanticError::MissingPayerMetadata),
750                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
751                 };
752                 let offer = OfferContents::try_from(offer_tlv_stream)?;
753
754                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
755                         return Err(SemanticError::UnsupportedChain);
756                 }
757
758                 if offer.amount().is_none() && amount.is_none() {
759                         return Err(SemanticError::MissingAmount);
760                 }
761
762                 offer.check_quantity(quantity)?;
763                 offer.check_amount_msats_for_quantity(amount, quantity)?;
764
765                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
766
767                 let payer_id = match payer_id {
768                         None => return Err(SemanticError::MissingPayerId),
769                         Some(payer_id) => payer_id,
770                 };
771
772                 Ok(InvoiceRequestContents {
773                         inner: InvoiceRequestContentsWithoutPayerId {
774                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
775                         },
776                         payer_id,
777                 })
778         }
779 }
780
781 #[cfg(test)]
782 mod tests {
783         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
784
785         use bitcoin::blockdata::constants::ChainHash;
786         use bitcoin::network::constants::Network;
787         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
788         use core::convert::{Infallible, TryFrom};
789         use core::num::NonZeroU64;
790         #[cfg(feature = "std")]
791         use core::time::Duration;
792         use crate::chain::keysinterface::KeyMaterial;
793         use crate::ln::features::InvoiceRequestFeatures;
794         use crate::ln::inbound_payment::ExpandedKey;
795         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
796         use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
797         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
798         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
799         use crate::offers::parse::{ParseError, SemanticError};
800         use crate::offers::payer::PayerTlvStreamRef;
801         use crate::offers::test_utils::*;
802         use crate::util::ser::{BigSize, Writeable};
803         use crate::util::string::PrintableString;
804
805         #[test]
806         fn builds_invoice_request_with_defaults() {
807                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
808                         .amount_msats(1000)
809                         .build().unwrap()
810                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
811                         .build().unwrap()
812                         .sign(payer_sign).unwrap();
813
814                 let mut buffer = Vec::new();
815                 invoice_request.write(&mut buffer).unwrap();
816
817                 assert_eq!(invoice_request.bytes, buffer.as_slice());
818                 assert_eq!(invoice_request.metadata(), &[1; 32]);
819                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
820                 assert_eq!(invoice_request.amount_msats(), None);
821                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
822                 assert_eq!(invoice_request.quantity(), None);
823                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
824                 assert_eq!(invoice_request.payer_note(), None);
825                 assert!(
826                         merkle::verify_signature(
827                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
828                         ).is_ok()
829                 );
830
831                 assert_eq!(
832                         invoice_request.as_tlv_stream(),
833                         (
834                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
835                                 OfferTlvStreamRef {
836                                         chains: None,
837                                         metadata: None,
838                                         currency: None,
839                                         amount: Some(1000),
840                                         description: Some(&String::from("foo")),
841                                         features: None,
842                                         absolute_expiry: None,
843                                         paths: None,
844                                         issuer: None,
845                                         quantity_max: None,
846                                         node_id: Some(&recipient_pubkey()),
847                                 },
848                                 InvoiceRequestTlvStreamRef {
849                                         chain: None,
850                                         amount: None,
851                                         features: None,
852                                         quantity: None,
853                                         payer_id: Some(&payer_pubkey()),
854                                         payer_note: None,
855                                 },
856                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
857                         ),
858                 );
859
860                 if let Err(e) = InvoiceRequest::try_from(buffer) {
861                         panic!("error parsing invoice request: {:?}", e);
862                 }
863         }
864
865         #[cfg(feature = "std")]
866         #[test]
867         fn builds_invoice_request_from_offer_with_expiration() {
868                 let future_expiry = Duration::from_secs(u64::max_value());
869                 let past_expiry = Duration::from_secs(0);
870
871                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
872                         .amount_msats(1000)
873                         .absolute_expiry(future_expiry)
874                         .build().unwrap()
875                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
876                         .build()
877                 {
878                         panic!("error building invoice_request: {:?}", e);
879                 }
880
881                 match OfferBuilder::new("foo".into(), recipient_pubkey())
882                         .amount_msats(1000)
883                         .absolute_expiry(past_expiry)
884                         .build().unwrap()
885                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
886                         .build()
887                 {
888                         Ok(_) => panic!("expected error"),
889                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
890                 }
891         }
892
893         #[test]
894         fn builds_invoice_request_with_derived_metadata() {
895                 let payer_id = payer_pubkey();
896                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
897                 let entropy = FixedEntropy {};
898                 let secp_ctx = Secp256k1::new();
899
900                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
901                         .amount_msats(1000)
902                         .build().unwrap();
903                 let invoice_request = offer
904                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
905                         .unwrap()
906                         .build().unwrap()
907                         .sign(payer_sign).unwrap();
908                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
909
910                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
911                         .unwrap()
912                         .build().unwrap()
913                         .sign(recipient_sign).unwrap();
914                 assert!(invoice.verify(&expanded_key, &secp_ctx));
915
916                 // Fails verification with altered fields
917                 let (
918                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
919                         mut invoice_tlv_stream, mut signature_tlv_stream
920                 ) = invoice.as_tlv_stream();
921                 invoice_request_tlv_stream.amount = Some(2000);
922                 invoice_tlv_stream.amount = Some(2000);
923
924                 let tlv_stream =
925                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
926                 let mut bytes = Vec::new();
927                 tlv_stream.write(&mut bytes).unwrap();
928
929                 let signature = merkle::sign_message(
930                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
931                 ).unwrap();
932                 signature_tlv_stream.signature = Some(&signature);
933
934                 let mut encoded_invoice = bytes;
935                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
936
937                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
938                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
939
940                 // Fails verification with altered metadata
941                 let (
942                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
943                         mut signature_tlv_stream
944                 ) = invoice.as_tlv_stream();
945                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
946                 payer_tlv_stream.metadata = Some(&metadata);
947
948                 let tlv_stream =
949                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
950                 let mut bytes = Vec::new();
951                 tlv_stream.write(&mut bytes).unwrap();
952
953                 let signature = merkle::sign_message(
954                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
955                 ).unwrap();
956                 signature_tlv_stream.signature = Some(&signature);
957
958                 let mut encoded_invoice = bytes;
959                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
960
961                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
962                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
963         }
964
965         #[test]
966         fn builds_invoice_request_with_derived_payer_id() {
967                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
968                 let entropy = FixedEntropy {};
969                 let secp_ctx = Secp256k1::new();
970
971                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
972                         .amount_msats(1000)
973                         .build().unwrap();
974                 let invoice_request = offer
975                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
976                         .unwrap()
977                         .build_and_sign()
978                         .unwrap();
979
980                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
981                         .unwrap()
982                         .build().unwrap()
983                         .sign(recipient_sign).unwrap();
984                 assert!(invoice.verify(&expanded_key, &secp_ctx));
985
986                 // Fails verification with altered fields
987                 let (
988                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
989                         mut invoice_tlv_stream, mut signature_tlv_stream
990                 ) = invoice.as_tlv_stream();
991                 invoice_request_tlv_stream.amount = Some(2000);
992                 invoice_tlv_stream.amount = Some(2000);
993
994                 let tlv_stream =
995                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
996                 let mut bytes = Vec::new();
997                 tlv_stream.write(&mut bytes).unwrap();
998
999                 let signature = merkle::sign_message(
1000                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1001                 ).unwrap();
1002                 signature_tlv_stream.signature = Some(&signature);
1003
1004                 let mut encoded_invoice = bytes;
1005                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1006
1007                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1008                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1009
1010                 // Fails verification with altered payer id
1011                 let (
1012                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1013                         mut signature_tlv_stream
1014                 ) = invoice.as_tlv_stream();
1015                 let payer_id = pubkey(1);
1016                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1017
1018                 let tlv_stream =
1019                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1020                 let mut bytes = Vec::new();
1021                 tlv_stream.write(&mut bytes).unwrap();
1022
1023                 let signature = merkle::sign_message(
1024                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1025                 ).unwrap();
1026                 signature_tlv_stream.signature = Some(&signature);
1027
1028                 let mut encoded_invoice = bytes;
1029                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1030
1031                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1032                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1033         }
1034
1035         #[test]
1036         fn builds_invoice_request_with_chain() {
1037                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1038                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1039
1040                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1041                         .amount_msats(1000)
1042                         .build().unwrap()
1043                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1044                         .chain(Network::Bitcoin).unwrap()
1045                         .build().unwrap()
1046                         .sign(payer_sign).unwrap();
1047                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1048                 assert_eq!(invoice_request.chain(), mainnet);
1049                 assert_eq!(tlv_stream.chain, None);
1050
1051                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1052                         .amount_msats(1000)
1053                         .chain(Network::Testnet)
1054                         .build().unwrap()
1055                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1056                         .chain(Network::Testnet).unwrap()
1057                         .build().unwrap()
1058                         .sign(payer_sign).unwrap();
1059                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1060                 assert_eq!(invoice_request.chain(), testnet);
1061                 assert_eq!(tlv_stream.chain, Some(&testnet));
1062
1063                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1064                         .amount_msats(1000)
1065                         .chain(Network::Bitcoin)
1066                         .chain(Network::Testnet)
1067                         .build().unwrap()
1068                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1069                         .chain(Network::Bitcoin).unwrap()
1070                         .build().unwrap()
1071                         .sign(payer_sign).unwrap();
1072                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1073                 assert_eq!(invoice_request.chain(), mainnet);
1074                 assert_eq!(tlv_stream.chain, None);
1075
1076                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1077                         .amount_msats(1000)
1078                         .chain(Network::Bitcoin)
1079                         .chain(Network::Testnet)
1080                         .build().unwrap()
1081                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1082                         .chain(Network::Bitcoin).unwrap()
1083                         .chain(Network::Testnet).unwrap()
1084                         .build().unwrap()
1085                         .sign(payer_sign).unwrap();
1086                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1087                 assert_eq!(invoice_request.chain(), testnet);
1088                 assert_eq!(tlv_stream.chain, Some(&testnet));
1089
1090                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1091                         .amount_msats(1000)
1092                         .chain(Network::Testnet)
1093                         .build().unwrap()
1094                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1095                         .chain(Network::Bitcoin)
1096                 {
1097                         Ok(_) => panic!("expected error"),
1098                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1099                 }
1100
1101                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1102                         .amount_msats(1000)
1103                         .chain(Network::Testnet)
1104                         .build().unwrap()
1105                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1106                         .build()
1107                 {
1108                         Ok(_) => panic!("expected error"),
1109                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1110                 }
1111         }
1112
1113         #[test]
1114         fn builds_invoice_request_with_amount() {
1115                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1116                         .amount_msats(1000)
1117                         .build().unwrap()
1118                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1119                         .amount_msats(1000).unwrap()
1120                         .build().unwrap()
1121                         .sign(payer_sign).unwrap();
1122                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1123                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1124                 assert_eq!(tlv_stream.amount, Some(1000));
1125
1126                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1127                         .amount_msats(1000)
1128                         .build().unwrap()
1129                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1130                         .amount_msats(1001).unwrap()
1131                         .amount_msats(1000).unwrap()
1132                         .build().unwrap()
1133                         .sign(payer_sign).unwrap();
1134                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1135                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1136                 assert_eq!(tlv_stream.amount, Some(1000));
1137
1138                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1139                         .amount_msats(1000)
1140                         .build().unwrap()
1141                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142                         .amount_msats(1001).unwrap()
1143                         .build().unwrap()
1144                         .sign(payer_sign).unwrap();
1145                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1146                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1147                 assert_eq!(tlv_stream.amount, Some(1001));
1148
1149                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1150                         .amount_msats(1000)
1151                         .build().unwrap()
1152                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1153                         .amount_msats(999)
1154                 {
1155                         Ok(_) => panic!("expected error"),
1156                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1157                 }
1158
1159                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1160                         .amount_msats(1000)
1161                         .supported_quantity(Quantity::Unbounded)
1162                         .build().unwrap()
1163                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164                         .quantity(2).unwrap()
1165                         .amount_msats(1000)
1166                 {
1167                         Ok(_) => panic!("expected error"),
1168                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1169                 }
1170
1171                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1172                         .amount_msats(1000)
1173                         .build().unwrap()
1174                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1175                         .amount_msats(MAX_VALUE_MSAT + 1)
1176                 {
1177                         Ok(_) => panic!("expected error"),
1178                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1179                 }
1180
1181                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1182                         .amount_msats(1000)
1183                         .supported_quantity(Quantity::Unbounded)
1184                         .build().unwrap()
1185                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186                         .amount_msats(1000).unwrap()
1187                         .quantity(2).unwrap()
1188                         .build()
1189                 {
1190                         Ok(_) => panic!("expected error"),
1191                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1192                 }
1193
1194                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1195                         .build().unwrap()
1196                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1197                         .build()
1198                 {
1199                         Ok(_) => panic!("expected error"),
1200                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1201                 }
1202
1203                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1204                         .amount_msats(1000)
1205                         .supported_quantity(Quantity::Unbounded)
1206                         .build().unwrap()
1207                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1208                         .quantity(u64::max_value()).unwrap()
1209                         .build()
1210                 {
1211                         Ok(_) => panic!("expected error"),
1212                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1213                 }
1214         }
1215
1216         #[test]
1217         fn builds_invoice_request_with_features() {
1218                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1219                         .amount_msats(1000)
1220                         .build().unwrap()
1221                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1222                         .features_unchecked(InvoiceRequestFeatures::unknown())
1223                         .build().unwrap()
1224                         .sign(payer_sign).unwrap();
1225                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1226                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1227                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1228
1229                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1230                         .amount_msats(1000)
1231                         .build().unwrap()
1232                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1233                         .features_unchecked(InvoiceRequestFeatures::unknown())
1234                         .features_unchecked(InvoiceRequestFeatures::empty())
1235                         .build().unwrap()
1236                         .sign(payer_sign).unwrap();
1237                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1238                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1239                 assert_eq!(tlv_stream.features, None);
1240         }
1241
1242         #[test]
1243         fn builds_invoice_request_with_quantity() {
1244                 let one = NonZeroU64::new(1).unwrap();
1245                 let ten = NonZeroU64::new(10).unwrap();
1246
1247                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1248                         .amount_msats(1000)
1249                         .supported_quantity(Quantity::One)
1250                         .build().unwrap()
1251                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1252                         .build().unwrap()
1253                         .sign(payer_sign).unwrap();
1254                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1255                 assert_eq!(invoice_request.quantity(), None);
1256                 assert_eq!(tlv_stream.quantity, None);
1257
1258                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1259                         .amount_msats(1000)
1260                         .supported_quantity(Quantity::One)
1261                         .build().unwrap()
1262                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1263                         .amount_msats(2_000).unwrap()
1264                         .quantity(2)
1265                 {
1266                         Ok(_) => panic!("expected error"),
1267                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1268                 }
1269
1270                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1271                         .amount_msats(1000)
1272                         .supported_quantity(Quantity::Bounded(ten))
1273                         .build().unwrap()
1274                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275                         .amount_msats(10_000).unwrap()
1276                         .quantity(10).unwrap()
1277                         .build().unwrap()
1278                         .sign(payer_sign).unwrap();
1279                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1280                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1281                 assert_eq!(tlv_stream.amount, Some(10_000));
1282
1283                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1284                         .amount_msats(1000)
1285                         .supported_quantity(Quantity::Bounded(ten))
1286                         .build().unwrap()
1287                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288                         .amount_msats(11_000).unwrap()
1289                         .quantity(11)
1290                 {
1291                         Ok(_) => panic!("expected error"),
1292                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1293                 }
1294
1295                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1296                         .amount_msats(1000)
1297                         .supported_quantity(Quantity::Unbounded)
1298                         .build().unwrap()
1299                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1300                         .amount_msats(2_000).unwrap()
1301                         .quantity(2).unwrap()
1302                         .build().unwrap()
1303                         .sign(payer_sign).unwrap();
1304                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1305                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1306                 assert_eq!(tlv_stream.amount, Some(2_000));
1307
1308                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1309                         .amount_msats(1000)
1310                         .supported_quantity(Quantity::Unbounded)
1311                         .build().unwrap()
1312                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1313                         .build()
1314                 {
1315                         Ok(_) => panic!("expected error"),
1316                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1317                 }
1318
1319                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1320                         .amount_msats(1000)
1321                         .supported_quantity(Quantity::Bounded(one))
1322                         .build().unwrap()
1323                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1324                         .build()
1325                 {
1326                         Ok(_) => panic!("expected error"),
1327                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1328                 }
1329         }
1330
1331         #[test]
1332         fn builds_invoice_request_with_payer_note() {
1333                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1334                         .amount_msats(1000)
1335                         .build().unwrap()
1336                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1337                         .payer_note("bar".into())
1338                         .build().unwrap()
1339                         .sign(payer_sign).unwrap();
1340                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1341                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1342                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1343
1344                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1345                         .amount_msats(1000)
1346                         .build().unwrap()
1347                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1348                         .payer_note("bar".into())
1349                         .payer_note("baz".into())
1350                         .build().unwrap()
1351                         .sign(payer_sign).unwrap();
1352                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1353                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1354                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1355         }
1356
1357         #[test]
1358         fn fails_signing_invoice_request() {
1359                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1360                         .amount_msats(1000)
1361                         .build().unwrap()
1362                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1363                         .build().unwrap()
1364                         .sign(|_| Err(()))
1365                 {
1366                         Ok(_) => panic!("expected error"),
1367                         Err(e) => assert_eq!(e, SignError::Signing(())),
1368                 }
1369
1370                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1371                         .amount_msats(1000)
1372                         .build().unwrap()
1373                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1374                         .build().unwrap()
1375                         .sign(recipient_sign)
1376                 {
1377                         Ok(_) => panic!("expected error"),
1378                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1379                 }
1380         }
1381
1382         #[test]
1383         fn fails_responding_with_unknown_required_features() {
1384                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1385                         .amount_msats(1000)
1386                         .build().unwrap()
1387                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1388                         .features_unchecked(InvoiceRequestFeatures::unknown())
1389                         .build().unwrap()
1390                         .sign(payer_sign).unwrap()
1391                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1392                 {
1393                         Ok(_) => panic!("expected error"),
1394                         Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1395                 }
1396         }
1397
1398         #[test]
1399         fn parses_invoice_request_with_metadata() {
1400                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1401                         .amount_msats(1000)
1402                         .build().unwrap()
1403                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1404                         .build().unwrap()
1405                         .sign(payer_sign).unwrap();
1406
1407                 let mut buffer = Vec::new();
1408                 invoice_request.write(&mut buffer).unwrap();
1409
1410                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1411                         panic!("error parsing invoice_request: {:?}", e);
1412                 }
1413         }
1414
1415         #[test]
1416         fn parses_invoice_request_with_chain() {
1417                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1418                         .amount_msats(1000)
1419                         .build().unwrap()
1420                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1421                         .chain(Network::Bitcoin).unwrap()
1422                         .build().unwrap()
1423                         .sign(payer_sign).unwrap();
1424
1425                 let mut buffer = Vec::new();
1426                 invoice_request.write(&mut buffer).unwrap();
1427
1428                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1429                         panic!("error parsing invoice_request: {:?}", e);
1430                 }
1431
1432                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1433                         .amount_msats(1000)
1434                         .build().unwrap()
1435                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1436                         .chain_unchecked(Network::Testnet)
1437                         .build_unchecked()
1438                         .sign(payer_sign).unwrap();
1439
1440                 let mut buffer = Vec::new();
1441                 invoice_request.write(&mut buffer).unwrap();
1442
1443                 match InvoiceRequest::try_from(buffer) {
1444                         Ok(_) => panic!("expected error"),
1445                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1446                 }
1447         }
1448
1449         #[test]
1450         fn parses_invoice_request_with_amount() {
1451                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1452                         .amount_msats(1000)
1453                         .build().unwrap()
1454                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1455                         .build().unwrap()
1456                         .sign(payer_sign).unwrap();
1457
1458                 let mut buffer = Vec::new();
1459                 invoice_request.write(&mut buffer).unwrap();
1460
1461                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1462                         panic!("error parsing invoice_request: {:?}", e);
1463                 }
1464
1465                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1466                         .build().unwrap()
1467                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1468                         .amount_msats(1000).unwrap()
1469                         .build().unwrap()
1470                         .sign(payer_sign).unwrap();
1471
1472                 let mut buffer = Vec::new();
1473                 invoice_request.write(&mut buffer).unwrap();
1474
1475                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1476                         panic!("error parsing invoice_request: {:?}", e);
1477                 }
1478
1479                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1480                         .build().unwrap()
1481                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1482                         .build_unchecked()
1483                         .sign(payer_sign).unwrap();
1484
1485                 let mut buffer = Vec::new();
1486                 invoice_request.write(&mut buffer).unwrap();
1487
1488                 match InvoiceRequest::try_from(buffer) {
1489                         Ok(_) => panic!("expected error"),
1490                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1491                 }
1492
1493                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1494                         .amount_msats(1000)
1495                         .build().unwrap()
1496                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1497                         .amount_msats_unchecked(999)
1498                         .build_unchecked()
1499                         .sign(payer_sign).unwrap();
1500
1501                 let mut buffer = Vec::new();
1502                 invoice_request.write(&mut buffer).unwrap();
1503
1504                 match InvoiceRequest::try_from(buffer) {
1505                         Ok(_) => panic!("expected error"),
1506                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1507                 }
1508
1509                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1510                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1511                         .build_unchecked()
1512                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1513                         .build_unchecked()
1514                         .sign(payer_sign).unwrap();
1515
1516                 let mut buffer = Vec::new();
1517                 invoice_request.write(&mut buffer).unwrap();
1518
1519                 match InvoiceRequest::try_from(buffer) {
1520                         Ok(_) => panic!("expected error"),
1521                         Err(e) => {
1522                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1523                         },
1524                 }
1525
1526                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1527                         .amount_msats(1000)
1528                         .supported_quantity(Quantity::Unbounded)
1529                         .build().unwrap()
1530                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531                         .quantity(u64::max_value()).unwrap()
1532                         .build_unchecked()
1533                         .sign(payer_sign).unwrap();
1534
1535                 let mut buffer = Vec::new();
1536                 invoice_request.write(&mut buffer).unwrap();
1537
1538                 match InvoiceRequest::try_from(buffer) {
1539                         Ok(_) => panic!("expected error"),
1540                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1541                 }
1542         }
1543
1544         #[test]
1545         fn parses_invoice_request_with_quantity() {
1546                 let one = NonZeroU64::new(1).unwrap();
1547                 let ten = NonZeroU64::new(10).unwrap();
1548
1549                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1550                         .amount_msats(1000)
1551                         .supported_quantity(Quantity::One)
1552                         .build().unwrap()
1553                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1554                         .build().unwrap()
1555                         .sign(payer_sign).unwrap();
1556
1557                 let mut buffer = Vec::new();
1558                 invoice_request.write(&mut buffer).unwrap();
1559
1560                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1561                         panic!("error parsing invoice_request: {:?}", e);
1562                 }
1563
1564                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1565                         .amount_msats(1000)
1566                         .supported_quantity(Quantity::One)
1567                         .build().unwrap()
1568                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1569                         .amount_msats(2_000).unwrap()
1570                         .quantity_unchecked(2)
1571                         .build_unchecked()
1572                         .sign(payer_sign).unwrap();
1573
1574                 let mut buffer = Vec::new();
1575                 invoice_request.write(&mut buffer).unwrap();
1576
1577                 match InvoiceRequest::try_from(buffer) {
1578                         Ok(_) => panic!("expected error"),
1579                         Err(e) => {
1580                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1581                         },
1582                 }
1583
1584                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1585                         .amount_msats(1000)
1586                         .supported_quantity(Quantity::Bounded(ten))
1587                         .build().unwrap()
1588                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1589                         .amount_msats(10_000).unwrap()
1590                         .quantity(10).unwrap()
1591                         .build().unwrap()
1592                         .sign(payer_sign).unwrap();
1593
1594                 let mut buffer = Vec::new();
1595                 invoice_request.write(&mut buffer).unwrap();
1596
1597                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1598                         panic!("error parsing invoice_request: {:?}", e);
1599                 }
1600
1601                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1602                         .amount_msats(1000)
1603                         .supported_quantity(Quantity::Bounded(ten))
1604                         .build().unwrap()
1605                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1606                         .amount_msats(11_000).unwrap()
1607                         .quantity_unchecked(11)
1608                         .build_unchecked()
1609                         .sign(payer_sign).unwrap();
1610
1611                 let mut buffer = Vec::new();
1612                 invoice_request.write(&mut buffer).unwrap();
1613
1614                 match InvoiceRequest::try_from(buffer) {
1615                         Ok(_) => panic!("expected error"),
1616                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1617                 }
1618
1619                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1620                         .amount_msats(1000)
1621                         .supported_quantity(Quantity::Unbounded)
1622                         .build().unwrap()
1623                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1624                         .amount_msats(2_000).unwrap()
1625                         .quantity(2).unwrap()
1626                         .build().unwrap()
1627                         .sign(payer_sign).unwrap();
1628
1629                 let mut buffer = Vec::new();
1630                 invoice_request.write(&mut buffer).unwrap();
1631
1632                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1633                         panic!("error parsing invoice_request: {:?}", e);
1634                 }
1635
1636                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1637                         .amount_msats(1000)
1638                         .supported_quantity(Quantity::Unbounded)
1639                         .build().unwrap()
1640                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1641                         .build_unchecked()
1642                         .sign(payer_sign).unwrap();
1643
1644                 let mut buffer = Vec::new();
1645                 invoice_request.write(&mut buffer).unwrap();
1646
1647                 match InvoiceRequest::try_from(buffer) {
1648                         Ok(_) => panic!("expected error"),
1649                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1650                 }
1651
1652                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1653                         .amount_msats(1000)
1654                         .supported_quantity(Quantity::Bounded(one))
1655                         .build().unwrap()
1656                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1657                         .build_unchecked()
1658                         .sign(payer_sign).unwrap();
1659
1660                 let mut buffer = Vec::new();
1661                 invoice_request.write(&mut buffer).unwrap();
1662
1663                 match InvoiceRequest::try_from(buffer) {
1664                         Ok(_) => panic!("expected error"),
1665                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1666                 }
1667         }
1668
1669         #[test]
1670         fn fails_parsing_invoice_request_without_metadata() {
1671                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1672                         .amount_msats(1000)
1673                         .build().unwrap();
1674                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1675                         .build().unwrap();
1676                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1677                 tlv_stream.0.metadata = None;
1678
1679                 let mut buffer = Vec::new();
1680                 tlv_stream.write(&mut buffer).unwrap();
1681
1682                 match InvoiceRequest::try_from(buffer) {
1683                         Ok(_) => panic!("expected error"),
1684                         Err(e) => {
1685                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1686                         },
1687                 }
1688         }
1689
1690         #[test]
1691         fn fails_parsing_invoice_request_without_payer_id() {
1692                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1693                         .amount_msats(1000)
1694                         .build().unwrap();
1695                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1696                         .build().unwrap();
1697                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1698                 tlv_stream.2.payer_id = None;
1699
1700                 let mut buffer = Vec::new();
1701                 tlv_stream.write(&mut buffer).unwrap();
1702
1703                 match InvoiceRequest::try_from(buffer) {
1704                         Ok(_) => panic!("expected error"),
1705                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1706                 }
1707         }
1708
1709         #[test]
1710         fn fails_parsing_invoice_request_without_node_id() {
1711                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1712                         .amount_msats(1000)
1713                         .build().unwrap();
1714                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715                         .build().unwrap();
1716                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1717                 tlv_stream.1.node_id = None;
1718
1719                 let mut buffer = Vec::new();
1720                 tlv_stream.write(&mut buffer).unwrap();
1721
1722                 match InvoiceRequest::try_from(buffer) {
1723                         Ok(_) => panic!("expected error"),
1724                         Err(e) => {
1725                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1726                         },
1727                 }
1728         }
1729
1730         #[test]
1731         fn fails_parsing_invoice_request_without_signature() {
1732                 let mut buffer = Vec::new();
1733                 OfferBuilder::new("foo".into(), recipient_pubkey())
1734                         .amount_msats(1000)
1735                         .build().unwrap()
1736                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1737                         .build().unwrap()
1738                         .invoice_request
1739                         .write(&mut buffer).unwrap();
1740
1741                 match InvoiceRequest::try_from(buffer) {
1742                         Ok(_) => panic!("expected error"),
1743                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1744                 }
1745         }
1746
1747         #[test]
1748         fn fails_parsing_invoice_request_with_invalid_signature() {
1749                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1750                         .amount_msats(1000)
1751                         .build().unwrap()
1752                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1753                         .build().unwrap()
1754                         .sign(payer_sign).unwrap();
1755                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1756                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1757
1758                 let mut buffer = Vec::new();
1759                 invoice_request.write(&mut buffer).unwrap();
1760
1761                 match InvoiceRequest::try_from(buffer) {
1762                         Ok(_) => panic!("expected error"),
1763                         Err(e) => {
1764                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1765                         },
1766                 }
1767         }
1768
1769         #[test]
1770         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1771                 let secp_ctx = Secp256k1::new();
1772                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1773                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1774                         .amount_msats(1000)
1775                         .build().unwrap()
1776                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1777                         .build().unwrap()
1778                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1779                         .unwrap();
1780
1781                 let mut encoded_invoice_request = Vec::new();
1782                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1783                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1784                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1785                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1786
1787                 match InvoiceRequest::try_from(encoded_invoice_request) {
1788                         Ok(_) => panic!("expected error"),
1789                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1790                 }
1791         }
1792 }