]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/offers/invoice_request.rs
Merge pull request #2226 from alecchendev/2023-04-persist-network-graph-on-rgs
[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::sign::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         /// [`payer_id`]: Self::payer_id
468         pub fn signature(&self) -> Signature {
469                 self.signature
470         }
471
472         /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
473         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
474         ///
475         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
476         /// creation time is used for the `created_at` parameter.
477         ///
478         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
479         ///
480         /// [`Duration`]: core::time::Duration
481         #[cfg(feature = "std")]
482         pub fn respond_with(
483                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
484         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
485                 let created_at = std::time::SystemTime::now()
486                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
487                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
488
489                 self.respond_with_no_std(payment_paths, payment_hash, created_at)
490         }
491
492         /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
493         ///
494         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
495         /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
496         /// [`std::time::SystemTime`] is not available.
497         ///
498         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
499         /// for the invoice.
500         ///
501         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
502         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
503         /// a preference. Note, however, that any privacy is lost if a public node id was used for
504         /// [`Offer::signing_pubkey`].
505         ///
506         /// Errors if the request contains unknown required features.
507         ///
508         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
509         ///
510         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
511         pub fn respond_with_no_std(
512                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
513                 created_at: core::time::Duration
514         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
515                 if self.features().requires_unknown_bits() {
516                         return Err(SemanticError::UnknownRequiredFeatures);
517                 }
518
519                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
520         }
521
522         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
523         /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
524         /// same [`ExpandedKey`] as the one used to create the offer.
525         ///
526         /// See [`InvoiceRequest::respond_with`] for further details.
527         ///
528         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
529         ///
530         /// [`Invoice`]: crate::offers::invoice::Invoice
531         #[cfg(feature = "std")]
532         pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
533                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
534                 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
535         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
536                 let created_at = std::time::SystemTime::now()
537                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
538                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
539
540                 self.verify_and_respond_using_derived_keys_no_std(
541                         payment_paths, payment_hash, created_at, expanded_key, secp_ctx
542                 )
543         }
544
545         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
546         /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
547         /// same [`ExpandedKey`] as the one used to create the offer.
548         ///
549         /// See [`InvoiceRequest::respond_with_no_std`] for further details.
550         ///
551         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
552         ///
553         /// [`Invoice`]: crate::offers::invoice::Invoice
554         pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
555                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
556                 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
557         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
558                 if self.features().requires_unknown_bits() {
559                         return Err(SemanticError::UnknownRequiredFeatures);
560                 }
561
562                 let keys = match self.verify(expanded_key, secp_ctx) {
563                         Err(()) => return Err(SemanticError::InvalidMetadata),
564                         Ok(None) => return Err(SemanticError::InvalidMetadata),
565                         Ok(Some(keys)) => keys,
566                 };
567
568                 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
569         }
570
571         /// Verifies that the request was for an offer created using the given key. Returns the derived
572         /// keys need to sign an [`Invoice`] for the request if they could be extracted from the
573         /// metadata.
574         ///
575         /// [`Invoice`]: crate::offers::invoice::Invoice
576         pub fn verify<T: secp256k1::Signing>(
577                 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
578         ) -> Result<Option<KeyPair>, ()> {
579                 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
580         }
581
582         #[cfg(test)]
583         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
584                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
585                         self.contents.as_tlv_stream();
586                 let signature_tlv_stream = SignatureTlvStreamRef {
587                         signature: Some(&self.signature),
588                 };
589                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
590         }
591 }
592
593 impl InvoiceRequestContents {
594         pub fn metadata(&self) -> &[u8] {
595                 self.inner.metadata()
596         }
597
598         pub(super) fn derives_keys(&self) -> bool {
599                 self.inner.payer.0.derives_keys()
600         }
601
602         pub(super) fn chain(&self) -> ChainHash {
603                 self.inner.chain()
604         }
605
606         pub(super) fn payer_id(&self) -> PublicKey {
607                 self.payer_id
608         }
609
610         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
611                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
612                 invoice_request.payer_id = Some(&self.payer_id);
613                 (payer, offer, invoice_request)
614         }
615 }
616
617 impl InvoiceRequestContentsWithoutPayerId {
618         pub(super) fn metadata(&self) -> &[u8] {
619                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
620         }
621
622         pub(super) fn chain(&self) -> ChainHash {
623                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
624         }
625
626         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
627                 let payer = PayerTlvStreamRef {
628                         metadata: self.payer.0.as_bytes(),
629                 };
630
631                 let offer = self.offer.as_tlv_stream();
632
633                 let features = {
634                         if self.features == InvoiceRequestFeatures::empty() { None }
635                         else { Some(&self.features) }
636                 };
637
638                 let invoice_request = InvoiceRequestTlvStreamRef {
639                         chain: self.chain.as_ref(),
640                         amount: self.amount_msats,
641                         features,
642                         quantity: self.quantity,
643                         payer_id: None,
644                         payer_note: self.payer_note.as_ref(),
645                 };
646
647                 (payer, offer, invoice_request)
648         }
649 }
650
651 impl Writeable for InvoiceRequest {
652         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
653                 WithoutLength(&self.bytes).write(writer)
654         }
655 }
656
657 impl Writeable for InvoiceRequestContents {
658         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
659                 self.as_tlv_stream().write(writer)
660         }
661 }
662
663 /// Valid type range for invoice_request TLV records.
664 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
665
666 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
667 ///
668 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
669 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
670
671 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
672         (80, chain: ChainHash),
673         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
674         (84, features: (InvoiceRequestFeatures, WithoutLength)),
675         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
676         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
677         (89, payer_note: (String, WithoutLength)),
678 });
679
680 type FullInvoiceRequestTlvStream =
681         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
682
683 #[cfg(test)]
684 type FullInvoiceRequestTlvStreamRef<'a> = (
685         PayerTlvStreamRef<'a>,
686         OfferTlvStreamRef<'a>,
687         InvoiceRequestTlvStreamRef<'a>,
688         SignatureTlvStreamRef<'a>,
689 );
690
691 impl SeekReadable for FullInvoiceRequestTlvStream {
692         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
693                 let payer = SeekReadable::read(r)?;
694                 let offer = SeekReadable::read(r)?;
695                 let invoice_request = SeekReadable::read(r)?;
696                 let signature = SeekReadable::read(r)?;
697
698                 Ok((payer, offer, invoice_request, signature))
699         }
700 }
701
702 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
703
704 type PartialInvoiceRequestTlvStreamRef<'a> = (
705         PayerTlvStreamRef<'a>,
706         OfferTlvStreamRef<'a>,
707         InvoiceRequestTlvStreamRef<'a>,
708 );
709
710 impl TryFrom<Vec<u8>> for InvoiceRequest {
711         type Error = ParseError;
712
713         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
714                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
715                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
716                 let (
717                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
718                         SignatureTlvStream { signature },
719                 ) = tlv_stream;
720                 let contents = InvoiceRequestContents::try_from(
721                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
722                 )?;
723
724                 let signature = match signature {
725                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
726                         Some(signature) => signature,
727                 };
728                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
729
730                 Ok(InvoiceRequest { bytes, contents, signature })
731         }
732 }
733
734 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
735         type Error = SemanticError;
736
737         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
738                 let (
739                         PayerTlvStream { metadata },
740                         offer_tlv_stream,
741                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
742                 ) = tlv_stream;
743
744                 let payer = match metadata {
745                         None => return Err(SemanticError::MissingPayerMetadata),
746                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
747                 };
748                 let offer = OfferContents::try_from(offer_tlv_stream)?;
749
750                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
751                         return Err(SemanticError::UnsupportedChain);
752                 }
753
754                 if offer.amount().is_none() && amount.is_none() {
755                         return Err(SemanticError::MissingAmount);
756                 }
757
758                 offer.check_quantity(quantity)?;
759                 offer.check_amount_msats_for_quantity(amount, quantity)?;
760
761                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
762
763                 let payer_id = match payer_id {
764                         None => return Err(SemanticError::MissingPayerId),
765                         Some(payer_id) => payer_id,
766                 };
767
768                 Ok(InvoiceRequestContents {
769                         inner: InvoiceRequestContentsWithoutPayerId {
770                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
771                         },
772                         payer_id,
773                 })
774         }
775 }
776
777 #[cfg(test)]
778 mod tests {
779         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
780
781         use bitcoin::blockdata::constants::ChainHash;
782         use bitcoin::network::constants::Network;
783         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
784         use core::convert::{Infallible, TryFrom};
785         use core::num::NonZeroU64;
786         #[cfg(feature = "std")]
787         use core::time::Duration;
788         use crate::sign::KeyMaterial;
789         use crate::ln::features::InvoiceRequestFeatures;
790         use crate::ln::inbound_payment::ExpandedKey;
791         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
792         use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
793         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
794         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
795         use crate::offers::parse::{ParseError, SemanticError};
796         use crate::offers::payer::PayerTlvStreamRef;
797         use crate::offers::test_utils::*;
798         use crate::util::ser::{BigSize, Writeable};
799         use crate::util::string::PrintableString;
800
801         #[test]
802         fn builds_invoice_request_with_defaults() {
803                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
804                         .amount_msats(1000)
805                         .build().unwrap()
806                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
807                         .build().unwrap()
808                         .sign(payer_sign).unwrap();
809
810                 let mut buffer = Vec::new();
811                 invoice_request.write(&mut buffer).unwrap();
812
813                 assert_eq!(invoice_request.bytes, buffer.as_slice());
814                 assert_eq!(invoice_request.metadata(), &[1; 32]);
815                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
816                 assert_eq!(invoice_request.amount_msats(), None);
817                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
818                 assert_eq!(invoice_request.quantity(), None);
819                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
820                 assert_eq!(invoice_request.payer_note(), None);
821                 assert!(
822                         merkle::verify_signature(
823                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
824                         ).is_ok()
825                 );
826
827                 assert_eq!(
828                         invoice_request.as_tlv_stream(),
829                         (
830                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
831                                 OfferTlvStreamRef {
832                                         chains: None,
833                                         metadata: None,
834                                         currency: None,
835                                         amount: Some(1000),
836                                         description: Some(&String::from("foo")),
837                                         features: None,
838                                         absolute_expiry: None,
839                                         paths: None,
840                                         issuer: None,
841                                         quantity_max: None,
842                                         node_id: Some(&recipient_pubkey()),
843                                 },
844                                 InvoiceRequestTlvStreamRef {
845                                         chain: None,
846                                         amount: None,
847                                         features: None,
848                                         quantity: None,
849                                         payer_id: Some(&payer_pubkey()),
850                                         payer_note: None,
851                                 },
852                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
853                         ),
854                 );
855
856                 if let Err(e) = InvoiceRequest::try_from(buffer) {
857                         panic!("error parsing invoice request: {:?}", e);
858                 }
859         }
860
861         #[cfg(feature = "std")]
862         #[test]
863         fn builds_invoice_request_from_offer_with_expiration() {
864                 let future_expiry = Duration::from_secs(u64::max_value());
865                 let past_expiry = Duration::from_secs(0);
866
867                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
868                         .amount_msats(1000)
869                         .absolute_expiry(future_expiry)
870                         .build().unwrap()
871                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
872                         .build()
873                 {
874                         panic!("error building invoice_request: {:?}", e);
875                 }
876
877                 match OfferBuilder::new("foo".into(), recipient_pubkey())
878                         .amount_msats(1000)
879                         .absolute_expiry(past_expiry)
880                         .build().unwrap()
881                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
882                         .build()
883                 {
884                         Ok(_) => panic!("expected error"),
885                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
886                 }
887         }
888
889         #[test]
890         fn builds_invoice_request_with_derived_metadata() {
891                 let payer_id = payer_pubkey();
892                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
893                 let entropy = FixedEntropy {};
894                 let secp_ctx = Secp256k1::new();
895
896                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
897                         .amount_msats(1000)
898                         .build().unwrap();
899                 let invoice_request = offer
900                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
901                         .unwrap()
902                         .build().unwrap()
903                         .sign(payer_sign).unwrap();
904                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
905
906                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
907                         .unwrap()
908                         .build().unwrap()
909                         .sign(recipient_sign).unwrap();
910                 assert!(invoice.verify(&expanded_key, &secp_ctx));
911
912                 // Fails verification with altered fields
913                 let (
914                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
915                         mut invoice_tlv_stream, mut signature_tlv_stream
916                 ) = invoice.as_tlv_stream();
917                 invoice_request_tlv_stream.amount = Some(2000);
918                 invoice_tlv_stream.amount = Some(2000);
919
920                 let tlv_stream =
921                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
922                 let mut bytes = Vec::new();
923                 tlv_stream.write(&mut bytes).unwrap();
924
925                 let signature = merkle::sign_message(
926                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
927                 ).unwrap();
928                 signature_tlv_stream.signature = Some(&signature);
929
930                 let mut encoded_invoice = bytes;
931                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
932
933                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
934                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
935
936                 // Fails verification with altered metadata
937                 let (
938                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
939                         mut signature_tlv_stream
940                 ) = invoice.as_tlv_stream();
941                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
942                 payer_tlv_stream.metadata = Some(&metadata);
943
944                 let tlv_stream =
945                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
946                 let mut bytes = Vec::new();
947                 tlv_stream.write(&mut bytes).unwrap();
948
949                 let signature = merkle::sign_message(
950                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
951                 ).unwrap();
952                 signature_tlv_stream.signature = Some(&signature);
953
954                 let mut encoded_invoice = bytes;
955                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
956
957                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
958                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
959         }
960
961         #[test]
962         fn builds_invoice_request_with_derived_payer_id() {
963                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
964                 let entropy = FixedEntropy {};
965                 let secp_ctx = Secp256k1::new();
966
967                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
968                         .amount_msats(1000)
969                         .build().unwrap();
970                 let invoice_request = offer
971                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
972                         .unwrap()
973                         .build_and_sign()
974                         .unwrap();
975
976                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
977                         .unwrap()
978                         .build().unwrap()
979                         .sign(recipient_sign).unwrap();
980                 assert!(invoice.verify(&expanded_key, &secp_ctx));
981
982                 // Fails verification with altered fields
983                 let (
984                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
985                         mut invoice_tlv_stream, mut signature_tlv_stream
986                 ) = invoice.as_tlv_stream();
987                 invoice_request_tlv_stream.amount = Some(2000);
988                 invoice_tlv_stream.amount = Some(2000);
989
990                 let tlv_stream =
991                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
992                 let mut bytes = Vec::new();
993                 tlv_stream.write(&mut bytes).unwrap();
994
995                 let signature = merkle::sign_message(
996                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
997                 ).unwrap();
998                 signature_tlv_stream.signature = Some(&signature);
999
1000                 let mut encoded_invoice = bytes;
1001                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1002
1003                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1004                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1005
1006                 // Fails verification with altered payer id
1007                 let (
1008                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1009                         mut signature_tlv_stream
1010                 ) = invoice.as_tlv_stream();
1011                 let payer_id = pubkey(1);
1012                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1013
1014                 let tlv_stream =
1015                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1016                 let mut bytes = Vec::new();
1017                 tlv_stream.write(&mut bytes).unwrap();
1018
1019                 let signature = merkle::sign_message(
1020                         recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1021                 ).unwrap();
1022                 signature_tlv_stream.signature = Some(&signature);
1023
1024                 let mut encoded_invoice = bytes;
1025                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1026
1027                 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1028                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1029         }
1030
1031         #[test]
1032         fn builds_invoice_request_with_chain() {
1033                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1034                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1035
1036                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1037                         .amount_msats(1000)
1038                         .build().unwrap()
1039                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1040                         .chain(Network::Bitcoin).unwrap()
1041                         .build().unwrap()
1042                         .sign(payer_sign).unwrap();
1043                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1044                 assert_eq!(invoice_request.chain(), mainnet);
1045                 assert_eq!(tlv_stream.chain, None);
1046
1047                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1048                         .amount_msats(1000)
1049                         .chain(Network::Testnet)
1050                         .build().unwrap()
1051                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1052                         .chain(Network::Testnet).unwrap()
1053                         .build().unwrap()
1054                         .sign(payer_sign).unwrap();
1055                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1056                 assert_eq!(invoice_request.chain(), testnet);
1057                 assert_eq!(tlv_stream.chain, Some(&testnet));
1058
1059                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1060                         .amount_msats(1000)
1061                         .chain(Network::Bitcoin)
1062                         .chain(Network::Testnet)
1063                         .build().unwrap()
1064                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1065                         .chain(Network::Bitcoin).unwrap()
1066                         .build().unwrap()
1067                         .sign(payer_sign).unwrap();
1068                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1069                 assert_eq!(invoice_request.chain(), mainnet);
1070                 assert_eq!(tlv_stream.chain, None);
1071
1072                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1073                         .amount_msats(1000)
1074                         .chain(Network::Bitcoin)
1075                         .chain(Network::Testnet)
1076                         .build().unwrap()
1077                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1078                         .chain(Network::Bitcoin).unwrap()
1079                         .chain(Network::Testnet).unwrap()
1080                         .build().unwrap()
1081                         .sign(payer_sign).unwrap();
1082                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1083                 assert_eq!(invoice_request.chain(), testnet);
1084                 assert_eq!(tlv_stream.chain, Some(&testnet));
1085
1086                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1087                         .amount_msats(1000)
1088                         .chain(Network::Testnet)
1089                         .build().unwrap()
1090                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1091                         .chain(Network::Bitcoin)
1092                 {
1093                         Ok(_) => panic!("expected error"),
1094                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1095                 }
1096
1097                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1098                         .amount_msats(1000)
1099                         .chain(Network::Testnet)
1100                         .build().unwrap()
1101                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1102                         .build()
1103                 {
1104                         Ok(_) => panic!("expected error"),
1105                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1106                 }
1107         }
1108
1109         #[test]
1110         fn builds_invoice_request_with_amount() {
1111                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1112                         .amount_msats(1000)
1113                         .build().unwrap()
1114                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1115                         .amount_msats(1000).unwrap()
1116                         .build().unwrap()
1117                         .sign(payer_sign).unwrap();
1118                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1119                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1120                 assert_eq!(tlv_stream.amount, Some(1000));
1121
1122                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1123                         .amount_msats(1000)
1124                         .build().unwrap()
1125                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1126                         .amount_msats(1001).unwrap()
1127                         .amount_msats(1000).unwrap()
1128                         .build().unwrap()
1129                         .sign(payer_sign).unwrap();
1130                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1131                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1132                 assert_eq!(tlv_stream.amount, Some(1000));
1133
1134                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1135                         .amount_msats(1000)
1136                         .build().unwrap()
1137                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1138                         .amount_msats(1001).unwrap()
1139                         .build().unwrap()
1140                         .sign(payer_sign).unwrap();
1141                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1142                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1143                 assert_eq!(tlv_stream.amount, Some(1001));
1144
1145                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1146                         .amount_msats(1000)
1147                         .build().unwrap()
1148                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1149                         .amount_msats(999)
1150                 {
1151                         Ok(_) => panic!("expected error"),
1152                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1153                 }
1154
1155                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1156                         .amount_msats(1000)
1157                         .supported_quantity(Quantity::Unbounded)
1158                         .build().unwrap()
1159                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1160                         .quantity(2).unwrap()
1161                         .amount_msats(1000)
1162                 {
1163                         Ok(_) => panic!("expected error"),
1164                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1165                 }
1166
1167                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1168                         .amount_msats(1000)
1169                         .build().unwrap()
1170                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1171                         .amount_msats(MAX_VALUE_MSAT + 1)
1172                 {
1173                         Ok(_) => panic!("expected error"),
1174                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1175                 }
1176
1177                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1178                         .amount_msats(1000)
1179                         .supported_quantity(Quantity::Unbounded)
1180                         .build().unwrap()
1181                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1182                         .amount_msats(1000).unwrap()
1183                         .quantity(2).unwrap()
1184                         .build()
1185                 {
1186                         Ok(_) => panic!("expected error"),
1187                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1188                 }
1189
1190                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1191                         .build().unwrap()
1192                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1193                         .build()
1194                 {
1195                         Ok(_) => panic!("expected error"),
1196                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1197                 }
1198
1199                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1200                         .amount_msats(1000)
1201                         .supported_quantity(Quantity::Unbounded)
1202                         .build().unwrap()
1203                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1204                         .quantity(u64::max_value()).unwrap()
1205                         .build()
1206                 {
1207                         Ok(_) => panic!("expected error"),
1208                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1209                 }
1210         }
1211
1212         #[test]
1213         fn builds_invoice_request_with_features() {
1214                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1215                         .amount_msats(1000)
1216                         .build().unwrap()
1217                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1218                         .features_unchecked(InvoiceRequestFeatures::unknown())
1219                         .build().unwrap()
1220                         .sign(payer_sign).unwrap();
1221                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1222                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1223                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1224
1225                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1226                         .amount_msats(1000)
1227                         .build().unwrap()
1228                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229                         .features_unchecked(InvoiceRequestFeatures::unknown())
1230                         .features_unchecked(InvoiceRequestFeatures::empty())
1231                         .build().unwrap()
1232                         .sign(payer_sign).unwrap();
1233                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1234                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1235                 assert_eq!(tlv_stream.features, None);
1236         }
1237
1238         #[test]
1239         fn builds_invoice_request_with_quantity() {
1240                 let one = NonZeroU64::new(1).unwrap();
1241                 let ten = NonZeroU64::new(10).unwrap();
1242
1243                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1244                         .amount_msats(1000)
1245                         .supported_quantity(Quantity::One)
1246                         .build().unwrap()
1247                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248                         .build().unwrap()
1249                         .sign(payer_sign).unwrap();
1250                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1251                 assert_eq!(invoice_request.quantity(), None);
1252                 assert_eq!(tlv_stream.quantity, None);
1253
1254                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1255                         .amount_msats(1000)
1256                         .supported_quantity(Quantity::One)
1257                         .build().unwrap()
1258                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1259                         .amount_msats(2_000).unwrap()
1260                         .quantity(2)
1261                 {
1262                         Ok(_) => panic!("expected error"),
1263                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1264                 }
1265
1266                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1267                         .amount_msats(1000)
1268                         .supported_quantity(Quantity::Bounded(ten))
1269                         .build().unwrap()
1270                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271                         .amount_msats(10_000).unwrap()
1272                         .quantity(10).unwrap()
1273                         .build().unwrap()
1274                         .sign(payer_sign).unwrap();
1275                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1276                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1277                 assert_eq!(tlv_stream.amount, Some(10_000));
1278
1279                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1280                         .amount_msats(1000)
1281                         .supported_quantity(Quantity::Bounded(ten))
1282                         .build().unwrap()
1283                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1284                         .amount_msats(11_000).unwrap()
1285                         .quantity(11)
1286                 {
1287                         Ok(_) => panic!("expected error"),
1288                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1289                 }
1290
1291                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1292                         .amount_msats(1000)
1293                         .supported_quantity(Quantity::Unbounded)
1294                         .build().unwrap()
1295                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1296                         .amount_msats(2_000).unwrap()
1297                         .quantity(2).unwrap()
1298                         .build().unwrap()
1299                         .sign(payer_sign).unwrap();
1300                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1301                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1302                 assert_eq!(tlv_stream.amount, Some(2_000));
1303
1304                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1305                         .amount_msats(1000)
1306                         .supported_quantity(Quantity::Unbounded)
1307                         .build().unwrap()
1308                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1309                         .build()
1310                 {
1311                         Ok(_) => panic!("expected error"),
1312                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1313                 }
1314
1315                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1316                         .amount_msats(1000)
1317                         .supported_quantity(Quantity::Bounded(one))
1318                         .build().unwrap()
1319                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1320                         .build()
1321                 {
1322                         Ok(_) => panic!("expected error"),
1323                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1324                 }
1325         }
1326
1327         #[test]
1328         fn builds_invoice_request_with_payer_note() {
1329                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1330                         .amount_msats(1000)
1331                         .build().unwrap()
1332                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1333                         .payer_note("bar".into())
1334                         .build().unwrap()
1335                         .sign(payer_sign).unwrap();
1336                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1337                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1338                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1339
1340                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1341                         .amount_msats(1000)
1342                         .build().unwrap()
1343                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344                         .payer_note("bar".into())
1345                         .payer_note("baz".into())
1346                         .build().unwrap()
1347                         .sign(payer_sign).unwrap();
1348                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1349                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1350                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1351         }
1352
1353         #[test]
1354         fn fails_signing_invoice_request() {
1355                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1356                         .amount_msats(1000)
1357                         .build().unwrap()
1358                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359                         .build().unwrap()
1360                         .sign(|_| Err(()))
1361                 {
1362                         Ok(_) => panic!("expected error"),
1363                         Err(e) => assert_eq!(e, SignError::Signing(())),
1364                 }
1365
1366                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1367                         .amount_msats(1000)
1368                         .build().unwrap()
1369                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1370                         .build().unwrap()
1371                         .sign(recipient_sign)
1372                 {
1373                         Ok(_) => panic!("expected error"),
1374                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1375                 }
1376         }
1377
1378         #[test]
1379         fn fails_responding_with_unknown_required_features() {
1380                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1381                         .amount_msats(1000)
1382                         .build().unwrap()
1383                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1384                         .features_unchecked(InvoiceRequestFeatures::unknown())
1385                         .build().unwrap()
1386                         .sign(payer_sign).unwrap()
1387                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1388                 {
1389                         Ok(_) => panic!("expected error"),
1390                         Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1391                 }
1392         }
1393
1394         #[test]
1395         fn parses_invoice_request_with_metadata() {
1396                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1397                         .amount_msats(1000)
1398                         .build().unwrap()
1399                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1400                         .build().unwrap()
1401                         .sign(payer_sign).unwrap();
1402
1403                 let mut buffer = Vec::new();
1404                 invoice_request.write(&mut buffer).unwrap();
1405
1406                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1407                         panic!("error parsing invoice_request: {:?}", e);
1408                 }
1409         }
1410
1411         #[test]
1412         fn parses_invoice_request_with_chain() {
1413                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1414                         .amount_msats(1000)
1415                         .build().unwrap()
1416                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1417                         .chain(Network::Bitcoin).unwrap()
1418                         .build().unwrap()
1419                         .sign(payer_sign).unwrap();
1420
1421                 let mut buffer = Vec::new();
1422                 invoice_request.write(&mut buffer).unwrap();
1423
1424                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1425                         panic!("error parsing invoice_request: {:?}", e);
1426                 }
1427
1428                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1429                         .amount_msats(1000)
1430                         .build().unwrap()
1431                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1432                         .chain_unchecked(Network::Testnet)
1433                         .build_unchecked()
1434                         .sign(payer_sign).unwrap();
1435
1436                 let mut buffer = Vec::new();
1437                 invoice_request.write(&mut buffer).unwrap();
1438
1439                 match InvoiceRequest::try_from(buffer) {
1440                         Ok(_) => panic!("expected error"),
1441                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1442                 }
1443         }
1444
1445         #[test]
1446         fn parses_invoice_request_with_amount() {
1447                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1448                         .amount_msats(1000)
1449                         .build().unwrap()
1450                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1451                         .build().unwrap()
1452                         .sign(payer_sign).unwrap();
1453
1454                 let mut buffer = Vec::new();
1455                 invoice_request.write(&mut buffer).unwrap();
1456
1457                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1458                         panic!("error parsing invoice_request: {:?}", e);
1459                 }
1460
1461                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1462                         .build().unwrap()
1463                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1464                         .amount_msats(1000).unwrap()
1465                         .build().unwrap()
1466                         .sign(payer_sign).unwrap();
1467
1468                 let mut buffer = Vec::new();
1469                 invoice_request.write(&mut buffer).unwrap();
1470
1471                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1472                         panic!("error parsing invoice_request: {:?}", e);
1473                 }
1474
1475                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1476                         .build().unwrap()
1477                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1478                         .build_unchecked()
1479                         .sign(payer_sign).unwrap();
1480
1481                 let mut buffer = Vec::new();
1482                 invoice_request.write(&mut buffer).unwrap();
1483
1484                 match InvoiceRequest::try_from(buffer) {
1485                         Ok(_) => panic!("expected error"),
1486                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1487                 }
1488
1489                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1490                         .amount_msats(1000)
1491                         .build().unwrap()
1492                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493                         .amount_msats_unchecked(999)
1494                         .build_unchecked()
1495                         .sign(payer_sign).unwrap();
1496
1497                 let mut buffer = Vec::new();
1498                 invoice_request.write(&mut buffer).unwrap();
1499
1500                 match InvoiceRequest::try_from(buffer) {
1501                         Ok(_) => panic!("expected error"),
1502                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1503                 }
1504
1505                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1506                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1507                         .build_unchecked()
1508                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1509                         .build_unchecked()
1510                         .sign(payer_sign).unwrap();
1511
1512                 let mut buffer = Vec::new();
1513                 invoice_request.write(&mut buffer).unwrap();
1514
1515                 match InvoiceRequest::try_from(buffer) {
1516                         Ok(_) => panic!("expected error"),
1517                         Err(e) => {
1518                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1519                         },
1520                 }
1521
1522                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1523                         .amount_msats(1000)
1524                         .supported_quantity(Quantity::Unbounded)
1525                         .build().unwrap()
1526                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1527                         .quantity(u64::max_value()).unwrap()
1528                         .build_unchecked()
1529                         .sign(payer_sign).unwrap();
1530
1531                 let mut buffer = Vec::new();
1532                 invoice_request.write(&mut buffer).unwrap();
1533
1534                 match InvoiceRequest::try_from(buffer) {
1535                         Ok(_) => panic!("expected error"),
1536                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1537                 }
1538         }
1539
1540         #[test]
1541         fn parses_invoice_request_with_quantity() {
1542                 let one = NonZeroU64::new(1).unwrap();
1543                 let ten = NonZeroU64::new(10).unwrap();
1544
1545                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1546                         .amount_msats(1000)
1547                         .supported_quantity(Quantity::One)
1548                         .build().unwrap()
1549                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1550                         .build().unwrap()
1551                         .sign(payer_sign).unwrap();
1552
1553                 let mut buffer = Vec::new();
1554                 invoice_request.write(&mut buffer).unwrap();
1555
1556                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1557                         panic!("error parsing invoice_request: {:?}", e);
1558                 }
1559
1560                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1561                         .amount_msats(1000)
1562                         .supported_quantity(Quantity::One)
1563                         .build().unwrap()
1564                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1565                         .amount_msats(2_000).unwrap()
1566                         .quantity_unchecked(2)
1567                         .build_unchecked()
1568                         .sign(payer_sign).unwrap();
1569
1570                 let mut buffer = Vec::new();
1571                 invoice_request.write(&mut buffer).unwrap();
1572
1573                 match InvoiceRequest::try_from(buffer) {
1574                         Ok(_) => panic!("expected error"),
1575                         Err(e) => {
1576                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1577                         },
1578                 }
1579
1580                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1581                         .amount_msats(1000)
1582                         .supported_quantity(Quantity::Bounded(ten))
1583                         .build().unwrap()
1584                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1585                         .amount_msats(10_000).unwrap()
1586                         .quantity(10).unwrap()
1587                         .build().unwrap()
1588                         .sign(payer_sign).unwrap();
1589
1590                 let mut buffer = Vec::new();
1591                 invoice_request.write(&mut buffer).unwrap();
1592
1593                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1594                         panic!("error parsing invoice_request: {:?}", e);
1595                 }
1596
1597                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1598                         .amount_msats(1000)
1599                         .supported_quantity(Quantity::Bounded(ten))
1600                         .build().unwrap()
1601                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1602                         .amount_msats(11_000).unwrap()
1603                         .quantity_unchecked(11)
1604                         .build_unchecked()
1605                         .sign(payer_sign).unwrap();
1606
1607                 let mut buffer = Vec::new();
1608                 invoice_request.write(&mut buffer).unwrap();
1609
1610                 match InvoiceRequest::try_from(buffer) {
1611                         Ok(_) => panic!("expected error"),
1612                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1613                 }
1614
1615                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1616                         .amount_msats(1000)
1617                         .supported_quantity(Quantity::Unbounded)
1618                         .build().unwrap()
1619                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620                         .amount_msats(2_000).unwrap()
1621                         .quantity(2).unwrap()
1622                         .build().unwrap()
1623                         .sign(payer_sign).unwrap();
1624
1625                 let mut buffer = Vec::new();
1626                 invoice_request.write(&mut buffer).unwrap();
1627
1628                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1629                         panic!("error parsing invoice_request: {:?}", e);
1630                 }
1631
1632                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1633                         .amount_msats(1000)
1634                         .supported_quantity(Quantity::Unbounded)
1635                         .build().unwrap()
1636                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1637                         .build_unchecked()
1638                         .sign(payer_sign).unwrap();
1639
1640                 let mut buffer = Vec::new();
1641                 invoice_request.write(&mut buffer).unwrap();
1642
1643                 match InvoiceRequest::try_from(buffer) {
1644                         Ok(_) => panic!("expected error"),
1645                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1646                 }
1647
1648                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1649                         .amount_msats(1000)
1650                         .supported_quantity(Quantity::Bounded(one))
1651                         .build().unwrap()
1652                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1653                         .build_unchecked()
1654                         .sign(payer_sign).unwrap();
1655
1656                 let mut buffer = Vec::new();
1657                 invoice_request.write(&mut buffer).unwrap();
1658
1659                 match InvoiceRequest::try_from(buffer) {
1660                         Ok(_) => panic!("expected error"),
1661                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1662                 }
1663         }
1664
1665         #[test]
1666         fn fails_parsing_invoice_request_without_metadata() {
1667                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1668                         .amount_msats(1000)
1669                         .build().unwrap();
1670                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1671                         .build().unwrap();
1672                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1673                 tlv_stream.0.metadata = None;
1674
1675                 let mut buffer = Vec::new();
1676                 tlv_stream.write(&mut buffer).unwrap();
1677
1678                 match InvoiceRequest::try_from(buffer) {
1679                         Ok(_) => panic!("expected error"),
1680                         Err(e) => {
1681                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1682                         },
1683                 }
1684         }
1685
1686         #[test]
1687         fn fails_parsing_invoice_request_without_payer_id() {
1688                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1689                         .amount_msats(1000)
1690                         .build().unwrap();
1691                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1692                         .build().unwrap();
1693                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1694                 tlv_stream.2.payer_id = None;
1695
1696                 let mut buffer = Vec::new();
1697                 tlv_stream.write(&mut buffer).unwrap();
1698
1699                 match InvoiceRequest::try_from(buffer) {
1700                         Ok(_) => panic!("expected error"),
1701                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1702                 }
1703         }
1704
1705         #[test]
1706         fn fails_parsing_invoice_request_without_node_id() {
1707                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1708                         .amount_msats(1000)
1709                         .build().unwrap();
1710                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1711                         .build().unwrap();
1712                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1713                 tlv_stream.1.node_id = None;
1714
1715                 let mut buffer = Vec::new();
1716                 tlv_stream.write(&mut buffer).unwrap();
1717
1718                 match InvoiceRequest::try_from(buffer) {
1719                         Ok(_) => panic!("expected error"),
1720                         Err(e) => {
1721                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1722                         },
1723                 }
1724         }
1725
1726         #[test]
1727         fn fails_parsing_invoice_request_without_signature() {
1728                 let mut buffer = Vec::new();
1729                 OfferBuilder::new("foo".into(), recipient_pubkey())
1730                         .amount_msats(1000)
1731                         .build().unwrap()
1732                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1733                         .build().unwrap()
1734                         .invoice_request
1735                         .write(&mut buffer).unwrap();
1736
1737                 match InvoiceRequest::try_from(buffer) {
1738                         Ok(_) => panic!("expected error"),
1739                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1740                 }
1741         }
1742
1743         #[test]
1744         fn fails_parsing_invoice_request_with_invalid_signature() {
1745                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1746                         .amount_msats(1000)
1747                         .build().unwrap()
1748                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1749                         .build().unwrap()
1750                         .sign(payer_sign).unwrap();
1751                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1752                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1753
1754                 let mut buffer = Vec::new();
1755                 invoice_request.write(&mut buffer).unwrap();
1756
1757                 match InvoiceRequest::try_from(buffer) {
1758                         Ok(_) => panic!("expected error"),
1759                         Err(e) => {
1760                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1761                         },
1762                 }
1763         }
1764
1765         #[test]
1766         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1767                 let secp_ctx = Secp256k1::new();
1768                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1769                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1770                         .amount_msats(1000)
1771                         .build().unwrap()
1772                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1773                         .build().unwrap()
1774                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1775                         .unwrap();
1776
1777                 let mut encoded_invoice_request = Vec::new();
1778                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1779                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1780                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1781                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1782
1783                 match InvoiceRequest::try_from(encoded_invoice_request) {
1784                         Ok(_) => panic!("expected error"),
1785                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1786                 }
1787         }
1788 }