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