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