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