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