a1a0520c62259409b4cd516ed9607eb17bad3296
[rust-lightning] / lightning / src / offers / invoice_request.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Data structures and encoding for `invoice_request` messages.
11 //!
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with an [`Invoice`].
15 //!
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
18 //!
19 //! [`Invoice`]: crate::offers::invoice::Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
21 //!
22 //! ```
23 //! extern crate bitcoin;
24 //! extern crate lightning;
25 //!
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
32 //!
33 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
38 //!
39 //! "lno1qcp4256ypq"
40 //!     .parse::<Offer>()?
41 //!     .request_invoice(vec![42; 64], pubkey)?
42 //!     .chain(Network::Testnet)?
43 //!     .amount_msats(1000)?
44 //!     .quantity(5)?
45 //!     .payer_note("foo".to_string())
46 //!     .build()?
47 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
48 //!     .expect("failed verifying signature")
49 //!     .write(&mut buffer)
50 //!     .unwrap();
51 //! # Ok(())
52 //! # }
53 //! ```
54
55 use bitcoin::blockdata::constants::ChainHash;
56 use bitcoin::network::constants::Network;
57 use bitcoin::secp256k1::{Message, PublicKey};
58 use bitcoin::secp256k1::schnorr::Signature;
59 use core::convert::TryFrom;
60 use crate::io;
61 use crate::ln::PaymentHash;
62 use crate::ln::features::InvoiceRequestFeatures;
63 use crate::ln::msgs::DecodeError;
64 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
65 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
66 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
67 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
68 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
69 use crate::onion_message::BlindedPath;
70 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
71 use crate::util::string::PrintableString;
72
73 use crate::prelude::*;
74
75 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
76
77 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
78 ///
79 /// See [module-level documentation] for usage.
80 ///
81 /// [module-level documentation]: self
82 pub struct InvoiceRequestBuilder<'a> {
83         offer: &'a Offer,
84         invoice_request: InvoiceRequestContents,
85 }
86
87 impl<'a> InvoiceRequestBuilder<'a> {
88         pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
89                 Self {
90                         offer,
91                         invoice_request: InvoiceRequestContents {
92                                 payer: PayerContents(metadata), offer: offer.contents.clone(), chain: None,
93                                 amount_msats: None, features: InvoiceRequestFeatures::empty(), quantity: None,
94                                 payer_id, payer_note: None,
95                         },
96                 }
97         }
98
99         /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
100         /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
101         /// by the offer.
102         ///
103         /// Successive calls to this method will override the previous setting.
104         pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
105                 let chain = ChainHash::using_genesis_block(network);
106                 if !self.offer.supports_chain(chain) {
107                         return Err(SemanticError::UnsupportedChain);
108                 }
109
110                 self.invoice_request.chain = Some(chain);
111                 Ok(self)
112         }
113
114         /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
115         /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
116         ///
117         /// Successive calls to this method will override the previous setting.
118         ///
119         /// [`quantity`]: Self::quantity
120         pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
121                 self.invoice_request.offer.check_amount_msats_for_quantity(
122                         Some(amount_msats), self.invoice_request.quantity
123                 )?;
124                 self.invoice_request.amount_msats = Some(amount_msats);
125                 Ok(self)
126         }
127
128         /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
129         /// does not conform to [`Offer::is_valid_quantity`].
130         ///
131         /// Successive calls to this method will override the previous setting.
132         pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
133                 self.invoice_request.offer.check_quantity(Some(quantity))?;
134                 self.invoice_request.quantity = Some(quantity);
135                 Ok(self)
136         }
137
138         /// Sets the [`InvoiceRequest::payer_note`].
139         ///
140         /// Successive calls to this method will override the previous setting.
141         pub fn payer_note(mut self, payer_note: String) -> Self {
142                 self.invoice_request.payer_note = Some(payer_note);
143                 self
144         }
145
146         /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
147         /// by [`UnsignedInvoiceRequest::sign`].
148         pub fn build(mut self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
149                 #[cfg(feature = "std")] {
150                         if self.offer.is_expired() {
151                                 return Err(SemanticError::AlreadyExpired);
152                         }
153                 }
154
155                 let chain = self.invoice_request.chain();
156                 if !self.offer.supports_chain(chain) {
157                         return Err(SemanticError::UnsupportedChain);
158                 }
159
160                 if chain == self.offer.implied_chain() {
161                         self.invoice_request.chain = None;
162                 }
163
164                 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
165                         return Err(SemanticError::MissingAmount);
166                 }
167
168                 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
169                 self.invoice_request.offer.check_amount_msats_for_quantity(
170                         self.invoice_request.amount_msats, self.invoice_request.quantity
171                 )?;
172
173                 let InvoiceRequestBuilder { offer, invoice_request } = self;
174                 Ok(UnsignedInvoiceRequest { offer, invoice_request })
175         }
176 }
177
178 #[cfg(test)]
179 impl<'a> InvoiceRequestBuilder<'a> {
180         fn chain_unchecked(mut self, network: Network) -> Self {
181                 let chain = ChainHash::using_genesis_block(network);
182                 self.invoice_request.chain = Some(chain);
183                 self
184         }
185
186         fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
187                 self.invoice_request.amount_msats = Some(amount_msats);
188                 self
189         }
190
191         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
192                 self.invoice_request.features = features;
193                 self
194         }
195
196         fn quantity_unchecked(mut self, quantity: u64) -> Self {
197                 self.invoice_request.quantity = Some(quantity);
198                 self
199         }
200
201         pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
202                 let InvoiceRequestBuilder { offer, invoice_request } = self;
203                 UnsignedInvoiceRequest { offer, invoice_request }
204         }
205 }
206
207 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
208 pub struct UnsignedInvoiceRequest<'a> {
209         offer: &'a Offer,
210         invoice_request: InvoiceRequestContents,
211 }
212
213 impl<'a> UnsignedInvoiceRequest<'a> {
214         /// Signs the invoice request using the given function.
215         pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
216         where
217                 F: FnOnce(&Message) -> Result<Signature, E>
218         {
219                 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
220                 // unknown TLV records, which are not stored in `OfferContents`.
221                 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
222                         self.invoice_request.as_tlv_stream();
223                 let offer_bytes = WithoutLength(&self.offer.bytes);
224                 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
225
226                 let mut bytes = Vec::new();
227                 unsigned_tlv_stream.write(&mut bytes).unwrap();
228
229                 let pubkey = self.invoice_request.payer_id;
230                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
231
232                 // Append the signature TLV record to the bytes.
233                 let signature_tlv_stream = SignatureTlvStreamRef {
234                         signature: Some(&signature),
235                 };
236                 signature_tlv_stream.write(&mut bytes).unwrap();
237
238                 Ok(InvoiceRequest {
239                         bytes,
240                         contents: self.invoice_request,
241                         signature,
242                 })
243         }
244 }
245
246 /// An `InvoiceRequest` is a request for an [`Invoice`] formulated from an [`Offer`].
247 ///
248 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
249 /// specifies these such that its recipient can send an invoice for payment.
250 ///
251 /// [`Invoice`]: crate::offers::invoice::Invoice
252 /// [`Offer`]: crate::offers::offer::Offer
253 #[derive(Clone, Debug, PartialEq)]
254 pub struct InvoiceRequest {
255         pub(super) bytes: Vec<u8>,
256         pub(super) contents: InvoiceRequestContents,
257         signature: Signature,
258 }
259
260 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Invoice`].
261 ///
262 /// [`Invoice`]: crate::offers::invoice::Invoice
263 #[derive(Clone, Debug, PartialEq)]
264 pub(super) struct InvoiceRequestContents {
265         payer: PayerContents,
266         pub(super) offer: OfferContents,
267         chain: Option<ChainHash>,
268         amount_msats: Option<u64>,
269         features: InvoiceRequestFeatures,
270         quantity: Option<u64>,
271         payer_id: PublicKey,
272         payer_note: Option<String>,
273 }
274
275 impl InvoiceRequest {
276         /// An unpredictable series of bytes, typically containing information about the derivation of
277         /// [`payer_id`].
278         ///
279         /// [`payer_id`]: Self::payer_id
280         pub fn metadata(&self) -> &[u8] {
281                 &self.contents.payer.0[..]
282         }
283
284         /// A chain from [`Offer::chains`] that the offer is valid for.
285         pub fn chain(&self) -> ChainHash {
286                 self.contents.chain()
287         }
288
289         /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
290         /// must be greater than or equal to [`Offer::amount`], converted if necessary.
291         ///
292         /// [`chain`]: Self::chain
293         pub fn amount_msats(&self) -> Option<u64> {
294                 self.contents.amount_msats
295         }
296
297         /// Features pertaining to requesting an invoice.
298         pub fn features(&self) -> &InvoiceRequestFeatures {
299                 &self.contents.features
300         }
301
302         /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
303         pub fn quantity(&self) -> Option<u64> {
304                 self.contents.quantity
305         }
306
307         /// A possibly transient pubkey used to sign the invoice request.
308         pub fn payer_id(&self) -> PublicKey {
309                 self.contents.payer_id
310         }
311
312         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
313         /// response.
314         pub fn payer_note(&self) -> Option<PrintableString> {
315                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
316         }
317
318         /// Signature of the invoice request using [`payer_id`].
319         ///
320         /// [`payer_id`]: Self::payer_id
321         pub fn signature(&self) -> Signature {
322                 self.signature
323         }
324
325         /// Creates an [`Invoice`] for the request with the given required fields and using the
326         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
327         ///
328         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
329         /// creation time is used for the `created_at` parameter.
330         ///
331         /// [`Invoice`]: crate::offers::invoice::Invoice
332         /// [`Duration`]: core::time::Duration
333         #[cfg(feature = "std")]
334         pub fn respond_with(
335                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
336         ) -> Result<InvoiceBuilder, SemanticError> {
337                 let created_at = std::time::SystemTime::now()
338                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
339                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
340
341                 self.respond_with_no_std(payment_paths, payment_hash, created_at)
342         }
343
344         /// Creates an [`Invoice`] for the request with the given required fields.
345         ///
346         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
347         /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
348         /// [`std::time::SystemTime`] is not available.
349         ///
350         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
351         /// for the invoice.
352         ///
353         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
354         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
355         /// a preference. Note, however, that any privacy is lost if a public node id was used for
356         /// [`Offer::signing_pubkey`].
357         ///
358         /// Errors if the request contains unknown required features.
359         ///
360         /// [`Invoice`]: crate::offers::invoice::Invoice
361         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
362         pub fn respond_with_no_std(
363                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
364                 created_at: core::time::Duration
365         ) -> Result<InvoiceBuilder, SemanticError> {
366                 if self.features().requires_unknown_bits() {
367                         return Err(SemanticError::UnknownRequiredFeatures);
368                 }
369
370                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
371         }
372
373         #[cfg(test)]
374         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
375                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
376                         self.contents.as_tlv_stream();
377                 let signature_tlv_stream = SignatureTlvStreamRef {
378                         signature: Some(&self.signature),
379                 };
380                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
381         }
382 }
383
384 impl InvoiceRequestContents {
385         pub(super) fn chain(&self) -> ChainHash {
386                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
387         }
388
389         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
390                 let payer = PayerTlvStreamRef {
391                         metadata: Some(&self.payer.0),
392                 };
393
394                 let offer = self.offer.as_tlv_stream();
395
396                 let features = {
397                         if self.features == InvoiceRequestFeatures::empty() { None }
398                         else { Some(&self.features) }
399                 };
400
401                 let invoice_request = InvoiceRequestTlvStreamRef {
402                         chain: self.chain.as_ref(),
403                         amount: self.amount_msats,
404                         features,
405                         quantity: self.quantity,
406                         payer_id: Some(&self.payer_id),
407                         payer_note: self.payer_note.as_ref(),
408                 };
409
410                 (payer, offer, invoice_request)
411         }
412 }
413
414 impl Writeable for InvoiceRequest {
415         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
416                 WithoutLength(&self.bytes).write(writer)
417         }
418 }
419
420 impl Writeable for InvoiceRequestContents {
421         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
422                 self.as_tlv_stream().write(writer)
423         }
424 }
425
426 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
427         (80, chain: ChainHash),
428         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
429         (84, features: (InvoiceRequestFeatures, WithoutLength)),
430         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
431         (88, payer_id: PublicKey),
432         (89, payer_note: (String, WithoutLength)),
433 });
434
435 type FullInvoiceRequestTlvStream =
436         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
437
438 #[cfg(test)]
439 type FullInvoiceRequestTlvStreamRef<'a> = (
440         PayerTlvStreamRef<'a>,
441         OfferTlvStreamRef<'a>,
442         InvoiceRequestTlvStreamRef<'a>,
443         SignatureTlvStreamRef<'a>,
444 );
445
446 impl SeekReadable for FullInvoiceRequestTlvStream {
447         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
448                 let payer = SeekReadable::read(r)?;
449                 let offer = SeekReadable::read(r)?;
450                 let invoice_request = SeekReadable::read(r)?;
451                 let signature = SeekReadable::read(r)?;
452
453                 Ok((payer, offer, invoice_request, signature))
454         }
455 }
456
457 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
458
459 type PartialInvoiceRequestTlvStreamRef<'a> = (
460         PayerTlvStreamRef<'a>,
461         OfferTlvStreamRef<'a>,
462         InvoiceRequestTlvStreamRef<'a>,
463 );
464
465 impl TryFrom<Vec<u8>> for InvoiceRequest {
466         type Error = ParseError;
467
468         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
469                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
470                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
471                 let (
472                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
473                         SignatureTlvStream { signature },
474                 ) = tlv_stream;
475                 let contents = InvoiceRequestContents::try_from(
476                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
477                 )?;
478
479                 let signature = match signature {
480                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
481                         Some(signature) => signature,
482                 };
483                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
484
485                 Ok(InvoiceRequest { bytes, contents, signature })
486         }
487 }
488
489 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
490         type Error = SemanticError;
491
492         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
493                 let (
494                         PayerTlvStream { metadata },
495                         offer_tlv_stream,
496                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
497                 ) = tlv_stream;
498
499                 let payer = match metadata {
500                         None => return Err(SemanticError::MissingPayerMetadata),
501                         Some(metadata) => PayerContents(metadata),
502                 };
503                 let offer = OfferContents::try_from(offer_tlv_stream)?;
504
505                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
506                         return Err(SemanticError::UnsupportedChain);
507                 }
508
509                 if offer.amount().is_none() && amount.is_none() {
510                         return Err(SemanticError::MissingAmount);
511                 }
512
513                 offer.check_quantity(quantity)?;
514                 offer.check_amount_msats_for_quantity(amount, quantity)?;
515
516                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
517
518                 let payer_id = match payer_id {
519                         None => return Err(SemanticError::MissingPayerId),
520                         Some(payer_id) => payer_id,
521                 };
522
523                 Ok(InvoiceRequestContents {
524                         payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
525                 })
526         }
527 }
528
529 #[cfg(test)]
530 mod tests {
531         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
532
533         use bitcoin::blockdata::constants::ChainHash;
534         use bitcoin::network::constants::Network;
535         use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
536         use bitcoin::secp256k1::schnorr::Signature;
537         use core::convert::{Infallible, TryFrom};
538         use core::num::NonZeroU64;
539         #[cfg(feature = "std")]
540         use core::time::Duration;
541         use crate::ln::features::InvoiceRequestFeatures;
542         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
543         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
544         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
545         use crate::offers::parse::{ParseError, SemanticError};
546         use crate::offers::payer::PayerTlvStreamRef;
547         use crate::util::ser::{BigSize, Writeable};
548         use crate::util::string::PrintableString;
549
550         fn payer_keys() -> KeyPair {
551                 let secp_ctx = Secp256k1::new();
552                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
553         }
554
555         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
556                 let secp_ctx = Secp256k1::new();
557                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
558                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
559         }
560
561         fn payer_pubkey() -> PublicKey {
562                 payer_keys().public_key()
563         }
564
565         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
566                 let secp_ctx = Secp256k1::new();
567                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
568                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
569         }
570
571         fn recipient_pubkey() -> PublicKey {
572                 let secp_ctx = Secp256k1::new();
573                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
574         }
575
576         #[test]
577         fn builds_invoice_request_with_defaults() {
578                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
579                         .amount_msats(1000)
580                         .build().unwrap()
581                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
582                         .build().unwrap()
583                         .sign(payer_sign).unwrap();
584
585                 let mut buffer = Vec::new();
586                 invoice_request.write(&mut buffer).unwrap();
587
588                 assert_eq!(invoice_request.bytes, buffer.as_slice());
589                 assert_eq!(invoice_request.metadata(), &[1; 32]);
590                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
591                 assert_eq!(invoice_request.amount_msats(), None);
592                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
593                 assert_eq!(invoice_request.quantity(), None);
594                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
595                 assert_eq!(invoice_request.payer_note(), None);
596                 assert!(
597                         merkle::verify_signature(
598                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
599                         ).is_ok()
600                 );
601
602                 assert_eq!(
603                         invoice_request.as_tlv_stream(),
604                         (
605                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
606                                 OfferTlvStreamRef {
607                                         chains: None,
608                                         metadata: None,
609                                         currency: None,
610                                         amount: Some(1000),
611                                         description: Some(&String::from("foo")),
612                                         features: None,
613                                         absolute_expiry: None,
614                                         paths: None,
615                                         issuer: None,
616                                         quantity_max: None,
617                                         node_id: Some(&recipient_pubkey()),
618                                 },
619                                 InvoiceRequestTlvStreamRef {
620                                         chain: None,
621                                         amount: None,
622                                         features: None,
623                                         quantity: None,
624                                         payer_id: Some(&payer_pubkey()),
625                                         payer_note: None,
626                                 },
627                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
628                         ),
629                 );
630
631                 if let Err(e) = InvoiceRequest::try_from(buffer) {
632                         panic!("error parsing invoice request: {:?}", e);
633                 }
634         }
635
636         #[cfg(feature = "std")]
637         #[test]
638         fn builds_invoice_request_from_offer_with_expiration() {
639                 let future_expiry = Duration::from_secs(u64::max_value());
640                 let past_expiry = Duration::from_secs(0);
641
642                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
643                         .amount_msats(1000)
644                         .absolute_expiry(future_expiry)
645                         .build().unwrap()
646                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
647                         .build()
648                 {
649                         panic!("error building invoice_request: {:?}", e);
650                 }
651
652                 match OfferBuilder::new("foo".into(), recipient_pubkey())
653                         .amount_msats(1000)
654                         .absolute_expiry(past_expiry)
655                         .build().unwrap()
656                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
657                         .build()
658                 {
659                         Ok(_) => panic!("expected error"),
660                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
661                 }
662         }
663
664         #[test]
665         fn builds_invoice_request_with_chain() {
666                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
667                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
668
669                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
670                         .amount_msats(1000)
671                         .build().unwrap()
672                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
673                         .chain(Network::Bitcoin).unwrap()
674                         .build().unwrap()
675                         .sign(payer_sign).unwrap();
676                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
677                 assert_eq!(invoice_request.chain(), mainnet);
678                 assert_eq!(tlv_stream.chain, None);
679
680                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
681                         .amount_msats(1000)
682                         .chain(Network::Testnet)
683                         .build().unwrap()
684                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
685                         .chain(Network::Testnet).unwrap()
686                         .build().unwrap()
687                         .sign(payer_sign).unwrap();
688                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
689                 assert_eq!(invoice_request.chain(), testnet);
690                 assert_eq!(tlv_stream.chain, Some(&testnet));
691
692                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
693                         .amount_msats(1000)
694                         .chain(Network::Bitcoin)
695                         .chain(Network::Testnet)
696                         .build().unwrap()
697                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
698                         .chain(Network::Bitcoin).unwrap()
699                         .build().unwrap()
700                         .sign(payer_sign).unwrap();
701                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
702                 assert_eq!(invoice_request.chain(), mainnet);
703                 assert_eq!(tlv_stream.chain, None);
704
705                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
706                         .amount_msats(1000)
707                         .chain(Network::Bitcoin)
708                         .chain(Network::Testnet)
709                         .build().unwrap()
710                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
711                         .chain(Network::Bitcoin).unwrap()
712                         .chain(Network::Testnet).unwrap()
713                         .build().unwrap()
714                         .sign(payer_sign).unwrap();
715                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
716                 assert_eq!(invoice_request.chain(), testnet);
717                 assert_eq!(tlv_stream.chain, Some(&testnet));
718
719                 match OfferBuilder::new("foo".into(), recipient_pubkey())
720                         .amount_msats(1000)
721                         .chain(Network::Testnet)
722                         .build().unwrap()
723                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
724                         .chain(Network::Bitcoin)
725                 {
726                         Ok(_) => panic!("expected error"),
727                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
728                 }
729
730                 match OfferBuilder::new("foo".into(), recipient_pubkey())
731                         .amount_msats(1000)
732                         .chain(Network::Testnet)
733                         .build().unwrap()
734                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
735                         .build()
736                 {
737                         Ok(_) => panic!("expected error"),
738                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
739                 }
740         }
741
742         #[test]
743         fn builds_invoice_request_with_amount() {
744                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
745                         .amount_msats(1000)
746                         .build().unwrap()
747                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
748                         .amount_msats(1000).unwrap()
749                         .build().unwrap()
750                         .sign(payer_sign).unwrap();
751                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
752                 assert_eq!(invoice_request.amount_msats(), Some(1000));
753                 assert_eq!(tlv_stream.amount, Some(1000));
754
755                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
756                         .amount_msats(1000)
757                         .build().unwrap()
758                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
759                         .amount_msats(1001).unwrap()
760                         .amount_msats(1000).unwrap()
761                         .build().unwrap()
762                         .sign(payer_sign).unwrap();
763                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
764                 assert_eq!(invoice_request.amount_msats(), Some(1000));
765                 assert_eq!(tlv_stream.amount, Some(1000));
766
767                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
768                         .amount_msats(1000)
769                         .build().unwrap()
770                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
771                         .amount_msats(1001).unwrap()
772                         .build().unwrap()
773                         .sign(payer_sign).unwrap();
774                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
775                 assert_eq!(invoice_request.amount_msats(), Some(1001));
776                 assert_eq!(tlv_stream.amount, Some(1001));
777
778                 match OfferBuilder::new("foo".into(), recipient_pubkey())
779                         .amount_msats(1000)
780                         .build().unwrap()
781                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
782                         .amount_msats(999)
783                 {
784                         Ok(_) => panic!("expected error"),
785                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
786                 }
787
788                 match OfferBuilder::new("foo".into(), recipient_pubkey())
789                         .amount_msats(1000)
790                         .supported_quantity(Quantity::Unbounded)
791                         .build().unwrap()
792                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
793                         .quantity(2).unwrap()
794                         .amount_msats(1000)
795                 {
796                         Ok(_) => panic!("expected error"),
797                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
798                 }
799
800                 match OfferBuilder::new("foo".into(), recipient_pubkey())
801                         .amount_msats(1000)
802                         .build().unwrap()
803                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
804                         .amount_msats(MAX_VALUE_MSAT + 1)
805                 {
806                         Ok(_) => panic!("expected error"),
807                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
808                 }
809
810                 match OfferBuilder::new("foo".into(), recipient_pubkey())
811                         .amount_msats(1000)
812                         .supported_quantity(Quantity::Unbounded)
813                         .build().unwrap()
814                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
815                         .amount_msats(1000).unwrap()
816                         .quantity(2).unwrap()
817                         .build()
818                 {
819                         Ok(_) => panic!("expected error"),
820                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
821                 }
822
823                 match OfferBuilder::new("foo".into(), recipient_pubkey())
824                         .build().unwrap()
825                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
826                         .build()
827                 {
828                         Ok(_) => panic!("expected error"),
829                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
830                 }
831
832                 match OfferBuilder::new("foo".into(), recipient_pubkey())
833                         .amount_msats(1000)
834                         .supported_quantity(Quantity::Unbounded)
835                         .build().unwrap()
836                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
837                         .quantity(u64::max_value()).unwrap()
838                         .build()
839                 {
840                         Ok(_) => panic!("expected error"),
841                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
842                 }
843         }
844
845         #[test]
846         fn builds_invoice_request_with_features() {
847                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
848                         .amount_msats(1000)
849                         .build().unwrap()
850                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
851                         .features_unchecked(InvoiceRequestFeatures::unknown())
852                         .build().unwrap()
853                         .sign(payer_sign).unwrap();
854                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
855                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
856                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
857
858                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
859                         .amount_msats(1000)
860                         .build().unwrap()
861                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
862                         .features_unchecked(InvoiceRequestFeatures::unknown())
863                         .features_unchecked(InvoiceRequestFeatures::empty())
864                         .build().unwrap()
865                         .sign(payer_sign).unwrap();
866                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
867                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
868                 assert_eq!(tlv_stream.features, None);
869         }
870
871         #[test]
872         fn builds_invoice_request_with_quantity() {
873                 let one = NonZeroU64::new(1).unwrap();
874                 let ten = NonZeroU64::new(10).unwrap();
875
876                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
877                         .amount_msats(1000)
878                         .supported_quantity(Quantity::One)
879                         .build().unwrap()
880                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
881                         .build().unwrap()
882                         .sign(payer_sign).unwrap();
883                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
884                 assert_eq!(invoice_request.quantity(), None);
885                 assert_eq!(tlv_stream.quantity, None);
886
887                 match OfferBuilder::new("foo".into(), recipient_pubkey())
888                         .amount_msats(1000)
889                         .supported_quantity(Quantity::One)
890                         .build().unwrap()
891                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
892                         .amount_msats(2_000).unwrap()
893                         .quantity(2)
894                 {
895                         Ok(_) => panic!("expected error"),
896                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
897                 }
898
899                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
900                         .amount_msats(1000)
901                         .supported_quantity(Quantity::Bounded(ten))
902                         .build().unwrap()
903                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
904                         .amount_msats(10_000).unwrap()
905                         .quantity(10).unwrap()
906                         .build().unwrap()
907                         .sign(payer_sign).unwrap();
908                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
909                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
910                 assert_eq!(tlv_stream.amount, Some(10_000));
911
912                 match OfferBuilder::new("foo".into(), recipient_pubkey())
913                         .amount_msats(1000)
914                         .supported_quantity(Quantity::Bounded(ten))
915                         .build().unwrap()
916                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
917                         .amount_msats(11_000).unwrap()
918                         .quantity(11)
919                 {
920                         Ok(_) => panic!("expected error"),
921                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
922                 }
923
924                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
925                         .amount_msats(1000)
926                         .supported_quantity(Quantity::Unbounded)
927                         .build().unwrap()
928                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
929                         .amount_msats(2_000).unwrap()
930                         .quantity(2).unwrap()
931                         .build().unwrap()
932                         .sign(payer_sign).unwrap();
933                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
934                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
935                 assert_eq!(tlv_stream.amount, Some(2_000));
936
937                 match OfferBuilder::new("foo".into(), recipient_pubkey())
938                         .amount_msats(1000)
939                         .supported_quantity(Quantity::Unbounded)
940                         .build().unwrap()
941                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
942                         .build()
943                 {
944                         Ok(_) => panic!("expected error"),
945                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
946                 }
947
948                 match OfferBuilder::new("foo".into(), recipient_pubkey())
949                         .amount_msats(1000)
950                         .supported_quantity(Quantity::Bounded(one))
951                         .build().unwrap()
952                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
953                         .build()
954                 {
955                         Ok(_) => panic!("expected error"),
956                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
957                 }
958         }
959
960         #[test]
961         fn builds_invoice_request_with_payer_note() {
962                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
963                         .amount_msats(1000)
964                         .build().unwrap()
965                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
966                         .payer_note("bar".into())
967                         .build().unwrap()
968                         .sign(payer_sign).unwrap();
969                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
970                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
971                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
972
973                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
974                         .amount_msats(1000)
975                         .build().unwrap()
976                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
977                         .payer_note("bar".into())
978                         .payer_note("baz".into())
979                         .build().unwrap()
980                         .sign(payer_sign).unwrap();
981                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
982                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
983                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
984         }
985
986         #[test]
987         fn fails_signing_invoice_request() {
988                 match OfferBuilder::new("foo".into(), recipient_pubkey())
989                         .amount_msats(1000)
990                         .build().unwrap()
991                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
992                         .build().unwrap()
993                         .sign(|_| Err(()))
994                 {
995                         Ok(_) => panic!("expected error"),
996                         Err(e) => assert_eq!(e, SignError::Signing(())),
997                 }
998
999                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1000                         .amount_msats(1000)
1001                         .build().unwrap()
1002                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1003                         .build().unwrap()
1004                         .sign(recipient_sign)
1005                 {
1006                         Ok(_) => panic!("expected error"),
1007                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
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 }