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