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