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