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::Network;
27 //! use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::ln::features::OfferFeatures;
29 //! use lightning::offers::invoice_request::UnsignedInvoiceRequest;
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(|message: &UnsignedInvoiceRequest|
51 //! 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::Network;
62 use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, self};
63 use bitcoin::secp256k1::schnorr::Signature;
65 use crate::sign::EntropySource;
67 use crate::blinded_path::BlindedPath;
68 use crate::ln::types::PaymentHash;
69 use crate::ln::channelmanager::PaymentId;
70 use crate::ln::features::InvoiceRequestFeatures;
71 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
72 use crate::ln::msgs::DecodeError;
73 use crate::offers::invoice::BlindedPayInfo;
74 use crate::offers::merkle::{SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
75 use crate::offers::offer::{Offer, OfferContents, OfferId, OfferTlvStream, OfferTlvStreamRef};
76 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
77 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
78 use crate::offers::signer::{Metadata, MetadataMaterial};
79 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, SeekReadable, WithoutLength, Writeable, Writer};
80 use crate::util::string::{PrintableString, UntrustedString};
82 #[cfg(not(c_bindings))]
84 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
88 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
91 #[allow(unused_imports)]
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(|message: &UnsignedInvoiceRequest|
231 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.
491 pub struct UnsignedInvoiceRequest {
493 contents: InvoiceRequestContents,
494 tagged_hash: TaggedHash,
497 /// A function for signing an [`UnsignedInvoiceRequest`].
498 pub trait SignInvoiceRequestFn {
499 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
500 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()>;
503 impl<F> SignInvoiceRequestFn for F
505 F: Fn(&UnsignedInvoiceRequest) -> Result<Signature, ()>,
507 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
512 impl<F> SignFn<UnsignedInvoiceRequest> for F
514 F: SignInvoiceRequestFn,
516 fn sign(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
517 self.sign_invoice_request(message)
521 impl UnsignedInvoiceRequest {
522 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
523 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
524 // unknown TLV records, which are not stored in `OfferContents`.
525 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
526 contents.as_tlv_stream();
527 let offer_bytes = WithoutLength(&offer.bytes);
528 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
530 let mut bytes = Vec::new();
531 unsigned_tlv_stream.write(&mut bytes).unwrap();
533 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
535 Self { bytes, contents, tagged_hash }
538 /// Returns the [`TaggedHash`] of the invoice to sign.
539 pub fn tagged_hash(&self) -> &TaggedHash {
544 macro_rules! unsigned_invoice_request_sign_method { (
545 $self: ident, $self_type: ty $(, $self_mut: tt)?
547 /// Signs the [`TaggedHash`] of the invoice request using the given function.
549 /// Note: The hash computation may have included unknown, odd TLV records.
550 pub fn sign<F: SignInvoiceRequestFn>(
551 $($self_mut)* $self: $self_type, sign: F
552 ) -> Result<InvoiceRequest, SignError> {
553 let pubkey = $self.contents.payer_id;
554 let signature = merkle::sign_message(sign, &$self, pubkey)?;
556 // Append the signature TLV record to the bytes.
557 let signature_tlv_stream = SignatureTlvStreamRef {
558 signature: Some(&signature),
560 signature_tlv_stream.write(&mut $self.bytes).unwrap();
563 #[cfg(not(c_bindings))]
566 bytes: $self.bytes.clone(),
567 #[cfg(not(c_bindings))]
568 contents: $self.contents,
570 contents: $self.contents.clone(),
576 #[cfg(not(c_bindings))]
577 impl UnsignedInvoiceRequest {
578 unsigned_invoice_request_sign_method!(self, Self, mut);
582 impl UnsignedInvoiceRequest {
583 unsigned_invoice_request_sign_method!(self, &mut Self);
586 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
587 fn as_ref(&self) -> &TaggedHash {
592 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
594 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
595 /// specifies these such that its recipient can send an invoice for payment.
597 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
598 /// [`Offer`]: crate::offers::offer::Offer
599 #[derive(Clone, Debug)]
600 #[cfg_attr(test, derive(PartialEq))]
601 pub struct InvoiceRequest {
602 pub(super) bytes: Vec<u8>,
603 pub(super) contents: InvoiceRequestContents,
604 signature: Signature,
607 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
608 /// ways to respond depending on whether the signing keys were derived.
609 #[derive(Clone, Debug)]
610 pub struct VerifiedInvoiceRequest {
611 /// The identifier of the [`Offer`] for which the [`InvoiceRequest`] was made.
612 pub offer_id: OfferId,
614 /// The verified request.
615 inner: InvoiceRequest,
617 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
619 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
620 /// [`respond_with`].
622 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
623 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
624 /// [`respond_with`]: Self::respond_with
625 pub keys: Option<Keypair>,
628 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
630 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
631 #[derive(Clone, Debug)]
632 #[cfg_attr(test, derive(PartialEq))]
633 pub(super) struct InvoiceRequestContents {
634 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
638 #[derive(Clone, Debug)]
639 #[cfg_attr(test, derive(PartialEq))]
640 pub(super) struct InvoiceRequestContentsWithoutPayerId {
641 payer: PayerContents,
642 pub(super) offer: OfferContents,
643 chain: Option<ChainHash>,
644 amount_msats: Option<u64>,
645 features: InvoiceRequestFeatures,
646 quantity: Option<u64>,
647 payer_note: Option<String>,
650 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
651 /// An unpredictable series of bytes, typically containing information about the derivation of
654 /// [`payer_id`]: Self::payer_id
655 pub fn payer_metadata(&$self) -> &[u8] {
659 /// A chain from [`Offer::chains`] that the offer is valid for.
660 pub fn chain(&$self) -> ChainHash {
664 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
665 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
667 /// [`chain`]: Self::chain
668 pub fn amount_msats(&$self) -> Option<u64> {
669 $contents.amount_msats()
672 /// Features pertaining to requesting an invoice.
673 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
674 &$contents.features()
677 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
678 pub fn quantity(&$self) -> Option<u64> {
682 /// A possibly transient pubkey used to sign the invoice request.
683 pub fn payer_id(&$self) -> PublicKey {
687 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
689 pub fn payer_note(&$self) -> Option<PrintableString> {
690 $contents.payer_note()
694 impl UnsignedInvoiceRequest {
695 offer_accessors!(self, self.contents.inner.offer);
696 invoice_request_accessors!(self, self.contents);
699 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
700 $self: ident, $contents: expr, $builder: ty
702 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
703 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
705 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
706 /// creation time is used for the `created_at` parameter.
708 /// [`Duration`]: core::time::Duration
709 #[cfg(feature = "std")]
711 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
712 ) -> Result<$builder, Bolt12SemanticError> {
713 let created_at = std::time::SystemTime::now()
714 .duration_since(std::time::SystemTime::UNIX_EPOCH)
715 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
717 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
720 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
722 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
723 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
724 /// where [`std::time::SystemTime`] is not available.
726 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
729 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
730 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
731 /// a preference. Note, however, that any privacy is lost if a public node id was used for
732 /// [`Offer::signing_pubkey`].
734 /// Errors if the request contains unknown required features.
738 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
739 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
741 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
742 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
743 pub fn respond_with_no_std(
744 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
745 created_at: core::time::Duration
746 ) -> Result<$builder, Bolt12SemanticError> {
747 if $contents.invoice_request_features().requires_unknown_bits() {
748 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
751 let signing_pubkey = match $contents.contents.inner.offer.signing_pubkey() {
752 Some(signing_pubkey) => signing_pubkey,
753 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
756 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
761 pub(super) fn respond_with_no_std_using_signing_pubkey(
762 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
763 created_at: core::time::Duration, signing_pubkey: PublicKey
764 ) -> Result<$builder, Bolt12SemanticError> {
765 debug_assert!($contents.contents.inner.offer.signing_pubkey().is_none());
767 if $contents.invoice_request_features().requires_unknown_bits() {
768 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
771 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
775 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
776 /// Verifies that the request was for an offer created using the given key. Returns the verified
777 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
778 /// if they could be extracted from the metadata.
780 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
782 #[cfg(not(c_bindings))]
783 T: secp256k1::Signing
785 $self: $self_type, key: &ExpandedKey,
786 #[cfg(not(c_bindings))]
787 secp_ctx: &Secp256k1<T>,
789 secp_ctx: &Secp256k1<secp256k1::All>,
790 ) -> Result<VerifiedInvoiceRequest, ()> {
791 let (offer_id, keys) = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
792 Ok(VerifiedInvoiceRequest {
794 #[cfg(not(c_bindings))]
797 inner: $self.clone(),
804 #[cfg(not(c_bindings))]
805 impl InvoiceRequest {
806 offer_accessors!(self, self.contents.inner.offer);
807 invoice_request_accessors!(self, self.contents);
808 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
809 invoice_request_verify_method!(self, Self);
813 impl InvoiceRequest {
814 offer_accessors!(self, self.contents.inner.offer);
815 invoice_request_accessors!(self, self.contents);
816 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
817 invoice_request_verify_method!(self, &Self);
820 impl InvoiceRequest {
821 /// Signature of the invoice request using [`payer_id`].
823 /// [`payer_id`]: Self::payer_id
824 pub fn signature(&self) -> Signature {
828 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
829 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
830 self.contents.as_tlv_stream();
831 let signature_tlv_stream = SignatureTlvStreamRef {
832 signature: Some(&self.signature),
834 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
838 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
839 $self: ident, $contents: expr, $builder: ty
841 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
842 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
843 /// the same [`ExpandedKey`] as the one used to create the offer.
845 /// See [`InvoiceRequest::respond_with`] for further details.
847 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
848 #[cfg(feature = "std")]
849 pub fn respond_using_derived_keys(
850 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
851 ) -> Result<$builder, Bolt12SemanticError> {
852 let created_at = std::time::SystemTime::now()
853 .duration_since(std::time::SystemTime::UNIX_EPOCH)
854 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
856 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
859 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
860 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
861 /// the same [`ExpandedKey`] as the one used to create the offer.
863 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
865 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
866 pub fn respond_using_derived_keys_no_std(
867 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
868 created_at: core::time::Duration
869 ) -> Result<$builder, Bolt12SemanticError> {
870 if $self.inner.invoice_request_features().requires_unknown_bits() {
871 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
874 let keys = match $self.keys {
875 None => return Err(Bolt12SemanticError::InvalidMetadata),
879 match $contents.contents.inner.offer.signing_pubkey() {
880 Some(signing_pubkey) => debug_assert_eq!(signing_pubkey, keys.public_key()),
881 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
884 <$builder>::for_offer_using_keys(
885 &$self.inner, payment_paths, created_at, payment_hash, keys
890 impl VerifiedInvoiceRequest {
891 offer_accessors!(self, self.inner.contents.inner.offer);
892 invoice_request_accessors!(self, self.inner.contents);
893 #[cfg(not(c_bindings))]
894 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
896 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
897 #[cfg(not(c_bindings))]
898 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
900 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
902 pub(crate) fn fields(&self) -> InvoiceRequestFields {
903 let InvoiceRequestContents {
905 inner: InvoiceRequestContentsWithoutPayerId {
906 payer: _, offer: _, chain: _, amount_msats: _, features: _, quantity, payer_note
908 } = &self.inner.contents;
910 InvoiceRequestFields {
913 payer_note_truncated: payer_note.clone()
914 .map(|mut s| { s.truncate(PAYER_NOTE_LIMIT); UntrustedString(s) }),
919 impl InvoiceRequestContents {
920 pub(super) fn metadata(&self) -> &[u8] {
921 self.inner.metadata()
924 pub(super) fn derives_keys(&self) -> bool {
925 self.inner.payer.0.derives_payer_keys()
928 pub(super) fn chain(&self) -> ChainHash {
932 pub(super) fn amount_msats(&self) -> Option<u64> {
933 self.inner.amount_msats
936 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
940 pub(super) fn quantity(&self) -> Option<u64> {
944 pub(super) fn payer_id(&self) -> PublicKey {
948 pub(super) fn payer_note(&self) -> Option<PrintableString> {
949 self.inner.payer_note.as_ref()
950 .map(|payer_note| PrintableString(payer_note.as_str()))
953 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
954 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
955 invoice_request.payer_id = Some(&self.payer_id);
956 (payer, offer, invoice_request)
960 impl InvoiceRequestContentsWithoutPayerId {
961 pub(super) fn metadata(&self) -> &[u8] {
962 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
965 pub(super) fn chain(&self) -> ChainHash {
966 self.chain.unwrap_or_else(|| self.offer.implied_chain())
969 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
970 let payer = PayerTlvStreamRef {
971 metadata: self.payer.0.as_bytes(),
974 let offer = self.offer.as_tlv_stream();
977 if self.features == InvoiceRequestFeatures::empty() { None }
978 else { Some(&self.features) }
981 let invoice_request = InvoiceRequestTlvStreamRef {
982 chain: self.chain.as_ref(),
983 amount: self.amount_msats,
985 quantity: self.quantity,
987 payer_note: self.payer_note.as_ref(),
991 (payer, offer, invoice_request)
995 impl Writeable for UnsignedInvoiceRequest {
996 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
997 WithoutLength(&self.bytes).write(writer)
1001 impl Writeable for InvoiceRequest {
1002 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1003 WithoutLength(&self.bytes).write(writer)
1007 impl Writeable for InvoiceRequestContents {
1008 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1009 self.as_tlv_stream().write(writer)
1013 /// Valid type range for invoice_request TLV records.
1014 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
1016 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
1018 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
1019 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
1021 // This TLV stream is used for both InvoiceRequest and Refund, but not all TLV records are valid for
1022 // InvoiceRequest as noted below.
1023 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
1024 (80, chain: ChainHash),
1025 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
1026 (84, features: (InvoiceRequestFeatures, WithoutLength)),
1027 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
1028 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
1029 (89, payer_note: (String, WithoutLength)),
1030 // Only used for Refund since the onion message of an InvoiceRequest has a reply path.
1031 (90, paths: (Vec<BlindedPath>, WithoutLength)),
1034 type FullInvoiceRequestTlvStream =
1035 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
1037 type FullInvoiceRequestTlvStreamRef<'a> = (
1038 PayerTlvStreamRef<'a>,
1039 OfferTlvStreamRef<'a>,
1040 InvoiceRequestTlvStreamRef<'a>,
1041 SignatureTlvStreamRef<'a>,
1044 impl SeekReadable for FullInvoiceRequestTlvStream {
1045 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1046 let payer = SeekReadable::read(r)?;
1047 let offer = SeekReadable::read(r)?;
1048 let invoice_request = SeekReadable::read(r)?;
1049 let signature = SeekReadable::read(r)?;
1051 Ok((payer, offer, invoice_request, signature))
1055 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1057 type PartialInvoiceRequestTlvStreamRef<'a> = (
1058 PayerTlvStreamRef<'a>,
1059 OfferTlvStreamRef<'a>,
1060 InvoiceRequestTlvStreamRef<'a>,
1063 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1064 type Error = Bolt12ParseError;
1066 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1067 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1068 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1070 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1072 let contents = InvoiceRequestContents::try_from(
1073 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1076 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1078 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1082 impl TryFrom<Vec<u8>> for InvoiceRequest {
1083 type Error = Bolt12ParseError;
1085 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1086 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1087 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1089 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1090 SignatureTlvStream { signature },
1092 let contents = InvoiceRequestContents::try_from(
1093 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1096 let signature = match signature {
1097 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1098 Some(signature) => signature,
1100 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1101 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1103 Ok(InvoiceRequest { bytes, contents, signature })
1107 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1108 type Error = Bolt12SemanticError;
1110 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1112 PayerTlvStream { metadata },
1114 InvoiceRequestTlvStream {
1115 chain, amount, features, quantity, payer_id, payer_note, paths,
1119 let payer = match metadata {
1120 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1121 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1123 let offer = OfferContents::try_from(offer_tlv_stream)?;
1125 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1126 return Err(Bolt12SemanticError::UnsupportedChain);
1129 if offer.amount().is_none() && amount.is_none() {
1130 return Err(Bolt12SemanticError::MissingAmount);
1133 offer.check_quantity(quantity)?;
1134 offer.check_amount_msats_for_quantity(amount, quantity)?;
1136 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1138 let payer_id = match payer_id {
1139 None => return Err(Bolt12SemanticError::MissingPayerId),
1140 Some(payer_id) => payer_id,
1143 if paths.is_some() {
1144 return Err(Bolt12SemanticError::UnexpectedPaths);
1147 Ok(InvoiceRequestContents {
1148 inner: InvoiceRequestContentsWithoutPayerId {
1149 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1156 /// Fields sent in an [`InvoiceRequest`] message to include in [`PaymentContext::Bolt12Offer`].
1158 /// [`PaymentContext::Bolt12Offer`]: crate::blinded_path::payment::PaymentContext::Bolt12Offer
1159 #[derive(Clone, Debug, Eq, PartialEq)]
1160 pub struct InvoiceRequestFields {
1161 /// A possibly transient pubkey used to sign the invoice request.
1162 pub payer_id: PublicKey,
1164 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
1165 pub quantity: Option<u64>,
1167 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
1168 /// response. Truncated to [`PAYER_NOTE_LIMIT`] characters.
1169 pub payer_note_truncated: Option<UntrustedString>,
1172 /// The maximum number of characters included in [`InvoiceRequestFields::payer_note_truncated`].
1173 pub const PAYER_NOTE_LIMIT: usize = 512;
1175 impl Writeable for InvoiceRequestFields {
1176 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1177 write_tlv_fields!(writer, {
1178 (0, self.payer_id, required),
1179 (2, self.quantity.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1180 (4, self.payer_note_truncated.as_ref().map(|s| WithoutLength(&s.0)), option),
1186 impl Readable for InvoiceRequestFields {
1187 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1188 _init_and_read_len_prefixed_tlv_fields!(reader, {
1189 (0, payer_id, required),
1190 (2, quantity, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1191 (4, payer_note_truncated, (option, encoding: (String, WithoutLength))),
1194 Ok(InvoiceRequestFields {
1195 payer_id: payer_id.0.unwrap(),
1197 payer_note_truncated: payer_note_truncated.map(|s| UntrustedString(s)),
1204 use super::{InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest};
1206 use bitcoin::blockdata::constants::ChainHash;
1207 use bitcoin::network::Network;
1208 use bitcoin::secp256k1::{Keypair, Secp256k1, SecretKey, self};
1209 use core::num::NonZeroU64;
1210 #[cfg(feature = "std")]
1211 use core::time::Duration;
1212 use crate::sign::KeyMaterial;
1213 use crate::ln::channelmanager::PaymentId;
1214 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1215 use crate::ln::inbound_payment::ExpandedKey;
1216 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1217 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1218 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1219 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1220 #[cfg(not(c_bindings))]
1222 crate::offers::offer::OfferBuilder,
1226 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1228 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1229 use crate::offers::payer::PayerTlvStreamRef;
1230 use crate::offers::test_utils::*;
1231 use crate::util::ser::{BigSize, Readable, Writeable};
1232 use crate::util::string::{PrintableString, UntrustedString};
1235 fn builds_invoice_request_with_defaults() {
1236 let unsigned_invoice_request = OfferBuilder::new(recipient_pubkey())
1239 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1242 let mut unsigned_invoice_request = unsigned_invoice_request;
1244 let mut buffer = Vec::new();
1245 unsigned_invoice_request.write(&mut buffer).unwrap();
1247 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1248 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1249 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1250 assert_eq!(unsigned_invoice_request.metadata(), None);
1251 assert_eq!(unsigned_invoice_request.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1252 assert_eq!(unsigned_invoice_request.description(), Some(PrintableString("")));
1253 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1254 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1255 assert_eq!(unsigned_invoice_request.paths(), &[]);
1256 assert_eq!(unsigned_invoice_request.issuer(), None);
1257 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1258 assert_eq!(unsigned_invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1259 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1260 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1261 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1262 assert_eq!(unsigned_invoice_request.quantity(), None);
1263 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1264 assert_eq!(unsigned_invoice_request.payer_note(), None);
1266 match UnsignedInvoiceRequest::try_from(buffer) {
1267 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1269 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1270 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1274 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1276 let mut buffer = Vec::new();
1277 invoice_request.write(&mut buffer).unwrap();
1279 assert_eq!(invoice_request.bytes, buffer.as_slice());
1280 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1281 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1282 assert_eq!(invoice_request.metadata(), None);
1283 assert_eq!(invoice_request.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1284 assert_eq!(invoice_request.description(), Some(PrintableString("")));
1285 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1286 assert_eq!(invoice_request.absolute_expiry(), None);
1287 assert_eq!(invoice_request.paths(), &[]);
1288 assert_eq!(invoice_request.issuer(), None);
1289 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1290 assert_eq!(invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1291 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1292 assert_eq!(invoice_request.amount_msats(), None);
1293 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1294 assert_eq!(invoice_request.quantity(), None);
1295 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1296 assert_eq!(invoice_request.payer_note(), None);
1298 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1299 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1302 invoice_request.as_tlv_stream(),
1304 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1310 description: Some(&String::from("")),
1312 absolute_expiry: None,
1316 node_id: Some(&recipient_pubkey()),
1318 InvoiceRequestTlvStreamRef {
1323 payer_id: Some(&payer_pubkey()),
1327 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1331 if let Err(e) = InvoiceRequest::try_from(buffer) {
1332 panic!("error parsing invoice request: {:?}", e);
1336 #[cfg(feature = "std")]
1338 fn builds_invoice_request_from_offer_with_expiration() {
1339 let future_expiry = Duration::from_secs(u64::max_value());
1340 let past_expiry = Duration::from_secs(0);
1342 if let Err(e) = OfferBuilder::new(recipient_pubkey())
1344 .absolute_expiry(future_expiry)
1346 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1349 panic!("error building invoice_request: {:?}", e);
1352 match OfferBuilder::new(recipient_pubkey())
1354 .absolute_expiry(past_expiry)
1356 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359 Ok(_) => panic!("expected error"),
1360 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1365 fn builds_invoice_request_with_derived_metadata() {
1366 let payer_id = payer_pubkey();
1367 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1368 let entropy = FixedEntropy {};
1369 let secp_ctx = Secp256k1::new();
1370 let payment_id = PaymentId([1; 32]);
1372 let offer = OfferBuilder::new(recipient_pubkey())
1375 let invoice_request = offer
1376 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1379 .sign(payer_sign).unwrap();
1380 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1382 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1385 .sign(recipient_sign).unwrap();
1386 match invoice.verify(&expanded_key, &secp_ctx) {
1387 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1388 Err(()) => panic!("verification failed"),
1391 // Fails verification with altered fields
1393 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1394 mut invoice_tlv_stream, mut signature_tlv_stream
1395 ) = invoice.as_tlv_stream();
1396 invoice_request_tlv_stream.amount = Some(2000);
1397 invoice_tlv_stream.amount = Some(2000);
1400 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1401 let mut bytes = Vec::new();
1402 tlv_stream.write(&mut bytes).unwrap();
1404 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1405 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1406 signature_tlv_stream.signature = Some(&signature);
1408 let mut encoded_invoice = bytes;
1409 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1411 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1412 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1414 // Fails verification with altered metadata
1416 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1417 mut signature_tlv_stream
1418 ) = invoice.as_tlv_stream();
1419 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1420 payer_tlv_stream.metadata = Some(&metadata);
1423 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1424 let mut bytes = Vec::new();
1425 tlv_stream.write(&mut bytes).unwrap();
1427 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1428 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1429 signature_tlv_stream.signature = Some(&signature);
1431 let mut encoded_invoice = bytes;
1432 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1434 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1435 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1439 fn builds_invoice_request_with_derived_payer_id() {
1440 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1441 let entropy = FixedEntropy {};
1442 let secp_ctx = Secp256k1::new();
1443 let payment_id = PaymentId([1; 32]);
1445 let offer = OfferBuilder::new(recipient_pubkey())
1448 let invoice_request = offer
1449 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1454 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1457 .sign(recipient_sign).unwrap();
1458 match invoice.verify(&expanded_key, &secp_ctx) {
1459 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1460 Err(()) => panic!("verification failed"),
1463 // Fails verification with altered fields
1465 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1466 mut invoice_tlv_stream, mut signature_tlv_stream
1467 ) = invoice.as_tlv_stream();
1468 invoice_request_tlv_stream.amount = Some(2000);
1469 invoice_tlv_stream.amount = Some(2000);
1472 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1473 let mut bytes = Vec::new();
1474 tlv_stream.write(&mut bytes).unwrap();
1476 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1477 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1478 signature_tlv_stream.signature = Some(&signature);
1480 let mut encoded_invoice = bytes;
1481 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1483 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1484 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1486 // Fails verification with altered payer id
1488 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1489 mut signature_tlv_stream
1490 ) = invoice.as_tlv_stream();
1491 let payer_id = pubkey(1);
1492 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1495 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1496 let mut bytes = Vec::new();
1497 tlv_stream.write(&mut bytes).unwrap();
1499 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1500 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1501 signature_tlv_stream.signature = Some(&signature);
1503 let mut encoded_invoice = bytes;
1504 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1506 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1507 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1511 fn builds_invoice_request_with_chain() {
1512 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1513 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1515 let invoice_request = OfferBuilder::new(recipient_pubkey())
1518 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1519 .chain(Network::Bitcoin).unwrap()
1521 .sign(payer_sign).unwrap();
1522 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1523 assert_eq!(invoice_request.chain(), mainnet);
1524 assert_eq!(tlv_stream.chain, None);
1526 let invoice_request = OfferBuilder::new(recipient_pubkey())
1528 .chain(Network::Testnet)
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531 .chain(Network::Testnet).unwrap()
1533 .sign(payer_sign).unwrap();
1534 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1535 assert_eq!(invoice_request.chain(), testnet);
1536 assert_eq!(tlv_stream.chain, Some(&testnet));
1538 let invoice_request = OfferBuilder::new(recipient_pubkey())
1540 .chain(Network::Bitcoin)
1541 .chain(Network::Testnet)
1543 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1544 .chain(Network::Bitcoin).unwrap()
1546 .sign(payer_sign).unwrap();
1547 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1548 assert_eq!(invoice_request.chain(), mainnet);
1549 assert_eq!(tlv_stream.chain, None);
1551 let invoice_request = OfferBuilder::new(recipient_pubkey())
1553 .chain(Network::Bitcoin)
1554 .chain(Network::Testnet)
1556 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1557 .chain(Network::Bitcoin).unwrap()
1558 .chain(Network::Testnet).unwrap()
1560 .sign(payer_sign).unwrap();
1561 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1562 assert_eq!(invoice_request.chain(), testnet);
1563 assert_eq!(tlv_stream.chain, Some(&testnet));
1565 match OfferBuilder::new(recipient_pubkey())
1567 .chain(Network::Testnet)
1569 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1570 .chain(Network::Bitcoin)
1572 Ok(_) => panic!("expected error"),
1573 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1576 match OfferBuilder::new(recipient_pubkey())
1578 .chain(Network::Testnet)
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1583 Ok(_) => panic!("expected error"),
1584 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1589 fn builds_invoice_request_with_amount() {
1590 let invoice_request = OfferBuilder::new(recipient_pubkey())
1593 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594 .amount_msats(1000).unwrap()
1596 .sign(payer_sign).unwrap();
1597 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1598 assert_eq!(invoice_request.amount_msats(), Some(1000));
1599 assert_eq!(tlv_stream.amount, Some(1000));
1601 let invoice_request = OfferBuilder::new(recipient_pubkey())
1604 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1605 .amount_msats(1001).unwrap()
1606 .amount_msats(1000).unwrap()
1608 .sign(payer_sign).unwrap();
1609 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1610 assert_eq!(invoice_request.amount_msats(), Some(1000));
1611 assert_eq!(tlv_stream.amount, Some(1000));
1613 let invoice_request = OfferBuilder::new(recipient_pubkey())
1616 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1617 .amount_msats(1001).unwrap()
1619 .sign(payer_sign).unwrap();
1620 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1621 assert_eq!(invoice_request.amount_msats(), Some(1001));
1622 assert_eq!(tlv_stream.amount, Some(1001));
1624 match OfferBuilder::new(recipient_pubkey())
1627 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1630 Ok(_) => panic!("expected error"),
1631 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1634 match OfferBuilder::new(recipient_pubkey())
1636 .supported_quantity(Quantity::Unbounded)
1638 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1639 .quantity(2).unwrap()
1642 Ok(_) => panic!("expected error"),
1643 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1646 match OfferBuilder::new(recipient_pubkey())
1649 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1650 .amount_msats(MAX_VALUE_MSAT + 1)
1652 Ok(_) => panic!("expected error"),
1653 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1656 match OfferBuilder::new(recipient_pubkey())
1658 .supported_quantity(Quantity::Unbounded)
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 .amount_msats(1000).unwrap()
1662 .quantity(2).unwrap()
1665 Ok(_) => panic!("expected error"),
1666 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1669 match OfferBuilder::new(recipient_pubkey())
1671 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1674 Ok(_) => panic!("expected error"),
1675 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1678 match OfferBuilder::new(recipient_pubkey())
1680 .supported_quantity(Quantity::Unbounded)
1682 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1683 .quantity(u64::max_value()).unwrap()
1686 Ok(_) => panic!("expected error"),
1687 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1692 fn builds_invoice_request_with_features() {
1693 let invoice_request = OfferBuilder::new(recipient_pubkey())
1696 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1697 .features_unchecked(InvoiceRequestFeatures::unknown())
1699 .sign(payer_sign).unwrap();
1700 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1701 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1702 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1704 let invoice_request = OfferBuilder::new(recipient_pubkey())
1707 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1708 .features_unchecked(InvoiceRequestFeatures::unknown())
1709 .features_unchecked(InvoiceRequestFeatures::empty())
1711 .sign(payer_sign).unwrap();
1712 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1713 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1714 assert_eq!(tlv_stream.features, None);
1718 fn builds_invoice_request_with_quantity() {
1719 let one = NonZeroU64::new(1).unwrap();
1720 let ten = NonZeroU64::new(10).unwrap();
1722 let invoice_request = OfferBuilder::new(recipient_pubkey())
1724 .supported_quantity(Quantity::One)
1726 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1728 .sign(payer_sign).unwrap();
1729 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1730 assert_eq!(invoice_request.quantity(), None);
1731 assert_eq!(tlv_stream.quantity, None);
1733 match OfferBuilder::new(recipient_pubkey())
1735 .supported_quantity(Quantity::One)
1737 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1738 .amount_msats(2_000).unwrap()
1741 Ok(_) => panic!("expected error"),
1742 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1745 let invoice_request = OfferBuilder::new(recipient_pubkey())
1747 .supported_quantity(Quantity::Bounded(ten))
1749 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750 .amount_msats(10_000).unwrap()
1751 .quantity(10).unwrap()
1753 .sign(payer_sign).unwrap();
1754 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1755 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1756 assert_eq!(tlv_stream.amount, Some(10_000));
1758 match OfferBuilder::new(recipient_pubkey())
1760 .supported_quantity(Quantity::Bounded(ten))
1762 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1763 .amount_msats(11_000).unwrap()
1766 Ok(_) => panic!("expected error"),
1767 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1770 let invoice_request = OfferBuilder::new(recipient_pubkey())
1772 .supported_quantity(Quantity::Unbounded)
1774 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1775 .amount_msats(2_000).unwrap()
1776 .quantity(2).unwrap()
1778 .sign(payer_sign).unwrap();
1779 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1780 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1781 assert_eq!(tlv_stream.amount, Some(2_000));
1783 match OfferBuilder::new(recipient_pubkey())
1785 .supported_quantity(Quantity::Unbounded)
1787 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1790 Ok(_) => panic!("expected error"),
1791 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1794 match OfferBuilder::new(recipient_pubkey())
1796 .supported_quantity(Quantity::Bounded(one))
1798 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1801 Ok(_) => panic!("expected error"),
1802 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1807 fn builds_invoice_request_with_payer_note() {
1808 let invoice_request = OfferBuilder::new(recipient_pubkey())
1811 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1812 .payer_note("bar".into())
1814 .sign(payer_sign).unwrap();
1815 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1816 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1817 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1819 let invoice_request = OfferBuilder::new(recipient_pubkey())
1822 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1823 .payer_note("bar".into())
1824 .payer_note("baz".into())
1826 .sign(payer_sign).unwrap();
1827 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1828 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1829 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1833 fn fails_signing_invoice_request() {
1834 match OfferBuilder::new(recipient_pubkey())
1837 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1841 Ok(_) => panic!("expected error"),
1842 Err(e) => assert_eq!(e, SignError::Signing),
1845 match OfferBuilder::new(recipient_pubkey())
1848 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1850 .sign(recipient_sign)
1852 Ok(_) => panic!("expected error"),
1853 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1858 fn fails_responding_with_unknown_required_features() {
1859 match OfferBuilder::new(recipient_pubkey())
1862 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1863 .features_unchecked(InvoiceRequestFeatures::unknown())
1865 .sign(payer_sign).unwrap()
1866 .respond_with_no_std(payment_paths(), payment_hash(), now())
1868 Ok(_) => panic!("expected error"),
1869 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1874 fn parses_invoice_request_with_metadata() {
1875 let invoice_request = OfferBuilder::new(recipient_pubkey())
1878 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1880 .sign(payer_sign).unwrap();
1882 let mut buffer = Vec::new();
1883 invoice_request.write(&mut buffer).unwrap();
1885 if let Err(e) = InvoiceRequest::try_from(buffer) {
1886 panic!("error parsing invoice_request: {:?}", e);
1891 fn parses_invoice_request_with_chain() {
1892 let invoice_request = OfferBuilder::new(recipient_pubkey())
1895 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1896 .chain(Network::Bitcoin).unwrap()
1898 .sign(payer_sign).unwrap();
1900 let mut buffer = Vec::new();
1901 invoice_request.write(&mut buffer).unwrap();
1903 if let Err(e) = InvoiceRequest::try_from(buffer) {
1904 panic!("error parsing invoice_request: {:?}", e);
1907 let invoice_request = OfferBuilder::new(recipient_pubkey())
1910 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1911 .chain_unchecked(Network::Testnet)
1913 .sign(payer_sign).unwrap();
1915 let mut buffer = Vec::new();
1916 invoice_request.write(&mut buffer).unwrap();
1918 match InvoiceRequest::try_from(buffer) {
1919 Ok(_) => panic!("expected error"),
1920 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1925 fn parses_invoice_request_with_amount() {
1926 let invoice_request = OfferBuilder::new(recipient_pubkey())
1929 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1931 .sign(payer_sign).unwrap();
1933 let mut buffer = Vec::new();
1934 invoice_request.write(&mut buffer).unwrap();
1936 if let Err(e) = InvoiceRequest::try_from(buffer) {
1937 panic!("error parsing invoice_request: {:?}", e);
1940 let invoice_request = OfferBuilder::new(recipient_pubkey())
1942 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1943 .amount_msats(1000).unwrap()
1945 .sign(payer_sign).unwrap();
1947 let mut buffer = Vec::new();
1948 invoice_request.write(&mut buffer).unwrap();
1950 if let Err(e) = InvoiceRequest::try_from(buffer) {
1951 panic!("error parsing invoice_request: {:?}", e);
1954 let invoice_request = OfferBuilder::new(recipient_pubkey())
1956 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1958 .sign(payer_sign).unwrap();
1960 let mut buffer = Vec::new();
1961 invoice_request.write(&mut buffer).unwrap();
1963 match InvoiceRequest::try_from(buffer) {
1964 Ok(_) => panic!("expected error"),
1965 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1968 let invoice_request = OfferBuilder::new(recipient_pubkey())
1971 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1972 .amount_msats_unchecked(999)
1974 .sign(payer_sign).unwrap();
1976 let mut buffer = Vec::new();
1977 invoice_request.write(&mut buffer).unwrap();
1979 match InvoiceRequest::try_from(buffer) {
1980 Ok(_) => panic!("expected error"),
1981 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1984 let invoice_request = OfferBuilder::new(recipient_pubkey())
1985 .description("foo".to_string())
1986 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1988 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1990 .sign(payer_sign).unwrap();
1992 let mut buffer = Vec::new();
1993 invoice_request.write(&mut buffer).unwrap();
1995 match InvoiceRequest::try_from(buffer) {
1996 Ok(_) => panic!("expected error"),
1998 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
2002 let invoice_request = OfferBuilder::new(recipient_pubkey())
2004 .supported_quantity(Quantity::Unbounded)
2006 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2007 .quantity(u64::max_value()).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::InvalidAmount)),
2021 fn parses_invoice_request_with_quantity() {
2022 let one = NonZeroU64::new(1).unwrap();
2023 let ten = NonZeroU64::new(10).unwrap();
2025 let invoice_request = OfferBuilder::new(recipient_pubkey())
2027 .supported_quantity(Quantity::One)
2029 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2031 .sign(payer_sign).unwrap();
2033 let mut buffer = Vec::new();
2034 invoice_request.write(&mut buffer).unwrap();
2036 if let Err(e) = InvoiceRequest::try_from(buffer) {
2037 panic!("error parsing invoice_request: {:?}", e);
2040 let invoice_request = OfferBuilder::new(recipient_pubkey())
2042 .supported_quantity(Quantity::One)
2044 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2045 .amount_msats(2_000).unwrap()
2046 .quantity_unchecked(2)
2048 .sign(payer_sign).unwrap();
2050 let mut buffer = Vec::new();
2051 invoice_request.write(&mut buffer).unwrap();
2053 match InvoiceRequest::try_from(buffer) {
2054 Ok(_) => panic!("expected error"),
2056 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
2060 let invoice_request = OfferBuilder::new(recipient_pubkey())
2062 .supported_quantity(Quantity::Bounded(ten))
2064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2065 .amount_msats(10_000).unwrap()
2066 .quantity(10).unwrap()
2068 .sign(payer_sign).unwrap();
2070 let mut buffer = Vec::new();
2071 invoice_request.write(&mut buffer).unwrap();
2073 if let Err(e) = InvoiceRequest::try_from(buffer) {
2074 panic!("error parsing invoice_request: {:?}", e);
2077 let invoice_request = OfferBuilder::new(recipient_pubkey())
2079 .supported_quantity(Quantity::Bounded(ten))
2081 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2082 .amount_msats(11_000).unwrap()
2083 .quantity_unchecked(11)
2085 .sign(payer_sign).unwrap();
2087 let mut buffer = Vec::new();
2088 invoice_request.write(&mut buffer).unwrap();
2090 match InvoiceRequest::try_from(buffer) {
2091 Ok(_) => panic!("expected error"),
2092 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
2095 let invoice_request = OfferBuilder::new(recipient_pubkey())
2097 .supported_quantity(Quantity::Unbounded)
2099 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2100 .amount_msats(2_000).unwrap()
2101 .quantity(2).unwrap()
2103 .sign(payer_sign).unwrap();
2105 let mut buffer = Vec::new();
2106 invoice_request.write(&mut buffer).unwrap();
2108 if let Err(e) = InvoiceRequest::try_from(buffer) {
2109 panic!("error parsing invoice_request: {:?}", e);
2112 let invoice_request = OfferBuilder::new(recipient_pubkey())
2114 .supported_quantity(Quantity::Unbounded)
2116 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2118 .sign(payer_sign).unwrap();
2120 let mut buffer = Vec::new();
2121 invoice_request.write(&mut buffer).unwrap();
2123 match InvoiceRequest::try_from(buffer) {
2124 Ok(_) => panic!("expected error"),
2125 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2128 let invoice_request = OfferBuilder::new(recipient_pubkey())
2130 .supported_quantity(Quantity::Bounded(one))
2132 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2134 .sign(payer_sign).unwrap();
2136 let mut buffer = Vec::new();
2137 invoice_request.write(&mut buffer).unwrap();
2139 match InvoiceRequest::try_from(buffer) {
2140 Ok(_) => panic!("expected error"),
2141 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2146 fn fails_parsing_invoice_request_without_metadata() {
2147 let offer = OfferBuilder::new(recipient_pubkey())
2150 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2152 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2153 tlv_stream.0.metadata = None;
2155 let mut buffer = Vec::new();
2156 tlv_stream.write(&mut buffer).unwrap();
2158 match InvoiceRequest::try_from(buffer) {
2159 Ok(_) => panic!("expected error"),
2161 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2167 fn fails_parsing_invoice_request_without_payer_id() {
2168 let offer = OfferBuilder::new(recipient_pubkey())
2171 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2173 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2174 tlv_stream.2.payer_id = None;
2176 let mut buffer = Vec::new();
2177 tlv_stream.write(&mut buffer).unwrap();
2179 match InvoiceRequest::try_from(buffer) {
2180 Ok(_) => panic!("expected error"),
2181 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2186 fn fails_parsing_invoice_request_without_node_id() {
2187 let offer = OfferBuilder::new(recipient_pubkey())
2190 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2192 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2193 tlv_stream.1.node_id = None;
2195 let mut buffer = Vec::new();
2196 tlv_stream.write(&mut buffer).unwrap();
2198 match InvoiceRequest::try_from(buffer) {
2199 Ok(_) => panic!("expected error"),
2201 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2207 fn fails_parsing_invoice_request_without_signature() {
2208 let mut buffer = Vec::new();
2209 OfferBuilder::new(recipient_pubkey())
2212 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2215 .write(&mut buffer).unwrap();
2217 match InvoiceRequest::try_from(buffer) {
2218 Ok(_) => panic!("expected error"),
2219 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2224 fn fails_parsing_invoice_request_with_invalid_signature() {
2225 let mut invoice_request = OfferBuilder::new(recipient_pubkey())
2228 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2230 .sign(payer_sign).unwrap();
2231 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2232 *last_signature_byte = last_signature_byte.wrapping_add(1);
2234 let mut buffer = Vec::new();
2235 invoice_request.write(&mut buffer).unwrap();
2237 match InvoiceRequest::try_from(buffer) {
2238 Ok(_) => panic!("expected error"),
2240 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2246 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2247 let secp_ctx = Secp256k1::new();
2248 let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2249 let invoice_request = OfferBuilder::new(keys.public_key())
2252 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2254 .sign(|message: &UnsignedInvoiceRequest|
2255 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2259 let mut encoded_invoice_request = Vec::new();
2260 invoice_request.write(&mut encoded_invoice_request).unwrap();
2261 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2262 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2263 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2265 match InvoiceRequest::try_from(encoded_invoice_request) {
2266 Ok(_) => panic!("expected error"),
2267 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2272 fn copies_verified_invoice_request_fields() {
2273 let node_id = recipient_pubkey();
2274 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
2275 let entropy = FixedEntropy {};
2276 let secp_ctx = Secp256k1::new();
2279 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
2280 let offer = OfferBuilder
2281 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
2282 .chain(Network::Testnet)
2284 .supported_quantity(Quantity::Unbounded)
2286 assert_eq!(offer.signing_pubkey(), Some(node_id));
2288 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2289 .chain(Network::Testnet).unwrap()
2290 .quantity(1).unwrap()
2291 .payer_note("0".repeat(PAYER_NOTE_LIMIT * 2))
2293 .sign(payer_sign).unwrap();
2294 match invoice_request.verify(&expanded_key, &secp_ctx) {
2295 Ok(invoice_request) => {
2296 let fields = invoice_request.fields();
2297 assert_eq!(invoice_request.offer_id, offer.id());
2300 InvoiceRequestFields {
2301 payer_id: payer_pubkey(),
2303 payer_note_truncated: Some(UntrustedString("0".repeat(PAYER_NOTE_LIMIT))),
2307 let mut buffer = Vec::new();
2308 fields.write(&mut buffer).unwrap();
2310 let deserialized_fields: InvoiceRequestFields =
2311 Readable::read(&mut buffer.as_slice()).unwrap();
2312 assert_eq!(deserialized_fields, fields);
2314 Err(_) => panic!("unexpected error"),