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