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