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