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