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