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