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