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