Refund encoding and parsing
[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 //! [`Refund`]: crate::offers::refund::Refund
20 //!
21 //! ```ignore
22 //! extern crate bitcoin;
23 //! extern crate lightning;
24 //!
25 //! use bitcoin::network::constants::Network;
26 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
27 //! use core::convert::Infallible;
28 //! use lightning::ln::features::OfferFeatures;
29 //! use lightning::offers::offer::Offer;
30 //! use lightning::util::ser::Writeable;
31 //!
32 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
33 //! let secp_ctx = Secp256k1::new();
34 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
35 //! let pubkey = PublicKey::from(keys);
36 //! let mut buffer = Vec::new();
37 //!
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         pub(super) 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         pub(super) 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 pertaining to requesting an 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, InvoiceRequestTlvStreamRef};
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, SignatureTlvStreamRef};
487         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
488         use crate::offers::parse::{ParseError, SemanticError};
489         use crate::offers::payer::PayerTlvStreamRef;
490         use crate::util::ser::{BigSize, Writeable};
491         use crate::util::string::PrintableString;
492
493         fn payer_keys() -> KeyPair {
494                 let secp_ctx = Secp256k1::new();
495                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
496         }
497
498         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
499                 let secp_ctx = Secp256k1::new();
500                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
501                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
502         }
503
504         fn payer_pubkey() -> PublicKey {
505                 payer_keys().public_key()
506         }
507
508         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
509                 let secp_ctx = Secp256k1::new();
510                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
511                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
512         }
513
514         fn recipient_pubkey() -> PublicKey {
515                 let secp_ctx = Secp256k1::new();
516                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
517         }
518
519         #[test]
520         fn builds_invoice_request_with_defaults() {
521                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
522                         .amount_msats(1000)
523                         .build().unwrap()
524                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
525                         .build().unwrap()
526                         .sign(payer_sign).unwrap();
527
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!(
542                         invoice_request.as_tlv_stream(),
543                         (
544                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
545                                 OfferTlvStreamRef {
546                                         chains: None,
547                                         metadata: None,
548                                         currency: None,
549                                         amount: Some(1000),
550                                         description: Some(&String::from("foo")),
551                                         features: None,
552                                         absolute_expiry: None,
553                                         paths: None,
554                                         issuer: None,
555                                         quantity_max: None,
556                                         node_id: Some(&recipient_pubkey()),
557                                 },
558                                 InvoiceRequestTlvStreamRef {
559                                         chain: None,
560                                         amount: None,
561                                         features: None,
562                                         quantity: None,
563                                         payer_id: Some(&payer_pubkey()),
564                                         payer_note: None,
565                                 },
566                                 SignatureTlvStreamRef { signature: invoice_request.signature().as_ref() },
567                         ),
568                 );
569
570                 if let Err(e) = InvoiceRequest::try_from(buffer) {
571                         panic!("error parsing invoice request: {:?}", e);
572                 }
573         }
574
575         #[cfg(feature = "std")]
576         #[test]
577         fn builds_invoice_request_from_offer_with_expiration() {
578                 let future_expiry = Duration::from_secs(u64::max_value());
579                 let past_expiry = Duration::from_secs(0);
580
581                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
582                         .amount_msats(1000)
583                         .absolute_expiry(future_expiry)
584                         .build().unwrap()
585                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
586                         .build()
587                 {
588                         panic!("error building invoice_request: {:?}", e);
589                 }
590
591                 match OfferBuilder::new("foo".into(), recipient_pubkey())
592                         .amount_msats(1000)
593                         .absolute_expiry(past_expiry)
594                         .build().unwrap()
595                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
596                         .build()
597                 {
598                         Ok(_) => panic!("expected error"),
599                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
600                 }
601         }
602
603         #[test]
604         fn builds_invoice_request_with_chain() {
605                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
606                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
607
608                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
609                         .amount_msats(1000)
610                         .build().unwrap()
611                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
612                         .chain(Network::Bitcoin).unwrap()
613                         .build().unwrap()
614                         .sign(payer_sign).unwrap();
615                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
616                 assert_eq!(invoice_request.chain(), mainnet);
617                 assert_eq!(tlv_stream.chain, None);
618
619                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
620                         .amount_msats(1000)
621                         .chain(Network::Testnet)
622                         .build().unwrap()
623                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
624                         .chain(Network::Testnet).unwrap()
625                         .build().unwrap()
626                         .sign(payer_sign).unwrap();
627                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
628                 assert_eq!(invoice_request.chain(), testnet);
629                 assert_eq!(tlv_stream.chain, Some(&testnet));
630
631                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
632                         .amount_msats(1000)
633                         .chain(Network::Bitcoin)
634                         .chain(Network::Testnet)
635                         .build().unwrap()
636                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
637                         .chain(Network::Bitcoin).unwrap()
638                         .build().unwrap()
639                         .sign(payer_sign).unwrap();
640                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
641                 assert_eq!(invoice_request.chain(), mainnet);
642                 assert_eq!(tlv_stream.chain, None);
643
644                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
645                         .amount_msats(1000)
646                         .chain(Network::Bitcoin)
647                         .chain(Network::Testnet)
648                         .build().unwrap()
649                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
650                         .chain(Network::Bitcoin).unwrap()
651                         .chain(Network::Testnet).unwrap()
652                         .build().unwrap()
653                         .sign(payer_sign).unwrap();
654                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
655                 assert_eq!(invoice_request.chain(), testnet);
656                 assert_eq!(tlv_stream.chain, Some(&testnet));
657
658                 match OfferBuilder::new("foo".into(), recipient_pubkey())
659                         .amount_msats(1000)
660                         .chain(Network::Testnet)
661                         .build().unwrap()
662                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
663                         .chain(Network::Bitcoin)
664                 {
665                         Ok(_) => panic!("expected error"),
666                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
667                 }
668
669                 match OfferBuilder::new("foo".into(), recipient_pubkey())
670                         .amount_msats(1000)
671                         .chain(Network::Testnet)
672                         .build().unwrap()
673                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
674                         .build()
675                 {
676                         Ok(_) => panic!("expected error"),
677                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
678                 }
679         }
680
681         #[test]
682         fn builds_invoice_request_with_amount() {
683                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
684                         .amount_msats(1000)
685                         .build().unwrap()
686                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
687                         .amount_msats(1000).unwrap()
688                         .build().unwrap()
689                         .sign(payer_sign).unwrap();
690                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
691                 assert_eq!(invoice_request.amount_msats(), Some(1000));
692                 assert_eq!(tlv_stream.amount, Some(1000));
693
694                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
695                         .amount_msats(1000)
696                         .build().unwrap()
697                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
698                         .amount_msats(1001).unwrap()
699                         .amount_msats(1000).unwrap()
700                         .build().unwrap()
701                         .sign(payer_sign).unwrap();
702                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
703                 assert_eq!(invoice_request.amount_msats(), Some(1000));
704                 assert_eq!(tlv_stream.amount, Some(1000));
705
706                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
707                         .amount_msats(1000)
708                         .build().unwrap()
709                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
710                         .amount_msats(1001).unwrap()
711                         .build().unwrap()
712                         .sign(payer_sign).unwrap();
713                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
714                 assert_eq!(invoice_request.amount_msats(), Some(1001));
715                 assert_eq!(tlv_stream.amount, Some(1001));
716
717                 match OfferBuilder::new("foo".into(), recipient_pubkey())
718                         .amount_msats(1000)
719                         .build().unwrap()
720                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
721                         .amount_msats(999)
722                 {
723                         Ok(_) => panic!("expected error"),
724                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
725                 }
726
727                 match OfferBuilder::new("foo".into(), recipient_pubkey())
728                         .amount_msats(1000)
729                         .supported_quantity(Quantity::Unbounded)
730                         .build().unwrap()
731                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
732                         .quantity(2).unwrap()
733                         .amount_msats(1000)
734                 {
735                         Ok(_) => panic!("expected error"),
736                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
737                 }
738
739                 match OfferBuilder::new("foo".into(), recipient_pubkey())
740                         .amount_msats(1000)
741                         .build().unwrap()
742                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
743                         .amount_msats(MAX_VALUE_MSAT + 1)
744                 {
745                         Ok(_) => panic!("expected error"),
746                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
747                 }
748
749                 match OfferBuilder::new("foo".into(), recipient_pubkey())
750                         .amount_msats(1000)
751                         .supported_quantity(Quantity::Unbounded)
752                         .build().unwrap()
753                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
754                         .amount_msats(1000).unwrap()
755                         .quantity(2).unwrap()
756                         .build()
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                         .build().unwrap()
764                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
765                         .build()
766                 {
767                         Ok(_) => panic!("expected error"),
768                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
769                 }
770         }
771
772         #[test]
773         fn builds_invoice_request_with_features() {
774                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
775                         .amount_msats(1000)
776                         .build().unwrap()
777                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
778                         .features_unchecked(InvoiceRequestFeatures::unknown())
779                         .build().unwrap()
780                         .sign(payer_sign).unwrap();
781                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
782                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
783                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
784
785                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
786                         .amount_msats(1000)
787                         .build().unwrap()
788                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
789                         .features_unchecked(InvoiceRequestFeatures::unknown())
790                         .features_unchecked(InvoiceRequestFeatures::empty())
791                         .build().unwrap()
792                         .sign(payer_sign).unwrap();
793                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
794                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
795                 assert_eq!(tlv_stream.features, None);
796         }
797
798         #[test]
799         fn builds_invoice_request_with_quantity() {
800                 let ten = NonZeroU64::new(10).unwrap();
801
802                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
803                         .amount_msats(1000)
804                         .supported_quantity(Quantity::one())
805                         .build().unwrap()
806                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
807                         .build().unwrap()
808                         .sign(payer_sign).unwrap();
809                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
810                 assert_eq!(invoice_request.quantity(), None);
811                 assert_eq!(tlv_stream.quantity, None);
812
813                 match OfferBuilder::new("foo".into(), recipient_pubkey())
814                         .amount_msats(1000)
815                         .supported_quantity(Quantity::one())
816                         .build().unwrap()
817                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
818                         .amount_msats(2_000).unwrap()
819                         .quantity(2)
820                 {
821                         Ok(_) => panic!("expected error"),
822                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
823                 }
824
825                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
826                         .amount_msats(1000)
827                         .supported_quantity(Quantity::Bounded(ten))
828                         .build().unwrap()
829                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
830                         .amount_msats(10_000).unwrap()
831                         .quantity(10).unwrap()
832                         .build().unwrap()
833                         .sign(payer_sign).unwrap();
834                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
835                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
836                 assert_eq!(tlv_stream.amount, Some(10_000));
837
838                 match OfferBuilder::new("foo".into(), recipient_pubkey())
839                         .amount_msats(1000)
840                         .supported_quantity(Quantity::Bounded(ten))
841                         .build().unwrap()
842                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
843                         .amount_msats(11_000).unwrap()
844                         .quantity(11)
845                 {
846                         Ok(_) => panic!("expected error"),
847                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
848                 }
849
850                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
851                         .amount_msats(1000)
852                         .supported_quantity(Quantity::Unbounded)
853                         .build().unwrap()
854                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
855                         .amount_msats(2_000).unwrap()
856                         .quantity(2).unwrap()
857                         .build().unwrap()
858                         .sign(payer_sign).unwrap();
859                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
860                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
861                 assert_eq!(tlv_stream.amount, Some(2_000));
862
863                 match OfferBuilder::new("foo".into(), recipient_pubkey())
864                         .amount_msats(1000)
865                         .supported_quantity(Quantity::Unbounded)
866                         .build().unwrap()
867                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
868                         .build()
869                 {
870                         Ok(_) => panic!("expected error"),
871                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
872                 }
873         }
874
875         #[test]
876         fn builds_invoice_request_with_payer_note() {
877                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
878                         .amount_msats(1000)
879                         .build().unwrap()
880                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
881                         .payer_note("bar".into())
882                         .build().unwrap()
883                         .sign(payer_sign).unwrap();
884                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
885                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
886                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
887
888                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
889                         .amount_msats(1000)
890                         .build().unwrap()
891                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
892                         .payer_note("bar".into())
893                         .payer_note("baz".into())
894                         .build().unwrap()
895                         .sign(payer_sign).unwrap();
896                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
897                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
898                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
899         }
900
901         #[test]
902         fn fails_signing_invoice_request() {
903                 match OfferBuilder::new("foo".into(), recipient_pubkey())
904                         .amount_msats(1000)
905                         .build().unwrap()
906                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
907                         .build().unwrap()
908                         .sign(|_| Err(()))
909                 {
910                         Ok(_) => panic!("expected error"),
911                         Err(e) => assert_eq!(e, SignError::Signing(())),
912                 }
913
914                 match OfferBuilder::new("foo".into(), recipient_pubkey())
915                         .amount_msats(1000)
916                         .build().unwrap()
917                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
918                         .build().unwrap()
919                         .sign(recipient_sign)
920                 {
921                         Ok(_) => panic!("expected error"),
922                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
923                 }
924         }
925
926         #[test]
927         fn parses_invoice_request_with_metadata() {
928                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
929                         .amount_msats(1000)
930                         .build().unwrap()
931                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
932                         .build().unwrap()
933                         .sign(payer_sign).unwrap();
934
935                 let mut buffer = Vec::new();
936                 invoice_request.write(&mut buffer).unwrap();
937
938                 if let Err(e) = InvoiceRequest::try_from(buffer) {
939                         panic!("error parsing invoice_request: {:?}", e);
940                 }
941         }
942
943         #[test]
944         fn parses_invoice_request_with_chain() {
945                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
946                         .amount_msats(1000)
947                         .build().unwrap()
948                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
949                         .chain(Network::Bitcoin).unwrap()
950                         .build().unwrap()
951                         .sign(payer_sign).unwrap();
952
953                 let mut buffer = Vec::new();
954                 invoice_request.write(&mut buffer).unwrap();
955
956                 if let Err(e) = InvoiceRequest::try_from(buffer) {
957                         panic!("error parsing invoice_request: {:?}", e);
958                 }
959
960                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
961                         .amount_msats(1000)
962                         .build().unwrap()
963                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
964                         .chain_unchecked(Network::Testnet)
965                         .build_unchecked()
966                         .sign(payer_sign).unwrap();
967
968                 let mut buffer = Vec::new();
969                 invoice_request.write(&mut buffer).unwrap();
970
971                 match InvoiceRequest::try_from(buffer) {
972                         Ok(_) => panic!("expected error"),
973                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
974                 }
975         }
976
977         #[test]
978         fn parses_invoice_request_with_amount() {
979                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
980                         .amount_msats(1000)
981                         .build().unwrap()
982                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
983                         .build().unwrap()
984                         .sign(payer_sign).unwrap();
985
986                 let mut buffer = Vec::new();
987                 invoice_request.write(&mut buffer).unwrap();
988
989                 if let Err(e) = InvoiceRequest::try_from(buffer) {
990                         panic!("error parsing invoice_request: {:?}", e);
991                 }
992
993                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
994                         .build().unwrap()
995                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
996                         .amount_msats(1000).unwrap()
997                         .build().unwrap()
998                         .sign(payer_sign).unwrap();
999
1000                 let mut buffer = Vec::new();
1001                 invoice_request.write(&mut buffer).unwrap();
1002
1003                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1004                         panic!("error parsing invoice_request: {:?}", e);
1005                 }
1006
1007                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1008                         .build().unwrap()
1009                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1010                         .build_unchecked()
1011                         .sign(payer_sign).unwrap();
1012
1013                 let mut buffer = Vec::new();
1014                 invoice_request.write(&mut buffer).unwrap();
1015
1016                 match InvoiceRequest::try_from(buffer) {
1017                         Ok(_) => panic!("expected error"),
1018                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1019                 }
1020
1021                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1022                         .amount_msats(1000)
1023                         .build().unwrap()
1024                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1025                         .amount_msats_unchecked(999)
1026                         .build_unchecked()
1027                         .sign(payer_sign).unwrap();
1028
1029                 let mut buffer = Vec::new();
1030                 invoice_request.write(&mut buffer).unwrap();
1031
1032                 match InvoiceRequest::try_from(buffer) {
1033                         Ok(_) => panic!("expected error"),
1034                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1035                 }
1036
1037                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1038                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1039                         .build_unchecked()
1040                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1041                         .build_unchecked()
1042                         .sign(payer_sign).unwrap();
1043
1044                 let mut buffer = Vec::new();
1045                 invoice_request.write(&mut buffer).unwrap();
1046
1047                 match InvoiceRequest::try_from(buffer) {
1048                         Ok(_) => panic!("expected error"),
1049                         Err(e) => {
1050                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1051                         },
1052                 }
1053         }
1054
1055         #[test]
1056         fn parses_invoice_request_with_quantity() {
1057                 let ten = NonZeroU64::new(10).unwrap();
1058
1059                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1060                         .amount_msats(1000)
1061                         .supported_quantity(Quantity::one())
1062                         .build().unwrap()
1063                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1064                         .build().unwrap()
1065                         .sign(payer_sign).unwrap();
1066
1067                 let mut buffer = Vec::new();
1068                 invoice_request.write(&mut buffer).unwrap();
1069
1070                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1071                         panic!("error parsing invoice_request: {:?}", e);
1072                 }
1073
1074                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1075                         .amount_msats(1000)
1076                         .supported_quantity(Quantity::one())
1077                         .build().unwrap()
1078                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1079                         .amount_msats(2_000).unwrap()
1080                         .quantity_unchecked(2)
1081                         .build_unchecked()
1082                         .sign(payer_sign).unwrap();
1083
1084                 let mut buffer = Vec::new();
1085                 invoice_request.write(&mut buffer).unwrap();
1086
1087                 match InvoiceRequest::try_from(buffer) {
1088                         Ok(_) => panic!("expected error"),
1089                         Err(e) => {
1090                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1091                         },
1092                 }
1093
1094                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1095                         .amount_msats(1000)
1096                         .supported_quantity(Quantity::Bounded(ten))
1097                         .build().unwrap()
1098                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1099                         .amount_msats(10_000).unwrap()
1100                         .quantity(10).unwrap()
1101                         .build().unwrap()
1102                         .sign(payer_sign).unwrap();
1103
1104                 let mut buffer = Vec::new();
1105                 invoice_request.write(&mut buffer).unwrap();
1106
1107                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1108                         panic!("error parsing invoice_request: {:?}", e);
1109                 }
1110
1111                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1112                         .amount_msats(1000)
1113                         .supported_quantity(Quantity::Bounded(ten))
1114                         .build().unwrap()
1115                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1116                         .amount_msats(11_000).unwrap()
1117                         .quantity_unchecked(11)
1118                         .build_unchecked()
1119                         .sign(payer_sign).unwrap();
1120
1121                 let mut buffer = Vec::new();
1122                 invoice_request.write(&mut buffer).unwrap();
1123
1124                 match InvoiceRequest::try_from(buffer) {
1125                         Ok(_) => panic!("expected error"),
1126                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1127                 }
1128
1129                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1130                         .amount_msats(1000)
1131                         .supported_quantity(Quantity::Unbounded)
1132                         .build().unwrap()
1133                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1134                         .amount_msats(2_000).unwrap()
1135                         .quantity(2).unwrap()
1136                         .build().unwrap()
1137                         .sign(payer_sign).unwrap();
1138
1139                 let mut buffer = Vec::new();
1140                 invoice_request.write(&mut buffer).unwrap();
1141
1142                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1143                         panic!("error parsing invoice_request: {:?}", e);
1144                 }
1145
1146                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1147                         .amount_msats(1000)
1148                         .supported_quantity(Quantity::Unbounded)
1149                         .build().unwrap()
1150                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151                         .build_unchecked()
1152                         .sign(payer_sign).unwrap();
1153
1154                 let mut buffer = Vec::new();
1155                 invoice_request.write(&mut buffer).unwrap();
1156
1157                 match InvoiceRequest::try_from(buffer) {
1158                         Ok(_) => panic!("expected error"),
1159                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1160                 }
1161         }
1162
1163         #[test]
1164         fn fails_parsing_invoice_request_without_metadata() {
1165                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1166                         .amount_msats(1000)
1167                         .build().unwrap();
1168                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1169                         .build().unwrap();
1170                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1171                 tlv_stream.0.metadata = None;
1172
1173                 let mut buffer = Vec::new();
1174                 tlv_stream.write(&mut buffer).unwrap();
1175
1176                 match InvoiceRequest::try_from(buffer) {
1177                         Ok(_) => panic!("expected error"),
1178                         Err(e) => {
1179                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1180                         },
1181                 }
1182         }
1183
1184         #[test]
1185         fn fails_parsing_invoice_request_without_payer_id() {
1186                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1187                         .amount_msats(1000)
1188                         .build().unwrap();
1189                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1190                         .build().unwrap();
1191                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1192                 tlv_stream.2.payer_id = None;
1193
1194                 let mut buffer = Vec::new();
1195                 tlv_stream.write(&mut buffer).unwrap();
1196
1197                 match InvoiceRequest::try_from(buffer) {
1198                         Ok(_) => panic!("expected error"),
1199                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1200                 }
1201         }
1202
1203         #[test]
1204         fn fails_parsing_invoice_request_without_node_id() {
1205                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1206                         .amount_msats(1000)
1207                         .build().unwrap();
1208                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1209                         .build().unwrap();
1210                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1211                 tlv_stream.1.node_id = None;
1212
1213                 let mut buffer = Vec::new();
1214                 tlv_stream.write(&mut buffer).unwrap();
1215
1216                 match InvoiceRequest::try_from(buffer) {
1217                         Ok(_) => panic!("expected error"),
1218                         Err(e) => {
1219                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1220                         },
1221                 }
1222         }
1223
1224         #[test]
1225         fn parses_invoice_request_without_signature() {
1226                 let mut buffer = Vec::new();
1227                 OfferBuilder::new("foo".into(), recipient_pubkey())
1228                         .amount_msats(1000)
1229                         .build().unwrap()
1230                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231                         .build().unwrap()
1232                         .invoice_request
1233                         .write(&mut buffer).unwrap();
1234
1235                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1236                         panic!("error parsing invoice_request: {:?}", e);
1237                 }
1238         }
1239
1240         #[test]
1241         fn fails_parsing_invoice_request_with_invalid_signature() {
1242                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1243                         .amount_msats(1000)
1244                         .build().unwrap()
1245                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1246                         .build().unwrap()
1247                         .sign(payer_sign).unwrap();
1248                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1249                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1250
1251                 let mut buffer = Vec::new();
1252                 invoice_request.write(&mut buffer).unwrap();
1253
1254                 match InvoiceRequest::try_from(buffer) {
1255                         Ok(_) => panic!("expected error"),
1256                         Err(e) => {
1257                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1258                         },
1259                 }
1260         }
1261
1262         #[test]
1263         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1264                 let secp_ctx = Secp256k1::new();
1265                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1266                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1267                         .amount_msats(1000)
1268                         .build().unwrap()
1269                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1270                         .build().unwrap()
1271                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1272                         .unwrap();
1273
1274                 let mut encoded_invoice_request = Vec::new();
1275                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1276                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1277                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1278                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1279
1280                 match InvoiceRequest::try_from(encoded_invoice_request) {
1281                         Ok(_) => panic!("expected error"),
1282                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1283                 }
1284         }
1285 }