e41a699f2e80787fa39a0181432eac8d7c4495f9
[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 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
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 payer_metadata(&$self) -> &[u8] {
450                 $contents.metadata()
451         }
452
453         /// A chain from [`Offer::chains`] that the offer is valid for.
454         pub fn chain(&$self) -> ChainHash {
455                 $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                 $contents.amount_msats()
464         }
465
466         /// Features pertaining to requesting an invoice.
467         pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
468                 &$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                 $contents.quantity()
474         }
475
476         /// A possibly transient pubkey used to sign the invoice request.
477         pub fn payer_id(&$self) -> PublicKey {
478                 $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                 $contents.payer_note()
485         }
486 } }
487
488 impl InvoiceRequest {
489         invoice_request_accessors!(self, self.contents);
490
491         /// Signature of the invoice request using [`payer_id`].
492         ///
493         /// [`payer_id`]: Self::payer_id
494         pub fn signature(&self) -> Signature {
495                 self.signature
496         }
497
498         /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
499         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
500         ///
501         /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
502         /// creation time is used for the `created_at` parameter.
503         ///
504         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
505         ///
506         /// [`Duration`]: core::time::Duration
507         #[cfg(feature = "std")]
508         pub fn respond_with(
509                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
510         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
511                 let created_at = std::time::SystemTime::now()
512                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
513                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
514
515                 self.respond_with_no_std(payment_paths, payment_hash, created_at)
516         }
517
518         /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
519         ///
520         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
521         /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
522         /// where [`std::time::SystemTime`] is not available.
523         ///
524         /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
525         /// for the invoice.
526         ///
527         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
528         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
529         /// a preference. Note, however, that any privacy is lost if a public node id was used for
530         /// [`Offer::signing_pubkey`].
531         ///
532         /// Errors if the request contains unknown required features.
533         ///
534         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
535         ///
536         /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
537         pub fn respond_with_no_std(
538                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
539                 created_at: core::time::Duration
540         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
541                 if self.invoice_request_features().requires_unknown_bits() {
542                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
543                 }
544
545                 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
546         }
547
548         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
549         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
550         /// the same [`ExpandedKey`] as the one used to create the offer.
551         ///
552         /// See [`InvoiceRequest::respond_with`] for further details.
553         ///
554         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
555         ///
556         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
557         #[cfg(feature = "std")]
558         pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
559                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
560                 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
561         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
562                 let created_at = std::time::SystemTime::now()
563                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
564                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
565
566                 self.verify_and_respond_using_derived_keys_no_std(
567                         payment_paths, payment_hash, created_at, expanded_key, secp_ctx
568                 )
569         }
570
571         /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
572         /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
573         /// the same [`ExpandedKey`] as the one used to create the offer.
574         ///
575         /// See [`InvoiceRequest::respond_with_no_std`] for further details.
576         ///
577         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
578         ///
579         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
580         pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
581                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
582                 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
583         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
584                 if self.invoice_request_features().requires_unknown_bits() {
585                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
586                 }
587
588                 let keys = match self.verify(expanded_key, secp_ctx) {
589                         Err(()) => return Err(Bolt12SemanticError::InvalidMetadata),
590                         Ok(None) => return Err(Bolt12SemanticError::InvalidMetadata),
591                         Ok(Some(keys)) => keys,
592                 };
593
594                 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
595         }
596
597         /// Verifies that the request was for an offer created using the given key. Returns the derived
598         /// keys need to sign an [`Bolt12Invoice`] for the request if they could be extracted from the
599         /// metadata.
600         ///
601         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
602         pub fn verify<T: secp256k1::Signing>(
603                 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
604         ) -> Result<Option<KeyPair>, ()> {
605                 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
606         }
607
608         #[cfg(test)]
609         fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
610                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
611                         self.contents.as_tlv_stream();
612                 let signature_tlv_stream = SignatureTlvStreamRef {
613                         signature: Some(&self.signature),
614                 };
615                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
616         }
617 }
618
619 impl InvoiceRequestContents {
620         pub(super) fn metadata(&self) -> &[u8] {
621                 self.inner.metadata()
622         }
623
624         pub(super) fn derives_keys(&self) -> bool {
625                 self.inner.payer.0.derives_keys()
626         }
627
628         pub(super) fn chain(&self) -> ChainHash {
629                 self.inner.chain()
630         }
631
632         fn amount_msats(&self) -> Option<u64> {
633                 self.inner.amount_msats
634         }
635
636         fn features(&self) -> &InvoiceRequestFeatures {
637                 &self.inner.features
638         }
639
640         fn quantity(&self) -> Option<u64> {
641                 self.inner.quantity
642         }
643
644         pub(super) fn payer_id(&self) -> PublicKey {
645                 self.payer_id
646         }
647
648         fn payer_note(&self) -> Option<PrintableString> {
649                 self.inner.payer_note.as_ref()
650                         .map(|payer_note| PrintableString(payer_note.as_str()))
651         }
652
653         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
654                 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
655                 invoice_request.payer_id = Some(&self.payer_id);
656                 (payer, offer, invoice_request)
657         }
658 }
659
660 impl InvoiceRequestContentsWithoutPayerId {
661         pub(super) fn metadata(&self) -> &[u8] {
662                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
663         }
664
665         pub(super) fn chain(&self) -> ChainHash {
666                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
667         }
668
669         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
670                 let payer = PayerTlvStreamRef {
671                         metadata: self.payer.0.as_bytes(),
672                 };
673
674                 let offer = self.offer.as_tlv_stream();
675
676                 let features = {
677                         if self.features == InvoiceRequestFeatures::empty() { None }
678                         else { Some(&self.features) }
679                 };
680
681                 let invoice_request = InvoiceRequestTlvStreamRef {
682                         chain: self.chain.as_ref(),
683                         amount: self.amount_msats,
684                         features,
685                         quantity: self.quantity,
686                         payer_id: None,
687                         payer_note: self.payer_note.as_ref(),
688                 };
689
690                 (payer, offer, invoice_request)
691         }
692 }
693
694 impl Writeable for UnsignedInvoiceRequest {
695         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
696                 WithoutLength(&self.bytes).write(writer)
697         }
698 }
699
700 impl Writeable for InvoiceRequest {
701         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
702                 WithoutLength(&self.bytes).write(writer)
703         }
704 }
705
706 impl Writeable for InvoiceRequestContents {
707         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
708                 self.as_tlv_stream().write(writer)
709         }
710 }
711
712 /// Valid type range for invoice_request TLV records.
713 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
714
715 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
716 ///
717 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
718 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
719
720 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
721         (80, chain: ChainHash),
722         (82, amount: (u64, HighZeroBytesDroppedBigSize)),
723         (84, features: (InvoiceRequestFeatures, WithoutLength)),
724         (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
725         (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
726         (89, payer_note: (String, WithoutLength)),
727 });
728
729 type FullInvoiceRequestTlvStream =
730         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
731
732 #[cfg(test)]
733 type FullInvoiceRequestTlvStreamRef<'a> = (
734         PayerTlvStreamRef<'a>,
735         OfferTlvStreamRef<'a>,
736         InvoiceRequestTlvStreamRef<'a>,
737         SignatureTlvStreamRef<'a>,
738 );
739
740 impl SeekReadable for FullInvoiceRequestTlvStream {
741         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
742                 let payer = SeekReadable::read(r)?;
743                 let offer = SeekReadable::read(r)?;
744                 let invoice_request = SeekReadable::read(r)?;
745                 let signature = SeekReadable::read(r)?;
746
747                 Ok((payer, offer, invoice_request, signature))
748         }
749 }
750
751 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
752
753 type PartialInvoiceRequestTlvStreamRef<'a> = (
754         PayerTlvStreamRef<'a>,
755         OfferTlvStreamRef<'a>,
756         InvoiceRequestTlvStreamRef<'a>,
757 );
758
759 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
760         type Error = Bolt12ParseError;
761
762         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
763                 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
764                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
765                 let (
766                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
767                 ) = tlv_stream;
768                 let contents = InvoiceRequestContents::try_from(
769                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
770                 )?;
771
772                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
773
774                 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
775         }
776 }
777
778 impl TryFrom<Vec<u8>> for InvoiceRequest {
779         type Error = Bolt12ParseError;
780
781         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
782                 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
783                 let ParsedMessage { bytes, tlv_stream } = invoice_request;
784                 let (
785                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
786                         SignatureTlvStream { signature },
787                 ) = tlv_stream;
788                 let contents = InvoiceRequestContents::try_from(
789                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
790                 )?;
791
792                 let signature = match signature {
793                         None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
794                         Some(signature) => signature,
795                 };
796                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
797
798                 Ok(InvoiceRequest { bytes, contents, signature })
799         }
800 }
801
802 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
803         type Error = Bolt12SemanticError;
804
805         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
806                 let (
807                         PayerTlvStream { metadata },
808                         offer_tlv_stream,
809                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
810                 ) = tlv_stream;
811
812                 let payer = match metadata {
813                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
814                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
815                 };
816                 let offer = OfferContents::try_from(offer_tlv_stream)?;
817
818                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
819                         return Err(Bolt12SemanticError::UnsupportedChain);
820                 }
821
822                 if offer.amount().is_none() && amount.is_none() {
823                         return Err(Bolt12SemanticError::MissingAmount);
824                 }
825
826                 offer.check_quantity(quantity)?;
827                 offer.check_amount_msats_for_quantity(amount, quantity)?;
828
829                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
830
831                 let payer_id = match payer_id {
832                         None => return Err(Bolt12SemanticError::MissingPayerId),
833                         Some(payer_id) => payer_id,
834                 };
835
836                 Ok(InvoiceRequestContents {
837                         inner: InvoiceRequestContentsWithoutPayerId {
838                                 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
839                         },
840                         payer_id,
841                 })
842         }
843 }
844
845 #[cfg(test)]
846 mod tests {
847         use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
848
849         use bitcoin::blockdata::constants::ChainHash;
850         use bitcoin::network::constants::Network;
851         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
852         use core::convert::{Infallible, TryFrom};
853         use core::num::NonZeroU64;
854         #[cfg(feature = "std")]
855         use core::time::Duration;
856         use crate::sign::KeyMaterial;
857         use crate::ln::features::InvoiceRequestFeatures;
858         use crate::ln::inbound_payment::ExpandedKey;
859         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
860         use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
861         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
862         use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
863         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
864         use crate::offers::payer::PayerTlvStreamRef;
865         use crate::offers::test_utils::*;
866         use crate::util::ser::{BigSize, Writeable};
867         use crate::util::string::PrintableString;
868
869         #[test]
870         fn builds_invoice_request_with_defaults() {
871                 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
872                         .amount_msats(1000)
873                         .build().unwrap()
874                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
875                         .build().unwrap();
876
877                 let mut buffer = Vec::new();
878                 unsigned_invoice_request.write(&mut buffer).unwrap();
879
880                 match UnsignedInvoiceRequest::try_from(buffer) {
881                         Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
882                         Ok(parsed) => {
883                                 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
884                                 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
885                         },
886                 }
887
888                 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
889
890                 let mut buffer = Vec::new();
891                 invoice_request.write(&mut buffer).unwrap();
892
893                 assert_eq!(invoice_request.bytes, buffer.as_slice());
894                 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
895                 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
896                 assert_eq!(invoice_request.amount_msats(), None);
897                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
898                 assert_eq!(invoice_request.quantity(), None);
899                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
900                 assert_eq!(invoice_request.payer_note(), None);
901                 assert!(
902                         merkle::verify_signature(
903                                 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
904                         ).is_ok()
905                 );
906
907                 assert_eq!(
908                         invoice_request.as_tlv_stream(),
909                         (
910                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
911                                 OfferTlvStreamRef {
912                                         chains: None,
913                                         metadata: None,
914                                         currency: None,
915                                         amount: Some(1000),
916                                         description: Some(&String::from("foo")),
917                                         features: None,
918                                         absolute_expiry: None,
919                                         paths: None,
920                                         issuer: None,
921                                         quantity_max: None,
922                                         node_id: Some(&recipient_pubkey()),
923                                 },
924                                 InvoiceRequestTlvStreamRef {
925                                         chain: None,
926                                         amount: None,
927                                         features: None,
928                                         quantity: None,
929                                         payer_id: Some(&payer_pubkey()),
930                                         payer_note: None,
931                                 },
932                                 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
933                         ),
934                 );
935
936                 if let Err(e) = InvoiceRequest::try_from(buffer) {
937                         panic!("error parsing invoice request: {:?}", e);
938                 }
939         }
940
941         #[cfg(feature = "std")]
942         #[test]
943         fn builds_invoice_request_from_offer_with_expiration() {
944                 let future_expiry = Duration::from_secs(u64::max_value());
945                 let past_expiry = Duration::from_secs(0);
946
947                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
948                         .amount_msats(1000)
949                         .absolute_expiry(future_expiry)
950                         .build().unwrap()
951                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
952                         .build()
953                 {
954                         panic!("error building invoice_request: {:?}", e);
955                 }
956
957                 match OfferBuilder::new("foo".into(), recipient_pubkey())
958                         .amount_msats(1000)
959                         .absolute_expiry(past_expiry)
960                         .build().unwrap()
961                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
962                         .build()
963                 {
964                         Ok(_) => panic!("expected error"),
965                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
966                 }
967         }
968
969         #[test]
970         fn builds_invoice_request_with_derived_metadata() {
971                 let payer_id = payer_pubkey();
972                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
973                 let entropy = FixedEntropy {};
974                 let secp_ctx = Secp256k1::new();
975
976                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
977                         .amount_msats(1000)
978                         .build().unwrap();
979                 let invoice_request = offer
980                         .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
981                         .unwrap()
982                         .build().unwrap()
983                         .sign(payer_sign).unwrap();
984                 assert_eq!(invoice_request.payer_id(), payer_pubkey());
985
986                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
987                         .unwrap()
988                         .build().unwrap()
989                         .sign(recipient_sign).unwrap();
990                 assert!(invoice.verify(&expanded_key, &secp_ctx));
991
992                 // Fails verification with altered fields
993                 let (
994                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
995                         mut invoice_tlv_stream, mut signature_tlv_stream
996                 ) = invoice.as_tlv_stream();
997                 invoice_request_tlv_stream.amount = Some(2000);
998                 invoice_tlv_stream.amount = Some(2000);
999
1000                 let tlv_stream =
1001                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1002                 let mut bytes = Vec::new();
1003                 tlv_stream.write(&mut bytes).unwrap();
1004
1005                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1006                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1007                 signature_tlv_stream.signature = Some(&signature);
1008
1009                 let mut encoded_invoice = bytes;
1010                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1011
1012                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1013                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1014
1015                 // Fails verification with altered metadata
1016                 let (
1017                         mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1018                         mut signature_tlv_stream
1019                 ) = invoice.as_tlv_stream();
1020                 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1021                 payer_tlv_stream.metadata = Some(&metadata);
1022
1023                 let tlv_stream =
1024                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1025                 let mut bytes = Vec::new();
1026                 tlv_stream.write(&mut bytes).unwrap();
1027
1028                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1029                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1030                 signature_tlv_stream.signature = Some(&signature);
1031
1032                 let mut encoded_invoice = bytes;
1033                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1034
1035                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1036                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1037         }
1038
1039         #[test]
1040         fn builds_invoice_request_with_derived_payer_id() {
1041                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1042                 let entropy = FixedEntropy {};
1043                 let secp_ctx = Secp256k1::new();
1044
1045                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1046                         .amount_msats(1000)
1047                         .build().unwrap();
1048                 let invoice_request = offer
1049                         .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1050                         .unwrap()
1051                         .build_and_sign()
1052                         .unwrap();
1053
1054                 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1055                         .unwrap()
1056                         .build().unwrap()
1057                         .sign(recipient_sign).unwrap();
1058                 assert!(invoice.verify(&expanded_key, &secp_ctx));
1059
1060                 // Fails verification with altered fields
1061                 let (
1062                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1063                         mut invoice_tlv_stream, mut signature_tlv_stream
1064                 ) = invoice.as_tlv_stream();
1065                 invoice_request_tlv_stream.amount = Some(2000);
1066                 invoice_tlv_stream.amount = Some(2000);
1067
1068                 let tlv_stream =
1069                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1070                 let mut bytes = Vec::new();
1071                 tlv_stream.write(&mut bytes).unwrap();
1072
1073                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1074                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1075                 signature_tlv_stream.signature = Some(&signature);
1076
1077                 let mut encoded_invoice = bytes;
1078                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1079
1080                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1081                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1082
1083                 // Fails verification with altered payer id
1084                 let (
1085                         payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1086                         mut signature_tlv_stream
1087                 ) = invoice.as_tlv_stream();
1088                 let payer_id = pubkey(1);
1089                 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1090
1091                 let tlv_stream =
1092                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1093                 let mut bytes = Vec::new();
1094                 tlv_stream.write(&mut bytes).unwrap();
1095
1096                 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1097                 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1098                 signature_tlv_stream.signature = Some(&signature);
1099
1100                 let mut encoded_invoice = bytes;
1101                 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1102
1103                 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1104                 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1105         }
1106
1107         #[test]
1108         fn builds_invoice_request_with_chain() {
1109                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1110                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1111
1112                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1113                         .amount_msats(1000)
1114                         .build().unwrap()
1115                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1116                         .chain(Network::Bitcoin).unwrap()
1117                         .build().unwrap()
1118                         .sign(payer_sign).unwrap();
1119                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1120                 assert_eq!(invoice_request.chain(), mainnet);
1121                 assert_eq!(tlv_stream.chain, None);
1122
1123                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1124                         .amount_msats(1000)
1125                         .chain(Network::Testnet)
1126                         .build().unwrap()
1127                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1128                         .chain(Network::Testnet).unwrap()
1129                         .build().unwrap()
1130                         .sign(payer_sign).unwrap();
1131                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1132                 assert_eq!(invoice_request.chain(), testnet);
1133                 assert_eq!(tlv_stream.chain, Some(&testnet));
1134
1135                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1136                         .amount_msats(1000)
1137                         .chain(Network::Bitcoin)
1138                         .chain(Network::Testnet)
1139                         .build().unwrap()
1140                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1141                         .chain(Network::Bitcoin).unwrap()
1142                         .build().unwrap()
1143                         .sign(payer_sign).unwrap();
1144                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1145                 assert_eq!(invoice_request.chain(), mainnet);
1146                 assert_eq!(tlv_stream.chain, None);
1147
1148                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1149                         .amount_msats(1000)
1150                         .chain(Network::Bitcoin)
1151                         .chain(Network::Testnet)
1152                         .build().unwrap()
1153                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1154                         .chain(Network::Bitcoin).unwrap()
1155                         .chain(Network::Testnet).unwrap()
1156                         .build().unwrap()
1157                         .sign(payer_sign).unwrap();
1158                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1159                 assert_eq!(invoice_request.chain(), testnet);
1160                 assert_eq!(tlv_stream.chain, Some(&testnet));
1161
1162                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1163                         .amount_msats(1000)
1164                         .chain(Network::Testnet)
1165                         .build().unwrap()
1166                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1167                         .chain(Network::Bitcoin)
1168                 {
1169                         Ok(_) => panic!("expected error"),
1170                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1171                 }
1172
1173                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1174                         .amount_msats(1000)
1175                         .chain(Network::Testnet)
1176                         .build().unwrap()
1177                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1178                         .build()
1179                 {
1180                         Ok(_) => panic!("expected error"),
1181                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1182                 }
1183         }
1184
1185         #[test]
1186         fn builds_invoice_request_with_amount() {
1187                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1188                         .amount_msats(1000)
1189                         .build().unwrap()
1190                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1191                         .amount_msats(1000).unwrap()
1192                         .build().unwrap()
1193                         .sign(payer_sign).unwrap();
1194                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1195                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1196                 assert_eq!(tlv_stream.amount, Some(1000));
1197
1198                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1199                         .amount_msats(1000)
1200                         .build().unwrap()
1201                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1202                         .amount_msats(1001).unwrap()
1203                         .amount_msats(1000).unwrap()
1204                         .build().unwrap()
1205                         .sign(payer_sign).unwrap();
1206                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1207                 assert_eq!(invoice_request.amount_msats(), Some(1000));
1208                 assert_eq!(tlv_stream.amount, Some(1000));
1209
1210                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1211                         .amount_msats(1000)
1212                         .build().unwrap()
1213                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1214                         .amount_msats(1001).unwrap()
1215                         .build().unwrap()
1216                         .sign(payer_sign).unwrap();
1217                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1218                 assert_eq!(invoice_request.amount_msats(), Some(1001));
1219                 assert_eq!(tlv_stream.amount, Some(1001));
1220
1221                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1222                         .amount_msats(1000)
1223                         .build().unwrap()
1224                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225                         .amount_msats(999)
1226                 {
1227                         Ok(_) => panic!("expected error"),
1228                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1229                 }
1230
1231                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1232                         .amount_msats(1000)
1233                         .supported_quantity(Quantity::Unbounded)
1234                         .build().unwrap()
1235                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236                         .quantity(2).unwrap()
1237                         .amount_msats(1000)
1238                 {
1239                         Ok(_) => panic!("expected error"),
1240                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1241                 }
1242
1243                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1244                         .amount_msats(1000)
1245                         .build().unwrap()
1246                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1247                         .amount_msats(MAX_VALUE_MSAT + 1)
1248                 {
1249                         Ok(_) => panic!("expected error"),
1250                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1251                 }
1252
1253                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1254                         .amount_msats(1000)
1255                         .supported_quantity(Quantity::Unbounded)
1256                         .build().unwrap()
1257                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258                         .amount_msats(1000).unwrap()
1259                         .quantity(2).unwrap()
1260                         .build()
1261                 {
1262                         Ok(_) => panic!("expected error"),
1263                         Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1264                 }
1265
1266                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1267                         .build().unwrap()
1268                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1269                         .build()
1270                 {
1271                         Ok(_) => panic!("expected error"),
1272                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1273                 }
1274
1275                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1276                         .amount_msats(1000)
1277                         .supported_quantity(Quantity::Unbounded)
1278                         .build().unwrap()
1279                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1280                         .quantity(u64::max_value()).unwrap()
1281                         .build()
1282                 {
1283                         Ok(_) => panic!("expected error"),
1284                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1285                 }
1286         }
1287
1288         #[test]
1289         fn builds_invoice_request_with_features() {
1290                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1291                         .amount_msats(1000)
1292                         .build().unwrap()
1293                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1294                         .features_unchecked(InvoiceRequestFeatures::unknown())
1295                         .build().unwrap()
1296                         .sign(payer_sign).unwrap();
1297                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1298                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1299                 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1300
1301                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1302                         .amount_msats(1000)
1303                         .build().unwrap()
1304                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1305                         .features_unchecked(InvoiceRequestFeatures::unknown())
1306                         .features_unchecked(InvoiceRequestFeatures::empty())
1307                         .build().unwrap()
1308                         .sign(payer_sign).unwrap();
1309                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1310                 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1311                 assert_eq!(tlv_stream.features, None);
1312         }
1313
1314         #[test]
1315         fn builds_invoice_request_with_quantity() {
1316                 let one = NonZeroU64::new(1).unwrap();
1317                 let ten = NonZeroU64::new(10).unwrap();
1318
1319                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1320                         .amount_msats(1000)
1321                         .supported_quantity(Quantity::One)
1322                         .build().unwrap()
1323                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1324                         .build().unwrap()
1325                         .sign(payer_sign).unwrap();
1326                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1327                 assert_eq!(invoice_request.quantity(), None);
1328                 assert_eq!(tlv_stream.quantity, None);
1329
1330                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1331                         .amount_msats(1000)
1332                         .supported_quantity(Quantity::One)
1333                         .build().unwrap()
1334                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1335                         .amount_msats(2_000).unwrap()
1336                         .quantity(2)
1337                 {
1338                         Ok(_) => panic!("expected error"),
1339                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1340                 }
1341
1342                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1343                         .amount_msats(1000)
1344                         .supported_quantity(Quantity::Bounded(ten))
1345                         .build().unwrap()
1346                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347                         .amount_msats(10_000).unwrap()
1348                         .quantity(10).unwrap()
1349                         .build().unwrap()
1350                         .sign(payer_sign).unwrap();
1351                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1352                 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1353                 assert_eq!(tlv_stream.amount, Some(10_000));
1354
1355                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1356                         .amount_msats(1000)
1357                         .supported_quantity(Quantity::Bounded(ten))
1358                         .build().unwrap()
1359                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1360                         .amount_msats(11_000).unwrap()
1361                         .quantity(11)
1362                 {
1363                         Ok(_) => panic!("expected error"),
1364                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1365                 }
1366
1367                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1368                         .amount_msats(1000)
1369                         .supported_quantity(Quantity::Unbounded)
1370                         .build().unwrap()
1371                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1372                         .amount_msats(2_000).unwrap()
1373                         .quantity(2).unwrap()
1374                         .build().unwrap()
1375                         .sign(payer_sign).unwrap();
1376                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1377                 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1378                 assert_eq!(tlv_stream.amount, Some(2_000));
1379
1380                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1381                         .amount_msats(1000)
1382                         .supported_quantity(Quantity::Unbounded)
1383                         .build().unwrap()
1384                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1385                         .build()
1386                 {
1387                         Ok(_) => panic!("expected error"),
1388                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1389                 }
1390
1391                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1392                         .amount_msats(1000)
1393                         .supported_quantity(Quantity::Bounded(one))
1394                         .build().unwrap()
1395                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1396                         .build()
1397                 {
1398                         Ok(_) => panic!("expected error"),
1399                         Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1400                 }
1401         }
1402
1403         #[test]
1404         fn builds_invoice_request_with_payer_note() {
1405                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1406                         .amount_msats(1000)
1407                         .build().unwrap()
1408                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1409                         .payer_note("bar".into())
1410                         .build().unwrap()
1411                         .sign(payer_sign).unwrap();
1412                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1413                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1414                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1415
1416                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1417                         .amount_msats(1000)
1418                         .build().unwrap()
1419                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1420                         .payer_note("bar".into())
1421                         .payer_note("baz".into())
1422                         .build().unwrap()
1423                         .sign(payer_sign).unwrap();
1424                 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1425                 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1426                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1427         }
1428
1429         #[test]
1430         fn fails_signing_invoice_request() {
1431                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1432                         .amount_msats(1000)
1433                         .build().unwrap()
1434                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1435                         .build().unwrap()
1436                         .sign(|_| Err(()))
1437                 {
1438                         Ok(_) => panic!("expected error"),
1439                         Err(e) => assert_eq!(e, SignError::Signing(())),
1440                 }
1441
1442                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1443                         .amount_msats(1000)
1444                         .build().unwrap()
1445                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446                         .build().unwrap()
1447                         .sign(recipient_sign)
1448                 {
1449                         Ok(_) => panic!("expected error"),
1450                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1451                 }
1452         }
1453
1454         #[test]
1455         fn fails_responding_with_unknown_required_features() {
1456                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1457                         .amount_msats(1000)
1458                         .build().unwrap()
1459                         .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1460                         .features_unchecked(InvoiceRequestFeatures::unknown())
1461                         .build().unwrap()
1462                         .sign(payer_sign).unwrap()
1463                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1464                 {
1465                         Ok(_) => panic!("expected error"),
1466                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1467                 }
1468         }
1469
1470         #[test]
1471         fn parses_invoice_request_with_metadata() {
1472                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1473                         .amount_msats(1000)
1474                         .build().unwrap()
1475                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1476                         .build().unwrap()
1477                         .sign(payer_sign).unwrap();
1478
1479                 let mut buffer = Vec::new();
1480                 invoice_request.write(&mut buffer).unwrap();
1481
1482                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1483                         panic!("error parsing invoice_request: {:?}", e);
1484                 }
1485         }
1486
1487         #[test]
1488         fn parses_invoice_request_with_chain() {
1489                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1490                         .amount_msats(1000)
1491                         .build().unwrap()
1492                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493                         .chain(Network::Bitcoin).unwrap()
1494                         .build().unwrap()
1495                         .sign(payer_sign).unwrap();
1496
1497                 let mut buffer = Vec::new();
1498                 invoice_request.write(&mut buffer).unwrap();
1499
1500                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1501                         panic!("error parsing invoice_request: {:?}", e);
1502                 }
1503
1504                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1505                         .amount_msats(1000)
1506                         .build().unwrap()
1507                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1508                         .chain_unchecked(Network::Testnet)
1509                         .build_unchecked()
1510                         .sign(payer_sign).unwrap();
1511
1512                 let mut buffer = Vec::new();
1513                 invoice_request.write(&mut buffer).unwrap();
1514
1515                 match InvoiceRequest::try_from(buffer) {
1516                         Ok(_) => panic!("expected error"),
1517                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1518                 }
1519         }
1520
1521         #[test]
1522         fn parses_invoice_request_with_amount() {
1523                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1524                         .amount_msats(1000)
1525                         .build().unwrap()
1526                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1527                         .build().unwrap()
1528                         .sign(payer_sign).unwrap();
1529
1530                 let mut buffer = Vec::new();
1531                 invoice_request.write(&mut buffer).unwrap();
1532
1533                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1534                         panic!("error parsing invoice_request: {:?}", e);
1535                 }
1536
1537                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1538                         .build().unwrap()
1539                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1540                         .amount_msats(1000).unwrap()
1541                         .build().unwrap()
1542                         .sign(payer_sign).unwrap();
1543
1544                 let mut buffer = Vec::new();
1545                 invoice_request.write(&mut buffer).unwrap();
1546
1547                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1548                         panic!("error parsing invoice_request: {:?}", e);
1549                 }
1550
1551                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1552                         .build().unwrap()
1553                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1554                         .build_unchecked()
1555                         .sign(payer_sign).unwrap();
1556
1557                 let mut buffer = Vec::new();
1558                 invoice_request.write(&mut buffer).unwrap();
1559
1560                 match InvoiceRequest::try_from(buffer) {
1561                         Ok(_) => panic!("expected error"),
1562                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1563                 }
1564
1565                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1566                         .amount_msats(1000)
1567                         .build().unwrap()
1568                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1569                         .amount_msats_unchecked(999)
1570                         .build_unchecked()
1571                         .sign(payer_sign).unwrap();
1572
1573                 let mut buffer = Vec::new();
1574                 invoice_request.write(&mut buffer).unwrap();
1575
1576                 match InvoiceRequest::try_from(buffer) {
1577                         Ok(_) => panic!("expected error"),
1578                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1579                 }
1580
1581                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1582                         .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1583                         .build_unchecked()
1584                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1585                         .build_unchecked()
1586                         .sign(payer_sign).unwrap();
1587
1588                 let mut buffer = Vec::new();
1589                 invoice_request.write(&mut buffer).unwrap();
1590
1591                 match InvoiceRequest::try_from(buffer) {
1592                         Ok(_) => panic!("expected error"),
1593                         Err(e) => {
1594                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1595                         },
1596                 }
1597
1598                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1599                         .amount_msats(1000)
1600                         .supported_quantity(Quantity::Unbounded)
1601                         .build().unwrap()
1602                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1603                         .quantity(u64::max_value()).unwrap()
1604                         .build_unchecked()
1605                         .sign(payer_sign).unwrap();
1606
1607                 let mut buffer = Vec::new();
1608                 invoice_request.write(&mut buffer).unwrap();
1609
1610                 match InvoiceRequest::try_from(buffer) {
1611                         Ok(_) => panic!("expected error"),
1612                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1613                 }
1614         }
1615
1616         #[test]
1617         fn parses_invoice_request_with_quantity() {
1618                 let one = NonZeroU64::new(1).unwrap();
1619                 let ten = NonZeroU64::new(10).unwrap();
1620
1621                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1622                         .amount_msats(1000)
1623                         .supported_quantity(Quantity::One)
1624                         .build().unwrap()
1625                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626                         .build().unwrap()
1627                         .sign(payer_sign).unwrap();
1628
1629                 let mut buffer = Vec::new();
1630                 invoice_request.write(&mut buffer).unwrap();
1631
1632                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1633                         panic!("error parsing invoice_request: {:?}", e);
1634                 }
1635
1636                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1637                         .amount_msats(1000)
1638                         .supported_quantity(Quantity::One)
1639                         .build().unwrap()
1640                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1641                         .amount_msats(2_000).unwrap()
1642                         .quantity_unchecked(2)
1643                         .build_unchecked()
1644                         .sign(payer_sign).unwrap();
1645
1646                 let mut buffer = Vec::new();
1647                 invoice_request.write(&mut buffer).unwrap();
1648
1649                 match InvoiceRequest::try_from(buffer) {
1650                         Ok(_) => panic!("expected error"),
1651                         Err(e) => {
1652                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1653                         },
1654                 }
1655
1656                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1657                         .amount_msats(1000)
1658                         .supported_quantity(Quantity::Bounded(ten))
1659                         .build().unwrap()
1660                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661                         .amount_msats(10_000).unwrap()
1662                         .quantity(10).unwrap()
1663                         .build().unwrap()
1664                         .sign(payer_sign).unwrap();
1665
1666                 let mut buffer = Vec::new();
1667                 invoice_request.write(&mut buffer).unwrap();
1668
1669                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1670                         panic!("error parsing invoice_request: {:?}", e);
1671                 }
1672
1673                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1674                         .amount_msats(1000)
1675                         .supported_quantity(Quantity::Bounded(ten))
1676                         .build().unwrap()
1677                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1678                         .amount_msats(11_000).unwrap()
1679                         .quantity_unchecked(11)
1680                         .build_unchecked()
1681                         .sign(payer_sign).unwrap();
1682
1683                 let mut buffer = Vec::new();
1684                 invoice_request.write(&mut buffer).unwrap();
1685
1686                 match InvoiceRequest::try_from(buffer) {
1687                         Ok(_) => panic!("expected error"),
1688                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1689                 }
1690
1691                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1692                         .amount_msats(1000)
1693                         .supported_quantity(Quantity::Unbounded)
1694                         .build().unwrap()
1695                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1696                         .amount_msats(2_000).unwrap()
1697                         .quantity(2).unwrap()
1698                         .build().unwrap()
1699                         .sign(payer_sign).unwrap();
1700
1701                 let mut buffer = Vec::new();
1702                 invoice_request.write(&mut buffer).unwrap();
1703
1704                 if let Err(e) = InvoiceRequest::try_from(buffer) {
1705                         panic!("error parsing invoice_request: {:?}", e);
1706                 }
1707
1708                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1709                         .amount_msats(1000)
1710                         .supported_quantity(Quantity::Unbounded)
1711                         .build().unwrap()
1712                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1713                         .build_unchecked()
1714                         .sign(payer_sign).unwrap();
1715
1716                 let mut buffer = Vec::new();
1717                 invoice_request.write(&mut buffer).unwrap();
1718
1719                 match InvoiceRequest::try_from(buffer) {
1720                         Ok(_) => panic!("expected error"),
1721                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1722                 }
1723
1724                 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1725                         .amount_msats(1000)
1726                         .supported_quantity(Quantity::Bounded(one))
1727                         .build().unwrap()
1728                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1729                         .build_unchecked()
1730                         .sign(payer_sign).unwrap();
1731
1732                 let mut buffer = Vec::new();
1733                 invoice_request.write(&mut buffer).unwrap();
1734
1735                 match InvoiceRequest::try_from(buffer) {
1736                         Ok(_) => panic!("expected error"),
1737                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1738                 }
1739         }
1740
1741         #[test]
1742         fn fails_parsing_invoice_request_without_metadata() {
1743                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1744                         .amount_msats(1000)
1745                         .build().unwrap();
1746                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1747                         .build().unwrap();
1748                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1749                 tlv_stream.0.metadata = None;
1750
1751                 let mut buffer = Vec::new();
1752                 tlv_stream.write(&mut buffer).unwrap();
1753
1754                 match InvoiceRequest::try_from(buffer) {
1755                         Ok(_) => panic!("expected error"),
1756                         Err(e) => {
1757                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1758                         },
1759                 }
1760         }
1761
1762         #[test]
1763         fn fails_parsing_invoice_request_without_payer_id() {
1764                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1765                         .amount_msats(1000)
1766                         .build().unwrap();
1767                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1768                         .build().unwrap();
1769                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1770                 tlv_stream.2.payer_id = None;
1771
1772                 let mut buffer = Vec::new();
1773                 tlv_stream.write(&mut buffer).unwrap();
1774
1775                 match InvoiceRequest::try_from(buffer) {
1776                         Ok(_) => panic!("expected error"),
1777                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1778                 }
1779         }
1780
1781         #[test]
1782         fn fails_parsing_invoice_request_without_node_id() {
1783                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1784                         .amount_msats(1000)
1785                         .build().unwrap();
1786                 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1787                         .build().unwrap();
1788                 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1789                 tlv_stream.1.node_id = None;
1790
1791                 let mut buffer = Vec::new();
1792                 tlv_stream.write(&mut buffer).unwrap();
1793
1794                 match InvoiceRequest::try_from(buffer) {
1795                         Ok(_) => panic!("expected error"),
1796                         Err(e) => {
1797                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1798                         },
1799                 }
1800         }
1801
1802         #[test]
1803         fn fails_parsing_invoice_request_without_signature() {
1804                 let mut buffer = Vec::new();
1805                 OfferBuilder::new("foo".into(), recipient_pubkey())
1806                         .amount_msats(1000)
1807                         .build().unwrap()
1808                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1809                         .build().unwrap()
1810                         .contents
1811                         .write(&mut buffer).unwrap();
1812
1813                 match InvoiceRequest::try_from(buffer) {
1814                         Ok(_) => panic!("expected error"),
1815                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1816                 }
1817         }
1818
1819         #[test]
1820         fn fails_parsing_invoice_request_with_invalid_signature() {
1821                 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1822                         .amount_msats(1000)
1823                         .build().unwrap()
1824                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1825                         .build().unwrap()
1826                         .sign(payer_sign).unwrap();
1827                 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1828                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1829
1830                 let mut buffer = Vec::new();
1831                 invoice_request.write(&mut buffer).unwrap();
1832
1833                 match InvoiceRequest::try_from(buffer) {
1834                         Ok(_) => panic!("expected error"),
1835                         Err(e) => {
1836                                 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1837                         },
1838                 }
1839         }
1840
1841         #[test]
1842         fn fails_parsing_invoice_request_with_extra_tlv_records() {
1843                 let secp_ctx = Secp256k1::new();
1844                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1845                 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1846                         .amount_msats(1000)
1847                         .build().unwrap()
1848                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1849                         .build().unwrap()
1850                         .sign::<_, Infallible>(
1851                                 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1852                         )
1853                         .unwrap();
1854
1855                 let mut encoded_invoice_request = Vec::new();
1856                 invoice_request.write(&mut encoded_invoice_request).unwrap();
1857                 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1858                 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1859                 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1860
1861                 match InvoiceRequest::try_from(encoded_invoice_request) {
1862                         Ok(_) => panic!("expected error"),
1863                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1864                 }
1865         }
1866 }