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