InvoiceRequest metadata and payer id derivation
[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 [`Invoice`] 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         /// [`Invoice`]: crate::offers::invoice::Invoice
469         /// [`Duration`]: core::time::Duration
470         #[cfg(feature = "std")]
471         pub fn respond_with(
472                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
473         ) -> Result<InvoiceBuilder, SemanticError> {
474                 let created_at = std::time::SystemTime::now()
475                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
476                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
477
478                 self.respond_with_no_std(payment_paths, payment_hash, created_at)
479         }
480
481         /// Creates an [`Invoice`] for the request with the given required fields.
482         ///
483         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
484         /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
485         /// [`std::time::SystemTime`] is not available.
486         ///
487         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
488         /// for the invoice.
489         ///
490         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
491         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
492         /// a preference. Note, however, that any privacy is lost if a public node id was used for
493         /// [`Offer::signing_pubkey`].
494         ///
495         /// Errors if the request contains unknown required features.
496         ///
497         /// [`Invoice`]: crate::offers::invoice::Invoice
498         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
499         pub fn respond_with_no_std(
500                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
501                 created_at: core::time::Duration
502         ) -> Result<InvoiceBuilder, SemanticError> {
503                 if self.features().requires_unknown_bits() {
504                         return Err(SemanticError::UnknownRequiredFeatures);
505                 }
506
507                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
508         }
509
510         /// Verifies that the request was for an offer created using the given key.
511         pub fn verify<T: secp256k1::Signing>(
512                 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
513         ) -> bool {
514                 self.contents.inner.offer.verify(TlvStream::new(&self.bytes), key, secp_ctx)
515         }
516
517         #[cfg(test)]
518         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
519                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
520                         self.contents.as_tlv_stream();
521                 let signature_tlv_stream = SignatureTlvStreamRef {
522                         signature: Some(&self.signature),
523                 };
524                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
525         }
526 }
527
528 impl InvoiceRequestContents {
529         pub fn metadata(&self) -> &[u8] {
530                 self.inner.metadata()
531         }
532
533         pub(super) fn chain(&self) -> ChainHash {
534                 self.inner.chain()
535         }
536
537         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
538                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
539                 invoice_request.payer_id = Some(&self.payer_id);
540                 (payer, offer, invoice_request)
541         }
542 }
543
544 impl InvoiceRequestContentsWithoutPayerId {
545         pub(super) fn metadata(&self) -> &[u8] {
546                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
547         }
548
549         pub(super) fn chain(&self) -> ChainHash {
550                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
551         }
552
553         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
554                 let payer = PayerTlvStreamRef {
555                         metadata: self.payer.0.as_bytes(),
556                 };
557
558                 let offer = self.offer.as_tlv_stream();
559
560                 let features = {
561                         if self.features == InvoiceRequestFeatures::empty() { None }
562                         else { Some(&self.features) }
563                 };
564
565                 let invoice_request = InvoiceRequestTlvStreamRef {
566                         chain: self.chain.as_ref(),
567                         amount: self.amount_msats,
568                         features,
569                         quantity: self.quantity,
570                         payer_id: None,
571                         payer_note: self.payer_note.as_ref(),
572                 };
573
574                 (payer, offer, invoice_request)
575         }
576 }
577
578 impl Writeable for InvoiceRequest {
579         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
580                 WithoutLength(&self.bytes).write(writer)
581         }
582 }
583
584 impl Writeable for InvoiceRequestContents {
585         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
586                 self.as_tlv_stream().write(writer)
587         }
588 }
589
590 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
591         (80, chain: ChainHash),
592         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
593         (84, features: (InvoiceRequestFeatures, WithoutLength)),
594         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
595         (88, payer_id: PublicKey),
596         (89, payer_note: (String, WithoutLength)),
597 });
598
599 type FullInvoiceRequestTlvStream =
600         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
601
602 #[cfg(test)]
603 type FullInvoiceRequestTlvStreamRef<'a> = (
604         PayerTlvStreamRef<'a>,
605         OfferTlvStreamRef<'a>,
606         InvoiceRequestTlvStreamRef<'a>,
607         SignatureTlvStreamRef<'a>,
608 );
609
610 impl SeekReadable for FullInvoiceRequestTlvStream {
611         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
612                 let payer = SeekReadable::read(r)?;
613                 let offer = SeekReadable::read(r)?;
614                 let invoice_request = SeekReadable::read(r)?;
615                 let signature = SeekReadable::read(r)?;
616
617                 Ok((payer, offer, invoice_request, signature))
618         }
619 }
620
621 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
622
623 type PartialInvoiceRequestTlvStreamRef<'a> = (
624         PayerTlvStreamRef<'a>,
625         OfferTlvStreamRef<'a>,
626         InvoiceRequestTlvStreamRef<'a>,
627 );
628
629 impl TryFrom<Vec<u8>> for InvoiceRequest {
630         type Error = ParseError;
631
632         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
633                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
634                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
635                 let (
636                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
637                         SignatureTlvStream { signature },
638                 ) = tlv_stream;
639                 let contents = InvoiceRequestContents::try_from(
640                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
641                 )?;
642
643                 let signature = match signature {
644                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
645                         Some(signature) => signature,
646                 };
647                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
648
649                 Ok(InvoiceRequest { bytes, contents, signature })
650         }
651 }
652
653 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
654         type Error = SemanticError;
655
656         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
657                 let (
658                         PayerTlvStream { metadata },
659                         offer_tlv_stream,
660                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
661                 ) = tlv_stream;
662
663                 let payer = match metadata {
664                         None => return Err(SemanticError::MissingPayerMetadata),
665                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
666                 };
667                 let offer = OfferContents::try_from(offer_tlv_stream)?;
668
669                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
670                         return Err(SemanticError::UnsupportedChain);
671                 }
672
673                 if offer.amount().is_none() && amount.is_none() {
674                         return Err(SemanticError::MissingAmount);
675                 }
676
677                 offer.check_quantity(quantity)?;
678                 offer.check_amount_msats_for_quantity(amount, quantity)?;
679
680                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
681
682                 let payer_id = match payer_id {
683                         None => return Err(SemanticError::MissingPayerId),
684                         Some(payer_id) => payer_id,
685                 };
686
687                 Ok(InvoiceRequestContents {
688                         inner: InvoiceRequestContentsWithoutPayerId {
689                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
690                         },
691                         payer_id,
692                 })
693         }
694 }
695
696 #[cfg(test)]
697 mod tests {
698         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
699
700         use bitcoin::blockdata::constants::ChainHash;
701         use bitcoin::network::constants::Network;
702         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
703         use core::convert::{Infallible, TryFrom};
704         use core::num::NonZeroU64;
705         #[cfg(feature = "std")]
706         use core::time::Duration;
707         use crate::ln::features::InvoiceRequestFeatures;
708         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
709         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
710         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
711         use crate::offers::parse::{ParseError, SemanticError};
712         use crate::offers::payer::PayerTlvStreamRef;
713         use crate::offers::test_utils::*;
714         use crate::util::ser::{BigSize, Writeable};
715         use crate::util::string::PrintableString;
716
717         #[test]
718         fn builds_invoice_request_with_defaults() {
719                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
720                         .amount_msats(1000)
721                         .build().unwrap()
722                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
723                         .build().unwrap()
724                         .sign(payer_sign).unwrap();
725
726                 let mut buffer = Vec::new();
727                 invoice_request.write(&mut buffer).unwrap();
728
729                 assert_eq!(invoice_request.bytes, buffer.as_slice());
730                 assert_eq!(invoice_request.metadata(), &[1; 32]);
731                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
732                 assert_eq!(invoice_request.amount_msats(), None);
733                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
734                 assert_eq!(invoice_request.quantity(), None);
735                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
736                 assert_eq!(invoice_request.payer_note(), None);
737                 assert!(
738                         merkle::verify_signature(
739                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
740                         ).is_ok()
741                 );
742
743                 assert_eq!(
744                         invoice_request.as_tlv_stream(),
745                         (
746                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
747                                 OfferTlvStreamRef {
748                                         chains: None,
749                                         metadata: None,
750                                         currency: None,
751                                         amount: Some(1000),
752                                         description: Some(&String::from("foo")),
753                                         features: None,
754                                         absolute_expiry: None,
755                                         paths: None,
756                                         issuer: None,
757                                         quantity_max: None,
758                                         node_id: Some(&recipient_pubkey()),
759                                 },
760                                 InvoiceRequestTlvStreamRef {
761                                         chain: None,
762                                         amount: None,
763                                         features: None,
764                                         quantity: None,
765                                         payer_id: Some(&payer_pubkey()),
766                                         payer_note: None,
767                                 },
768                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
769                         ),
770                 );
771
772                 if let Err(e) = InvoiceRequest::try_from(buffer) {
773                         panic!("error parsing invoice request: {:?}", e);
774                 }
775         }
776
777         #[cfg(feature = "std")]
778         #[test]
779         fn builds_invoice_request_from_offer_with_expiration() {
780                 let future_expiry = Duration::from_secs(u64::max_value());
781                 let past_expiry = Duration::from_secs(0);
782
783                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
784                         .amount_msats(1000)
785                         .absolute_expiry(future_expiry)
786                         .build().unwrap()
787                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
788                         .build()
789                 {
790                         panic!("error building invoice_request: {:?}", e);
791                 }
792
793                 match OfferBuilder::new("foo".into(), recipient_pubkey())
794                         .amount_msats(1000)
795                         .absolute_expiry(past_expiry)
796                         .build().unwrap()
797                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
798                         .build()
799                 {
800                         Ok(_) => panic!("expected error"),
801                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
802                 }
803         }
804
805         #[test]
806         fn builds_invoice_request_with_chain() {
807                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
808                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
809
810                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
811                         .amount_msats(1000)
812                         .build().unwrap()
813                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
814                         .chain(Network::Bitcoin).unwrap()
815                         .build().unwrap()
816                         .sign(payer_sign).unwrap();
817                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
818                 assert_eq!(invoice_request.chain(), mainnet);
819                 assert_eq!(tlv_stream.chain, None);
820
821                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
822                         .amount_msats(1000)
823                         .chain(Network::Testnet)
824                         .build().unwrap()
825                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
826                         .chain(Network::Testnet).unwrap()
827                         .build().unwrap()
828                         .sign(payer_sign).unwrap();
829                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
830                 assert_eq!(invoice_request.chain(), testnet);
831                 assert_eq!(tlv_stream.chain, Some(&testnet));
832
833                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
834                         .amount_msats(1000)
835                         .chain(Network::Bitcoin)
836                         .chain(Network::Testnet)
837                         .build().unwrap()
838                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
839                         .chain(Network::Bitcoin).unwrap()
840                         .build().unwrap()
841                         .sign(payer_sign).unwrap();
842                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
843                 assert_eq!(invoice_request.chain(), mainnet);
844                 assert_eq!(tlv_stream.chain, None);
845
846                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
847                         .amount_msats(1000)
848                         .chain(Network::Bitcoin)
849                         .chain(Network::Testnet)
850                         .build().unwrap()
851                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
852                         .chain(Network::Bitcoin).unwrap()
853                         .chain(Network::Testnet).unwrap()
854                         .build().unwrap()
855                         .sign(payer_sign).unwrap();
856                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
857                 assert_eq!(invoice_request.chain(), testnet);
858                 assert_eq!(tlv_stream.chain, Some(&testnet));
859
860                 match OfferBuilder::new("foo".into(), recipient_pubkey())
861                         .amount_msats(1000)
862                         .chain(Network::Testnet)
863                         .build().unwrap()
864                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
865                         .chain(Network::Bitcoin)
866                 {
867                         Ok(_) => panic!("expected error"),
868                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
869                 }
870
871                 match OfferBuilder::new("foo".into(), recipient_pubkey())
872                         .amount_msats(1000)
873                         .chain(Network::Testnet)
874                         .build().unwrap()
875                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
876                         .build()
877                 {
878                         Ok(_) => panic!("expected error"),
879                         Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
880                 }
881         }
882
883         #[test]
884         fn builds_invoice_request_with_amount() {
885                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
886                         .amount_msats(1000)
887                         .build().unwrap()
888                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
889                         .amount_msats(1000).unwrap()
890                         .build().unwrap()
891                         .sign(payer_sign).unwrap();
892                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
893                 assert_eq!(invoice_request.amount_msats(), Some(1000));
894                 assert_eq!(tlv_stream.amount, Some(1000));
895
896                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
897                         .amount_msats(1000)
898                         .build().unwrap()
899                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
900                         .amount_msats(1001).unwrap()
901                         .amount_msats(1000).unwrap()
902                         .build().unwrap()
903                         .sign(payer_sign).unwrap();
904                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
905                 assert_eq!(invoice_request.amount_msats(), Some(1000));
906                 assert_eq!(tlv_stream.amount, Some(1000));
907
908                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
909                         .amount_msats(1000)
910                         .build().unwrap()
911                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
912                         .amount_msats(1001).unwrap()
913                         .build().unwrap()
914                         .sign(payer_sign).unwrap();
915                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
916                 assert_eq!(invoice_request.amount_msats(), Some(1001));
917                 assert_eq!(tlv_stream.amount, Some(1001));
918
919                 match OfferBuilder::new("foo".into(), recipient_pubkey())
920                         .amount_msats(1000)
921                         .build().unwrap()
922                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
923                         .amount_msats(999)
924                 {
925                         Ok(_) => panic!("expected error"),
926                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
927                 }
928
929                 match OfferBuilder::new("foo".into(), recipient_pubkey())
930                         .amount_msats(1000)
931                         .supported_quantity(Quantity::Unbounded)
932                         .build().unwrap()
933                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
934                         .quantity(2).unwrap()
935                         .amount_msats(1000)
936                 {
937                         Ok(_) => panic!("expected error"),
938                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
939                 }
940
941                 match OfferBuilder::new("foo".into(), recipient_pubkey())
942                         .amount_msats(1000)
943                         .build().unwrap()
944                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
945                         .amount_msats(MAX_VALUE_MSAT + 1)
946                 {
947                         Ok(_) => panic!("expected error"),
948                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
949                 }
950
951                 match OfferBuilder::new("foo".into(), recipient_pubkey())
952                         .amount_msats(1000)
953                         .supported_quantity(Quantity::Unbounded)
954                         .build().unwrap()
955                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
956                         .amount_msats(1000).unwrap()
957                         .quantity(2).unwrap()
958                         .build()
959                 {
960                         Ok(_) => panic!("expected error"),
961                         Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
962                 }
963
964                 match OfferBuilder::new("foo".into(), recipient_pubkey())
965                         .build().unwrap()
966                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
967                         .build()
968                 {
969                         Ok(_) => panic!("expected error"),
970                         Err(e) => assert_eq!(e, SemanticError::MissingAmount),
971                 }
972
973                 match OfferBuilder::new("foo".into(), recipient_pubkey())
974                         .amount_msats(1000)
975                         .supported_quantity(Quantity::Unbounded)
976                         .build().unwrap()
977                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
978                         .quantity(u64::max_value()).unwrap()
979                         .build()
980                 {
981                         Ok(_) => panic!("expected error"),
982                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
983                 }
984         }
985
986         #[test]
987         fn builds_invoice_request_with_features() {
988                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
989                         .amount_msats(1000)
990                         .build().unwrap()
991                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
992                         .features_unchecked(InvoiceRequestFeatures::unknown())
993                         .build().unwrap()
994                         .sign(payer_sign).unwrap();
995                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
996                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
997                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
998
999                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1000                         .amount_msats(1000)
1001                         .build().unwrap()
1002                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1003                         .features_unchecked(InvoiceRequestFeatures::unknown())
1004                         .features_unchecked(InvoiceRequestFeatures::empty())
1005                         .build().unwrap()
1006                         .sign(payer_sign).unwrap();
1007                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1008                 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1009                 assert_eq!(tlv_stream.features, None);
1010         }
1011
1012         #[test]
1013         fn builds_invoice_request_with_quantity() {
1014                 let one = NonZeroU64::new(1).unwrap();
1015                 let ten = NonZeroU64::new(10).unwrap();
1016
1017                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1018                         .amount_msats(1000)
1019                         .supported_quantity(Quantity::One)
1020                         .build().unwrap()
1021                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1022                         .build().unwrap()
1023                         .sign(payer_sign).unwrap();
1024                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1025                 assert_eq!(invoice_request.quantity(), None);
1026                 assert_eq!(tlv_stream.quantity, None);
1027
1028                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1029                         .amount_msats(1000)
1030                         .supported_quantity(Quantity::One)
1031                         .build().unwrap()
1032                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1033                         .amount_msats(2_000).unwrap()
1034                         .quantity(2)
1035                 {
1036                         Ok(_) => panic!("expected error"),
1037                         Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1038                 }
1039
1040                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1041                         .amount_msats(1000)
1042                         .supported_quantity(Quantity::Bounded(ten))
1043                         .build().unwrap()
1044                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1045                         .amount_msats(10_000).unwrap()
1046                         .quantity(10).unwrap()
1047                         .build().unwrap()
1048                         .sign(payer_sign).unwrap();
1049                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1050                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1051                 assert_eq!(tlv_stream.amount, Some(10_000));
1052
1053                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1054                         .amount_msats(1000)
1055                         .supported_quantity(Quantity::Bounded(ten))
1056                         .build().unwrap()
1057                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1058                         .amount_msats(11_000).unwrap()
1059                         .quantity(11)
1060                 {
1061                         Ok(_) => panic!("expected error"),
1062                         Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1063                 }
1064
1065                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1066                         .amount_msats(1000)
1067                         .supported_quantity(Quantity::Unbounded)
1068                         .build().unwrap()
1069                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1070                         .amount_msats(2_000).unwrap()
1071                         .quantity(2).unwrap()
1072                         .build().unwrap()
1073                         .sign(payer_sign).unwrap();
1074                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1075                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1076                 assert_eq!(tlv_stream.amount, Some(2_000));
1077
1078                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1079                         .amount_msats(1000)
1080                         .supported_quantity(Quantity::Unbounded)
1081                         .build().unwrap()
1082                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1083                         .build()
1084                 {
1085                         Ok(_) => panic!("expected error"),
1086                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1087                 }
1088
1089                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1090                         .amount_msats(1000)
1091                         .supported_quantity(Quantity::Bounded(one))
1092                         .build().unwrap()
1093                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1094                         .build()
1095                 {
1096                         Ok(_) => panic!("expected error"),
1097                         Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1098                 }
1099         }
1100
1101         #[test]
1102         fn builds_invoice_request_with_payer_note() {
1103                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1104                         .amount_msats(1000)
1105                         .build().unwrap()
1106                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1107                         .payer_note("bar".into())
1108                         .build().unwrap()
1109                         .sign(payer_sign).unwrap();
1110                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1111                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1112                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1113
1114                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1115                         .amount_msats(1000)
1116                         .build().unwrap()
1117                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1118                         .payer_note("bar".into())
1119                         .payer_note("baz".into())
1120                         .build().unwrap()
1121                         .sign(payer_sign).unwrap();
1122                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1123                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1124                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1125         }
1126
1127         #[test]
1128         fn fails_signing_invoice_request() {
1129                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1130                         .amount_msats(1000)
1131                         .build().unwrap()
1132                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1133                         .build().unwrap()
1134                         .sign(|_| Err(()))
1135                 {
1136                         Ok(_) => panic!("expected error"),
1137                         Err(e) => assert_eq!(e, SignError::Signing(())),
1138                 }
1139
1140                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1141                         .amount_msats(1000)
1142                         .build().unwrap()
1143                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1144                         .build().unwrap()
1145                         .sign(recipient_sign)
1146                 {
1147                         Ok(_) => panic!("expected error"),
1148                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1149                 }
1150         }
1151
1152         #[test]
1153         fn fails_responding_with_unknown_required_features() {
1154                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1155                         .amount_msats(1000)
1156                         .build().unwrap()
1157                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1158                         .features_unchecked(InvoiceRequestFeatures::unknown())
1159                         .build().unwrap()
1160                         .sign(payer_sign).unwrap()
1161                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1162                 {
1163                         Ok(_) => panic!("expected error"),
1164                         Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1165                 }
1166         }
1167
1168         #[test]
1169         fn parses_invoice_request_with_metadata() {
1170                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1171                         .amount_msats(1000)
1172                         .build().unwrap()
1173                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1174                         .build().unwrap()
1175                         .sign(payer_sign).unwrap();
1176
1177                 let mut buffer = Vec::new();
1178                 invoice_request.write(&mut buffer).unwrap();
1179
1180                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1181                         panic!("error parsing invoice_request: {:?}", e);
1182                 }
1183         }
1184
1185         #[test]
1186         fn parses_invoice_request_with_chain() {
1187                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1188                         .amount_msats(1000)
1189                         .build().unwrap()
1190                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1191                         .chain(Network::Bitcoin).unwrap()
1192                         .build().unwrap()
1193                         .sign(payer_sign).unwrap();
1194
1195                 let mut buffer = Vec::new();
1196                 invoice_request.write(&mut buffer).unwrap();
1197
1198                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1199                         panic!("error parsing invoice_request: {:?}", e);
1200                 }
1201
1202                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1203                         .amount_msats(1000)
1204                         .build().unwrap()
1205                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1206                         .chain_unchecked(Network::Testnet)
1207                         .build_unchecked()
1208                         .sign(payer_sign).unwrap();
1209
1210                 let mut buffer = Vec::new();
1211                 invoice_request.write(&mut buffer).unwrap();
1212
1213                 match InvoiceRequest::try_from(buffer) {
1214                         Ok(_) => panic!("expected error"),
1215                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1216                 }
1217         }
1218
1219         #[test]
1220         fn parses_invoice_request_with_amount() {
1221                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1222                         .amount_msats(1000)
1223                         .build().unwrap()
1224                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225                         .build().unwrap()
1226                         .sign(payer_sign).unwrap();
1227
1228                 let mut buffer = Vec::new();
1229                 invoice_request.write(&mut buffer).unwrap();
1230
1231                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1232                         panic!("error parsing invoice_request: {:?}", e);
1233                 }
1234
1235                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1236                         .build().unwrap()
1237                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1238                         .amount_msats(1000).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                         .build().unwrap()
1251                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1252                         .build_unchecked()
1253                         .sign(payer_sign).unwrap();
1254
1255                 let mut buffer = Vec::new();
1256                 invoice_request.write(&mut buffer).unwrap();
1257
1258                 match InvoiceRequest::try_from(buffer) {
1259                         Ok(_) => panic!("expected error"),
1260                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1261                 }
1262
1263                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1264                         .amount_msats(1000)
1265                         .build().unwrap()
1266                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1267                         .amount_msats_unchecked(999)
1268                         .build_unchecked()
1269                         .sign(payer_sign).unwrap();
1270
1271                 let mut buffer = Vec::new();
1272                 invoice_request.write(&mut buffer).unwrap();
1273
1274                 match InvoiceRequest::try_from(buffer) {
1275                         Ok(_) => panic!("expected error"),
1276                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1277                 }
1278
1279                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1280                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1281                         .build_unchecked()
1282                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1283                         .build_unchecked()
1284                         .sign(payer_sign).unwrap();
1285
1286                 let mut buffer = Vec::new();
1287                 invoice_request.write(&mut buffer).unwrap();
1288
1289                 match InvoiceRequest::try_from(buffer) {
1290                         Ok(_) => panic!("expected error"),
1291                         Err(e) => {
1292                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1293                         },
1294                 }
1295
1296                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1297                         .amount_msats(1000)
1298                         .supported_quantity(Quantity::Unbounded)
1299                         .build().unwrap()
1300                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1301                         .quantity(u64::max_value()).unwrap()
1302                         .build_unchecked()
1303                         .sign(payer_sign).unwrap();
1304
1305                 let mut buffer = Vec::new();
1306                 invoice_request.write(&mut buffer).unwrap();
1307
1308                 match InvoiceRequest::try_from(buffer) {
1309                         Ok(_) => panic!("expected error"),
1310                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1311                 }
1312         }
1313
1314         #[test]
1315         fn parses_invoice_request_with_quantity() {
1316                 let one = NonZeroU64::new(1).unwrap();
1317                 let ten = NonZeroU64::new(10).unwrap();
1318
1319                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1320                         .amount_msats(1000)
1321                         .supported_quantity(Quantity::One)
1322                         .build().unwrap()
1323                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1324                         .build().unwrap()
1325                         .sign(payer_sign).unwrap();
1326
1327                 let mut buffer = Vec::new();
1328                 invoice_request.write(&mut buffer).unwrap();
1329
1330                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1331                         panic!("error parsing invoice_request: {:?}", e);
1332                 }
1333
1334                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1335                         .amount_msats(1000)
1336                         .supported_quantity(Quantity::One)
1337                         .build().unwrap()
1338                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1339                         .amount_msats(2_000).unwrap()
1340                         .quantity_unchecked(2)
1341                         .build_unchecked()
1342                         .sign(payer_sign).unwrap();
1343
1344                 let mut buffer = Vec::new();
1345                 invoice_request.write(&mut buffer).unwrap();
1346
1347                 match InvoiceRequest::try_from(buffer) {
1348                         Ok(_) => panic!("expected error"),
1349                         Err(e) => {
1350                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1351                         },
1352                 }
1353
1354                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1355                         .amount_msats(1000)
1356                         .supported_quantity(Quantity::Bounded(ten))
1357                         .build().unwrap()
1358                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359                         .amount_msats(10_000).unwrap()
1360                         .quantity(10).unwrap()
1361                         .build().unwrap()
1362                         .sign(payer_sign).unwrap();
1363
1364                 let mut buffer = Vec::new();
1365                 invoice_request.write(&mut buffer).unwrap();
1366
1367                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1368                         panic!("error parsing invoice_request: {:?}", e);
1369                 }
1370
1371                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1372                         .amount_msats(1000)
1373                         .supported_quantity(Quantity::Bounded(ten))
1374                         .build().unwrap()
1375                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1376                         .amount_msats(11_000).unwrap()
1377                         .quantity_unchecked(11)
1378                         .build_unchecked()
1379                         .sign(payer_sign).unwrap();
1380
1381                 let mut buffer = Vec::new();
1382                 invoice_request.write(&mut buffer).unwrap();
1383
1384                 match InvoiceRequest::try_from(buffer) {
1385                         Ok(_) => panic!("expected error"),
1386                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1387                 }
1388
1389                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1390                         .amount_msats(1000)
1391                         .supported_quantity(Quantity::Unbounded)
1392                         .build().unwrap()
1393                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1394                         .amount_msats(2_000).unwrap()
1395                         .quantity(2).unwrap()
1396                         .build().unwrap()
1397                         .sign(payer_sign).unwrap();
1398
1399                 let mut buffer = Vec::new();
1400                 invoice_request.write(&mut buffer).unwrap();
1401
1402                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1403                         panic!("error parsing invoice_request: {:?}", e);
1404                 }
1405
1406                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1407                         .amount_msats(1000)
1408                         .supported_quantity(Quantity::Unbounded)
1409                         .build().unwrap()
1410                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1411                         .build_unchecked()
1412                         .sign(payer_sign).unwrap();
1413
1414                 let mut buffer = Vec::new();
1415                 invoice_request.write(&mut buffer).unwrap();
1416
1417                 match InvoiceRequest::try_from(buffer) {
1418                         Ok(_) => panic!("expected error"),
1419                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1420                 }
1421
1422                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1423                         .amount_msats(1000)
1424                         .supported_quantity(Quantity::Bounded(one))
1425                         .build().unwrap()
1426                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1427                         .build_unchecked()
1428                         .sign(payer_sign).unwrap();
1429
1430                 let mut buffer = Vec::new();
1431                 invoice_request.write(&mut buffer).unwrap();
1432
1433                 match InvoiceRequest::try_from(buffer) {
1434                         Ok(_) => panic!("expected error"),
1435                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1436                 }
1437         }
1438
1439         #[test]
1440         fn fails_parsing_invoice_request_without_metadata() {
1441                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1442                         .amount_msats(1000)
1443                         .build().unwrap();
1444                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1445                         .build().unwrap();
1446                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1447                 tlv_stream.0.metadata = None;
1448
1449                 let mut buffer = Vec::new();
1450                 tlv_stream.write(&mut buffer).unwrap();
1451
1452                 match InvoiceRequest::try_from(buffer) {
1453                         Ok(_) => panic!("expected error"),
1454                         Err(e) => {
1455                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1456                         },
1457                 }
1458         }
1459
1460         #[test]
1461         fn fails_parsing_invoice_request_without_payer_id() {
1462                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1463                         .amount_msats(1000)
1464                         .build().unwrap();
1465                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1466                         .build().unwrap();
1467                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1468                 tlv_stream.2.payer_id = None;
1469
1470                 let mut buffer = Vec::new();
1471                 tlv_stream.write(&mut buffer).unwrap();
1472
1473                 match InvoiceRequest::try_from(buffer) {
1474                         Ok(_) => panic!("expected error"),
1475                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1476                 }
1477         }
1478
1479         #[test]
1480         fn fails_parsing_invoice_request_without_node_id() {
1481                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1482                         .amount_msats(1000)
1483                         .build().unwrap();
1484                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1485                         .build().unwrap();
1486                 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1487                 tlv_stream.1.node_id = None;
1488
1489                 let mut buffer = Vec::new();
1490                 tlv_stream.write(&mut buffer).unwrap();
1491
1492                 match InvoiceRequest::try_from(buffer) {
1493                         Ok(_) => panic!("expected error"),
1494                         Err(e) => {
1495                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1496                         },
1497                 }
1498         }
1499
1500         #[test]
1501         fn fails_parsing_invoice_request_without_signature() {
1502                 let mut buffer = Vec::new();
1503                 OfferBuilder::new("foo".into(), recipient_pubkey())
1504                         .amount_msats(1000)
1505                         .build().unwrap()
1506                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1507                         .build().unwrap()
1508                         .invoice_request
1509                         .write(&mut buffer).unwrap();
1510
1511                 match InvoiceRequest::try_from(buffer) {
1512                         Ok(_) => panic!("expected error"),
1513                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1514                 }
1515         }
1516
1517         #[test]
1518         fn fails_parsing_invoice_request_with_invalid_signature() {
1519                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1520                         .amount_msats(1000)
1521                         .build().unwrap()
1522                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1523                         .build().unwrap()
1524                         .sign(payer_sign).unwrap();
1525                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1526                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1527
1528                 let mut buffer = Vec::new();
1529                 invoice_request.write(&mut buffer).unwrap();
1530
1531                 match InvoiceRequest::try_from(buffer) {
1532                         Ok(_) => panic!("expected error"),
1533                         Err(e) => {
1534                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1535                         },
1536                 }
1537         }
1538
1539         #[test]
1540         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1541                 let secp_ctx = Secp256k1::new();
1542                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1543                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1544                         .amount_msats(1000)
1545                         .build().unwrap()
1546                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1547                         .build().unwrap()
1548                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1549                         .unwrap();
1550
1551                 let mut encoded_invoice_request = Vec::new();
1552                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1553                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1554                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1555                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1556
1557                 match InvoiceRequest::try_from(encoded_invoice_request) {
1558                         Ok(_) => panic!("expected error"),
1559                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1560                 }
1561         }
1562 }