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