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