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