Fix (and DRY) the conditionals before calling `peer_disconnected`
[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 ordered from most-preferred to least-preferred, if there's
337         /// a preference. Note, however, that any privacy is lost if a public node id was used for
338         /// [`Offer::signing_pubkey`].
339         ///
340         /// Errors if the request contains unknown required features.
341         ///
342         /// [`Duration`]: core::time::Duration
343         /// [`Invoice`]: crate::offers::invoice::Invoice
344         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
345         pub fn respond_with(
346                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
347                 #[cfg(any(test, not(feature = "std")))]
348                 created_at: core::time::Duration
349         ) -> Result<InvoiceBuilder, SemanticError> {
350                 if self.features().requires_unknown_bits() {
351                         return Err(SemanticError::UnknownRequiredFeatures);
352                 }
353
354                 #[cfg(all(not(test), feature = "std"))]
355                 let created_at = std::time::SystemTime::now()
356                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
357                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
358
359                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
360         }
361
362         #[cfg(test)]
363         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
364                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
365                         self.contents.as_tlv_stream();
366                 let signature_tlv_stream = SignatureTlvStreamRef {
367                         signature: Some(&self.signature),
368                 };
369                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
370         }
371 }
372
373 impl InvoiceRequestContents {
374         pub(super) fn chain(&self) -> ChainHash {
375                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
376         }
377
378         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
379                 let payer = PayerTlvStreamRef {
380                         metadata: Some(&self.payer.0),
381                 };
382
383                 let offer = self.offer.as_tlv_stream();
384
385                 let features = {
386                         if self.features == InvoiceRequestFeatures::empty() { None }
387                         else { Some(&self.features) }
388                 };
389
390                 let invoice_request = InvoiceRequestTlvStreamRef {
391                         chain: self.chain.as_ref(),
392                         amount: self.amount_msats,
393                         features,
394                         quantity: self.quantity,
395                         payer_id: Some(&self.payer_id),
396                         payer_note: self.payer_note.as_ref(),
397                 };
398
399                 (payer, offer, invoice_request)
400         }
401 }
402
403 impl Writeable for InvoiceRequest {
404         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
405                 WithoutLength(&self.bytes).write(writer)
406         }
407 }
408
409 impl Writeable for InvoiceRequestContents {
410         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
411                 self.as_tlv_stream().write(writer)
412         }
413 }
414
415 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
416         (80, chain: ChainHash),
417         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
418         (84, features: (InvoiceRequestFeatures, WithoutLength)),
419         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
420         (88, payer_id: PublicKey),
421         (89, payer_note: (String, WithoutLength)),
422 });
423
424 type FullInvoiceRequestTlvStream =
425         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
426
427 #[cfg(test)]
428 type FullInvoiceRequestTlvStreamRef<'a> = (
429         PayerTlvStreamRef<'a>,
430         OfferTlvStreamRef<'a>,
431         InvoiceRequestTlvStreamRef<'a>,
432         SignatureTlvStreamRef<'a>,
433 );
434
435 impl SeekReadable for FullInvoiceRequestTlvStream {
436         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
437                 let payer = SeekReadable::read(r)?;
438                 let offer = SeekReadable::read(r)?;
439                 let invoice_request = SeekReadable::read(r)?;
440                 let signature = SeekReadable::read(r)?;
441
442                 Ok((payer, offer, invoice_request, signature))
443         }
444 }
445
446 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
447
448 type PartialInvoiceRequestTlvStreamRef<'a> = (
449         PayerTlvStreamRef<'a>,
450         OfferTlvStreamRef<'a>,
451         InvoiceRequestTlvStreamRef<'a>,
452 );
453
454 impl TryFrom<Vec<u8>> for InvoiceRequest {
455         type Error = ParseError;
456
457         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
458                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
459                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
460                 let (
461                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
462                         SignatureTlvStream { signature },
463                 ) = tlv_stream;
464                 let contents = InvoiceRequestContents::try_from(
465                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
466                 )?;
467
468                 let signature = match signature {
469                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
470                         Some(signature) => signature,
471                 };
472                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
473
474                 Ok(InvoiceRequest { bytes, contents, signature })
475         }
476 }
477
478 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
479         type Error = SemanticError;
480
481         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
482                 let (
483                         PayerTlvStream { metadata },
484                         offer_tlv_stream,
485                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
486                 ) = tlv_stream;
487
488                 let payer = match metadata {
489                         None => return Err(SemanticError::MissingPayerMetadata),
490                         Some(metadata) => PayerContents(metadata),
491                 };
492                 let offer = OfferContents::try_from(offer_tlv_stream)?;
493
494                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
495                         return Err(SemanticError::UnsupportedChain);
496                 }
497
498                 if offer.amount().is_none() && amount.is_none() {
499                         return Err(SemanticError::MissingAmount);
500                 }
501
502                 offer.check_quantity(quantity)?;
503                 offer.check_amount_msats_for_quantity(amount, quantity)?;
504
505                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
506
507                 let payer_id = match payer_id {
508                         None => return Err(SemanticError::MissingPayerId),
509                         Some(payer_id) => payer_id,
510                 };
511
512                 Ok(InvoiceRequestContents {
513                         payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
514                 })
515         }
516 }
517
518 #[cfg(test)]
519 mod tests {
520         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
521
522         use bitcoin::blockdata::constants::ChainHash;
523         use bitcoin::network::constants::Network;
524         use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
525         use bitcoin::secp256k1::schnorr::Signature;
526         use core::convert::{Infallible, TryFrom};
527         use core::num::NonZeroU64;
528         #[cfg(feature = "std")]
529         use core::time::Duration;
530         use crate::ln::features::InvoiceRequestFeatures;
531         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
532         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
533         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
534         use crate::offers::parse::{ParseError, SemanticError};
535         use crate::offers::payer::PayerTlvStreamRef;
536         use crate::util::ser::{BigSize, Writeable};
537         use crate::util::string::PrintableString;
538
539         fn payer_keys() -> KeyPair {
540                 let secp_ctx = Secp256k1::new();
541                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
542         }
543
544         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
545                 let secp_ctx = Secp256k1::new();
546                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
547                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
548         }
549
550         fn payer_pubkey() -> PublicKey {
551                 payer_keys().public_key()
552         }
553
554         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
555                 let secp_ctx = Secp256k1::new();
556                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
557                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
558         }
559
560         fn recipient_pubkey() -> PublicKey {
561                 let secp_ctx = Secp256k1::new();
562                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
563         }
564
565         #[test]
566         fn builds_invoice_request_with_defaults() {
567                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
568                         .amount_msats(1000)
569                         .build().unwrap()
570                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
571                         .build().unwrap()
572                         .sign(payer_sign).unwrap();
573
574                 let mut buffer = Vec::new();
575                 invoice_request.write(&mut buffer).unwrap();
576
577                 assert_eq!(invoice_request.bytes, buffer.as_slice());
578                 assert_eq!(invoice_request.metadata(), &[1; 32]);
579                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
580                 assert_eq!(invoice_request.amount_msats(), None);
581                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
582                 assert_eq!(invoice_request.quantity(), None);
583                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
584                 assert_eq!(invoice_request.payer_note(), None);
585                 assert!(
586                         merkle::verify_signature(
587                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
588                         ).is_ok()
589                 );
590
591                 assert_eq!(
592                         invoice_request.as_tlv_stream(),
593                         (
594                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
595                                 OfferTlvStreamRef {
596                                         chains: None,
597                                         metadata: None,
598                                         currency: None,
599                                         amount: Some(1000),
600                                         description: Some(&String::from("foo")),
601                                         features: None,
602                                         absolute_expiry: None,
603                                         paths: None,
604                                         issuer: None,
605                                         quantity_max: None,
606                                         node_id: Some(&recipient_pubkey()),
607                                 },
608                                 InvoiceRequestTlvStreamRef {
609                                         chain: None,
610                                         amount: None,
611                                         features: None,
612                                         quantity: None,
613                                         payer_id: Some(&payer_pubkey()),
614                                         payer_note: None,
615                                 },
616                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
617                         ),
618                 );
619
620                 if let Err(e) = InvoiceRequest::try_from(buffer) {
621                         panic!("error parsing invoice request: {:?}", e);
622                 }
623         }
624
625         #[cfg(feature = "std")]
626         #[test]
627         fn builds_invoice_request_from_offer_with_expiration() {
628                 let future_expiry = Duration::from_secs(u64::max_value());
629                 let past_expiry = Duration::from_secs(0);
630
631                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
632                         .amount_msats(1000)
633                         .absolute_expiry(future_expiry)
634                         .build().unwrap()
635                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
636                         .build()
637                 {
638                         panic!("error building invoice_request: {:?}", e);
639                 }
640
641                 match OfferBuilder::new("foo".into(), recipient_pubkey())
642                         .amount_msats(1000)
643                         .absolute_expiry(past_expiry)
644                         .build().unwrap()
645                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
646                         .build()
647                 {
648                         Ok(_) => panic!("expected error"),
649                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
650                 }
651         }
652
653         #[test]
654         fn builds_invoice_request_with_chain() {
655                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
656                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
657
658                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
659                         .amount_msats(1000)
660                         .build().unwrap()
661                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
662                         .chain(Network::Bitcoin).unwrap()
663                         .build().unwrap()
664                         .sign(payer_sign).unwrap();
665                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
666                 assert_eq!(invoice_request.chain(), mainnet);
667                 assert_eq!(tlv_stream.chain, None);
668
669                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
670                         .amount_msats(1000)
671                         .chain(Network::Testnet)
672                         .build().unwrap()
673                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
674                         .chain(Network::Testnet).unwrap()
675                         .build().unwrap()
676                         .sign(payer_sign).unwrap();
677                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
678                 assert_eq!(invoice_request.chain(), testnet);
679                 assert_eq!(tlv_stream.chain, Some(&testnet));
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                         .build().unwrap()
689                         .sign(payer_sign).unwrap();
690                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
691                 assert_eq!(invoice_request.chain(), mainnet);
692                 assert_eq!(tlv_stream.chain, None);
693
694                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
695                         .amount_msats(1000)
696                         .chain(Network::Bitcoin)
697                         .chain(Network::Testnet)
698                         .build().unwrap()
699                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
700                         .chain(Network::Bitcoin).unwrap()
701                         .chain(Network::Testnet).unwrap()
702                         .build().unwrap()
703                         .sign(payer_sign).unwrap();
704                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
705                 assert_eq!(invoice_request.chain(), testnet);
706                 assert_eq!(tlv_stream.chain, Some(&testnet));
707
708                 match OfferBuilder::new("foo".into(), recipient_pubkey())
709                         .amount_msats(1000)
710                         .chain(Network::Testnet)
711                         .build().unwrap()
712                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
713                         .chain(Network::Bitcoin)
714                 {
715                         Ok(_) => panic!("expected error"),
716                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
717                 }
718
719                 match OfferBuilder::new("foo".into(), recipient_pubkey())
720                         .amount_msats(1000)
721                         .chain(Network::Testnet)
722                         .build().unwrap()
723                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
724                         .build()
725                 {
726                         Ok(_) => panic!("expected error"),
727                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
728                 }
729         }
730
731         #[test]
732         fn builds_invoice_request_with_amount() {
733                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
734                         .amount_msats(1000)
735                         .build().unwrap()
736                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
737                         .amount_msats(1000).unwrap()
738                         .build().unwrap()
739                         .sign(payer_sign).unwrap();
740                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
741                 assert_eq!(invoice_request.amount_msats(), Some(1000));
742                 assert_eq!(tlv_stream.amount, Some(1000));
743
744                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
745                         .amount_msats(1000)
746                         .build().unwrap()
747                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
748                         .amount_msats(1001).unwrap()
749                         .amount_msats(1000).unwrap()
750                         .build().unwrap()
751                         .sign(payer_sign).unwrap();
752                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
753                 assert_eq!(invoice_request.amount_msats(), Some(1000));
754                 assert_eq!(tlv_stream.amount, Some(1000));
755
756                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
757                         .amount_msats(1000)
758                         .build().unwrap()
759                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
760                         .amount_msats(1001).unwrap()
761                         .build().unwrap()
762                         .sign(payer_sign).unwrap();
763                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
764                 assert_eq!(invoice_request.amount_msats(), Some(1001));
765                 assert_eq!(tlv_stream.amount, Some(1001));
766
767                 match OfferBuilder::new("foo".into(), recipient_pubkey())
768                         .amount_msats(1000)
769                         .build().unwrap()
770                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
771                         .amount_msats(999)
772                 {
773                         Ok(_) => panic!("expected error"),
774                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
775                 }
776
777                 match OfferBuilder::new("foo".into(), recipient_pubkey())
778                         .amount_msats(1000)
779                         .supported_quantity(Quantity::Unbounded)
780                         .build().unwrap()
781                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
782                         .quantity(2).unwrap()
783                         .amount_msats(1000)
784                 {
785                         Ok(_) => panic!("expected error"),
786                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
787                 }
788
789                 match OfferBuilder::new("foo".into(), recipient_pubkey())
790                         .amount_msats(1000)
791                         .build().unwrap()
792                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
793                         .amount_msats(MAX_VALUE_MSAT + 1)
794                 {
795                         Ok(_) => panic!("expected error"),
796                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
797                 }
798
799                 match OfferBuilder::new("foo".into(), recipient_pubkey())
800                         .amount_msats(1000)
801                         .supported_quantity(Quantity::Unbounded)
802                         .build().unwrap()
803                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
804                         .amount_msats(1000).unwrap()
805                         .quantity(2).unwrap()
806                         .build()
807                 {
808                         Ok(_) => panic!("expected error"),
809                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
810                 }
811
812                 match OfferBuilder::new("foo".into(), recipient_pubkey())
813                         .build().unwrap()
814                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
815                         .build()
816                 {
817                         Ok(_) => panic!("expected error"),
818                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
819                 }
820         }
821
822         #[test]
823         fn builds_invoice_request_with_features() {
824                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
825                         .amount_msats(1000)
826                         .build().unwrap()
827                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
828                         .features_unchecked(InvoiceRequestFeatures::unknown())
829                         .build().unwrap()
830                         .sign(payer_sign).unwrap();
831                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
832                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
833                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
834
835                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
836                         .amount_msats(1000)
837                         .build().unwrap()
838                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
839                         .features_unchecked(InvoiceRequestFeatures::unknown())
840                         .features_unchecked(InvoiceRequestFeatures::empty())
841                         .build().unwrap()
842                         .sign(payer_sign).unwrap();
843                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
844                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
845                 assert_eq!(tlv_stream.features, None);
846         }
847
848         #[test]
849         fn builds_invoice_request_with_quantity() {
850                 let one = NonZeroU64::new(1).unwrap();
851                 let ten = NonZeroU64::new(10).unwrap();
852
853                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
854                         .amount_msats(1000)
855                         .supported_quantity(Quantity::One)
856                         .build().unwrap()
857                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
858                         .build().unwrap()
859                         .sign(payer_sign).unwrap();
860                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
861                 assert_eq!(invoice_request.quantity(), None);
862                 assert_eq!(tlv_stream.quantity, None);
863
864                 match OfferBuilder::new("foo".into(), recipient_pubkey())
865                         .amount_msats(1000)
866                         .supported_quantity(Quantity::One)
867                         .build().unwrap()
868                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
869                         .amount_msats(2_000).unwrap()
870                         .quantity(2)
871                 {
872                         Ok(_) => panic!("expected error"),
873                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
874                 }
875
876                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
877                         .amount_msats(1000)
878                         .supported_quantity(Quantity::Bounded(ten))
879                         .build().unwrap()
880                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
881                         .amount_msats(10_000).unwrap()
882                         .quantity(10).unwrap()
883                         .build().unwrap()
884                         .sign(payer_sign).unwrap();
885                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
886                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
887                 assert_eq!(tlv_stream.amount, Some(10_000));
888
889                 match OfferBuilder::new("foo".into(), recipient_pubkey())
890                         .amount_msats(1000)
891                         .supported_quantity(Quantity::Bounded(ten))
892                         .build().unwrap()
893                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
894                         .amount_msats(11_000).unwrap()
895                         .quantity(11)
896                 {
897                         Ok(_) => panic!("expected error"),
898                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
899                 }
900
901                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
902                         .amount_msats(1000)
903                         .supported_quantity(Quantity::Unbounded)
904                         .build().unwrap()
905                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
906                         .amount_msats(2_000).unwrap()
907                         .quantity(2).unwrap()
908                         .build().unwrap()
909                         .sign(payer_sign).unwrap();
910                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
911                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
912                 assert_eq!(tlv_stream.amount, Some(2_000));
913
914                 match OfferBuilder::new("foo".into(), recipient_pubkey())
915                         .amount_msats(1000)
916                         .supported_quantity(Quantity::Unbounded)
917                         .build().unwrap()
918                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
919                         .build()
920                 {
921                         Ok(_) => panic!("expected error"),
922                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
923                 }
924
925                 match OfferBuilder::new("foo".into(), recipient_pubkey())
926                         .amount_msats(1000)
927                         .supported_quantity(Quantity::Bounded(one))
928                         .build().unwrap()
929                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
930                         .build()
931                 {
932                         Ok(_) => panic!("expected error"),
933                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
934                 }
935         }
936
937         #[test]
938         fn builds_invoice_request_with_payer_note() {
939                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
940                         .amount_msats(1000)
941                         .build().unwrap()
942                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
943                         .payer_note("bar".into())
944                         .build().unwrap()
945                         .sign(payer_sign).unwrap();
946                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
947                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
948                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
949
950                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
951                         .amount_msats(1000)
952                         .build().unwrap()
953                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
954                         .payer_note("bar".into())
955                         .payer_note("baz".into())
956                         .build().unwrap()
957                         .sign(payer_sign).unwrap();
958                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
959                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
960                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
961         }
962
963         #[test]
964         fn fails_signing_invoice_request() {
965                 match OfferBuilder::new("foo".into(), recipient_pubkey())
966                         .amount_msats(1000)
967                         .build().unwrap()
968                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
969                         .build().unwrap()
970                         .sign(|_| Err(()))
971                 {
972                         Ok(_) => panic!("expected error"),
973                         Err(e) => assert_eq!(e, SignError::Signing(())),
974                 }
975
976                 match OfferBuilder::new("foo".into(), recipient_pubkey())
977                         .amount_msats(1000)
978                         .build().unwrap()
979                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
980                         .build().unwrap()
981                         .sign(recipient_sign)
982                 {
983                         Ok(_) => panic!("expected error"),
984                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
985                 }
986         }
987
988         #[test]
989         fn parses_invoice_request_with_metadata() {
990                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
991                         .amount_msats(1000)
992                         .build().unwrap()
993                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
994                         .build().unwrap()
995                         .sign(payer_sign).unwrap();
996
997                 let mut buffer = Vec::new();
998                 invoice_request.write(&mut buffer).unwrap();
999
1000                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1001                         panic!("error parsing invoice_request: {:?}", e);
1002                 }
1003         }
1004
1005         #[test]
1006         fn parses_invoice_request_with_chain() {
1007                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1008                         .amount_msats(1000)
1009                         .build().unwrap()
1010                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1011                         .chain(Network::Bitcoin).unwrap()
1012                         .build().unwrap()
1013                         .sign(payer_sign).unwrap();
1014
1015                 let mut buffer = Vec::new();
1016                 invoice_request.write(&mut buffer).unwrap();
1017
1018                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1019                         panic!("error parsing invoice_request: {:?}", e);
1020                 }
1021
1022                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1023                         .amount_msats(1000)
1024                         .build().unwrap()
1025                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1026                         .chain_unchecked(Network::Testnet)
1027                         .build_unchecked()
1028                         .sign(payer_sign).unwrap();
1029
1030                 let mut buffer = Vec::new();
1031                 invoice_request.write(&mut buffer).unwrap();
1032
1033                 match InvoiceRequest::try_from(buffer) {
1034                         Ok(_) => panic!("expected error"),
1035                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1036                 }
1037         }
1038
1039         #[test]
1040         fn parses_invoice_request_with_amount() {
1041                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1042                         .amount_msats(1000)
1043                         .build().unwrap()
1044                         .request_invoice(vec![1; 32], payer_pubkey()).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                         .amount_msats(1000).unwrap()
1059                         .build().unwrap()
1060                         .sign(payer_sign).unwrap();
1061
1062                 let mut buffer = Vec::new();
1063                 invoice_request.write(&mut buffer).unwrap();
1064
1065                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1066                         panic!("error parsing invoice_request: {:?}", e);
1067                 }
1068
1069                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1070                         .build().unwrap()
1071                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1072                         .build_unchecked()
1073                         .sign(payer_sign).unwrap();
1074
1075                 let mut buffer = Vec::new();
1076                 invoice_request.write(&mut buffer).unwrap();
1077
1078                 match InvoiceRequest::try_from(buffer) {
1079                         Ok(_) => panic!("expected error"),
1080                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1081                 }
1082
1083                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1084                         .amount_msats(1000)
1085                         .build().unwrap()
1086                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1087                         .amount_msats_unchecked(999)
1088                         .build_unchecked()
1089                         .sign(payer_sign).unwrap();
1090
1091                 let mut buffer = Vec::new();
1092                 invoice_request.write(&mut buffer).unwrap();
1093
1094                 match InvoiceRequest::try_from(buffer) {
1095                         Ok(_) => panic!("expected error"),
1096                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1097                 }
1098
1099                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1100                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1101                         .build_unchecked()
1102                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1103                         .build_unchecked()
1104                         .sign(payer_sign).unwrap();
1105
1106                 let mut buffer = Vec::new();
1107                 invoice_request.write(&mut buffer).unwrap();
1108
1109                 match InvoiceRequest::try_from(buffer) {
1110                         Ok(_) => panic!("expected error"),
1111                         Err(e) => {
1112                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1113                         },
1114                 }
1115         }
1116
1117         #[test]
1118         fn parses_invoice_request_with_quantity() {
1119                 let one = NonZeroU64::new(1).unwrap();
1120                 let ten = NonZeroU64::new(10).unwrap();
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                         .build().unwrap()
1128                         .sign(payer_sign).unwrap();
1129
1130                 let mut buffer = Vec::new();
1131                 invoice_request.write(&mut buffer).unwrap();
1132
1133                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1134                         panic!("error parsing invoice_request: {:?}", e);
1135                 }
1136
1137                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1138                         .amount_msats(1000)
1139                         .supported_quantity(Quantity::One)
1140                         .build().unwrap()
1141                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142                         .amount_msats(2_000).unwrap()
1143                         .quantity_unchecked(2)
1144                         .build_unchecked()
1145                         .sign(payer_sign).unwrap();
1146
1147                 let mut buffer = Vec::new();
1148                 invoice_request.write(&mut buffer).unwrap();
1149
1150                 match InvoiceRequest::try_from(buffer) {
1151                         Ok(_) => panic!("expected error"),
1152                         Err(e) => {
1153                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1154                         },
1155                 }
1156
1157                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1158                         .amount_msats(1000)
1159                         .supported_quantity(Quantity::Bounded(ten))
1160                         .build().unwrap()
1161                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1162                         .amount_msats(10_000).unwrap()
1163                         .quantity(10).unwrap()
1164                         .build().unwrap()
1165                         .sign(payer_sign).unwrap();
1166
1167                 let mut buffer = Vec::new();
1168                 invoice_request.write(&mut buffer).unwrap();
1169
1170                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1171                         panic!("error parsing invoice_request: {:?}", e);
1172                 }
1173
1174                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1175                         .amount_msats(1000)
1176                         .supported_quantity(Quantity::Bounded(ten))
1177                         .build().unwrap()
1178                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1179                         .amount_msats(11_000).unwrap()
1180                         .quantity_unchecked(11)
1181                         .build_unchecked()
1182                         .sign(payer_sign).unwrap();
1183
1184                 let mut buffer = Vec::new();
1185                 invoice_request.write(&mut buffer).unwrap();
1186
1187                 match InvoiceRequest::try_from(buffer) {
1188                         Ok(_) => panic!("expected error"),
1189                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1190                 }
1191
1192                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1193                         .amount_msats(1000)
1194                         .supported_quantity(Quantity::Unbounded)
1195                         .build().unwrap()
1196                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1197                         .amount_msats(2_000).unwrap()
1198                         .quantity(2).unwrap()
1199                         .build().unwrap()
1200                         .sign(payer_sign).unwrap();
1201
1202                 let mut buffer = Vec::new();
1203                 invoice_request.write(&mut buffer).unwrap();
1204
1205                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1206                         panic!("error parsing invoice_request: {:?}", e);
1207                 }
1208
1209                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1210                         .amount_msats(1000)
1211                         .supported_quantity(Quantity::Unbounded)
1212                         .build().unwrap()
1213                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1214                         .build_unchecked()
1215                         .sign(payer_sign).unwrap();
1216
1217                 let mut buffer = Vec::new();
1218                 invoice_request.write(&mut buffer).unwrap();
1219
1220                 match InvoiceRequest::try_from(buffer) {
1221                         Ok(_) => panic!("expected error"),
1222                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1223                 }
1224
1225                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1226                         .amount_msats(1000)
1227                         .supported_quantity(Quantity::Bounded(one))
1228                         .build().unwrap()
1229                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1230                         .build_unchecked()
1231                         .sign(payer_sign).unwrap();
1232
1233                 let mut buffer = Vec::new();
1234                 invoice_request.write(&mut buffer).unwrap();
1235
1236                 match InvoiceRequest::try_from(buffer) {
1237                         Ok(_) => panic!("expected error"),
1238                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1239                 }
1240         }
1241
1242         #[test]
1243         fn fails_parsing_invoice_request_without_metadata() {
1244                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1245                         .amount_msats(1000)
1246                         .build().unwrap();
1247                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248                         .build().unwrap();
1249                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1250                 tlv_stream.0.metadata = None;
1251
1252                 let mut buffer = Vec::new();
1253                 tlv_stream.write(&mut buffer).unwrap();
1254
1255                 match InvoiceRequest::try_from(buffer) {
1256                         Ok(_) => panic!("expected error"),
1257                         Err(e) => {
1258                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1259                         },
1260                 }
1261         }
1262
1263         #[test]
1264         fn fails_parsing_invoice_request_without_payer_id() {
1265                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1266                         .amount_msats(1000)
1267                         .build().unwrap();
1268                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1269                         .build().unwrap();
1270                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1271                 tlv_stream.2.payer_id = None;
1272
1273                 let mut buffer = Vec::new();
1274                 tlv_stream.write(&mut buffer).unwrap();
1275
1276                 match InvoiceRequest::try_from(buffer) {
1277                         Ok(_) => panic!("expected error"),
1278                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1279                 }
1280         }
1281
1282         #[test]
1283         fn fails_parsing_invoice_request_without_node_id() {
1284                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1285                         .amount_msats(1000)
1286                         .build().unwrap();
1287                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288                         .build().unwrap();
1289                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1290                 tlv_stream.1.node_id = None;
1291
1292                 let mut buffer = Vec::new();
1293                 tlv_stream.write(&mut buffer).unwrap();
1294
1295                 match InvoiceRequest::try_from(buffer) {
1296                         Ok(_) => panic!("expected error"),
1297                         Err(e) => {
1298                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1299                         },
1300                 }
1301         }
1302
1303         #[test]
1304         fn fails_parsing_invoice_request_without_signature() {
1305                 let mut buffer = Vec::new();
1306                 OfferBuilder::new("foo".into(), recipient_pubkey())
1307                         .amount_msats(1000)
1308                         .build().unwrap()
1309                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1310                         .build().unwrap()
1311                         .invoice_request
1312                         .write(&mut buffer).unwrap();
1313
1314                 match InvoiceRequest::try_from(buffer) {
1315                         Ok(_) => panic!("expected error"),
1316                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1317                 }
1318         }
1319
1320         #[test]
1321         fn fails_parsing_invoice_request_with_invalid_signature() {
1322                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1323                         .amount_msats(1000)
1324                         .build().unwrap()
1325                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1326                         .build().unwrap()
1327                         .sign(payer_sign).unwrap();
1328                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1329                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1330
1331                 let mut buffer = Vec::new();
1332                 invoice_request.write(&mut buffer).unwrap();
1333
1334                 match InvoiceRequest::try_from(buffer) {
1335                         Ok(_) => panic!("expected error"),
1336                         Err(e) => {
1337                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1338                         },
1339                 }
1340         }
1341
1342         #[test]
1343         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1344                 let secp_ctx = Secp256k1::new();
1345                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1346                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1347                         .amount_msats(1000)
1348                         .build().unwrap()
1349                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1350                         .build().unwrap()
1351                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1352                         .unwrap();
1353
1354                 let mut encoded_invoice_request = Vec::new();
1355                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1356                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1357                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1358                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1359
1360                 match InvoiceRequest::try_from(encoded_invoice_request) {
1361                         Ok(_) => panic!("expected error"),
1362                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1363                 }
1364         }
1365 }