1 // This file is Copyright its original authors, visible in version control
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
10 //! Data structures and encoding for `invoice_request` messages.
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`].
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
23 //! extern crate bitcoin;
24 //! extern crate lightning;
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;
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();
39 //! # use lightning::offers::invoice_request::{ExplicitPayerId, InvoiceRequestBuilder};
40 //! # <InvoiceRequestBuilder<ExplicitPayerId, _>>::from(
42 //! .parse::<Offer>()?
43 //! .request_invoice(vec![42; 64], pubkey)?
45 //! .chain(Network::Testnet)?
46 //! .amount_msats(1000)?
48 //! .payer_note("foo".to_string())
50 //! .sign::<_, Infallible>(
51 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
53 //! .expect("failed verifying signature")
54 //! .write(&mut buffer)
60 use bitcoin::blockdata::constants::ChainHash;
61 use bitcoin::network::constants::Network;
62 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
63 use bitcoin::secp256k1::schnorr::Signature;
64 use core::convert::{AsRef, Infallible, TryFrom};
66 use crate::sign::EntropySource;
68 use crate::blinded_path::BlindedPath;
69 use crate::ln::PaymentHash;
70 use crate::ln::channelmanager::PaymentId;
71 use crate::ln::features::InvoiceRequestFeatures;
72 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
73 use crate::ln::msgs::DecodeError;
74 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
75 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
76 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
77 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
78 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
79 use crate::offers::signer::{Metadata, MetadataMaterial};
80 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
81 use crate::util::string::PrintableString;
83 use crate::prelude::*;
85 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
86 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
88 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
90 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
92 /// See [module-level documentation] for usage.
94 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
96 /// [module-level documentation]: self
97 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
99 invoice_request: InvoiceRequestContentsWithoutPayerId,
100 payer_id: Option<PublicKey>,
101 payer_id_strategy: core::marker::PhantomData<P>,
102 secp_ctx: Option<&'b Secp256k1<T>>,
105 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
107 /// See [module-level documentation] for usage.
109 /// [module-level documentation]: self
111 pub struct InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
113 invoice_request: InvoiceRequestContentsWithoutPayerId,
114 payer_id: Option<PublicKey>,
115 payer_id_strategy: core::marker::PhantomData<ExplicitPayerId>,
116 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
119 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
121 /// See [module-level documentation] for usage.
123 /// [module-level documentation]: self
125 pub struct InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
127 invoice_request: InvoiceRequestContentsWithoutPayerId,
128 payer_id: Option<PublicKey>,
129 payer_id_strategy: core::marker::PhantomData<DerivedPayerId>,
130 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
133 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
135 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
136 pub trait PayerIdStrategy {}
138 /// [`InvoiceRequest::payer_id`] will be explicitly set.
140 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
141 pub struct ExplicitPayerId {}
143 /// [`InvoiceRequest::payer_id`] will be derived.
145 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
146 pub struct DerivedPayerId {}
148 impl PayerIdStrategy for ExplicitPayerId {}
149 impl PayerIdStrategy for DerivedPayerId {}
151 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
152 #[cfg_attr(c_bindings, allow(dead_code))]
153 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
156 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
157 payer_id: Some(payer_id),
158 payer_id_strategy: core::marker::PhantomData,
163 #[cfg_attr(c_bindings, allow(dead_code))]
164 pub(super) fn deriving_metadata<ES: Deref>(
165 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
166 payment_id: PaymentId,
167 ) -> Self where ES::Target: EntropySource {
168 let nonce = Nonce::from_entropy_source(entropy_source);
169 let payment_id = Some(payment_id);
170 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
171 let metadata = Metadata::Derived(derivation_material);
174 invoice_request: Self::create_contents(offer, metadata),
175 payer_id: Some(payer_id),
176 payer_id_strategy: core::marker::PhantomData,
181 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
182 /// by [`UnsignedInvoiceRequest::sign`].
183 pub fn build($self: $self_type) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
184 let (unsigned_invoice_request, keys, _) = $self.build_with_checks()?;
185 debug_assert!(keys.is_none());
186 Ok(unsigned_invoice_request)
190 macro_rules! invoice_request_derived_payer_id_builder_methods { (
191 $self: ident, $self_type: ty, $secp_context: ty
193 #[cfg_attr(c_bindings, allow(dead_code))]
194 pub(super) fn deriving_payer_id<ES: Deref>(
195 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
196 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
197 ) -> Self where ES::Target: EntropySource {
198 let nonce = Nonce::from_entropy_source(entropy_source);
199 let payment_id = Some(payment_id);
200 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
201 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
204 invoice_request: Self::create_contents(offer, metadata),
206 payer_id_strategy: core::marker::PhantomData,
207 secp_ctx: Some(secp_ctx),
211 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
212 pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
213 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
215 let mut unsigned_invoice_request = unsigned_invoice_request;
216 debug_assert!(keys.is_some());
218 let secp_ctx = secp_ctx.unwrap();
219 let keys = keys.unwrap();
220 let invoice_request = unsigned_invoice_request
221 .sign::<_, Infallible>(
222 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
229 macro_rules! invoice_request_builder_methods { (
230 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
232 #[cfg_attr(c_bindings, allow(dead_code))]
233 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
234 let offer = offer.contents.clone();
235 InvoiceRequestContentsWithoutPayerId {
236 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
237 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
241 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
242 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
245 /// Successive calls to this method will override the previous setting.
246 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
247 $self.chain_hash(ChainHash::using_genesis_block(network))
250 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
251 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
254 /// Successive calls to this method will override the previous setting.
255 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
256 if !$self.offer.supports_chain(chain) {
257 return Err(Bolt12SemanticError::UnsupportedChain);
260 $self.invoice_request.chain = Some(chain);
264 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
265 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
267 /// Successive calls to this method will override the previous setting.
269 /// [`quantity`]: Self::quantity
270 pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
271 $self.invoice_request.offer.check_amount_msats_for_quantity(
272 Some(amount_msats), $self.invoice_request.quantity
274 $self.invoice_request.amount_msats = Some(amount_msats);
278 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
279 /// does not conform to [`Offer::is_valid_quantity`].
281 /// Successive calls to this method will override the previous setting.
282 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
283 $self.invoice_request.offer.check_quantity(Some(quantity))?;
284 $self.invoice_request.quantity = Some(quantity);
288 /// Sets the [`InvoiceRequest::payer_note`].
290 /// Successive calls to this method will override the previous setting.
291 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
292 $self.invoice_request.payer_note = Some(payer_note);
296 fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
297 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>),
300 #[cfg(feature = "std")] {
301 if $self.offer.is_expired() {
302 return Err(Bolt12SemanticError::AlreadyExpired);
306 let chain = $self.invoice_request.chain();
307 if !$self.offer.supports_chain(chain) {
308 return Err(Bolt12SemanticError::UnsupportedChain);
311 if chain == $self.offer.implied_chain() {
312 $self.invoice_request.chain = None;
315 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
316 return Err(Bolt12SemanticError::MissingAmount);
319 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
320 $self.invoice_request.offer.check_amount_msats_for_quantity(
321 $self.invoice_request.amount_msats, $self.invoice_request.quantity
324 Ok($self.build_without_checks())
327 fn build_without_checks($($self_mut)* $self: $self_type) ->
328 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>)
330 // Create the metadata for stateless verification of a Bolt12Invoice.
332 let secp_ctx = $self.secp_ctx.clone();
333 if $self.invoice_request.payer.0.has_derivation_material() {
334 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
336 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
337 debug_assert!(tlv_stream.2.payer_id.is_none());
338 tlv_stream.0.metadata = None;
339 if !metadata.derives_payer_keys() {
340 tlv_stream.2.payer_id = $self.payer_id.as_ref();
343 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
344 metadata = derived_metadata;
346 if let Some(keys) = keys {
347 debug_assert!($self.payer_id.is_none());
348 $self.payer_id = Some(keys.public_key());
351 $self.invoice_request.payer.0 = metadata;
354 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
355 debug_assert!($self.payer_id.is_some());
356 let payer_id = $self.payer_id.unwrap();
358 let invoice_request = InvoiceRequestContents {
359 #[cfg(not(c_bindings))]
360 inner: $self.invoice_request,
362 inner: $self.invoice_request.clone(),
365 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
367 (unsigned_invoice_request, keys, secp_ctx)
372 macro_rules! invoice_request_builder_test_methods { (
373 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
375 #[cfg_attr(c_bindings, allow(dead_code))]
376 fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
377 let chain = ChainHash::using_genesis_block(network);
378 $self.invoice_request.chain = Some(chain);
382 #[cfg_attr(c_bindings, allow(dead_code))]
383 fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
384 $self.invoice_request.amount_msats = Some(amount_msats);
388 #[cfg_attr(c_bindings, allow(dead_code))]
389 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
390 $self.invoice_request.features = features;
394 #[cfg_attr(c_bindings, allow(dead_code))]
395 fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
396 $self.invoice_request.quantity = Some(quantity);
400 #[cfg_attr(c_bindings, allow(dead_code))]
401 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
402 $self.build_without_checks().0
406 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
407 invoice_request_explicit_payer_id_builder_methods!(self, Self);
410 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
411 invoice_request_derived_payer_id_builder_methods!(self, Self, T);
414 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
415 invoice_request_builder_methods!(self, Self, Self, self, T, mut);
418 invoice_request_builder_test_methods!(self, Self, Self, self, mut);
421 #[cfg(all(c_bindings, not(test)))]
422 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
423 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
424 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
427 #[cfg(all(c_bindings, test))]
428 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
429 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
430 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
431 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
434 #[cfg(all(c_bindings, not(test)))]
435 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
436 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
437 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
440 #[cfg(all(c_bindings, test))]
441 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
442 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
443 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
444 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
448 impl<'a, 'b> From<InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>>
449 for InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, secp256k1::All> {
450 fn from(builder: InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>) -> Self {
451 let InvoiceRequestWithExplicitPayerIdBuilder {
452 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
456 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
462 impl<'a, 'b> From<InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>>
463 for InvoiceRequestBuilder<'a, 'b, DerivedPayerId, secp256k1::All> {
464 fn from(builder: InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>) -> Self {
465 let InvoiceRequestWithDerivedPayerIdBuilder {
466 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
470 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
475 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
479 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
480 /// such, it may include unknown, odd TLV records.
481 pub struct UnsignedInvoiceRequest {
483 contents: InvoiceRequestContents,
484 tagged_hash: TaggedHash,
487 impl UnsignedInvoiceRequest {
488 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
489 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
490 // unknown TLV records, which are not stored in `OfferContents`.
491 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
492 contents.as_tlv_stream();
493 let offer_bytes = WithoutLength(&offer.bytes);
494 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
496 let mut bytes = Vec::new();
497 unsigned_tlv_stream.write(&mut bytes).unwrap();
499 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
501 Self { bytes, contents, tagged_hash }
504 /// Returns the [`TaggedHash`] of the invoice to sign.
505 pub fn tagged_hash(&self) -> &TaggedHash {
510 macro_rules! unsigned_invoice_request_sign_method { (
511 $self: ident, $self_type: ty $(, $self_mut: tt)?
513 /// Signs the [`TaggedHash`] of the invoice request using the given function.
515 /// Note: The hash computation may have included unknown, odd TLV records.
517 /// This is not exported to bindings users as functions are not yet mapped.
518 pub fn sign<F, E>($($self_mut)* $self: $self_type, sign: F) -> Result<InvoiceRequest, SignError<E>>
520 F: FnOnce(&Self) -> Result<Signature, E>
522 let pubkey = $self.contents.payer_id;
523 let signature = merkle::sign_message(sign, &$self, pubkey)?;
525 // Append the signature TLV record to the bytes.
526 let signature_tlv_stream = SignatureTlvStreamRef {
527 signature: Some(&signature),
529 signature_tlv_stream.write(&mut $self.bytes).unwrap();
532 #[cfg(not(c_bindings))]
535 bytes: $self.bytes.clone(),
536 #[cfg(not(c_bindings))]
537 contents: $self.contents,
539 contents: $self.contents.clone(),
545 #[cfg(not(c_bindings))]
546 impl UnsignedInvoiceRequest {
547 unsigned_invoice_request_sign_method!(self, Self, mut);
551 impl UnsignedInvoiceRequest {
552 unsigned_invoice_request_sign_method!(self, &mut Self);
555 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
556 fn as_ref(&self) -> &TaggedHash {
561 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
563 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
564 /// specifies these such that its recipient can send an invoice for payment.
566 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
567 /// [`Offer`]: crate::offers::offer::Offer
568 #[derive(Clone, Debug)]
569 #[cfg_attr(test, derive(PartialEq))]
570 pub struct InvoiceRequest {
571 pub(super) bytes: Vec<u8>,
572 pub(super) contents: InvoiceRequestContents,
573 signature: Signature,
576 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
577 /// ways to respond depending on whether the signing keys were derived.
578 #[derive(Clone, Debug)]
579 pub struct VerifiedInvoiceRequest {
580 /// The verified request.
581 inner: InvoiceRequest,
583 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
585 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
586 /// [`respond_with`].
588 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
589 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
590 /// [`respond_with`]: Self::respond_with
591 pub keys: Option<KeyPair>,
594 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
596 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
597 #[derive(Clone, Debug)]
598 #[cfg_attr(test, derive(PartialEq))]
599 pub(super) struct InvoiceRequestContents {
600 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
604 #[derive(Clone, Debug)]
605 #[cfg_attr(test, derive(PartialEq))]
606 pub(super) struct InvoiceRequestContentsWithoutPayerId {
607 payer: PayerContents,
608 pub(super) offer: OfferContents,
609 chain: Option<ChainHash>,
610 amount_msats: Option<u64>,
611 features: InvoiceRequestFeatures,
612 quantity: Option<u64>,
613 payer_note: Option<String>,
616 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
617 /// An unpredictable series of bytes, typically containing information about the derivation of
620 /// [`payer_id`]: Self::payer_id
621 pub fn payer_metadata(&$self) -> &[u8] {
625 /// A chain from [`Offer::chains`] that the offer is valid for.
626 pub fn chain(&$self) -> ChainHash {
630 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
631 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
633 /// [`chain`]: Self::chain
634 pub fn amount_msats(&$self) -> Option<u64> {
635 $contents.amount_msats()
638 /// Features pertaining to requesting an invoice.
639 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
640 &$contents.features()
643 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
644 pub fn quantity(&$self) -> Option<u64> {
648 /// A possibly transient pubkey used to sign the invoice request.
649 pub fn payer_id(&$self) -> PublicKey {
653 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
655 pub fn payer_note(&$self) -> Option<PrintableString> {
656 $contents.payer_note()
660 impl UnsignedInvoiceRequest {
661 offer_accessors!(self, self.contents.inner.offer);
662 invoice_request_accessors!(self, self.contents);
665 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
666 $self: ident, $contents: expr, $builder: ty
668 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
669 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
671 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
672 /// creation time is used for the `created_at` parameter.
674 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
676 /// [`Duration`]: core::time::Duration
677 #[cfg(feature = "std")]
679 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
680 ) -> Result<$builder, Bolt12SemanticError> {
681 let created_at = std::time::SystemTime::now()
682 .duration_since(std::time::SystemTime::UNIX_EPOCH)
683 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
685 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
688 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
690 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
691 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
692 /// where [`std::time::SystemTime`] is not available.
694 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
697 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
698 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
699 /// a preference. Note, however, that any privacy is lost if a public node id was used for
700 /// [`Offer::signing_pubkey`].
702 /// Errors if the request contains unknown required features.
706 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
707 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
709 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
711 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
712 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
713 pub fn respond_with_no_std(
714 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
715 created_at: core::time::Duration
716 ) -> Result<$builder, Bolt12SemanticError> {
717 if $contents.invoice_request_features().requires_unknown_bits() {
718 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
721 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash)
725 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
726 /// Verifies that the request was for an offer created using the given key. Returns the verified
727 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
728 /// if they could be extracted from the metadata.
730 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
731 pub fn verify<T: secp256k1::Signing>(
732 $self: $self_type, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
733 ) -> Result<VerifiedInvoiceRequest, ()> {
734 let keys = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
735 Ok(VerifiedInvoiceRequest {
743 impl InvoiceRequest {
744 offer_accessors!(self, self.contents.inner.offer);
745 invoice_request_accessors!(self, self.contents);
746 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
747 invoice_request_verify_method!(self, Self);
749 /// Signature of the invoice request using [`payer_id`].
751 /// [`payer_id`]: Self::payer_id
752 pub fn signature(&self) -> Signature {
756 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
757 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
758 self.contents.as_tlv_stream();
759 let signature_tlv_stream = SignatureTlvStreamRef {
760 signature: Some(&self.signature),
762 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
766 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
767 $self: ident, $contents: expr, $builder: ty
769 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
770 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
771 /// the same [`ExpandedKey`] as the one used to create the offer.
773 /// See [`InvoiceRequest::respond_with`] for further details.
775 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
777 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
778 #[cfg(feature = "std")]
779 pub fn respond_using_derived_keys(
780 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
781 ) -> Result<$builder, Bolt12SemanticError> {
782 let created_at = std::time::SystemTime::now()
783 .duration_since(std::time::SystemTime::UNIX_EPOCH)
784 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
786 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
789 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
790 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
791 /// the same [`ExpandedKey`] as the one used to create the offer.
793 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
795 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
797 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
798 pub fn respond_using_derived_keys_no_std(
799 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
800 created_at: core::time::Duration
801 ) -> Result<$builder, Bolt12SemanticError> {
802 if $self.inner.invoice_request_features().requires_unknown_bits() {
803 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
806 let keys = match $self.keys {
807 None => return Err(Bolt12SemanticError::InvalidMetadata),
811 <$builder>::for_offer_using_keys(
812 &$self.inner, payment_paths, created_at, payment_hash, keys
817 impl VerifiedInvoiceRequest {
818 offer_accessors!(self, self.inner.contents.inner.offer);
819 invoice_request_accessors!(self, self.inner.contents);
820 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
821 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
824 impl InvoiceRequestContents {
825 pub(super) fn metadata(&self) -> &[u8] {
826 self.inner.metadata()
829 pub(super) fn derives_keys(&self) -> bool {
830 self.inner.payer.0.derives_payer_keys()
833 pub(super) fn chain(&self) -> ChainHash {
837 pub(super) fn amount_msats(&self) -> Option<u64> {
838 self.inner.amount_msats
841 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
845 pub(super) fn quantity(&self) -> Option<u64> {
849 pub(super) fn payer_id(&self) -> PublicKey {
853 pub(super) fn payer_note(&self) -> Option<PrintableString> {
854 self.inner.payer_note.as_ref()
855 .map(|payer_note| PrintableString(payer_note.as_str()))
858 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
859 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
860 invoice_request.payer_id = Some(&self.payer_id);
861 (payer, offer, invoice_request)
865 impl InvoiceRequestContentsWithoutPayerId {
866 pub(super) fn metadata(&self) -> &[u8] {
867 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
870 pub(super) fn chain(&self) -> ChainHash {
871 self.chain.unwrap_or_else(|| self.offer.implied_chain())
874 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
875 let payer = PayerTlvStreamRef {
876 metadata: self.payer.0.as_bytes(),
879 let offer = self.offer.as_tlv_stream();
882 if self.features == InvoiceRequestFeatures::empty() { None }
883 else { Some(&self.features) }
886 let invoice_request = InvoiceRequestTlvStreamRef {
887 chain: self.chain.as_ref(),
888 amount: self.amount_msats,
890 quantity: self.quantity,
892 payer_note: self.payer_note.as_ref(),
895 (payer, offer, invoice_request)
899 impl Writeable for UnsignedInvoiceRequest {
900 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
901 WithoutLength(&self.bytes).write(writer)
905 impl Writeable for InvoiceRequest {
906 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
907 WithoutLength(&self.bytes).write(writer)
911 impl Writeable for InvoiceRequestContents {
912 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
913 self.as_tlv_stream().write(writer)
917 /// Valid type range for invoice_request TLV records.
918 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
920 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
922 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
923 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
925 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
926 (80, chain: ChainHash),
927 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
928 (84, features: (InvoiceRequestFeatures, WithoutLength)),
929 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
930 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
931 (89, payer_note: (String, WithoutLength)),
934 type FullInvoiceRequestTlvStream =
935 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
937 type FullInvoiceRequestTlvStreamRef<'a> = (
938 PayerTlvStreamRef<'a>,
939 OfferTlvStreamRef<'a>,
940 InvoiceRequestTlvStreamRef<'a>,
941 SignatureTlvStreamRef<'a>,
944 impl SeekReadable for FullInvoiceRequestTlvStream {
945 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
946 let payer = SeekReadable::read(r)?;
947 let offer = SeekReadable::read(r)?;
948 let invoice_request = SeekReadable::read(r)?;
949 let signature = SeekReadable::read(r)?;
951 Ok((payer, offer, invoice_request, signature))
955 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
957 type PartialInvoiceRequestTlvStreamRef<'a> = (
958 PayerTlvStreamRef<'a>,
959 OfferTlvStreamRef<'a>,
960 InvoiceRequestTlvStreamRef<'a>,
963 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
964 type Error = Bolt12ParseError;
966 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
967 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
968 let ParsedMessage { bytes, tlv_stream } = invoice_request;
970 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
972 let contents = InvoiceRequestContents::try_from(
973 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
976 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
978 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
982 impl TryFrom<Vec<u8>> for InvoiceRequest {
983 type Error = Bolt12ParseError;
985 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
986 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
987 let ParsedMessage { bytes, tlv_stream } = invoice_request;
989 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
990 SignatureTlvStream { signature },
992 let contents = InvoiceRequestContents::try_from(
993 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
996 let signature = match signature {
997 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
998 Some(signature) => signature,
1000 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
1001 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1003 Ok(InvoiceRequest { bytes, contents, signature })
1007 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1008 type Error = Bolt12SemanticError;
1010 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1012 PayerTlvStream { metadata },
1014 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1017 let payer = match metadata {
1018 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1019 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1021 let offer = OfferContents::try_from(offer_tlv_stream)?;
1023 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1024 return Err(Bolt12SemanticError::UnsupportedChain);
1027 if offer.amount().is_none() && amount.is_none() {
1028 return Err(Bolt12SemanticError::MissingAmount);
1031 offer.check_quantity(quantity)?;
1032 offer.check_amount_msats_for_quantity(amount, quantity)?;
1034 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1036 let payer_id = match payer_id {
1037 None => return Err(Bolt12SemanticError::MissingPayerId),
1038 Some(payer_id) => payer_id,
1041 Ok(InvoiceRequestContents {
1042 inner: InvoiceRequestContentsWithoutPayerId {
1043 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1052 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1054 use bitcoin::blockdata::constants::ChainHash;
1055 use bitcoin::network::constants::Network;
1056 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1057 use core::convert::{Infallible, TryFrom};
1058 use core::num::NonZeroU64;
1059 #[cfg(feature = "std")]
1060 use core::time::Duration;
1061 use crate::sign::KeyMaterial;
1062 use crate::ln::channelmanager::PaymentId;
1063 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1064 use crate::ln::inbound_payment::ExpandedKey;
1065 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1066 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1067 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1068 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1069 #[cfg(not(c_bindings))]
1071 crate::offers::offer::OfferBuilder,
1075 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1077 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1078 use crate::offers::payer::PayerTlvStreamRef;
1079 use crate::offers::test_utils::*;
1080 use crate::util::ser::{BigSize, Writeable};
1081 use crate::util::string::PrintableString;
1084 fn builds_invoice_request_with_defaults() {
1085 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1088 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1091 let mut unsigned_invoice_request = unsigned_invoice_request;
1093 let mut buffer = Vec::new();
1094 unsigned_invoice_request.write(&mut buffer).unwrap();
1096 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1097 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1098 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1099 assert_eq!(unsigned_invoice_request.metadata(), None);
1100 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1101 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1102 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1103 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1104 assert_eq!(unsigned_invoice_request.paths(), &[]);
1105 assert_eq!(unsigned_invoice_request.issuer(), None);
1106 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1107 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1108 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1109 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1110 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1111 assert_eq!(unsigned_invoice_request.quantity(), None);
1112 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1113 assert_eq!(unsigned_invoice_request.payer_note(), None);
1115 match UnsignedInvoiceRequest::try_from(buffer) {
1116 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1118 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1119 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1123 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1125 let mut buffer = Vec::new();
1126 invoice_request.write(&mut buffer).unwrap();
1128 assert_eq!(invoice_request.bytes, buffer.as_slice());
1129 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1130 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1131 assert_eq!(invoice_request.metadata(), None);
1132 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1133 assert_eq!(invoice_request.description(), PrintableString("foo"));
1134 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1135 assert_eq!(invoice_request.absolute_expiry(), None);
1136 assert_eq!(invoice_request.paths(), &[]);
1137 assert_eq!(invoice_request.issuer(), None);
1138 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1139 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1140 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1141 assert_eq!(invoice_request.amount_msats(), None);
1142 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1143 assert_eq!(invoice_request.quantity(), None);
1144 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1145 assert_eq!(invoice_request.payer_note(), None);
1147 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1148 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1151 invoice_request.as_tlv_stream(),
1153 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1159 description: Some(&String::from("foo")),
1161 absolute_expiry: None,
1165 node_id: Some(&recipient_pubkey()),
1167 InvoiceRequestTlvStreamRef {
1172 payer_id: Some(&payer_pubkey()),
1175 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1179 if let Err(e) = InvoiceRequest::try_from(buffer) {
1180 panic!("error parsing invoice request: {:?}", e);
1184 #[cfg(feature = "std")]
1186 fn builds_invoice_request_from_offer_with_expiration() {
1187 let future_expiry = Duration::from_secs(u64::max_value());
1188 let past_expiry = Duration::from_secs(0);
1190 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1192 .absolute_expiry(future_expiry)
1194 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1197 panic!("error building invoice_request: {:?}", e);
1200 match OfferBuilder::new("foo".into(), recipient_pubkey())
1202 .absolute_expiry(past_expiry)
1204 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1207 Ok(_) => panic!("expected error"),
1208 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1213 fn builds_invoice_request_with_derived_metadata() {
1214 let payer_id = payer_pubkey();
1215 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1216 let entropy = FixedEntropy {};
1217 let secp_ctx = Secp256k1::new();
1218 let payment_id = PaymentId([1; 32]);
1220 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1223 let invoice_request = offer
1224 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1227 .sign(payer_sign).unwrap();
1228 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1230 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1233 .sign(recipient_sign).unwrap();
1234 match invoice.verify(&expanded_key, &secp_ctx) {
1235 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1236 Err(()) => panic!("verification failed"),
1239 // Fails verification with altered fields
1241 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1242 mut invoice_tlv_stream, mut signature_tlv_stream
1243 ) = invoice.as_tlv_stream();
1244 invoice_request_tlv_stream.amount = Some(2000);
1245 invoice_tlv_stream.amount = Some(2000);
1248 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1249 let mut bytes = Vec::new();
1250 tlv_stream.write(&mut bytes).unwrap();
1252 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1253 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1254 signature_tlv_stream.signature = Some(&signature);
1256 let mut encoded_invoice = bytes;
1257 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1259 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1260 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1262 // Fails verification with altered metadata
1264 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1265 mut signature_tlv_stream
1266 ) = invoice.as_tlv_stream();
1267 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1268 payer_tlv_stream.metadata = Some(&metadata);
1271 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1272 let mut bytes = Vec::new();
1273 tlv_stream.write(&mut bytes).unwrap();
1275 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1276 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1277 signature_tlv_stream.signature = Some(&signature);
1279 let mut encoded_invoice = bytes;
1280 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1282 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1283 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1287 fn builds_invoice_request_with_derived_payer_id() {
1288 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1289 let entropy = FixedEntropy {};
1290 let secp_ctx = Secp256k1::new();
1291 let payment_id = PaymentId([1; 32]);
1293 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1296 let invoice_request = offer
1297 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1302 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1305 .sign(recipient_sign).unwrap();
1306 match invoice.verify(&expanded_key, &secp_ctx) {
1307 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1308 Err(()) => panic!("verification failed"),
1311 // Fails verification with altered fields
1313 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1314 mut invoice_tlv_stream, mut signature_tlv_stream
1315 ) = invoice.as_tlv_stream();
1316 invoice_request_tlv_stream.amount = Some(2000);
1317 invoice_tlv_stream.amount = Some(2000);
1320 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1321 let mut bytes = Vec::new();
1322 tlv_stream.write(&mut bytes).unwrap();
1324 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1325 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1326 signature_tlv_stream.signature = Some(&signature);
1328 let mut encoded_invoice = bytes;
1329 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1331 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1332 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1334 // Fails verification with altered payer id
1336 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1337 mut signature_tlv_stream
1338 ) = invoice.as_tlv_stream();
1339 let payer_id = pubkey(1);
1340 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1343 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1344 let mut bytes = Vec::new();
1345 tlv_stream.write(&mut bytes).unwrap();
1347 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1348 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1349 signature_tlv_stream.signature = Some(&signature);
1351 let mut encoded_invoice = bytes;
1352 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1354 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1355 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1359 fn builds_invoice_request_with_chain() {
1360 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1361 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1363 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1366 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1367 .chain(Network::Bitcoin).unwrap()
1369 .sign(payer_sign).unwrap();
1370 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1371 assert_eq!(invoice_request.chain(), mainnet);
1372 assert_eq!(tlv_stream.chain, None);
1374 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1376 .chain(Network::Testnet)
1378 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1379 .chain(Network::Testnet).unwrap()
1381 .sign(payer_sign).unwrap();
1382 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1383 assert_eq!(invoice_request.chain(), testnet);
1384 assert_eq!(tlv_stream.chain, Some(&testnet));
1386 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1388 .chain(Network::Bitcoin)
1389 .chain(Network::Testnet)
1391 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1392 .chain(Network::Bitcoin).unwrap()
1394 .sign(payer_sign).unwrap();
1395 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1396 assert_eq!(invoice_request.chain(), mainnet);
1397 assert_eq!(tlv_stream.chain, None);
1399 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1401 .chain(Network::Bitcoin)
1402 .chain(Network::Testnet)
1404 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .chain(Network::Bitcoin).unwrap()
1406 .chain(Network::Testnet).unwrap()
1408 .sign(payer_sign).unwrap();
1409 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1410 assert_eq!(invoice_request.chain(), testnet);
1411 assert_eq!(tlv_stream.chain, Some(&testnet));
1413 match OfferBuilder::new("foo".into(), recipient_pubkey())
1415 .chain(Network::Testnet)
1417 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1418 .chain(Network::Bitcoin)
1420 Ok(_) => panic!("expected error"),
1421 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1424 match OfferBuilder::new("foo".into(), recipient_pubkey())
1426 .chain(Network::Testnet)
1428 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1431 Ok(_) => panic!("expected error"),
1432 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1437 fn builds_invoice_request_with_amount() {
1438 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1441 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442 .amount_msats(1000).unwrap()
1444 .sign(payer_sign).unwrap();
1445 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1446 assert_eq!(invoice_request.amount_msats(), Some(1000));
1447 assert_eq!(tlv_stream.amount, Some(1000));
1449 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1452 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1453 .amount_msats(1001).unwrap()
1454 .amount_msats(1000).unwrap()
1456 .sign(payer_sign).unwrap();
1457 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1458 assert_eq!(invoice_request.amount_msats(), Some(1000));
1459 assert_eq!(tlv_stream.amount, Some(1000));
1461 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1464 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1465 .amount_msats(1001).unwrap()
1467 .sign(payer_sign).unwrap();
1468 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1469 assert_eq!(invoice_request.amount_msats(), Some(1001));
1470 assert_eq!(tlv_stream.amount, Some(1001));
1472 match OfferBuilder::new("foo".into(), recipient_pubkey())
1475 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1478 Ok(_) => panic!("expected error"),
1479 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1482 match OfferBuilder::new("foo".into(), recipient_pubkey())
1484 .supported_quantity(Quantity::Unbounded)
1486 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1487 .quantity(2).unwrap()
1490 Ok(_) => panic!("expected error"),
1491 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1494 match OfferBuilder::new("foo".into(), recipient_pubkey())
1497 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1498 .amount_msats(MAX_VALUE_MSAT + 1)
1500 Ok(_) => panic!("expected error"),
1501 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1504 match OfferBuilder::new("foo".into(), recipient_pubkey())
1506 .supported_quantity(Quantity::Unbounded)
1508 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1509 .amount_msats(1000).unwrap()
1510 .quantity(2).unwrap()
1513 Ok(_) => panic!("expected error"),
1514 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1517 match OfferBuilder::new("foo".into(), recipient_pubkey())
1519 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1522 Ok(_) => panic!("expected error"),
1523 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1526 match OfferBuilder::new("foo".into(), recipient_pubkey())
1528 .supported_quantity(Quantity::Unbounded)
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531 .quantity(u64::max_value()).unwrap()
1534 Ok(_) => panic!("expected error"),
1535 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1540 fn builds_invoice_request_with_features() {
1541 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1544 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1545 .features_unchecked(InvoiceRequestFeatures::unknown())
1547 .sign(payer_sign).unwrap();
1548 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1549 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1550 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1552 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1555 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1556 .features_unchecked(InvoiceRequestFeatures::unknown())
1557 .features_unchecked(InvoiceRequestFeatures::empty())
1559 .sign(payer_sign).unwrap();
1560 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1561 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1562 assert_eq!(tlv_stream.features, None);
1566 fn builds_invoice_request_with_quantity() {
1567 let one = NonZeroU64::new(1).unwrap();
1568 let ten = NonZeroU64::new(10).unwrap();
1570 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1572 .supported_quantity(Quantity::One)
1574 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1576 .sign(payer_sign).unwrap();
1577 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1578 assert_eq!(invoice_request.quantity(), None);
1579 assert_eq!(tlv_stream.quantity, None);
1581 match OfferBuilder::new("foo".into(), recipient_pubkey())
1583 .supported_quantity(Quantity::One)
1585 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1586 .amount_msats(2_000).unwrap()
1589 Ok(_) => panic!("expected error"),
1590 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1593 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1595 .supported_quantity(Quantity::Bounded(ten))
1597 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598 .amount_msats(10_000).unwrap()
1599 .quantity(10).unwrap()
1601 .sign(payer_sign).unwrap();
1602 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1603 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1604 assert_eq!(tlv_stream.amount, Some(10_000));
1606 match OfferBuilder::new("foo".into(), recipient_pubkey())
1608 .supported_quantity(Quantity::Bounded(ten))
1610 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1611 .amount_msats(11_000).unwrap()
1614 Ok(_) => panic!("expected error"),
1615 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1618 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1620 .supported_quantity(Quantity::Unbounded)
1622 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623 .amount_msats(2_000).unwrap()
1624 .quantity(2).unwrap()
1626 .sign(payer_sign).unwrap();
1627 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1628 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1629 assert_eq!(tlv_stream.amount, Some(2_000));
1631 match OfferBuilder::new("foo".into(), recipient_pubkey())
1633 .supported_quantity(Quantity::Unbounded)
1635 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1638 Ok(_) => panic!("expected error"),
1639 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1642 match OfferBuilder::new("foo".into(), recipient_pubkey())
1644 .supported_quantity(Quantity::Bounded(one))
1646 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1649 Ok(_) => panic!("expected error"),
1650 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1655 fn builds_invoice_request_with_payer_note() {
1656 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1659 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1660 .payer_note("bar".into())
1662 .sign(payer_sign).unwrap();
1663 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1664 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1665 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1667 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1670 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1671 .payer_note("bar".into())
1672 .payer_note("baz".into())
1674 .sign(payer_sign).unwrap();
1675 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1676 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1677 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1681 fn fails_signing_invoice_request() {
1682 match OfferBuilder::new("foo".into(), recipient_pubkey())
1685 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1689 Ok(_) => panic!("expected error"),
1690 Err(e) => assert_eq!(e, SignError::Signing(())),
1693 match OfferBuilder::new("foo".into(), recipient_pubkey())
1696 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1698 .sign(recipient_sign)
1700 Ok(_) => panic!("expected error"),
1701 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1706 fn fails_responding_with_unknown_required_features() {
1707 match OfferBuilder::new("foo".into(), recipient_pubkey())
1710 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1711 .features_unchecked(InvoiceRequestFeatures::unknown())
1713 .sign(payer_sign).unwrap()
1714 .respond_with_no_std(payment_paths(), payment_hash(), now())
1716 Ok(_) => panic!("expected error"),
1717 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1722 fn parses_invoice_request_with_metadata() {
1723 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1726 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1728 .sign(payer_sign).unwrap();
1730 let mut buffer = Vec::new();
1731 invoice_request.write(&mut buffer).unwrap();
1733 if let Err(e) = InvoiceRequest::try_from(buffer) {
1734 panic!("error parsing invoice_request: {:?}", e);
1739 fn parses_invoice_request_with_chain() {
1740 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1743 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1744 .chain(Network::Bitcoin).unwrap()
1746 .sign(payer_sign).unwrap();
1748 let mut buffer = Vec::new();
1749 invoice_request.write(&mut buffer).unwrap();
1751 if let Err(e) = InvoiceRequest::try_from(buffer) {
1752 panic!("error parsing invoice_request: {:?}", e);
1755 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1758 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1759 .chain_unchecked(Network::Testnet)
1761 .sign(payer_sign).unwrap();
1763 let mut buffer = Vec::new();
1764 invoice_request.write(&mut buffer).unwrap();
1766 match InvoiceRequest::try_from(buffer) {
1767 Ok(_) => panic!("expected error"),
1768 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1773 fn parses_invoice_request_with_amount() {
1774 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1777 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1779 .sign(payer_sign).unwrap();
1781 let mut buffer = Vec::new();
1782 invoice_request.write(&mut buffer).unwrap();
1784 if let Err(e) = InvoiceRequest::try_from(buffer) {
1785 panic!("error parsing invoice_request: {:?}", e);
1788 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1790 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1791 .amount_msats(1000).unwrap()
1793 .sign(payer_sign).unwrap();
1795 let mut buffer = Vec::new();
1796 invoice_request.write(&mut buffer).unwrap();
1798 if let Err(e) = InvoiceRequest::try_from(buffer) {
1799 panic!("error parsing invoice_request: {:?}", e);
1802 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1804 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1806 .sign(payer_sign).unwrap();
1808 let mut buffer = Vec::new();
1809 invoice_request.write(&mut buffer).unwrap();
1811 match InvoiceRequest::try_from(buffer) {
1812 Ok(_) => panic!("expected error"),
1813 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1816 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1819 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1820 .amount_msats_unchecked(999)
1822 .sign(payer_sign).unwrap();
1824 let mut buffer = Vec::new();
1825 invoice_request.write(&mut buffer).unwrap();
1827 match InvoiceRequest::try_from(buffer) {
1828 Ok(_) => panic!("expected error"),
1829 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1832 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1833 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1835 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1837 .sign(payer_sign).unwrap();
1839 let mut buffer = Vec::new();
1840 invoice_request.write(&mut buffer).unwrap();
1842 match InvoiceRequest::try_from(buffer) {
1843 Ok(_) => panic!("expected error"),
1845 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1849 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1851 .supported_quantity(Quantity::Unbounded)
1853 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1854 .quantity(u64::max_value()).unwrap()
1856 .sign(payer_sign).unwrap();
1858 let mut buffer = Vec::new();
1859 invoice_request.write(&mut buffer).unwrap();
1861 match InvoiceRequest::try_from(buffer) {
1862 Ok(_) => panic!("expected error"),
1863 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1868 fn parses_invoice_request_with_quantity() {
1869 let one = NonZeroU64::new(1).unwrap();
1870 let ten = NonZeroU64::new(10).unwrap();
1872 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1874 .supported_quantity(Quantity::One)
1876 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1878 .sign(payer_sign).unwrap();
1880 let mut buffer = Vec::new();
1881 invoice_request.write(&mut buffer).unwrap();
1883 if let Err(e) = InvoiceRequest::try_from(buffer) {
1884 panic!("error parsing invoice_request: {:?}", e);
1887 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1889 .supported_quantity(Quantity::One)
1891 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1892 .amount_msats(2_000).unwrap()
1893 .quantity_unchecked(2)
1895 .sign(payer_sign).unwrap();
1897 let mut buffer = Vec::new();
1898 invoice_request.write(&mut buffer).unwrap();
1900 match InvoiceRequest::try_from(buffer) {
1901 Ok(_) => panic!("expected error"),
1903 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1907 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1909 .supported_quantity(Quantity::Bounded(ten))
1911 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1912 .amount_msats(10_000).unwrap()
1913 .quantity(10).unwrap()
1915 .sign(payer_sign).unwrap();
1917 let mut buffer = Vec::new();
1918 invoice_request.write(&mut buffer).unwrap();
1920 if let Err(e) = InvoiceRequest::try_from(buffer) {
1921 panic!("error parsing invoice_request: {:?}", e);
1924 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1926 .supported_quantity(Quantity::Bounded(ten))
1928 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1929 .amount_msats(11_000).unwrap()
1930 .quantity_unchecked(11)
1932 .sign(payer_sign).unwrap();
1934 let mut buffer = Vec::new();
1935 invoice_request.write(&mut buffer).unwrap();
1937 match InvoiceRequest::try_from(buffer) {
1938 Ok(_) => panic!("expected error"),
1939 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1942 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1944 .supported_quantity(Quantity::Unbounded)
1946 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1947 .amount_msats(2_000).unwrap()
1948 .quantity(2).unwrap()
1950 .sign(payer_sign).unwrap();
1952 let mut buffer = Vec::new();
1953 invoice_request.write(&mut buffer).unwrap();
1955 if let Err(e) = InvoiceRequest::try_from(buffer) {
1956 panic!("error parsing invoice_request: {:?}", e);
1959 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1961 .supported_quantity(Quantity::Unbounded)
1963 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1965 .sign(payer_sign).unwrap();
1967 let mut buffer = Vec::new();
1968 invoice_request.write(&mut buffer).unwrap();
1970 match InvoiceRequest::try_from(buffer) {
1971 Ok(_) => panic!("expected error"),
1972 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1975 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1977 .supported_quantity(Quantity::Bounded(one))
1979 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1981 .sign(payer_sign).unwrap();
1983 let mut buffer = Vec::new();
1984 invoice_request.write(&mut buffer).unwrap();
1986 match InvoiceRequest::try_from(buffer) {
1987 Ok(_) => panic!("expected error"),
1988 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1993 fn fails_parsing_invoice_request_without_metadata() {
1994 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1997 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1999 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2000 tlv_stream.0.metadata = None;
2002 let mut buffer = Vec::new();
2003 tlv_stream.write(&mut buffer).unwrap();
2005 match InvoiceRequest::try_from(buffer) {
2006 Ok(_) => panic!("expected error"),
2008 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2014 fn fails_parsing_invoice_request_without_payer_id() {
2015 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2018 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2020 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2021 tlv_stream.2.payer_id = None;
2023 let mut buffer = Vec::new();
2024 tlv_stream.write(&mut buffer).unwrap();
2026 match InvoiceRequest::try_from(buffer) {
2027 Ok(_) => panic!("expected error"),
2028 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2033 fn fails_parsing_invoice_request_without_node_id() {
2034 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2037 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2039 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2040 tlv_stream.1.node_id = None;
2042 let mut buffer = Vec::new();
2043 tlv_stream.write(&mut buffer).unwrap();
2045 match InvoiceRequest::try_from(buffer) {
2046 Ok(_) => panic!("expected error"),
2048 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2054 fn fails_parsing_invoice_request_without_signature() {
2055 let mut buffer = Vec::new();
2056 OfferBuilder::new("foo".into(), recipient_pubkey())
2059 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2062 .write(&mut buffer).unwrap();
2064 match InvoiceRequest::try_from(buffer) {
2065 Ok(_) => panic!("expected error"),
2066 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2071 fn fails_parsing_invoice_request_with_invalid_signature() {
2072 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2075 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2077 .sign(payer_sign).unwrap();
2078 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2079 *last_signature_byte = last_signature_byte.wrapping_add(1);
2081 let mut buffer = Vec::new();
2082 invoice_request.write(&mut buffer).unwrap();
2084 match InvoiceRequest::try_from(buffer) {
2085 Ok(_) => panic!("expected error"),
2087 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2093 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2094 let secp_ctx = Secp256k1::new();
2095 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2096 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2099 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2101 .sign::<_, Infallible>(
2102 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2106 let mut encoded_invoice_request = Vec::new();
2107 invoice_request.write(&mut encoded_invoice_request).unwrap();
2108 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2109 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2110 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2112 match InvoiceRequest::try_from(encoded_invoice_request) {
2113 Ok(_) => panic!("expected error"),
2114 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),