690bc8d0bdb72d03fc0914b628ed1842a0ef9701
[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 //! [`Refund`]: crate::offers::refund::Refund
20 //!
21 //! ```ignore
22 //! extern crate bitcoin;
23 //! extern crate lightning;
24 //!
25 //! use bitcoin::network::constants::Network;
26 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
27 //! use core::convert::Infallible;
28 //! use lightning::ln::features::OfferFeatures;
29 //! use lightning::offers::offer::Offer;
30 //! use lightning::util::ser::Writeable;
31 //!
32 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
33 //! let secp_ctx = Secp256k1::new();
34 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
35 //! let pubkey = PublicKey::from(keys);
36 //! let mut buffer = Vec::new();
37 //!
38 //! "lno1qcp4256ypq"
39 //!     .parse::<Offer>()?
40 //!     .request_invoice(vec![42; 64], pubkey)?
41 //!     .chain(Network::Testnet)?
42 //!     .amount_msats(1000)?
43 //!     .quantity(5)?
44 //!     .payer_note("foo".to_string())
45 //!     .build()?
46 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
47 //!     .expect("failed verifying signature")
48 //!     .write(&mut buffer)
49 //!     .unwrap();
50 //! # Ok(())
51 //! # }
52 //! ```
53
54 use bitcoin::blockdata::constants::ChainHash;
55 use bitcoin::network::constants::Network;
56 use bitcoin::secp256k1::{Message, PublicKey};
57 use bitcoin::secp256k1::schnorr::Signature;
58 use core::convert::TryFrom;
59 use crate::io;
60 use crate::ln::features::InvoiceRequestFeatures;
61 use crate::ln::msgs::DecodeError;
62 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
63 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
64 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
65 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
66 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
67 use crate::util::string::PrintableString;
68
69 use crate::prelude::*;
70
71 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
72
73 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
74 ///
75 /// See [module-level documentation] for usage.
76 ///
77 /// [module-level documentation]: self
78 pub struct InvoiceRequestBuilder<'a> {
79         offer: &'a Offer,
80         invoice_request: InvoiceRequestContents,
81 }
82
83 impl<'a> InvoiceRequestBuilder<'a> {
84         pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
85                 Self {
86                         offer,
87                         invoice_request: InvoiceRequestContents {
88                                 payer: PayerContents(metadata), offer: offer.contents.clone(), chain: None,
89                                 amount_msats: None, features: InvoiceRequestFeatures::empty(), quantity: None,
90                                 payer_id, payer_note: None,
91                         },
92                 }
93         }
94
95         /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
96         /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
97         /// by the offer.
98         ///
99         /// Successive calls to this method will override the previous setting.
100         pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
101                 let chain = ChainHash::using_genesis_block(network);
102                 if !self.offer.supports_chain(chain) {
103                         return Err(SemanticError::UnsupportedChain);
104                 }
105
106                 self.invoice_request.chain = Some(chain);
107                 Ok(self)
108         }
109
110         /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
111         /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
112         ///
113         /// Successive calls to this method will override the previous setting.
114         ///
115         /// [`quantity`]: Self::quantity
116         pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
117                 self.invoice_request.offer.check_amount_msats_for_quantity(
118                         Some(amount_msats), self.invoice_request.quantity
119                 )?;
120                 self.invoice_request.amount_msats = Some(amount_msats);
121                 Ok(self)
122         }
123
124         /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
125         /// does not conform to [`Offer::is_valid_quantity`].
126         ///
127         /// Successive calls to this method will override the previous setting.
128         pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
129                 self.invoice_request.offer.check_quantity(Some(quantity))?;
130                 self.invoice_request.quantity = Some(quantity);
131                 Ok(self)
132         }
133
134         /// Sets the [`InvoiceRequest::payer_note`].
135         ///
136         /// Successive calls to this method will override the previous setting.
137         pub fn payer_note(mut self, payer_note: String) -> Self {
138                 self.invoice_request.payer_note = Some(payer_note);
139                 self
140         }
141
142         /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
143         /// by [`UnsignedInvoiceRequest::sign`].
144         pub fn build(mut self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
145                 #[cfg(feature = "std")] {
146                         if self.offer.is_expired() {
147                                 return Err(SemanticError::AlreadyExpired);
148                         }
149                 }
150
151                 let chain = self.invoice_request.chain();
152                 if !self.offer.supports_chain(chain) {
153                         return Err(SemanticError::UnsupportedChain);
154                 }
155
156                 if chain == self.offer.implied_chain() {
157                         self.invoice_request.chain = None;
158                 }
159
160                 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
161                         return Err(SemanticError::MissingAmount);
162                 }
163
164                 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
165                 self.invoice_request.offer.check_amount_msats_for_quantity(
166                         self.invoice_request.amount_msats, self.invoice_request.quantity
167                 )?;
168
169                 let InvoiceRequestBuilder { offer, invoice_request } = self;
170                 Ok(UnsignedInvoiceRequest { offer, invoice_request })
171         }
172 }
173
174 #[cfg(test)]
175 impl<'a> InvoiceRequestBuilder<'a> {
176         fn chain_unchecked(mut self, network: Network) -> Self {
177                 let chain = ChainHash::using_genesis_block(network);
178                 self.invoice_request.chain = Some(chain);
179                 self
180         }
181
182         fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
183                 self.invoice_request.amount_msats = Some(amount_msats);
184                 self
185         }
186
187         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
188                 self.invoice_request.features = features;
189                 self
190         }
191
192         fn quantity_unchecked(mut self, quantity: u64) -> Self {
193                 self.invoice_request.quantity = Some(quantity);
194                 self
195         }
196
197         pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
198                 let InvoiceRequestBuilder { offer, invoice_request } = self;
199                 UnsignedInvoiceRequest { offer, invoice_request }
200         }
201 }
202
203 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
204 pub struct UnsignedInvoiceRequest<'a> {
205         offer: &'a Offer,
206         invoice_request: InvoiceRequestContents,
207 }
208
209 impl<'a> UnsignedInvoiceRequest<'a> {
210         /// Signs the invoice request using the given function.
211         pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
212         where
213                 F: FnOnce(&Message) -> Result<Signature, E>
214         {
215                 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
216                 // unknown TLV records, which are not stored in `OfferContents`.
217                 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
218                         self.invoice_request.as_tlv_stream();
219                 let offer_bytes = WithoutLength(&self.offer.bytes);
220                 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
221
222                 let mut bytes = Vec::new();
223                 unsigned_tlv_stream.write(&mut bytes).unwrap();
224
225                 let pubkey = self.invoice_request.payer_id;
226                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
227
228                 // Append the signature TLV record to the bytes.
229                 let signature_tlv_stream = SignatureTlvStreamRef {
230                         signature: Some(&signature),
231                 };
232                 signature_tlv_stream.write(&mut bytes).unwrap();
233
234                 Ok(InvoiceRequest {
235                         bytes,
236                         contents: self.invoice_request,
237                         signature,
238                 })
239         }
240 }
241
242 /// An `InvoiceRequest` is a request for an `Invoice` formulated from an [`Offer`].
243 ///
244 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
245 /// specifies these such that its recipient can send an invoice for payment.
246 ///
247 /// [`Offer`]: crate::offers::offer::Offer
248 #[derive(Clone, Debug)]
249 pub struct InvoiceRequest {
250         pub(super) bytes: Vec<u8>,
251         contents: InvoiceRequestContents,
252         signature: Signature,
253 }
254
255 /// The contents of an [`InvoiceRequest`], which may be shared with an `Invoice`.
256 #[derive(Clone, Debug)]
257 pub(super) struct InvoiceRequestContents {
258         payer: PayerContents,
259         offer: OfferContents,
260         chain: Option<ChainHash>,
261         amount_msats: Option<u64>,
262         features: InvoiceRequestFeatures,
263         quantity: Option<u64>,
264         payer_id: PublicKey,
265         payer_note: Option<String>,
266 }
267
268 impl InvoiceRequest {
269         /// An unpredictable series of bytes, typically containing information about the derivation of
270         /// [`payer_id`].
271         ///
272         /// [`payer_id`]: Self::payer_id
273         pub fn metadata(&self) -> &[u8] {
274                 &self.contents.payer.0[..]
275         }
276
277         /// A chain from [`Offer::chains`] that the offer is valid for.
278         pub fn chain(&self) -> ChainHash {
279                 self.contents.chain()
280         }
281
282         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
283         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
284         ///
285         /// [`chain`]: Self::chain
286         pub fn amount_msats(&self) -> Option<u64> {
287                 self.contents.amount_msats
288         }
289
290         /// Features pertaining to requesting an invoice.
291         pub fn features(&self) -> &InvoiceRequestFeatures {
292                 &self.contents.features
293         }
294
295         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
296         pub fn quantity(&self) -> Option<u64> {
297                 self.contents.quantity
298         }
299
300         /// A possibly transient pubkey used to sign the invoice request.
301         pub fn payer_id(&self) -> PublicKey {
302                 self.contents.payer_id
303         }
304
305         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
306         /// response.
307         pub fn payer_note(&self) -> Option<PrintableString> {
308                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
309         }
310
311         /// Signature of the invoice request using [`payer_id`].
312         ///
313         /// [`payer_id`]: Self::payer_id
314         pub fn signature(&self) -> Signature {
315                 self.signature
316         }
317
318         #[cfg(test)]
319         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
320                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
321                         self.contents.as_tlv_stream();
322                 let signature_tlv_stream = SignatureTlvStreamRef {
323                         signature: Some(&self.signature),
324                 };
325                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
326         }
327 }
328
329 impl InvoiceRequestContents {
330         fn chain(&self) -> ChainHash {
331                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
332         }
333
334         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
335                 let payer = PayerTlvStreamRef {
336                         metadata: Some(&self.payer.0),
337                 };
338
339                 let offer = self.offer.as_tlv_stream();
340
341                 let features = {
342                         if self.features == InvoiceRequestFeatures::empty() { None }
343                         else { Some(&self.features) }
344                 };
345
346                 let invoice_request = InvoiceRequestTlvStreamRef {
347                         chain: self.chain.as_ref(),
348                         amount: self.amount_msats,
349                         features,
350                         quantity: self.quantity,
351                         payer_id: Some(&self.payer_id),
352                         payer_note: self.payer_note.as_ref(),
353                 };
354
355                 (payer, offer, invoice_request)
356         }
357 }
358
359 impl Writeable for InvoiceRequest {
360         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
361                 WithoutLength(&self.bytes).write(writer)
362         }
363 }
364
365 impl Writeable for InvoiceRequestContents {
366         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
367                 self.as_tlv_stream().write(writer)
368         }
369 }
370
371 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
372         (80, chain: ChainHash),
373         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
374         (84, features: InvoiceRequestFeatures),
375         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
376         (88, payer_id: PublicKey),
377         (89, payer_note: (String, WithoutLength)),
378 });
379
380 type FullInvoiceRequestTlvStream =
381         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
382
383 #[cfg(test)]
384 type FullInvoiceRequestTlvStreamRef<'a> = (
385         PayerTlvStreamRef<'a>,
386         OfferTlvStreamRef<'a>,
387         InvoiceRequestTlvStreamRef<'a>,
388         SignatureTlvStreamRef<'a>,
389 );
390
391 impl SeekReadable for FullInvoiceRequestTlvStream {
392         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
393                 let payer = SeekReadable::read(r)?;
394                 let offer = SeekReadable::read(r)?;
395                 let invoice_request = SeekReadable::read(r)?;
396                 let signature = SeekReadable::read(r)?;
397
398                 Ok((payer, offer, invoice_request, signature))
399         }
400 }
401
402 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
403
404 type PartialInvoiceRequestTlvStreamRef<'a> = (
405         PayerTlvStreamRef<'a>,
406         OfferTlvStreamRef<'a>,
407         InvoiceRequestTlvStreamRef<'a>,
408 );
409
410 impl TryFrom<Vec<u8>> for InvoiceRequest {
411         type Error = ParseError;
412
413         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
414                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
415                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
416                 let (
417                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
418                         SignatureTlvStream { signature },
419                 ) = tlv_stream;
420                 let contents = InvoiceRequestContents::try_from(
421                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
422                 )?;
423
424                 let signature = match signature {
425                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
426                         Some(signature) => signature,
427                 };
428                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
429
430                 Ok(InvoiceRequest { bytes, contents, signature })
431         }
432 }
433
434 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
435         type Error = SemanticError;
436
437         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
438                 let (
439                         PayerTlvStream { metadata },
440                         offer_tlv_stream,
441                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
442                 ) = tlv_stream;
443
444                 let payer = match metadata {
445                         None => return Err(SemanticError::MissingPayerMetadata),
446                         Some(metadata) => PayerContents(metadata),
447                 };
448                 let offer = OfferContents::try_from(offer_tlv_stream)?;
449
450                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
451                         return Err(SemanticError::UnsupportedChain);
452                 }
453
454                 if offer.amount().is_none() && amount.is_none() {
455                         return Err(SemanticError::MissingAmount);
456                 }
457
458                 offer.check_quantity(quantity)?;
459                 offer.check_amount_msats_for_quantity(amount, quantity)?;
460
461                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
462
463                 let payer_id = match payer_id {
464                         None => return Err(SemanticError::MissingPayerId),
465                         Some(payer_id) => payer_id,
466                 };
467
468                 Ok(InvoiceRequestContents {
469                         payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
470                 })
471         }
472 }
473
474 #[cfg(test)]
475 mod tests {
476         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
477
478         use bitcoin::blockdata::constants::ChainHash;
479         use bitcoin::network::constants::Network;
480         use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
481         use bitcoin::secp256k1::schnorr::Signature;
482         use core::convert::{Infallible, TryFrom};
483         use core::num::NonZeroU64;
484         #[cfg(feature = "std")]
485         use core::time::Duration;
486         use crate::ln::features::InvoiceRequestFeatures;
487         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
488         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
489         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
490         use crate::offers::parse::{ParseError, SemanticError};
491         use crate::offers::payer::PayerTlvStreamRef;
492         use crate::util::ser::{BigSize, Writeable};
493         use crate::util::string::PrintableString;
494
495         fn payer_keys() -> KeyPair {
496                 let secp_ctx = Secp256k1::new();
497                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
498         }
499
500         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
501                 let secp_ctx = Secp256k1::new();
502                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
503                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
504         }
505
506         fn payer_pubkey() -> PublicKey {
507                 payer_keys().public_key()
508         }
509
510         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
511                 let secp_ctx = Secp256k1::new();
512                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
513                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
514         }
515
516         fn recipient_pubkey() -> PublicKey {
517                 let secp_ctx = Secp256k1::new();
518                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
519         }
520
521         #[test]
522         fn builds_invoice_request_with_defaults() {
523                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
524                         .amount_msats(1000)
525                         .build().unwrap()
526                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
527                         .build().unwrap()
528                         .sign(payer_sign).unwrap();
529
530                 let mut buffer = Vec::new();
531                 invoice_request.write(&mut buffer).unwrap();
532
533                 assert_eq!(invoice_request.bytes, buffer.as_slice());
534                 assert_eq!(invoice_request.metadata(), &[1; 32]);
535                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
536                 assert_eq!(invoice_request.amount_msats(), None);
537                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
538                 assert_eq!(invoice_request.quantity(), None);
539                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
540                 assert_eq!(invoice_request.payer_note(), None);
541                 assert!(
542                         merkle::verify_signature(
543                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
544                         ).is_ok()
545                 );
546
547                 assert_eq!(
548                         invoice_request.as_tlv_stream(),
549                         (
550                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
551                                 OfferTlvStreamRef {
552                                         chains: None,
553                                         metadata: None,
554                                         currency: None,
555                                         amount: Some(1000),
556                                         description: Some(&String::from("foo")),
557                                         features: None,
558                                         absolute_expiry: None,
559                                         paths: None,
560                                         issuer: None,
561                                         quantity_max: None,
562                                         node_id: Some(&recipient_pubkey()),
563                                 },
564                                 InvoiceRequestTlvStreamRef {
565                                         chain: None,
566                                         amount: None,
567                                         features: None,
568                                         quantity: None,
569                                         payer_id: Some(&payer_pubkey()),
570                                         payer_note: None,
571                                 },
572                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
573                         ),
574                 );
575
576                 if let Err(e) = InvoiceRequest::try_from(buffer) {
577                         panic!("error parsing invoice request: {:?}", e);
578                 }
579         }
580
581         #[cfg(feature = "std")]
582         #[test]
583         fn builds_invoice_request_from_offer_with_expiration() {
584                 let future_expiry = Duration::from_secs(u64::max_value());
585                 let past_expiry = Duration::from_secs(0);
586
587                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
588                         .amount_msats(1000)
589                         .absolute_expiry(future_expiry)
590                         .build().unwrap()
591                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
592                         .build()
593                 {
594                         panic!("error building invoice_request: {:?}", e);
595                 }
596
597                 match OfferBuilder::new("foo".into(), recipient_pubkey())
598                         .amount_msats(1000)
599                         .absolute_expiry(past_expiry)
600                         .build().unwrap()
601                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
602                         .build()
603                 {
604                         Ok(_) => panic!("expected error"),
605                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
606                 }
607         }
608
609         #[test]
610         fn builds_invoice_request_with_chain() {
611                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
612                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
613
614                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
615                         .amount_msats(1000)
616                         .build().unwrap()
617                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
618                         .chain(Network::Bitcoin).unwrap()
619                         .build().unwrap()
620                         .sign(payer_sign).unwrap();
621                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
622                 assert_eq!(invoice_request.chain(), mainnet);
623                 assert_eq!(tlv_stream.chain, None);
624
625                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
626                         .amount_msats(1000)
627                         .chain(Network::Testnet)
628                         .build().unwrap()
629                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
630                         .chain(Network::Testnet).unwrap()
631                         .build().unwrap()
632                         .sign(payer_sign).unwrap();
633                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
634                 assert_eq!(invoice_request.chain(), testnet);
635                 assert_eq!(tlv_stream.chain, Some(&testnet));
636
637                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
638                         .amount_msats(1000)
639                         .chain(Network::Bitcoin)
640                         .chain(Network::Testnet)
641                         .build().unwrap()
642                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
643                         .chain(Network::Bitcoin).unwrap()
644                         .build().unwrap()
645                         .sign(payer_sign).unwrap();
646                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
647                 assert_eq!(invoice_request.chain(), mainnet);
648                 assert_eq!(tlv_stream.chain, None);
649
650                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
651                         .amount_msats(1000)
652                         .chain(Network::Bitcoin)
653                         .chain(Network::Testnet)
654                         .build().unwrap()
655                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
656                         .chain(Network::Bitcoin).unwrap()
657                         .chain(Network::Testnet).unwrap()
658                         .build().unwrap()
659                         .sign(payer_sign).unwrap();
660                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
661                 assert_eq!(invoice_request.chain(), testnet);
662                 assert_eq!(tlv_stream.chain, Some(&testnet));
663
664                 match OfferBuilder::new("foo".into(), recipient_pubkey())
665                         .amount_msats(1000)
666                         .chain(Network::Testnet)
667                         .build().unwrap()
668                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
669                         .chain(Network::Bitcoin)
670                 {
671                         Ok(_) => panic!("expected error"),
672                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
673                 }
674
675                 match OfferBuilder::new("foo".into(), recipient_pubkey())
676                         .amount_msats(1000)
677                         .chain(Network::Testnet)
678                         .build().unwrap()
679                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
680                         .build()
681                 {
682                         Ok(_) => panic!("expected error"),
683                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
684                 }
685         }
686
687         #[test]
688         fn builds_invoice_request_with_amount() {
689                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
690                         .amount_msats(1000)
691                         .build().unwrap()
692                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
693                         .amount_msats(1000).unwrap()
694                         .build().unwrap()
695                         .sign(payer_sign).unwrap();
696                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
697                 assert_eq!(invoice_request.amount_msats(), Some(1000));
698                 assert_eq!(tlv_stream.amount, Some(1000));
699
700                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
701                         .amount_msats(1000)
702                         .build().unwrap()
703                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
704                         .amount_msats(1001).unwrap()
705                         .amount_msats(1000).unwrap()
706                         .build().unwrap()
707                         .sign(payer_sign).unwrap();
708                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
709                 assert_eq!(invoice_request.amount_msats(), Some(1000));
710                 assert_eq!(tlv_stream.amount, Some(1000));
711
712                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
713                         .amount_msats(1000)
714                         .build().unwrap()
715                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
716                         .amount_msats(1001).unwrap()
717                         .build().unwrap()
718                         .sign(payer_sign).unwrap();
719                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
720                 assert_eq!(invoice_request.amount_msats(), Some(1001));
721                 assert_eq!(tlv_stream.amount, Some(1001));
722
723                 match OfferBuilder::new("foo".into(), recipient_pubkey())
724                         .amount_msats(1000)
725                         .build().unwrap()
726                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
727                         .amount_msats(999)
728                 {
729                         Ok(_) => panic!("expected error"),
730                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
731                 }
732
733                 match OfferBuilder::new("foo".into(), recipient_pubkey())
734                         .amount_msats(1000)
735                         .supported_quantity(Quantity::Unbounded)
736                         .build().unwrap()
737                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
738                         .quantity(2).unwrap()
739                         .amount_msats(1000)
740                 {
741                         Ok(_) => panic!("expected error"),
742                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
743                 }
744
745                 match OfferBuilder::new("foo".into(), recipient_pubkey())
746                         .amount_msats(1000)
747                         .build().unwrap()
748                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
749                         .amount_msats(MAX_VALUE_MSAT + 1)
750                 {
751                         Ok(_) => panic!("expected error"),
752                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
753                 }
754
755                 match OfferBuilder::new("foo".into(), recipient_pubkey())
756                         .amount_msats(1000)
757                         .supported_quantity(Quantity::Unbounded)
758                         .build().unwrap()
759                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
760                         .amount_msats(1000).unwrap()
761                         .quantity(2).unwrap()
762                         .build()
763                 {
764                         Ok(_) => panic!("expected error"),
765                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
766                 }
767
768                 match OfferBuilder::new("foo".into(), recipient_pubkey())
769                         .build().unwrap()
770                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
771                         .build()
772                 {
773                         Ok(_) => panic!("expected error"),
774                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
775                 }
776         }
777
778         #[test]
779         fn builds_invoice_request_with_features() {
780                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
781                         .amount_msats(1000)
782                         .build().unwrap()
783                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
784                         .features_unchecked(InvoiceRequestFeatures::unknown())
785                         .build().unwrap()
786                         .sign(payer_sign).unwrap();
787                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
788                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
789                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
790
791                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
792                         .amount_msats(1000)
793                         .build().unwrap()
794                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
795                         .features_unchecked(InvoiceRequestFeatures::unknown())
796                         .features_unchecked(InvoiceRequestFeatures::empty())
797                         .build().unwrap()
798                         .sign(payer_sign).unwrap();
799                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
800                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
801                 assert_eq!(tlv_stream.features, None);
802         }
803
804         #[test]
805         fn builds_invoice_request_with_quantity() {
806                 let ten = NonZeroU64::new(10).unwrap();
807
808                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
809                         .amount_msats(1000)
810                         .supported_quantity(Quantity::one())
811                         .build().unwrap()
812                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
813                         .build().unwrap()
814                         .sign(payer_sign).unwrap();
815                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
816                 assert_eq!(invoice_request.quantity(), None);
817                 assert_eq!(tlv_stream.quantity, None);
818
819                 match OfferBuilder::new("foo".into(), recipient_pubkey())
820                         .amount_msats(1000)
821                         .supported_quantity(Quantity::one())
822                         .build().unwrap()
823                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
824                         .amount_msats(2_000).unwrap()
825                         .quantity(2)
826                 {
827                         Ok(_) => panic!("expected error"),
828                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
829                 }
830
831                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
832                         .amount_msats(1000)
833                         .supported_quantity(Quantity::Bounded(ten))
834                         .build().unwrap()
835                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
836                         .amount_msats(10_000).unwrap()
837                         .quantity(10).unwrap()
838                         .build().unwrap()
839                         .sign(payer_sign).unwrap();
840                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
841                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
842                 assert_eq!(tlv_stream.amount, Some(10_000));
843
844                 match OfferBuilder::new("foo".into(), recipient_pubkey())
845                         .amount_msats(1000)
846                         .supported_quantity(Quantity::Bounded(ten))
847                         .build().unwrap()
848                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
849                         .amount_msats(11_000).unwrap()
850                         .quantity(11)
851                 {
852                         Ok(_) => panic!("expected error"),
853                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
854                 }
855
856                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
857                         .amount_msats(1000)
858                         .supported_quantity(Quantity::Unbounded)
859                         .build().unwrap()
860                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
861                         .amount_msats(2_000).unwrap()
862                         .quantity(2).unwrap()
863                         .build().unwrap()
864                         .sign(payer_sign).unwrap();
865                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
866                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
867                 assert_eq!(tlv_stream.amount, Some(2_000));
868
869                 match OfferBuilder::new("foo".into(), recipient_pubkey())
870                         .amount_msats(1000)
871                         .supported_quantity(Quantity::Unbounded)
872                         .build().unwrap()
873                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
874                         .build()
875                 {
876                         Ok(_) => panic!("expected error"),
877                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
878                 }
879         }
880
881         #[test]
882         fn builds_invoice_request_with_payer_note() {
883                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
884                         .amount_msats(1000)
885                         .build().unwrap()
886                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
887                         .payer_note("bar".into())
888                         .build().unwrap()
889                         .sign(payer_sign).unwrap();
890                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
891                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
892                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
893
894                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
895                         .amount_msats(1000)
896                         .build().unwrap()
897                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
898                         .payer_note("bar".into())
899                         .payer_note("baz".into())
900                         .build().unwrap()
901                         .sign(payer_sign).unwrap();
902                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
903                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
904                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
905         }
906
907         #[test]
908         fn fails_signing_invoice_request() {
909                 match OfferBuilder::new("foo".into(), recipient_pubkey())
910                         .amount_msats(1000)
911                         .build().unwrap()
912                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
913                         .build().unwrap()
914                         .sign(|_| Err(()))
915                 {
916                         Ok(_) => panic!("expected error"),
917                         Err(e) => assert_eq!(e, SignError::Signing(())),
918                 }
919
920                 match OfferBuilder::new("foo".into(), recipient_pubkey())
921                         .amount_msats(1000)
922                         .build().unwrap()
923                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
924                         .build().unwrap()
925                         .sign(recipient_sign)
926                 {
927                         Ok(_) => panic!("expected error"),
928                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
929                 }
930         }
931
932         #[test]
933         fn parses_invoice_request_with_metadata() {
934                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
935                         .amount_msats(1000)
936                         .build().unwrap()
937                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
938                         .build().unwrap()
939                         .sign(payer_sign).unwrap();
940
941                 let mut buffer = Vec::new();
942                 invoice_request.write(&mut buffer).unwrap();
943
944                 if let Err(e) = InvoiceRequest::try_from(buffer) {
945                         panic!("error parsing invoice_request: {:?}", e);
946                 }
947         }
948
949         #[test]
950         fn parses_invoice_request_with_chain() {
951                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
952                         .amount_msats(1000)
953                         .build().unwrap()
954                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
955                         .chain(Network::Bitcoin).unwrap()
956                         .build().unwrap()
957                         .sign(payer_sign).unwrap();
958
959                 let mut buffer = Vec::new();
960                 invoice_request.write(&mut buffer).unwrap();
961
962                 if let Err(e) = InvoiceRequest::try_from(buffer) {
963                         panic!("error parsing invoice_request: {:?}", e);
964                 }
965
966                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
967                         .amount_msats(1000)
968                         .build().unwrap()
969                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
970                         .chain_unchecked(Network::Testnet)
971                         .build_unchecked()
972                         .sign(payer_sign).unwrap();
973
974                 let mut buffer = Vec::new();
975                 invoice_request.write(&mut buffer).unwrap();
976
977                 match InvoiceRequest::try_from(buffer) {
978                         Ok(_) => panic!("expected error"),
979                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
980                 }
981         }
982
983         #[test]
984         fn parses_invoice_request_with_amount() {
985                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
986                         .amount_msats(1000)
987                         .build().unwrap()
988                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
989                         .build().unwrap()
990                         .sign(payer_sign).unwrap();
991
992                 let mut buffer = Vec::new();
993                 invoice_request.write(&mut buffer).unwrap();
994
995                 if let Err(e) = InvoiceRequest::try_from(buffer) {
996                         panic!("error parsing invoice_request: {:?}", e);
997                 }
998
999                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1000                         .build().unwrap()
1001                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1002                         .amount_msats(1000).unwrap()
1003                         .build().unwrap()
1004                         .sign(payer_sign).unwrap();
1005
1006                 let mut buffer = Vec::new();
1007                 invoice_request.write(&mut buffer).unwrap();
1008
1009                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1010                         panic!("error parsing invoice_request: {:?}", e);
1011                 }
1012
1013                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1014                         .build().unwrap()
1015                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1016                         .build_unchecked()
1017                         .sign(payer_sign).unwrap();
1018
1019                 let mut buffer = Vec::new();
1020                 invoice_request.write(&mut buffer).unwrap();
1021
1022                 match InvoiceRequest::try_from(buffer) {
1023                         Ok(_) => panic!("expected error"),
1024                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1025                 }
1026
1027                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1028                         .amount_msats(1000)
1029                         .build().unwrap()
1030                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1031                         .amount_msats_unchecked(999)
1032                         .build_unchecked()
1033                         .sign(payer_sign).unwrap();
1034
1035                 let mut buffer = Vec::new();
1036                 invoice_request.write(&mut buffer).unwrap();
1037
1038                 match InvoiceRequest::try_from(buffer) {
1039                         Ok(_) => panic!("expected error"),
1040                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1041                 }
1042
1043                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1044                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1045                         .build_unchecked()
1046                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1047                         .build_unchecked()
1048                         .sign(payer_sign).unwrap();
1049
1050                 let mut buffer = Vec::new();
1051                 invoice_request.write(&mut buffer).unwrap();
1052
1053                 match InvoiceRequest::try_from(buffer) {
1054                         Ok(_) => panic!("expected error"),
1055                         Err(e) => {
1056                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1057                         },
1058                 }
1059         }
1060
1061         #[test]
1062         fn parses_invoice_request_with_quantity() {
1063                 let ten = NonZeroU64::new(10).unwrap();
1064
1065                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1066                         .amount_msats(1000)
1067                         .supported_quantity(Quantity::one())
1068                         .build().unwrap()
1069                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1070                         .build().unwrap()
1071                         .sign(payer_sign).unwrap();
1072
1073                 let mut buffer = Vec::new();
1074                 invoice_request.write(&mut buffer).unwrap();
1075
1076                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1077                         panic!("error parsing invoice_request: {:?}", e);
1078                 }
1079
1080                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1081                         .amount_msats(1000)
1082                         .supported_quantity(Quantity::one())
1083                         .build().unwrap()
1084                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1085                         .amount_msats(2_000).unwrap()
1086                         .quantity_unchecked(2)
1087                         .build_unchecked()
1088                         .sign(payer_sign).unwrap();
1089
1090                 let mut buffer = Vec::new();
1091                 invoice_request.write(&mut buffer).unwrap();
1092
1093                 match InvoiceRequest::try_from(buffer) {
1094                         Ok(_) => panic!("expected error"),
1095                         Err(e) => {
1096                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1097                         },
1098                 }
1099
1100                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1101                         .amount_msats(1000)
1102                         .supported_quantity(Quantity::Bounded(ten))
1103                         .build().unwrap()
1104                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1105                         .amount_msats(10_000).unwrap()
1106                         .quantity(10).unwrap()
1107                         .build().unwrap()
1108                         .sign(payer_sign).unwrap();
1109
1110                 let mut buffer = Vec::new();
1111                 invoice_request.write(&mut buffer).unwrap();
1112
1113                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1114                         panic!("error parsing invoice_request: {:?}", e);
1115                 }
1116
1117                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1118                         .amount_msats(1000)
1119                         .supported_quantity(Quantity::Bounded(ten))
1120                         .build().unwrap()
1121                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1122                         .amount_msats(11_000).unwrap()
1123                         .quantity_unchecked(11)
1124                         .build_unchecked()
1125                         .sign(payer_sign).unwrap();
1126
1127                 let mut buffer = Vec::new();
1128                 invoice_request.write(&mut buffer).unwrap();
1129
1130                 match InvoiceRequest::try_from(buffer) {
1131                         Ok(_) => panic!("expected error"),
1132                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1133                 }
1134
1135                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1136                         .amount_msats(1000)
1137                         .supported_quantity(Quantity::Unbounded)
1138                         .build().unwrap()
1139                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1140                         .amount_msats(2_000).unwrap()
1141                         .quantity(2).unwrap()
1142                         .build().unwrap()
1143                         .sign(payer_sign).unwrap();
1144
1145                 let mut buffer = Vec::new();
1146                 invoice_request.write(&mut buffer).unwrap();
1147
1148                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1149                         panic!("error parsing invoice_request: {:?}", e);
1150                 }
1151
1152                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1153                         .amount_msats(1000)
1154                         .supported_quantity(Quantity::Unbounded)
1155                         .build().unwrap()
1156                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1157                         .build_unchecked()
1158                         .sign(payer_sign).unwrap();
1159
1160                 let mut buffer = Vec::new();
1161                 invoice_request.write(&mut buffer).unwrap();
1162
1163                 match InvoiceRequest::try_from(buffer) {
1164                         Ok(_) => panic!("expected error"),
1165                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1166                 }
1167         }
1168
1169         #[test]
1170         fn fails_parsing_invoice_request_without_metadata() {
1171                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1172                         .amount_msats(1000)
1173                         .build().unwrap();
1174                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1175                         .build().unwrap();
1176                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1177                 tlv_stream.0.metadata = None;
1178
1179                 let mut buffer = Vec::new();
1180                 tlv_stream.write(&mut buffer).unwrap();
1181
1182                 match InvoiceRequest::try_from(buffer) {
1183                         Ok(_) => panic!("expected error"),
1184                         Err(e) => {
1185                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1186                         },
1187                 }
1188         }
1189
1190         #[test]
1191         fn fails_parsing_invoice_request_without_payer_id() {
1192                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1193                         .amount_msats(1000)
1194                         .build().unwrap();
1195                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1196                         .build().unwrap();
1197                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1198                 tlv_stream.2.payer_id = None;
1199
1200                 let mut buffer = Vec::new();
1201                 tlv_stream.write(&mut buffer).unwrap();
1202
1203                 match InvoiceRequest::try_from(buffer) {
1204                         Ok(_) => panic!("expected error"),
1205                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1206                 }
1207         }
1208
1209         #[test]
1210         fn fails_parsing_invoice_request_without_node_id() {
1211                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1212                         .amount_msats(1000)
1213                         .build().unwrap();
1214                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1215                         .build().unwrap();
1216                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1217                 tlv_stream.1.node_id = None;
1218
1219                 let mut buffer = Vec::new();
1220                 tlv_stream.write(&mut buffer).unwrap();
1221
1222                 match InvoiceRequest::try_from(buffer) {
1223                         Ok(_) => panic!("expected error"),
1224                         Err(e) => {
1225                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1226                         },
1227                 }
1228         }
1229
1230         #[test]
1231         fn fails_parsing_invoice_request_without_signature() {
1232                 let mut buffer = Vec::new();
1233                 OfferBuilder::new("foo".into(), recipient_pubkey())
1234                         .amount_msats(1000)
1235                         .build().unwrap()
1236                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1237                         .build().unwrap()
1238                         .invoice_request
1239                         .write(&mut buffer).unwrap();
1240
1241                 match InvoiceRequest::try_from(buffer) {
1242                         Ok(_) => panic!("expected error"),
1243                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1244                 }
1245         }
1246
1247         #[test]
1248         fn fails_parsing_invoice_request_with_invalid_signature() {
1249                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1250                         .amount_msats(1000)
1251                         .build().unwrap()
1252                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1253                         .build().unwrap()
1254                         .sign(payer_sign).unwrap();
1255                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1256                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1257
1258                 let mut buffer = Vec::new();
1259                 invoice_request.write(&mut buffer).unwrap();
1260
1261                 match InvoiceRequest::try_from(buffer) {
1262                         Ok(_) => panic!("expected error"),
1263                         Err(e) => {
1264                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1265                         },
1266                 }
1267         }
1268
1269         #[test]
1270         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1271                 let secp_ctx = Secp256k1::new();
1272                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1273                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1274                         .amount_msats(1000)
1275                         .build().unwrap()
1276                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1277                         .build().unwrap()
1278                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1279                         .unwrap();
1280
1281                 let mut encoded_invoice_request = Vec::new();
1282                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1283                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1284                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1285                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1286
1287                 match InvoiceRequest::try_from(encoded_invoice_request) {
1288                         Ok(_) => panic!("expected error"),
1289                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1290                 }
1291         }
1292 }