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;
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 #[cfg(not(c_bindings))]
85 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
89 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
92 use crate::prelude::*;
94 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
95 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
97 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
99 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
101 /// See [module-level documentation] for usage.
103 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
105 /// [module-level documentation]: self
106 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
108 invoice_request: InvoiceRequestContentsWithoutPayerId,
109 payer_id: Option<PublicKey>,
110 payer_id_strategy: core::marker::PhantomData<P>,
111 secp_ctx: Option<&'b Secp256k1<T>>,
114 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
116 /// See [module-level documentation] for usage.
118 /// [module-level documentation]: self
120 pub struct InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
122 invoice_request: InvoiceRequestContentsWithoutPayerId,
123 payer_id: Option<PublicKey>,
124 payer_id_strategy: core::marker::PhantomData<ExplicitPayerId>,
125 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
128 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
130 /// See [module-level documentation] for usage.
132 /// [module-level documentation]: self
134 pub struct InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
136 invoice_request: InvoiceRequestContentsWithoutPayerId,
137 payer_id: Option<PublicKey>,
138 payer_id_strategy: core::marker::PhantomData<DerivedPayerId>,
139 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
142 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
144 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
145 pub trait PayerIdStrategy {}
147 /// [`InvoiceRequest::payer_id`] will be explicitly set.
149 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
150 pub struct ExplicitPayerId {}
152 /// [`InvoiceRequest::payer_id`] will be derived.
154 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
155 pub struct DerivedPayerId {}
157 impl PayerIdStrategy for ExplicitPayerId {}
158 impl PayerIdStrategy for DerivedPayerId {}
160 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
161 #[cfg_attr(c_bindings, allow(dead_code))]
162 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
165 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
166 payer_id: Some(payer_id),
167 payer_id_strategy: core::marker::PhantomData,
172 #[cfg_attr(c_bindings, allow(dead_code))]
173 pub(super) fn deriving_metadata<ES: Deref>(
174 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
175 payment_id: PaymentId,
176 ) -> Self where ES::Target: EntropySource {
177 let nonce = Nonce::from_entropy_source(entropy_source);
178 let payment_id = Some(payment_id);
179 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
180 let metadata = Metadata::Derived(derivation_material);
183 invoice_request: Self::create_contents(offer, metadata),
184 payer_id: Some(payer_id),
185 payer_id_strategy: core::marker::PhantomData,
190 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
191 /// by [`UnsignedInvoiceRequest::sign`].
192 pub fn build($self: $self_type) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
193 let (unsigned_invoice_request, keys, _) = $self.build_with_checks()?;
194 debug_assert!(keys.is_none());
195 Ok(unsigned_invoice_request)
199 macro_rules! invoice_request_derived_payer_id_builder_methods { (
200 $self: ident, $self_type: ty, $secp_context: ty
202 #[cfg_attr(c_bindings, allow(dead_code))]
203 pub(super) fn deriving_payer_id<ES: Deref>(
204 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
205 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
206 ) -> Self where ES::Target: EntropySource {
207 let nonce = Nonce::from_entropy_source(entropy_source);
208 let payment_id = Some(payment_id);
209 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
210 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
213 invoice_request: Self::create_contents(offer, metadata),
215 payer_id_strategy: core::marker::PhantomData,
216 secp_ctx: Some(secp_ctx),
220 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
221 pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
222 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
224 let mut unsigned_invoice_request = unsigned_invoice_request;
225 debug_assert!(keys.is_some());
227 let secp_ctx = secp_ctx.unwrap();
228 let keys = keys.unwrap();
229 let invoice_request = unsigned_invoice_request
230 .sign::<_, Infallible>(
231 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
238 macro_rules! invoice_request_builder_methods { (
239 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
241 #[cfg_attr(c_bindings, allow(dead_code))]
242 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
243 let offer = offer.contents.clone();
244 InvoiceRequestContentsWithoutPayerId {
245 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
246 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
250 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
251 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
254 /// Successive calls to this method will override the previous setting.
255 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
256 $self.chain_hash(ChainHash::using_genesis_block(network))
259 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
260 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
263 /// Successive calls to this method will override the previous setting.
264 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
265 if !$self.offer.supports_chain(chain) {
266 return Err(Bolt12SemanticError::UnsupportedChain);
269 $self.invoice_request.chain = Some(chain);
273 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
274 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
276 /// Successive calls to this method will override the previous setting.
278 /// [`quantity`]: Self::quantity
279 pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
280 $self.invoice_request.offer.check_amount_msats_for_quantity(
281 Some(amount_msats), $self.invoice_request.quantity
283 $self.invoice_request.amount_msats = Some(amount_msats);
287 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
288 /// does not conform to [`Offer::is_valid_quantity`].
290 /// Successive calls to this method will override the previous setting.
291 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
292 $self.invoice_request.offer.check_quantity(Some(quantity))?;
293 $self.invoice_request.quantity = Some(quantity);
297 /// Sets the [`InvoiceRequest::payer_note`].
299 /// Successive calls to this method will override the previous setting.
300 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
301 $self.invoice_request.payer_note = Some(payer_note);
305 fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
306 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>),
309 #[cfg(feature = "std")] {
310 if $self.offer.is_expired() {
311 return Err(Bolt12SemanticError::AlreadyExpired);
315 let chain = $self.invoice_request.chain();
316 if !$self.offer.supports_chain(chain) {
317 return Err(Bolt12SemanticError::UnsupportedChain);
320 if chain == $self.offer.implied_chain() {
321 $self.invoice_request.chain = None;
324 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
325 return Err(Bolt12SemanticError::MissingAmount);
328 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
329 $self.invoice_request.offer.check_amount_msats_for_quantity(
330 $self.invoice_request.amount_msats, $self.invoice_request.quantity
333 Ok($self.build_without_checks())
336 fn build_without_checks($($self_mut)* $self: $self_type) ->
337 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>)
339 // Create the metadata for stateless verification of a Bolt12Invoice.
341 let secp_ctx = $self.secp_ctx.clone();
342 if $self.invoice_request.payer.0.has_derivation_material() {
343 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
345 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
346 debug_assert!(tlv_stream.2.payer_id.is_none());
347 tlv_stream.0.metadata = None;
348 if !metadata.derives_payer_keys() {
349 tlv_stream.2.payer_id = $self.payer_id.as_ref();
352 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
353 metadata = derived_metadata;
355 if let Some(keys) = keys {
356 debug_assert!($self.payer_id.is_none());
357 $self.payer_id = Some(keys.public_key());
360 $self.invoice_request.payer.0 = metadata;
363 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
364 debug_assert!($self.payer_id.is_some());
365 let payer_id = $self.payer_id.unwrap();
367 let invoice_request = InvoiceRequestContents {
368 #[cfg(not(c_bindings))]
369 inner: $self.invoice_request,
371 inner: $self.invoice_request.clone(),
374 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
376 (unsigned_invoice_request, keys, secp_ctx)
381 macro_rules! invoice_request_builder_test_methods { (
382 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
384 #[cfg_attr(c_bindings, allow(dead_code))]
385 fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
386 let chain = ChainHash::using_genesis_block(network);
387 $self.invoice_request.chain = Some(chain);
391 #[cfg_attr(c_bindings, allow(dead_code))]
392 fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
393 $self.invoice_request.amount_msats = Some(amount_msats);
397 #[cfg_attr(c_bindings, allow(dead_code))]
398 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
399 $self.invoice_request.features = features;
403 #[cfg_attr(c_bindings, allow(dead_code))]
404 fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
405 $self.invoice_request.quantity = Some(quantity);
409 #[cfg_attr(c_bindings, allow(dead_code))]
410 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
411 $self.build_without_checks().0
415 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
416 invoice_request_explicit_payer_id_builder_methods!(self, Self);
419 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
420 invoice_request_derived_payer_id_builder_methods!(self, Self, T);
423 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
424 invoice_request_builder_methods!(self, Self, Self, self, T, mut);
427 invoice_request_builder_test_methods!(self, Self, Self, self, mut);
430 #[cfg(all(c_bindings, not(test)))]
431 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
432 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
433 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
436 #[cfg(all(c_bindings, test))]
437 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
438 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
439 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
440 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
443 #[cfg(all(c_bindings, not(test)))]
444 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
445 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
446 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
449 #[cfg(all(c_bindings, test))]
450 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
451 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
452 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
453 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
457 impl<'a, 'b> From<InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>>
458 for InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, secp256k1::All> {
459 fn from(builder: InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>) -> Self {
460 let InvoiceRequestWithExplicitPayerIdBuilder {
461 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
465 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
471 impl<'a, 'b> From<InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>>
472 for InvoiceRequestBuilder<'a, 'b, DerivedPayerId, secp256k1::All> {
473 fn from(builder: InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>) -> Self {
474 let InvoiceRequestWithDerivedPayerIdBuilder {
475 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
479 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
484 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
488 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
489 /// such, it may include unknown, odd TLV records.
490 pub struct UnsignedInvoiceRequest {
492 contents: InvoiceRequestContents,
493 tagged_hash: TaggedHash,
496 impl UnsignedInvoiceRequest {
497 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
498 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
499 // unknown TLV records, which are not stored in `OfferContents`.
500 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
501 contents.as_tlv_stream();
502 let offer_bytes = WithoutLength(&offer.bytes);
503 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
505 let mut bytes = Vec::new();
506 unsigned_tlv_stream.write(&mut bytes).unwrap();
508 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
510 Self { bytes, contents, tagged_hash }
513 /// Returns the [`TaggedHash`] of the invoice to sign.
514 pub fn tagged_hash(&self) -> &TaggedHash {
519 macro_rules! unsigned_invoice_request_sign_method { (
520 $self: ident, $self_type: ty $(, $self_mut: tt)?
522 /// Signs the [`TaggedHash`] of the invoice request using the given function.
524 /// Note: The hash computation may have included unknown, odd TLV records.
526 /// This is not exported to bindings users as functions are not yet mapped.
527 pub fn sign<F, E>($($self_mut)* $self: $self_type, sign: F) -> Result<InvoiceRequest, SignError<E>>
529 F: FnOnce(&Self) -> Result<Signature, E>
531 let pubkey = $self.contents.payer_id;
532 let signature = merkle::sign_message(sign, &$self, pubkey)?;
534 // Append the signature TLV record to the bytes.
535 let signature_tlv_stream = SignatureTlvStreamRef {
536 signature: Some(&signature),
538 signature_tlv_stream.write(&mut $self.bytes).unwrap();
541 #[cfg(not(c_bindings))]
544 bytes: $self.bytes.clone(),
545 #[cfg(not(c_bindings))]
546 contents: $self.contents,
548 contents: $self.contents.clone(),
554 #[cfg(not(c_bindings))]
555 impl UnsignedInvoiceRequest {
556 unsigned_invoice_request_sign_method!(self, Self, mut);
560 impl UnsignedInvoiceRequest {
561 unsigned_invoice_request_sign_method!(self, &mut Self);
564 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
565 fn as_ref(&self) -> &TaggedHash {
570 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
572 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
573 /// specifies these such that its recipient can send an invoice for payment.
575 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
576 /// [`Offer`]: crate::offers::offer::Offer
577 #[derive(Clone, Debug)]
578 #[cfg_attr(test, derive(PartialEq))]
579 pub struct InvoiceRequest {
580 pub(super) bytes: Vec<u8>,
581 pub(super) contents: InvoiceRequestContents,
582 signature: Signature,
585 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
586 /// ways to respond depending on whether the signing keys were derived.
587 #[derive(Clone, Debug)]
588 pub struct VerifiedInvoiceRequest {
589 /// The verified request.
590 inner: InvoiceRequest,
592 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
594 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
595 /// [`respond_with`].
597 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
598 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
599 /// [`respond_with`]: Self::respond_with
600 pub keys: Option<KeyPair>,
603 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
605 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
606 #[derive(Clone, Debug)]
607 #[cfg_attr(test, derive(PartialEq))]
608 pub(super) struct InvoiceRequestContents {
609 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
613 #[derive(Clone, Debug)]
614 #[cfg_attr(test, derive(PartialEq))]
615 pub(super) struct InvoiceRequestContentsWithoutPayerId {
616 payer: PayerContents,
617 pub(super) offer: OfferContents,
618 chain: Option<ChainHash>,
619 amount_msats: Option<u64>,
620 features: InvoiceRequestFeatures,
621 quantity: Option<u64>,
622 payer_note: Option<String>,
625 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
626 /// An unpredictable series of bytes, typically containing information about the derivation of
629 /// [`payer_id`]: Self::payer_id
630 pub fn payer_metadata(&$self) -> &[u8] {
634 /// A chain from [`Offer::chains`] that the offer is valid for.
635 pub fn chain(&$self) -> ChainHash {
639 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
640 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
642 /// [`chain`]: Self::chain
643 pub fn amount_msats(&$self) -> Option<u64> {
644 $contents.amount_msats()
647 /// Features pertaining to requesting an invoice.
648 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
649 &$contents.features()
652 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
653 pub fn quantity(&$self) -> Option<u64> {
657 /// A possibly transient pubkey used to sign the invoice request.
658 pub fn payer_id(&$self) -> PublicKey {
662 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
664 pub fn payer_note(&$self) -> Option<PrintableString> {
665 $contents.payer_note()
669 impl UnsignedInvoiceRequest {
670 offer_accessors!(self, self.contents.inner.offer);
671 invoice_request_accessors!(self, self.contents);
674 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
675 $self: ident, $contents: expr, $builder: ty
677 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
678 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
680 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
681 /// creation time is used for the `created_at` parameter.
683 /// [`Duration`]: core::time::Duration
684 #[cfg(feature = "std")]
686 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
687 ) -> Result<$builder, Bolt12SemanticError> {
688 let created_at = std::time::SystemTime::now()
689 .duration_since(std::time::SystemTime::UNIX_EPOCH)
690 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
692 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
695 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
697 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
698 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
699 /// where [`std::time::SystemTime`] is not available.
701 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
704 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
705 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
706 /// a preference. Note, however, that any privacy is lost if a public node id was used for
707 /// [`Offer::signing_pubkey`].
709 /// Errors if the request contains unknown required features.
713 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
714 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
716 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
717 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
718 pub fn respond_with_no_std(
719 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
720 created_at: core::time::Duration
721 ) -> Result<$builder, Bolt12SemanticError> {
722 if $contents.invoice_request_features().requires_unknown_bits() {
723 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
726 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash)
730 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
731 /// Verifies that the request was for an offer created using the given key. Returns the verified
732 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
733 /// if they could be extracted from the metadata.
735 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
737 #[cfg(not(c_bindings))]
738 T: secp256k1::Signing
740 $self: $self_type, key: &ExpandedKey,
741 #[cfg(not(c_bindings))]
742 secp_ctx: &Secp256k1<T>,
744 secp_ctx: &Secp256k1<secp256k1::All>,
745 ) -> Result<VerifiedInvoiceRequest, ()> {
746 let keys = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
747 Ok(VerifiedInvoiceRequest {
748 #[cfg(not(c_bindings))]
751 inner: $self.clone(),
758 #[cfg(not(c_bindings))]
759 impl InvoiceRequest {
760 offer_accessors!(self, self.contents.inner.offer);
761 invoice_request_accessors!(self, self.contents);
762 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
763 invoice_request_verify_method!(self, Self);
767 impl InvoiceRequest {
768 offer_accessors!(self, self.contents.inner.offer);
769 invoice_request_accessors!(self, self.contents);
770 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
771 invoice_request_verify_method!(self, &Self);
774 impl InvoiceRequest {
775 /// Signature of the invoice request using [`payer_id`].
777 /// [`payer_id`]: Self::payer_id
778 pub fn signature(&self) -> Signature {
782 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
783 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
784 self.contents.as_tlv_stream();
785 let signature_tlv_stream = SignatureTlvStreamRef {
786 signature: Some(&self.signature),
788 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
792 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
793 $self: ident, $contents: expr, $builder: ty
795 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
796 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
797 /// the same [`ExpandedKey`] as the one used to create the offer.
799 /// See [`InvoiceRequest::respond_with`] for further details.
801 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
802 #[cfg(feature = "std")]
803 pub fn respond_using_derived_keys(
804 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
805 ) -> Result<$builder, Bolt12SemanticError> {
806 let created_at = std::time::SystemTime::now()
807 .duration_since(std::time::SystemTime::UNIX_EPOCH)
808 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
810 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
813 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
814 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
815 /// the same [`ExpandedKey`] as the one used to create the offer.
817 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
819 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
820 pub fn respond_using_derived_keys_no_std(
821 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
822 created_at: core::time::Duration
823 ) -> Result<$builder, Bolt12SemanticError> {
824 if $self.inner.invoice_request_features().requires_unknown_bits() {
825 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
828 let keys = match $self.keys {
829 None => return Err(Bolt12SemanticError::InvalidMetadata),
833 <$builder>::for_offer_using_keys(
834 &$self.inner, payment_paths, created_at, payment_hash, keys
839 impl VerifiedInvoiceRequest {
840 offer_accessors!(self, self.inner.contents.inner.offer);
841 invoice_request_accessors!(self, self.inner.contents);
842 #[cfg(not(c_bindings))]
843 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
845 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
846 #[cfg(not(c_bindings))]
847 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
849 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
852 impl InvoiceRequestContents {
853 pub(super) fn metadata(&self) -> &[u8] {
854 self.inner.metadata()
857 pub(super) fn derives_keys(&self) -> bool {
858 self.inner.payer.0.derives_payer_keys()
861 pub(super) fn chain(&self) -> ChainHash {
865 pub(super) fn amount_msats(&self) -> Option<u64> {
866 self.inner.amount_msats
869 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
873 pub(super) fn quantity(&self) -> Option<u64> {
877 pub(super) fn payer_id(&self) -> PublicKey {
881 pub(super) fn payer_note(&self) -> Option<PrintableString> {
882 self.inner.payer_note.as_ref()
883 .map(|payer_note| PrintableString(payer_note.as_str()))
886 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
887 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
888 invoice_request.payer_id = Some(&self.payer_id);
889 (payer, offer, invoice_request)
893 impl InvoiceRequestContentsWithoutPayerId {
894 pub(super) fn metadata(&self) -> &[u8] {
895 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
898 pub(super) fn chain(&self) -> ChainHash {
899 self.chain.unwrap_or_else(|| self.offer.implied_chain())
902 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
903 let payer = PayerTlvStreamRef {
904 metadata: self.payer.0.as_bytes(),
907 let offer = self.offer.as_tlv_stream();
910 if self.features == InvoiceRequestFeatures::empty() { None }
911 else { Some(&self.features) }
914 let invoice_request = InvoiceRequestTlvStreamRef {
915 chain: self.chain.as_ref(),
916 amount: self.amount_msats,
918 quantity: self.quantity,
920 payer_note: self.payer_note.as_ref(),
923 (payer, offer, invoice_request)
927 impl Writeable for UnsignedInvoiceRequest {
928 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
929 WithoutLength(&self.bytes).write(writer)
933 impl Writeable for InvoiceRequest {
934 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
935 WithoutLength(&self.bytes).write(writer)
939 impl Writeable for InvoiceRequestContents {
940 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
941 self.as_tlv_stream().write(writer)
945 /// Valid type range for invoice_request TLV records.
946 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
948 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
950 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
951 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
953 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
954 (80, chain: ChainHash),
955 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
956 (84, features: (InvoiceRequestFeatures, WithoutLength)),
957 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
958 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
959 (89, payer_note: (String, WithoutLength)),
962 type FullInvoiceRequestTlvStream =
963 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
965 type FullInvoiceRequestTlvStreamRef<'a> = (
966 PayerTlvStreamRef<'a>,
967 OfferTlvStreamRef<'a>,
968 InvoiceRequestTlvStreamRef<'a>,
969 SignatureTlvStreamRef<'a>,
972 impl SeekReadable for FullInvoiceRequestTlvStream {
973 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
974 let payer = SeekReadable::read(r)?;
975 let offer = SeekReadable::read(r)?;
976 let invoice_request = SeekReadable::read(r)?;
977 let signature = SeekReadable::read(r)?;
979 Ok((payer, offer, invoice_request, signature))
983 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
985 type PartialInvoiceRequestTlvStreamRef<'a> = (
986 PayerTlvStreamRef<'a>,
987 OfferTlvStreamRef<'a>,
988 InvoiceRequestTlvStreamRef<'a>,
991 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
992 type Error = Bolt12ParseError;
994 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
995 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
996 let ParsedMessage { bytes, tlv_stream } = invoice_request;
998 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1000 let contents = InvoiceRequestContents::try_from(
1001 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1004 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1006 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1010 impl TryFrom<Vec<u8>> for InvoiceRequest {
1011 type Error = Bolt12ParseError;
1013 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1014 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1015 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1017 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1018 SignatureTlvStream { signature },
1020 let contents = InvoiceRequestContents::try_from(
1021 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1024 let signature = match signature {
1025 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1026 Some(signature) => signature,
1028 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
1029 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1031 Ok(InvoiceRequest { bytes, contents, signature })
1035 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1036 type Error = Bolt12SemanticError;
1038 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1040 PayerTlvStream { metadata },
1042 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1045 let payer = match metadata {
1046 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1047 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1049 let offer = OfferContents::try_from(offer_tlv_stream)?;
1051 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1052 return Err(Bolt12SemanticError::UnsupportedChain);
1055 if offer.amount().is_none() && amount.is_none() {
1056 return Err(Bolt12SemanticError::MissingAmount);
1059 offer.check_quantity(quantity)?;
1060 offer.check_amount_msats_for_quantity(amount, quantity)?;
1062 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1064 let payer_id = match payer_id {
1065 None => return Err(Bolt12SemanticError::MissingPayerId),
1066 Some(payer_id) => payer_id,
1069 Ok(InvoiceRequestContents {
1070 inner: InvoiceRequestContentsWithoutPayerId {
1071 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1080 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1082 use bitcoin::blockdata::constants::ChainHash;
1083 use bitcoin::network::constants::Network;
1084 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1085 use core::convert::{Infallible, TryFrom};
1086 use core::num::NonZeroU64;
1087 #[cfg(feature = "std")]
1088 use core::time::Duration;
1089 use crate::sign::KeyMaterial;
1090 use crate::ln::channelmanager::PaymentId;
1091 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1092 use crate::ln::inbound_payment::ExpandedKey;
1093 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1094 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1095 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1096 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1097 #[cfg(not(c_bindings))]
1099 crate::offers::offer::OfferBuilder,
1103 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1105 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1106 use crate::offers::payer::PayerTlvStreamRef;
1107 use crate::offers::test_utils::*;
1108 use crate::util::ser::{BigSize, Writeable};
1109 use crate::util::string::PrintableString;
1112 fn builds_invoice_request_with_defaults() {
1113 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1116 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1119 let mut unsigned_invoice_request = unsigned_invoice_request;
1121 let mut buffer = Vec::new();
1122 unsigned_invoice_request.write(&mut buffer).unwrap();
1124 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1125 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1126 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1127 assert_eq!(unsigned_invoice_request.metadata(), None);
1128 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1129 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1130 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1131 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1132 assert_eq!(unsigned_invoice_request.paths(), &[]);
1133 assert_eq!(unsigned_invoice_request.issuer(), None);
1134 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1135 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1136 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1137 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1138 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1139 assert_eq!(unsigned_invoice_request.quantity(), None);
1140 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1141 assert_eq!(unsigned_invoice_request.payer_note(), None);
1143 match UnsignedInvoiceRequest::try_from(buffer) {
1144 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1146 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1147 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1151 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1153 let mut buffer = Vec::new();
1154 invoice_request.write(&mut buffer).unwrap();
1156 assert_eq!(invoice_request.bytes, buffer.as_slice());
1157 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1158 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1159 assert_eq!(invoice_request.metadata(), None);
1160 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1161 assert_eq!(invoice_request.description(), PrintableString("foo"));
1162 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1163 assert_eq!(invoice_request.absolute_expiry(), None);
1164 assert_eq!(invoice_request.paths(), &[]);
1165 assert_eq!(invoice_request.issuer(), None);
1166 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1167 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1168 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1169 assert_eq!(invoice_request.amount_msats(), None);
1170 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1171 assert_eq!(invoice_request.quantity(), None);
1172 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1173 assert_eq!(invoice_request.payer_note(), None);
1175 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1176 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1179 invoice_request.as_tlv_stream(),
1181 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1187 description: Some(&String::from("foo")),
1189 absolute_expiry: None,
1193 node_id: Some(&recipient_pubkey()),
1195 InvoiceRequestTlvStreamRef {
1200 payer_id: Some(&payer_pubkey()),
1203 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1207 if let Err(e) = InvoiceRequest::try_from(buffer) {
1208 panic!("error parsing invoice request: {:?}", e);
1212 #[cfg(feature = "std")]
1214 fn builds_invoice_request_from_offer_with_expiration() {
1215 let future_expiry = Duration::from_secs(u64::max_value());
1216 let past_expiry = Duration::from_secs(0);
1218 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1220 .absolute_expiry(future_expiry)
1222 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225 panic!("error building invoice_request: {:?}", e);
1228 match OfferBuilder::new("foo".into(), recipient_pubkey())
1230 .absolute_expiry(past_expiry)
1232 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1235 Ok(_) => panic!("expected error"),
1236 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1241 fn builds_invoice_request_with_derived_metadata() {
1242 let payer_id = payer_pubkey();
1243 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1244 let entropy = FixedEntropy {};
1245 let secp_ctx = Secp256k1::new();
1246 let payment_id = PaymentId([1; 32]);
1248 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1251 let invoice_request = offer
1252 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1255 .sign(payer_sign).unwrap();
1256 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1258 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1261 .sign(recipient_sign).unwrap();
1262 match invoice.verify(&expanded_key, &secp_ctx) {
1263 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1264 Err(()) => panic!("verification failed"),
1267 // Fails verification with altered fields
1269 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1270 mut invoice_tlv_stream, mut signature_tlv_stream
1271 ) = invoice.as_tlv_stream();
1272 invoice_request_tlv_stream.amount = Some(2000);
1273 invoice_tlv_stream.amount = Some(2000);
1276 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1277 let mut bytes = Vec::new();
1278 tlv_stream.write(&mut bytes).unwrap();
1280 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1281 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1282 signature_tlv_stream.signature = Some(&signature);
1284 let mut encoded_invoice = bytes;
1285 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1287 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1288 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1290 // Fails verification with altered metadata
1292 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1293 mut signature_tlv_stream
1294 ) = invoice.as_tlv_stream();
1295 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1296 payer_tlv_stream.metadata = Some(&metadata);
1299 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1300 let mut bytes = Vec::new();
1301 tlv_stream.write(&mut bytes).unwrap();
1303 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1304 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1305 signature_tlv_stream.signature = Some(&signature);
1307 let mut encoded_invoice = bytes;
1308 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1310 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1311 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1315 fn builds_invoice_request_with_derived_payer_id() {
1316 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1317 let entropy = FixedEntropy {};
1318 let secp_ctx = Secp256k1::new();
1319 let payment_id = PaymentId([1; 32]);
1321 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1324 let invoice_request = offer
1325 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1330 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1333 .sign(recipient_sign).unwrap();
1334 match invoice.verify(&expanded_key, &secp_ctx) {
1335 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1336 Err(()) => panic!("verification failed"),
1339 // Fails verification with altered fields
1341 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1342 mut invoice_tlv_stream, mut signature_tlv_stream
1343 ) = invoice.as_tlv_stream();
1344 invoice_request_tlv_stream.amount = Some(2000);
1345 invoice_tlv_stream.amount = Some(2000);
1348 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1349 let mut bytes = Vec::new();
1350 tlv_stream.write(&mut bytes).unwrap();
1352 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1353 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1354 signature_tlv_stream.signature = Some(&signature);
1356 let mut encoded_invoice = bytes;
1357 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1359 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1360 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1362 // Fails verification with altered payer id
1364 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1365 mut signature_tlv_stream
1366 ) = invoice.as_tlv_stream();
1367 let payer_id = pubkey(1);
1368 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1371 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1372 let mut bytes = Vec::new();
1373 tlv_stream.write(&mut bytes).unwrap();
1375 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1376 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1377 signature_tlv_stream.signature = Some(&signature);
1379 let mut encoded_invoice = bytes;
1380 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1382 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1383 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1387 fn builds_invoice_request_with_chain() {
1388 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1389 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1391 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1394 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1395 .chain(Network::Bitcoin).unwrap()
1397 .sign(payer_sign).unwrap();
1398 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1399 assert_eq!(invoice_request.chain(), mainnet);
1400 assert_eq!(tlv_stream.chain, None);
1402 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1404 .chain(Network::Testnet)
1406 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1407 .chain(Network::Testnet).unwrap()
1409 .sign(payer_sign).unwrap();
1410 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1411 assert_eq!(invoice_request.chain(), testnet);
1412 assert_eq!(tlv_stream.chain, Some(&testnet));
1414 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1416 .chain(Network::Bitcoin)
1417 .chain(Network::Testnet)
1419 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1420 .chain(Network::Bitcoin).unwrap()
1422 .sign(payer_sign).unwrap();
1423 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1424 assert_eq!(invoice_request.chain(), mainnet);
1425 assert_eq!(tlv_stream.chain, None);
1427 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1429 .chain(Network::Bitcoin)
1430 .chain(Network::Testnet)
1432 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1433 .chain(Network::Bitcoin).unwrap()
1434 .chain(Network::Testnet).unwrap()
1436 .sign(payer_sign).unwrap();
1437 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1438 assert_eq!(invoice_request.chain(), testnet);
1439 assert_eq!(tlv_stream.chain, Some(&testnet));
1441 match OfferBuilder::new("foo".into(), recipient_pubkey())
1443 .chain(Network::Testnet)
1445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446 .chain(Network::Bitcoin)
1448 Ok(_) => panic!("expected error"),
1449 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1452 match OfferBuilder::new("foo".into(), recipient_pubkey())
1454 .chain(Network::Testnet)
1456 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1459 Ok(_) => panic!("expected error"),
1460 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1465 fn builds_invoice_request_with_amount() {
1466 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1469 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1470 .amount_msats(1000).unwrap()
1472 .sign(payer_sign).unwrap();
1473 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1474 assert_eq!(invoice_request.amount_msats(), Some(1000));
1475 assert_eq!(tlv_stream.amount, Some(1000));
1477 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1481 .amount_msats(1001).unwrap()
1482 .amount_msats(1000).unwrap()
1484 .sign(payer_sign).unwrap();
1485 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1486 assert_eq!(invoice_request.amount_msats(), Some(1000));
1487 assert_eq!(tlv_stream.amount, Some(1000));
1489 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .amount_msats(1001).unwrap()
1495 .sign(payer_sign).unwrap();
1496 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1497 assert_eq!(invoice_request.amount_msats(), Some(1001));
1498 assert_eq!(tlv_stream.amount, Some(1001));
1500 match OfferBuilder::new("foo".into(), recipient_pubkey())
1503 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 Ok(_) => panic!("expected error"),
1507 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1510 match OfferBuilder::new("foo".into(), recipient_pubkey())
1512 .supported_quantity(Quantity::Unbounded)
1514 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1515 .quantity(2).unwrap()
1518 Ok(_) => panic!("expected error"),
1519 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1522 match OfferBuilder::new("foo".into(), recipient_pubkey())
1525 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1526 .amount_msats(MAX_VALUE_MSAT + 1)
1528 Ok(_) => panic!("expected error"),
1529 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1532 match OfferBuilder::new("foo".into(), recipient_pubkey())
1534 .supported_quantity(Quantity::Unbounded)
1536 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1537 .amount_msats(1000).unwrap()
1538 .quantity(2).unwrap()
1541 Ok(_) => panic!("expected error"),
1542 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1545 match OfferBuilder::new("foo".into(), recipient_pubkey())
1547 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1550 Ok(_) => panic!("expected error"),
1551 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1554 match OfferBuilder::new("foo".into(), recipient_pubkey())
1556 .supported_quantity(Quantity::Unbounded)
1558 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1559 .quantity(u64::max_value()).unwrap()
1562 Ok(_) => panic!("expected error"),
1563 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1568 fn builds_invoice_request_with_features() {
1569 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1572 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1573 .features_unchecked(InvoiceRequestFeatures::unknown())
1575 .sign(payer_sign).unwrap();
1576 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1577 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1578 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1580 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1583 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1584 .features_unchecked(InvoiceRequestFeatures::unknown())
1585 .features_unchecked(InvoiceRequestFeatures::empty())
1587 .sign(payer_sign).unwrap();
1588 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1589 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1590 assert_eq!(tlv_stream.features, None);
1594 fn builds_invoice_request_with_quantity() {
1595 let one = NonZeroU64::new(1).unwrap();
1596 let ten = NonZeroU64::new(10).unwrap();
1598 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1600 .supported_quantity(Quantity::One)
1602 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1604 .sign(payer_sign).unwrap();
1605 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1606 assert_eq!(invoice_request.quantity(), None);
1607 assert_eq!(tlv_stream.quantity, None);
1609 match OfferBuilder::new("foo".into(), recipient_pubkey())
1611 .supported_quantity(Quantity::One)
1613 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1614 .amount_msats(2_000).unwrap()
1617 Ok(_) => panic!("expected error"),
1618 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1621 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1623 .supported_quantity(Quantity::Bounded(ten))
1625 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 .amount_msats(10_000).unwrap()
1627 .quantity(10).unwrap()
1629 .sign(payer_sign).unwrap();
1630 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1631 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1632 assert_eq!(tlv_stream.amount, Some(10_000));
1634 match OfferBuilder::new("foo".into(), recipient_pubkey())
1636 .supported_quantity(Quantity::Bounded(ten))
1638 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1639 .amount_msats(11_000).unwrap()
1642 Ok(_) => panic!("expected error"),
1643 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1646 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1648 .supported_quantity(Quantity::Unbounded)
1650 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1651 .amount_msats(2_000).unwrap()
1652 .quantity(2).unwrap()
1654 .sign(payer_sign).unwrap();
1655 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1656 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1657 assert_eq!(tlv_stream.amount, Some(2_000));
1659 match OfferBuilder::new("foo".into(), recipient_pubkey())
1661 .supported_quantity(Quantity::Unbounded)
1663 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1666 Ok(_) => panic!("expected error"),
1667 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1670 match OfferBuilder::new("foo".into(), recipient_pubkey())
1672 .supported_quantity(Quantity::Bounded(one))
1674 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1677 Ok(_) => panic!("expected error"),
1678 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1683 fn builds_invoice_request_with_payer_note() {
1684 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1687 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1688 .payer_note("bar".into())
1690 .sign(payer_sign).unwrap();
1691 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1692 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1693 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1695 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1698 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1699 .payer_note("bar".into())
1700 .payer_note("baz".into())
1702 .sign(payer_sign).unwrap();
1703 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1704 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1705 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1709 fn fails_signing_invoice_request() {
1710 match OfferBuilder::new("foo".into(), recipient_pubkey())
1713 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1717 Ok(_) => panic!("expected error"),
1718 Err(e) => assert_eq!(e, SignError::Signing(())),
1721 match OfferBuilder::new("foo".into(), recipient_pubkey())
1724 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1726 .sign(recipient_sign)
1728 Ok(_) => panic!("expected error"),
1729 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1734 fn fails_responding_with_unknown_required_features() {
1735 match OfferBuilder::new("foo".into(), recipient_pubkey())
1738 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1739 .features_unchecked(InvoiceRequestFeatures::unknown())
1741 .sign(payer_sign).unwrap()
1742 .respond_with_no_std(payment_paths(), payment_hash(), now())
1744 Ok(_) => panic!("expected error"),
1745 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1750 fn parses_invoice_request_with_metadata() {
1751 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1754 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1756 .sign(payer_sign).unwrap();
1758 let mut buffer = Vec::new();
1759 invoice_request.write(&mut buffer).unwrap();
1761 if let Err(e) = InvoiceRequest::try_from(buffer) {
1762 panic!("error parsing invoice_request: {:?}", e);
1767 fn parses_invoice_request_with_chain() {
1768 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1771 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1772 .chain(Network::Bitcoin).unwrap()
1774 .sign(payer_sign).unwrap();
1776 let mut buffer = Vec::new();
1777 invoice_request.write(&mut buffer).unwrap();
1779 if let Err(e) = InvoiceRequest::try_from(buffer) {
1780 panic!("error parsing invoice_request: {:?}", e);
1783 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1786 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1787 .chain_unchecked(Network::Testnet)
1789 .sign(payer_sign).unwrap();
1791 let mut buffer = Vec::new();
1792 invoice_request.write(&mut buffer).unwrap();
1794 match InvoiceRequest::try_from(buffer) {
1795 Ok(_) => panic!("expected error"),
1796 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1801 fn parses_invoice_request_with_amount() {
1802 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1805 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .sign(payer_sign).unwrap();
1809 let mut buffer = Vec::new();
1810 invoice_request.write(&mut buffer).unwrap();
1812 if let Err(e) = InvoiceRequest::try_from(buffer) {
1813 panic!("error parsing invoice_request: {:?}", e);
1816 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1818 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1819 .amount_msats(1000).unwrap()
1821 .sign(payer_sign).unwrap();
1823 let mut buffer = Vec::new();
1824 invoice_request.write(&mut buffer).unwrap();
1826 if let Err(e) = InvoiceRequest::try_from(buffer) {
1827 panic!("error parsing invoice_request: {:?}", e);
1830 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1832 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1834 .sign(payer_sign).unwrap();
1836 let mut buffer = Vec::new();
1837 invoice_request.write(&mut buffer).unwrap();
1839 match InvoiceRequest::try_from(buffer) {
1840 Ok(_) => panic!("expected error"),
1841 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1844 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1847 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1848 .amount_msats_unchecked(999)
1850 .sign(payer_sign).unwrap();
1852 let mut buffer = Vec::new();
1853 invoice_request.write(&mut buffer).unwrap();
1855 match InvoiceRequest::try_from(buffer) {
1856 Ok(_) => panic!("expected error"),
1857 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1860 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1861 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1863 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1865 .sign(payer_sign).unwrap();
1867 let mut buffer = Vec::new();
1868 invoice_request.write(&mut buffer).unwrap();
1870 match InvoiceRequest::try_from(buffer) {
1871 Ok(_) => panic!("expected error"),
1873 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1877 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1879 .supported_quantity(Quantity::Unbounded)
1881 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1882 .quantity(u64::max_value()).unwrap()
1884 .sign(payer_sign).unwrap();
1886 let mut buffer = Vec::new();
1887 invoice_request.write(&mut buffer).unwrap();
1889 match InvoiceRequest::try_from(buffer) {
1890 Ok(_) => panic!("expected error"),
1891 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1896 fn parses_invoice_request_with_quantity() {
1897 let one = NonZeroU64::new(1).unwrap();
1898 let ten = NonZeroU64::new(10).unwrap();
1900 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1902 .supported_quantity(Quantity::One)
1904 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1906 .sign(payer_sign).unwrap();
1908 let mut buffer = Vec::new();
1909 invoice_request.write(&mut buffer).unwrap();
1911 if let Err(e) = InvoiceRequest::try_from(buffer) {
1912 panic!("error parsing invoice_request: {:?}", e);
1915 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1917 .supported_quantity(Quantity::One)
1919 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1920 .amount_msats(2_000).unwrap()
1921 .quantity_unchecked(2)
1923 .sign(payer_sign).unwrap();
1925 let mut buffer = Vec::new();
1926 invoice_request.write(&mut buffer).unwrap();
1928 match InvoiceRequest::try_from(buffer) {
1929 Ok(_) => panic!("expected error"),
1931 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1935 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1937 .supported_quantity(Quantity::Bounded(ten))
1939 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1940 .amount_msats(10_000).unwrap()
1941 .quantity(10).unwrap()
1943 .sign(payer_sign).unwrap();
1945 let mut buffer = Vec::new();
1946 invoice_request.write(&mut buffer).unwrap();
1948 if let Err(e) = InvoiceRequest::try_from(buffer) {
1949 panic!("error parsing invoice_request: {:?}", e);
1952 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1954 .supported_quantity(Quantity::Bounded(ten))
1956 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1957 .amount_msats(11_000).unwrap()
1958 .quantity_unchecked(11)
1960 .sign(payer_sign).unwrap();
1962 let mut buffer = Vec::new();
1963 invoice_request.write(&mut buffer).unwrap();
1965 match InvoiceRequest::try_from(buffer) {
1966 Ok(_) => panic!("expected error"),
1967 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1970 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1972 .supported_quantity(Quantity::Unbounded)
1974 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1975 .amount_msats(2_000).unwrap()
1976 .quantity(2).unwrap()
1978 .sign(payer_sign).unwrap();
1980 let mut buffer = Vec::new();
1981 invoice_request.write(&mut buffer).unwrap();
1983 if let Err(e) = InvoiceRequest::try_from(buffer) {
1984 panic!("error parsing invoice_request: {:?}", e);
1987 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1989 .supported_quantity(Quantity::Unbounded)
1991 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1993 .sign(payer_sign).unwrap();
1995 let mut buffer = Vec::new();
1996 invoice_request.write(&mut buffer).unwrap();
1998 match InvoiceRequest::try_from(buffer) {
1999 Ok(_) => panic!("expected error"),
2000 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2003 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2005 .supported_quantity(Quantity::Bounded(one))
2007 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2009 .sign(payer_sign).unwrap();
2011 let mut buffer = Vec::new();
2012 invoice_request.write(&mut buffer).unwrap();
2014 match InvoiceRequest::try_from(buffer) {
2015 Ok(_) => panic!("expected error"),
2016 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2021 fn fails_parsing_invoice_request_without_metadata() {
2022 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2025 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2027 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2028 tlv_stream.0.metadata = None;
2030 let mut buffer = Vec::new();
2031 tlv_stream.write(&mut buffer).unwrap();
2033 match InvoiceRequest::try_from(buffer) {
2034 Ok(_) => panic!("expected error"),
2036 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2042 fn fails_parsing_invoice_request_without_payer_id() {
2043 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2046 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2048 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2049 tlv_stream.2.payer_id = None;
2051 let mut buffer = Vec::new();
2052 tlv_stream.write(&mut buffer).unwrap();
2054 match InvoiceRequest::try_from(buffer) {
2055 Ok(_) => panic!("expected error"),
2056 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2061 fn fails_parsing_invoice_request_without_node_id() {
2062 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2065 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2067 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2068 tlv_stream.1.node_id = None;
2070 let mut buffer = Vec::new();
2071 tlv_stream.write(&mut buffer).unwrap();
2073 match InvoiceRequest::try_from(buffer) {
2074 Ok(_) => panic!("expected error"),
2076 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2082 fn fails_parsing_invoice_request_without_signature() {
2083 let mut buffer = Vec::new();
2084 OfferBuilder::new("foo".into(), recipient_pubkey())
2087 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2090 .write(&mut buffer).unwrap();
2092 match InvoiceRequest::try_from(buffer) {
2093 Ok(_) => panic!("expected error"),
2094 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2099 fn fails_parsing_invoice_request_with_invalid_signature() {
2100 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2103 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2105 .sign(payer_sign).unwrap();
2106 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2107 *last_signature_byte = last_signature_byte.wrapping_add(1);
2109 let mut buffer = Vec::new();
2110 invoice_request.write(&mut buffer).unwrap();
2112 match InvoiceRequest::try_from(buffer) {
2113 Ok(_) => panic!("expected error"),
2115 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2121 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2122 let secp_ctx = Secp256k1::new();
2123 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2124 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2127 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2129 .sign::<_, Infallible>(
2130 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2134 let mut encoded_invoice_request = Vec::new();
2135 invoice_request.write(&mut encoded_invoice_request).unwrap();
2136 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2137 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2138 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2140 match InvoiceRequest::try_from(encoded_invoice_request) {
2141 Ok(_) => panic!("expected error"),
2142 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),