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 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::constants::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::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.
490 pub struct UnsignedInvoiceRequest {
492 contents: InvoiceRequestContents,
493 tagged_hash: TaggedHash,
496 /// A function for signing an [`UnsignedInvoiceRequest`].
497 pub trait SignInvoiceRequestFn {
498 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
499 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()>;
502 impl<F> SignInvoiceRequestFn for F
504 F: Fn(&UnsignedInvoiceRequest) -> Result<Signature, ()>,
506 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
511 impl<F> SignFn<UnsignedInvoiceRequest> for F
513 F: SignInvoiceRequestFn,
515 fn sign(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
516 self.sign_invoice_request(message)
520 impl UnsignedInvoiceRequest {
521 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
522 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
523 // unknown TLV records, which are not stored in `OfferContents`.
524 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
525 contents.as_tlv_stream();
526 let offer_bytes = WithoutLength(&offer.bytes);
527 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
529 let mut bytes = Vec::new();
530 unsigned_tlv_stream.write(&mut bytes).unwrap();
532 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
534 Self { bytes, contents, tagged_hash }
537 /// Returns the [`TaggedHash`] of the invoice to sign.
538 pub fn tagged_hash(&self) -> &TaggedHash {
543 macro_rules! unsigned_invoice_request_sign_method { (
544 $self: ident, $self_type: ty $(, $self_mut: tt)?
546 /// Signs the [`TaggedHash`] of the invoice request using the given function.
548 /// Note: The hash computation may have included unknown, odd TLV records.
549 pub fn sign<F: SignInvoiceRequestFn>(
550 $($self_mut)* $self: $self_type, sign: F
551 ) -> Result<InvoiceRequest, SignError> {
552 let pubkey = $self.contents.payer_id;
553 let signature = merkle::sign_message(sign, &$self, pubkey)?;
555 // Append the signature TLV record to the bytes.
556 let signature_tlv_stream = SignatureTlvStreamRef {
557 signature: Some(&signature),
559 signature_tlv_stream.write(&mut $self.bytes).unwrap();
562 #[cfg(not(c_bindings))]
565 bytes: $self.bytes.clone(),
566 #[cfg(not(c_bindings))]
567 contents: $self.contents,
569 contents: $self.contents.clone(),
575 #[cfg(not(c_bindings))]
576 impl UnsignedInvoiceRequest {
577 unsigned_invoice_request_sign_method!(self, Self, mut);
581 impl UnsignedInvoiceRequest {
582 unsigned_invoice_request_sign_method!(self, &mut Self);
585 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
586 fn as_ref(&self) -> &TaggedHash {
591 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
593 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
594 /// specifies these such that its recipient can send an invoice for payment.
596 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
597 /// [`Offer`]: crate::offers::offer::Offer
598 #[derive(Clone, Debug)]
599 #[cfg_attr(test, derive(PartialEq))]
600 pub struct InvoiceRequest {
601 pub(super) bytes: Vec<u8>,
602 pub(super) contents: InvoiceRequestContents,
603 signature: Signature,
606 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
607 /// ways to respond depending on whether the signing keys were derived.
608 #[derive(Clone, Debug)]
609 pub struct VerifiedInvoiceRequest {
610 /// The identifier of the [`Offer`] for which the [`InvoiceRequest`] was made.
611 pub offer_id: OfferId,
613 /// The verified request.
614 inner: InvoiceRequest,
616 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
618 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
619 /// [`respond_with`].
621 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
622 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
623 /// [`respond_with`]: Self::respond_with
624 pub keys: Option<KeyPair>,
627 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
629 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
630 #[derive(Clone, Debug)]
631 #[cfg_attr(test, derive(PartialEq))]
632 pub(super) struct InvoiceRequestContents {
633 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
637 #[derive(Clone, Debug)]
638 #[cfg_attr(test, derive(PartialEq))]
639 pub(super) struct InvoiceRequestContentsWithoutPayerId {
640 payer: PayerContents,
641 pub(super) offer: OfferContents,
642 chain: Option<ChainHash>,
643 amount_msats: Option<u64>,
644 features: InvoiceRequestFeatures,
645 quantity: Option<u64>,
646 payer_note: Option<String>,
649 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
650 /// An unpredictable series of bytes, typically containing information about the derivation of
653 /// [`payer_id`]: Self::payer_id
654 pub fn payer_metadata(&$self) -> &[u8] {
658 /// A chain from [`Offer::chains`] that the offer is valid for.
659 pub fn chain(&$self) -> ChainHash {
663 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
664 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
666 /// [`chain`]: Self::chain
667 pub fn amount_msats(&$self) -> Option<u64> {
668 $contents.amount_msats()
671 /// Features pertaining to requesting an invoice.
672 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
673 &$contents.features()
676 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
677 pub fn quantity(&$self) -> Option<u64> {
681 /// A possibly transient pubkey used to sign the invoice request.
682 pub fn payer_id(&$self) -> PublicKey {
686 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
688 pub fn payer_note(&$self) -> Option<PrintableString> {
689 $contents.payer_note()
693 impl UnsignedInvoiceRequest {
694 offer_accessors!(self, self.contents.inner.offer);
695 invoice_request_accessors!(self, self.contents);
698 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
699 $self: ident, $contents: expr, $builder: ty
701 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
702 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
704 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
705 /// creation time is used for the `created_at` parameter.
707 /// [`Duration`]: core::time::Duration
708 #[cfg(feature = "std")]
710 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
711 ) -> Result<$builder, Bolt12SemanticError> {
712 let created_at = std::time::SystemTime::now()
713 .duration_since(std::time::SystemTime::UNIX_EPOCH)
714 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
716 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
719 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
721 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
722 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
723 /// where [`std::time::SystemTime`] is not available.
725 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
728 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
729 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
730 /// a preference. Note, however, that any privacy is lost if a public node id was used for
731 /// [`Offer::signing_pubkey`].
733 /// Errors if the request contains unknown required features.
737 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
738 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
740 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
741 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
742 pub fn respond_with_no_std(
743 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
744 created_at: core::time::Duration
745 ) -> Result<$builder, Bolt12SemanticError> {
746 if $contents.invoice_request_features().requires_unknown_bits() {
747 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
750 let signing_pubkey = match $contents.contents.inner.offer.signing_pubkey() {
751 Some(signing_pubkey) => signing_pubkey,
752 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
755 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
759 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
760 /// Verifies that the request was for an offer created using the given key. Returns the verified
761 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
762 /// if they could be extracted from the metadata.
764 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
766 #[cfg(not(c_bindings))]
767 T: secp256k1::Signing
769 $self: $self_type, key: &ExpandedKey,
770 #[cfg(not(c_bindings))]
771 secp_ctx: &Secp256k1<T>,
773 secp_ctx: &Secp256k1<secp256k1::All>,
774 ) -> Result<VerifiedInvoiceRequest, ()> {
775 let (offer_id, keys) = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
776 Ok(VerifiedInvoiceRequest {
778 #[cfg(not(c_bindings))]
781 inner: $self.clone(),
788 #[cfg(not(c_bindings))]
789 impl InvoiceRequest {
790 offer_accessors!(self, self.contents.inner.offer);
791 invoice_request_accessors!(self, self.contents);
792 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
793 invoice_request_verify_method!(self, Self);
797 impl InvoiceRequest {
798 offer_accessors!(self, self.contents.inner.offer);
799 invoice_request_accessors!(self, self.contents);
800 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
801 invoice_request_verify_method!(self, &Self);
804 impl InvoiceRequest {
805 /// Signature of the invoice request using [`payer_id`].
807 /// [`payer_id`]: Self::payer_id
808 pub fn signature(&self) -> Signature {
812 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
813 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
814 self.contents.as_tlv_stream();
815 let signature_tlv_stream = SignatureTlvStreamRef {
816 signature: Some(&self.signature),
818 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
822 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
823 $self: ident, $contents: expr, $builder: ty
825 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
826 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
827 /// the same [`ExpandedKey`] as the one used to create the offer.
829 /// See [`InvoiceRequest::respond_with`] for further details.
831 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
832 #[cfg(feature = "std")]
833 pub fn respond_using_derived_keys(
834 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
835 ) -> Result<$builder, Bolt12SemanticError> {
836 let created_at = std::time::SystemTime::now()
837 .duration_since(std::time::SystemTime::UNIX_EPOCH)
838 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
840 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
843 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
844 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
845 /// the same [`ExpandedKey`] as the one used to create the offer.
847 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
849 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
850 pub fn respond_using_derived_keys_no_std(
851 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
852 created_at: core::time::Duration
853 ) -> Result<$builder, Bolt12SemanticError> {
854 if $self.inner.invoice_request_features().requires_unknown_bits() {
855 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
858 let keys = match $self.keys {
859 None => return Err(Bolt12SemanticError::InvalidMetadata),
863 match $contents.contents.inner.offer.signing_pubkey() {
864 Some(signing_pubkey) => debug_assert_eq!(signing_pubkey, keys.public_key()),
865 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
868 <$builder>::for_offer_using_keys(
869 &$self.inner, payment_paths, created_at, payment_hash, keys
874 impl VerifiedInvoiceRequest {
875 offer_accessors!(self, self.inner.contents.inner.offer);
876 invoice_request_accessors!(self, self.inner.contents);
877 #[cfg(not(c_bindings))]
878 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
880 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
881 #[cfg(not(c_bindings))]
882 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
884 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
886 pub(crate) fn fields(&self) -> InvoiceRequestFields {
887 let InvoiceRequestContents {
889 inner: InvoiceRequestContentsWithoutPayerId {
890 payer: _, offer: _, chain: _, amount_msats, features, quantity, payer_note
892 } = &self.inner.contents;
894 InvoiceRequestFields {
896 amount_msats: *amount_msats,
897 features: features.clone(),
899 payer_note_truncated: payer_note.clone()
900 .map(|mut s| { s.truncate(PAYER_NOTE_LIMIT); UntrustedString(s) }),
905 impl InvoiceRequestContents {
906 pub(super) fn metadata(&self) -> &[u8] {
907 self.inner.metadata()
910 pub(super) fn derives_keys(&self) -> bool {
911 self.inner.payer.0.derives_payer_keys()
914 pub(super) fn chain(&self) -> ChainHash {
918 pub(super) fn amount_msats(&self) -> Option<u64> {
919 self.inner.amount_msats
922 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
926 pub(super) fn quantity(&self) -> Option<u64> {
930 pub(super) fn payer_id(&self) -> PublicKey {
934 pub(super) fn payer_note(&self) -> Option<PrintableString> {
935 self.inner.payer_note.as_ref()
936 .map(|payer_note| PrintableString(payer_note.as_str()))
939 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
940 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
941 invoice_request.payer_id = Some(&self.payer_id);
942 (payer, offer, invoice_request)
946 impl InvoiceRequestContentsWithoutPayerId {
947 pub(super) fn metadata(&self) -> &[u8] {
948 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
951 pub(super) fn chain(&self) -> ChainHash {
952 self.chain.unwrap_or_else(|| self.offer.implied_chain())
955 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
956 let payer = PayerTlvStreamRef {
957 metadata: self.payer.0.as_bytes(),
960 let offer = self.offer.as_tlv_stream();
963 if self.features == InvoiceRequestFeatures::empty() { None }
964 else { Some(&self.features) }
967 let invoice_request = InvoiceRequestTlvStreamRef {
968 chain: self.chain.as_ref(),
969 amount: self.amount_msats,
971 quantity: self.quantity,
973 payer_note: self.payer_note.as_ref(),
976 (payer, offer, invoice_request)
980 impl Writeable for UnsignedInvoiceRequest {
981 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
982 WithoutLength(&self.bytes).write(writer)
986 impl Writeable for InvoiceRequest {
987 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
988 WithoutLength(&self.bytes).write(writer)
992 impl Writeable for InvoiceRequestContents {
993 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
994 self.as_tlv_stream().write(writer)
998 /// Valid type range for invoice_request TLV records.
999 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
1001 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
1003 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
1004 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
1006 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
1007 (80, chain: ChainHash),
1008 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
1009 (84, features: (InvoiceRequestFeatures, WithoutLength)),
1010 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
1011 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
1012 (89, payer_note: (String, WithoutLength)),
1015 type FullInvoiceRequestTlvStream =
1016 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
1018 type FullInvoiceRequestTlvStreamRef<'a> = (
1019 PayerTlvStreamRef<'a>,
1020 OfferTlvStreamRef<'a>,
1021 InvoiceRequestTlvStreamRef<'a>,
1022 SignatureTlvStreamRef<'a>,
1025 impl SeekReadable for FullInvoiceRequestTlvStream {
1026 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1027 let payer = SeekReadable::read(r)?;
1028 let offer = SeekReadable::read(r)?;
1029 let invoice_request = SeekReadable::read(r)?;
1030 let signature = SeekReadable::read(r)?;
1032 Ok((payer, offer, invoice_request, signature))
1036 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1038 type PartialInvoiceRequestTlvStreamRef<'a> = (
1039 PayerTlvStreamRef<'a>,
1040 OfferTlvStreamRef<'a>,
1041 InvoiceRequestTlvStreamRef<'a>,
1044 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1045 type Error = Bolt12ParseError;
1047 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1048 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1049 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1051 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1053 let contents = InvoiceRequestContents::try_from(
1054 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1057 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1059 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1063 impl TryFrom<Vec<u8>> for InvoiceRequest {
1064 type Error = Bolt12ParseError;
1066 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1067 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1068 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1070 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1071 SignatureTlvStream { signature },
1073 let contents = InvoiceRequestContents::try_from(
1074 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1077 let signature = match signature {
1078 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1079 Some(signature) => signature,
1081 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1082 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1084 Ok(InvoiceRequest { bytes, contents, signature })
1088 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1089 type Error = Bolt12SemanticError;
1091 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1093 PayerTlvStream { metadata },
1095 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1098 let payer = match metadata {
1099 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1100 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1102 let offer = OfferContents::try_from(offer_tlv_stream)?;
1104 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1105 return Err(Bolt12SemanticError::UnsupportedChain);
1108 if offer.amount().is_none() && amount.is_none() {
1109 return Err(Bolt12SemanticError::MissingAmount);
1112 offer.check_quantity(quantity)?;
1113 offer.check_amount_msats_for_quantity(amount, quantity)?;
1115 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1117 let payer_id = match payer_id {
1118 None => return Err(Bolt12SemanticError::MissingPayerId),
1119 Some(payer_id) => payer_id,
1122 Ok(InvoiceRequestContents {
1123 inner: InvoiceRequestContentsWithoutPayerId {
1124 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1131 /// Fields sent in an [`InvoiceRequest`] message to include in [`PaymentContext::Bolt12Offer`].
1133 /// [`PaymentContext::Bolt12Offer`]: crate::blinded_path::payment::PaymentContext::Bolt12Offer
1134 #[derive(Clone, Debug, Eq, PartialEq)]
1135 pub struct InvoiceRequestFields {
1136 /// A possibly transient pubkey used to sign the invoice request.
1137 pub payer_id: PublicKey,
1139 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
1140 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
1142 /// [`chain`]: InvoiceRequest::chain
1143 pub amount_msats: Option<u64>,
1145 /// Features pertaining to requesting an invoice.
1146 pub features: InvoiceRequestFeatures,
1148 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
1149 pub quantity: Option<u64>,
1151 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
1152 /// response. Truncated to [`PAYER_NOTE_LIMIT`] characters.
1153 pub payer_note_truncated: Option<UntrustedString>,
1156 /// The maximum number of characters included in [`InvoiceRequestFields::payer_note_truncated`].
1157 pub const PAYER_NOTE_LIMIT: usize = 512;
1159 impl Writeable for InvoiceRequestFields {
1160 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1161 write_tlv_fields!(writer, {
1162 (0, self.payer_id, required),
1163 (2, self.amount_msats.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1164 (4, WithoutLength(&self.features), required),
1165 (6, self.quantity.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1166 (8, self.payer_note_truncated.as_ref().map(|s| WithoutLength(&s.0)), option),
1172 impl Readable for InvoiceRequestFields {
1173 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1174 _init_and_read_len_prefixed_tlv_fields!(reader, {
1175 (0, payer_id, required),
1176 (2, amount_msats, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1177 (4, features, (option, encoding: (InvoiceRequestFeatures, WithoutLength))),
1178 (6, quantity, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1179 (8, payer_note_truncated, (option, encoding: (String, WithoutLength))),
1181 let features = features.unwrap_or(InvoiceRequestFeatures::empty());
1183 Ok(InvoiceRequestFields {
1184 payer_id: payer_id.0.unwrap(), amount_msats, features, quantity,
1185 payer_note_truncated: payer_note_truncated.map(|s| UntrustedString(s)),
1192 use super::{InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest};
1194 use bitcoin::blockdata::constants::ChainHash;
1195 use bitcoin::network::constants::Network;
1196 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1197 use core::num::NonZeroU64;
1198 #[cfg(feature = "std")]
1199 use core::time::Duration;
1200 use crate::sign::KeyMaterial;
1201 use crate::ln::channelmanager::PaymentId;
1202 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1203 use crate::ln::inbound_payment::ExpandedKey;
1204 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1205 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1206 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1207 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1208 #[cfg(not(c_bindings))]
1210 crate::offers::offer::OfferBuilder,
1214 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1216 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1217 use crate::offers::payer::PayerTlvStreamRef;
1218 use crate::offers::test_utils::*;
1219 use crate::util::ser::{BigSize, Readable, Writeable};
1220 use crate::util::string::{PrintableString, UntrustedString};
1223 fn builds_invoice_request_with_defaults() {
1224 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1227 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1230 let mut unsigned_invoice_request = unsigned_invoice_request;
1232 let mut buffer = Vec::new();
1233 unsigned_invoice_request.write(&mut buffer).unwrap();
1235 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1236 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1237 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1238 assert_eq!(unsigned_invoice_request.metadata(), None);
1239 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1240 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1241 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1242 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1243 assert_eq!(unsigned_invoice_request.paths(), &[]);
1244 assert_eq!(unsigned_invoice_request.issuer(), None);
1245 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1246 assert_eq!(unsigned_invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1247 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1248 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1249 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1250 assert_eq!(unsigned_invoice_request.quantity(), None);
1251 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1252 assert_eq!(unsigned_invoice_request.payer_note(), None);
1254 match UnsignedInvoiceRequest::try_from(buffer) {
1255 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1257 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1258 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1262 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1264 let mut buffer = Vec::new();
1265 invoice_request.write(&mut buffer).unwrap();
1267 assert_eq!(invoice_request.bytes, buffer.as_slice());
1268 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1269 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1270 assert_eq!(invoice_request.metadata(), None);
1271 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1272 assert_eq!(invoice_request.description(), PrintableString("foo"));
1273 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1274 assert_eq!(invoice_request.absolute_expiry(), None);
1275 assert_eq!(invoice_request.paths(), &[]);
1276 assert_eq!(invoice_request.issuer(), None);
1277 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1278 assert_eq!(invoice_request.signing_pubkey(), Some(recipient_pubkey()));
1279 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1280 assert_eq!(invoice_request.amount_msats(), None);
1281 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1282 assert_eq!(invoice_request.quantity(), None);
1283 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1284 assert_eq!(invoice_request.payer_note(), None);
1286 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1287 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1290 invoice_request.as_tlv_stream(),
1292 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1298 description: Some(&String::from("foo")),
1300 absolute_expiry: None,
1304 node_id: Some(&recipient_pubkey()),
1306 InvoiceRequestTlvStreamRef {
1311 payer_id: Some(&payer_pubkey()),
1314 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1318 if let Err(e) = InvoiceRequest::try_from(buffer) {
1319 panic!("error parsing invoice request: {:?}", e);
1323 #[cfg(feature = "std")]
1325 fn builds_invoice_request_from_offer_with_expiration() {
1326 let future_expiry = Duration::from_secs(u64::max_value());
1327 let past_expiry = Duration::from_secs(0);
1329 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1331 .absolute_expiry(future_expiry)
1333 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1336 panic!("error building invoice_request: {:?}", e);
1339 match OfferBuilder::new("foo".into(), recipient_pubkey())
1341 .absolute_expiry(past_expiry)
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1346 Ok(_) => panic!("expected error"),
1347 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1352 fn builds_invoice_request_with_derived_metadata() {
1353 let payer_id = payer_pubkey();
1354 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1355 let entropy = FixedEntropy {};
1356 let secp_ctx = Secp256k1::new();
1357 let payment_id = PaymentId([1; 32]);
1359 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1362 let invoice_request = offer
1363 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1366 .sign(payer_sign).unwrap();
1367 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1369 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1372 .sign(recipient_sign).unwrap();
1373 match invoice.verify(&expanded_key, &secp_ctx) {
1374 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1375 Err(()) => panic!("verification failed"),
1378 // Fails verification with altered fields
1380 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1381 mut invoice_tlv_stream, mut signature_tlv_stream
1382 ) = invoice.as_tlv_stream();
1383 invoice_request_tlv_stream.amount = Some(2000);
1384 invoice_tlv_stream.amount = Some(2000);
1387 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1388 let mut bytes = Vec::new();
1389 tlv_stream.write(&mut bytes).unwrap();
1391 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1392 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1393 signature_tlv_stream.signature = Some(&signature);
1395 let mut encoded_invoice = bytes;
1396 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1398 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1399 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1401 // Fails verification with altered metadata
1403 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1404 mut signature_tlv_stream
1405 ) = invoice.as_tlv_stream();
1406 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1407 payer_tlv_stream.metadata = Some(&metadata);
1410 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1411 let mut bytes = Vec::new();
1412 tlv_stream.write(&mut bytes).unwrap();
1414 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1415 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1416 signature_tlv_stream.signature = Some(&signature);
1418 let mut encoded_invoice = bytes;
1419 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1421 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1422 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1426 fn builds_invoice_request_with_derived_payer_id() {
1427 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1428 let entropy = FixedEntropy {};
1429 let secp_ctx = Secp256k1::new();
1430 let payment_id = PaymentId([1; 32]);
1432 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1435 let invoice_request = offer
1436 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1441 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1444 .sign(recipient_sign).unwrap();
1445 match invoice.verify(&expanded_key, &secp_ctx) {
1446 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1447 Err(()) => panic!("verification failed"),
1450 // Fails verification with altered fields
1452 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1453 mut invoice_tlv_stream, mut signature_tlv_stream
1454 ) = invoice.as_tlv_stream();
1455 invoice_request_tlv_stream.amount = Some(2000);
1456 invoice_tlv_stream.amount = Some(2000);
1459 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1460 let mut bytes = Vec::new();
1461 tlv_stream.write(&mut bytes).unwrap();
1463 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1464 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1465 signature_tlv_stream.signature = Some(&signature);
1467 let mut encoded_invoice = bytes;
1468 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1470 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1471 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1473 // Fails verification with altered payer id
1475 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1476 mut signature_tlv_stream
1477 ) = invoice.as_tlv_stream();
1478 let payer_id = pubkey(1);
1479 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1482 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1483 let mut bytes = Vec::new();
1484 tlv_stream.write(&mut bytes).unwrap();
1486 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1487 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1488 signature_tlv_stream.signature = Some(&signature);
1490 let mut encoded_invoice = bytes;
1491 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1493 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1494 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1498 fn builds_invoice_request_with_chain() {
1499 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1500 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1502 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1505 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 .chain(Network::Bitcoin).unwrap()
1508 .sign(payer_sign).unwrap();
1509 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1510 assert_eq!(invoice_request.chain(), mainnet);
1511 assert_eq!(tlv_stream.chain, None);
1513 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1515 .chain(Network::Testnet)
1517 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1518 .chain(Network::Testnet).unwrap()
1520 .sign(payer_sign).unwrap();
1521 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1522 assert_eq!(invoice_request.chain(), testnet);
1523 assert_eq!(tlv_stream.chain, Some(&testnet));
1525 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1527 .chain(Network::Bitcoin)
1528 .chain(Network::Testnet)
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531 .chain(Network::Bitcoin).unwrap()
1533 .sign(payer_sign).unwrap();
1534 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1535 assert_eq!(invoice_request.chain(), mainnet);
1536 assert_eq!(tlv_stream.chain, None);
1538 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1540 .chain(Network::Bitcoin)
1541 .chain(Network::Testnet)
1543 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1544 .chain(Network::Bitcoin).unwrap()
1545 .chain(Network::Testnet).unwrap()
1547 .sign(payer_sign).unwrap();
1548 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1549 assert_eq!(invoice_request.chain(), testnet);
1550 assert_eq!(tlv_stream.chain, Some(&testnet));
1552 match OfferBuilder::new("foo".into(), recipient_pubkey())
1554 .chain(Network::Testnet)
1556 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1557 .chain(Network::Bitcoin)
1559 Ok(_) => panic!("expected error"),
1560 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1563 match OfferBuilder::new("foo".into(), recipient_pubkey())
1565 .chain(Network::Testnet)
1567 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1570 Ok(_) => panic!("expected error"),
1571 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1576 fn builds_invoice_request_with_amount() {
1577 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1581 .amount_msats(1000).unwrap()
1583 .sign(payer_sign).unwrap();
1584 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1585 assert_eq!(invoice_request.amount_msats(), Some(1000));
1586 assert_eq!(tlv_stream.amount, Some(1000));
1588 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1591 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1592 .amount_msats(1001).unwrap()
1593 .amount_msats(1000).unwrap()
1595 .sign(payer_sign).unwrap();
1596 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1597 assert_eq!(invoice_request.amount_msats(), Some(1000));
1598 assert_eq!(tlv_stream.amount, Some(1000));
1600 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1603 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1604 .amount_msats(1001).unwrap()
1606 .sign(payer_sign).unwrap();
1607 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1608 assert_eq!(invoice_request.amount_msats(), Some(1001));
1609 assert_eq!(tlv_stream.amount, Some(1001));
1611 match OfferBuilder::new("foo".into(), recipient_pubkey())
1614 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1617 Ok(_) => panic!("expected error"),
1618 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1621 match OfferBuilder::new("foo".into(), recipient_pubkey())
1623 .supported_quantity(Quantity::Unbounded)
1625 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 .quantity(2).unwrap()
1629 Ok(_) => panic!("expected error"),
1630 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1633 match OfferBuilder::new("foo".into(), recipient_pubkey())
1636 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1637 .amount_msats(MAX_VALUE_MSAT + 1)
1639 Ok(_) => panic!("expected error"),
1640 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1643 match OfferBuilder::new("foo".into(), recipient_pubkey())
1645 .supported_quantity(Quantity::Unbounded)
1647 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1648 .amount_msats(1000).unwrap()
1649 .quantity(2).unwrap()
1652 Ok(_) => panic!("expected error"),
1653 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1656 match OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 Ok(_) => panic!("expected error"),
1662 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1665 match OfferBuilder::new("foo".into(), recipient_pubkey())
1667 .supported_quantity(Quantity::Unbounded)
1669 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1670 .quantity(u64::max_value()).unwrap()
1673 Ok(_) => panic!("expected error"),
1674 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1679 fn builds_invoice_request_with_features() {
1680 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1683 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1684 .features_unchecked(InvoiceRequestFeatures::unknown())
1686 .sign(payer_sign).unwrap();
1687 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1688 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1689 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1691 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1694 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1695 .features_unchecked(InvoiceRequestFeatures::unknown())
1696 .features_unchecked(InvoiceRequestFeatures::empty())
1698 .sign(payer_sign).unwrap();
1699 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1700 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1701 assert_eq!(tlv_stream.features, None);
1705 fn builds_invoice_request_with_quantity() {
1706 let one = NonZeroU64::new(1).unwrap();
1707 let ten = NonZeroU64::new(10).unwrap();
1709 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1711 .supported_quantity(Quantity::One)
1713 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715 .sign(payer_sign).unwrap();
1716 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1717 assert_eq!(invoice_request.quantity(), None);
1718 assert_eq!(tlv_stream.quantity, None);
1720 match OfferBuilder::new("foo".into(), recipient_pubkey())
1722 .supported_quantity(Quantity::One)
1724 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1725 .amount_msats(2_000).unwrap()
1728 Ok(_) => panic!("expected error"),
1729 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1732 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1734 .supported_quantity(Quantity::Bounded(ten))
1736 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1737 .amount_msats(10_000).unwrap()
1738 .quantity(10).unwrap()
1740 .sign(payer_sign).unwrap();
1741 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1742 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1743 assert_eq!(tlv_stream.amount, Some(10_000));
1745 match OfferBuilder::new("foo".into(), recipient_pubkey())
1747 .supported_quantity(Quantity::Bounded(ten))
1749 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750 .amount_msats(11_000).unwrap()
1753 Ok(_) => panic!("expected error"),
1754 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1757 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1759 .supported_quantity(Quantity::Unbounded)
1761 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1762 .amount_msats(2_000).unwrap()
1763 .quantity(2).unwrap()
1765 .sign(payer_sign).unwrap();
1766 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1767 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1768 assert_eq!(tlv_stream.amount, Some(2_000));
1770 match OfferBuilder::new("foo".into(), recipient_pubkey())
1772 .supported_quantity(Quantity::Unbounded)
1774 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1777 Ok(_) => panic!("expected error"),
1778 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1781 match OfferBuilder::new("foo".into(), recipient_pubkey())
1783 .supported_quantity(Quantity::Bounded(one))
1785 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1788 Ok(_) => panic!("expected error"),
1789 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1794 fn builds_invoice_request_with_payer_note() {
1795 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1798 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1799 .payer_note("bar".into())
1801 .sign(payer_sign).unwrap();
1802 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1803 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1804 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1806 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1809 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1810 .payer_note("bar".into())
1811 .payer_note("baz".into())
1813 .sign(payer_sign).unwrap();
1814 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1815 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1816 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1820 fn fails_signing_invoice_request() {
1821 match OfferBuilder::new("foo".into(), recipient_pubkey())
1824 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1828 Ok(_) => panic!("expected error"),
1829 Err(e) => assert_eq!(e, SignError::Signing),
1832 match OfferBuilder::new("foo".into(), recipient_pubkey())
1835 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1837 .sign(recipient_sign)
1839 Ok(_) => panic!("expected error"),
1840 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1845 fn fails_responding_with_unknown_required_features() {
1846 match OfferBuilder::new("foo".into(), recipient_pubkey())
1849 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1850 .features_unchecked(InvoiceRequestFeatures::unknown())
1852 .sign(payer_sign).unwrap()
1853 .respond_with_no_std(payment_paths(), payment_hash(), now())
1855 Ok(_) => panic!("expected error"),
1856 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1861 fn parses_invoice_request_with_metadata() {
1862 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1865 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1867 .sign(payer_sign).unwrap();
1869 let mut buffer = Vec::new();
1870 invoice_request.write(&mut buffer).unwrap();
1872 if let Err(e) = InvoiceRequest::try_from(buffer) {
1873 panic!("error parsing invoice_request: {:?}", e);
1878 fn parses_invoice_request_with_chain() {
1879 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1882 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1883 .chain(Network::Bitcoin).unwrap()
1885 .sign(payer_sign).unwrap();
1887 let mut buffer = Vec::new();
1888 invoice_request.write(&mut buffer).unwrap();
1890 if let Err(e) = InvoiceRequest::try_from(buffer) {
1891 panic!("error parsing invoice_request: {:?}", e);
1894 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1897 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1898 .chain_unchecked(Network::Testnet)
1900 .sign(payer_sign).unwrap();
1902 let mut buffer = Vec::new();
1903 invoice_request.write(&mut buffer).unwrap();
1905 match InvoiceRequest::try_from(buffer) {
1906 Ok(_) => panic!("expected error"),
1907 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1912 fn parses_invoice_request_with_amount() {
1913 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1916 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1918 .sign(payer_sign).unwrap();
1920 let mut buffer = Vec::new();
1921 invoice_request.write(&mut buffer).unwrap();
1923 if let Err(e) = InvoiceRequest::try_from(buffer) {
1924 panic!("error parsing invoice_request: {:?}", e);
1927 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1929 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1930 .amount_msats(1000).unwrap()
1932 .sign(payer_sign).unwrap();
1934 let mut buffer = Vec::new();
1935 invoice_request.write(&mut buffer).unwrap();
1937 if let Err(e) = InvoiceRequest::try_from(buffer) {
1938 panic!("error parsing invoice_request: {:?}", e);
1941 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1943 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1945 .sign(payer_sign).unwrap();
1947 let mut buffer = Vec::new();
1948 invoice_request.write(&mut buffer).unwrap();
1950 match InvoiceRequest::try_from(buffer) {
1951 Ok(_) => panic!("expected error"),
1952 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1955 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1958 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1959 .amount_msats_unchecked(999)
1961 .sign(payer_sign).unwrap();
1963 let mut buffer = Vec::new();
1964 invoice_request.write(&mut buffer).unwrap();
1966 match InvoiceRequest::try_from(buffer) {
1967 Ok(_) => panic!("expected error"),
1968 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1971 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1972 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1974 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1976 .sign(payer_sign).unwrap();
1978 let mut buffer = Vec::new();
1979 invoice_request.write(&mut buffer).unwrap();
1981 match InvoiceRequest::try_from(buffer) {
1982 Ok(_) => panic!("expected error"),
1984 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1988 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1990 .supported_quantity(Quantity::Unbounded)
1992 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1993 .quantity(u64::max_value()).unwrap()
1995 .sign(payer_sign).unwrap();
1997 let mut buffer = Vec::new();
1998 invoice_request.write(&mut buffer).unwrap();
2000 match InvoiceRequest::try_from(buffer) {
2001 Ok(_) => panic!("expected error"),
2002 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
2007 fn parses_invoice_request_with_quantity() {
2008 let one = NonZeroU64::new(1).unwrap();
2009 let ten = NonZeroU64::new(10).unwrap();
2011 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2013 .supported_quantity(Quantity::One)
2015 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2017 .sign(payer_sign).unwrap();
2019 let mut buffer = Vec::new();
2020 invoice_request.write(&mut buffer).unwrap();
2022 if let Err(e) = InvoiceRequest::try_from(buffer) {
2023 panic!("error parsing invoice_request: {:?}", e);
2026 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2028 .supported_quantity(Quantity::One)
2030 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2031 .amount_msats(2_000).unwrap()
2032 .quantity_unchecked(2)
2034 .sign(payer_sign).unwrap();
2036 let mut buffer = Vec::new();
2037 invoice_request.write(&mut buffer).unwrap();
2039 match InvoiceRequest::try_from(buffer) {
2040 Ok(_) => panic!("expected error"),
2042 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
2046 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2048 .supported_quantity(Quantity::Bounded(ten))
2050 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2051 .amount_msats(10_000).unwrap()
2052 .quantity(10).unwrap()
2054 .sign(payer_sign).unwrap();
2056 let mut buffer = Vec::new();
2057 invoice_request.write(&mut buffer).unwrap();
2059 if let Err(e) = InvoiceRequest::try_from(buffer) {
2060 panic!("error parsing invoice_request: {:?}", e);
2063 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2065 .supported_quantity(Quantity::Bounded(ten))
2067 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2068 .amount_msats(11_000).unwrap()
2069 .quantity_unchecked(11)
2071 .sign(payer_sign).unwrap();
2073 let mut buffer = Vec::new();
2074 invoice_request.write(&mut buffer).unwrap();
2076 match InvoiceRequest::try_from(buffer) {
2077 Ok(_) => panic!("expected error"),
2078 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
2081 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2083 .supported_quantity(Quantity::Unbounded)
2085 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2086 .amount_msats(2_000).unwrap()
2087 .quantity(2).unwrap()
2089 .sign(payer_sign).unwrap();
2091 let mut buffer = Vec::new();
2092 invoice_request.write(&mut buffer).unwrap();
2094 if let Err(e) = InvoiceRequest::try_from(buffer) {
2095 panic!("error parsing invoice_request: {:?}", e);
2098 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2100 .supported_quantity(Quantity::Unbounded)
2102 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2104 .sign(payer_sign).unwrap();
2106 let mut buffer = Vec::new();
2107 invoice_request.write(&mut buffer).unwrap();
2109 match InvoiceRequest::try_from(buffer) {
2110 Ok(_) => panic!("expected error"),
2111 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2114 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2116 .supported_quantity(Quantity::Bounded(one))
2118 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2120 .sign(payer_sign).unwrap();
2122 let mut buffer = Vec::new();
2123 invoice_request.write(&mut buffer).unwrap();
2125 match InvoiceRequest::try_from(buffer) {
2126 Ok(_) => panic!("expected error"),
2127 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2132 fn fails_parsing_invoice_request_without_metadata() {
2133 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2136 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2138 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2139 tlv_stream.0.metadata = None;
2141 let mut buffer = Vec::new();
2142 tlv_stream.write(&mut buffer).unwrap();
2144 match InvoiceRequest::try_from(buffer) {
2145 Ok(_) => panic!("expected error"),
2147 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2153 fn fails_parsing_invoice_request_without_payer_id() {
2154 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2157 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2159 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2160 tlv_stream.2.payer_id = None;
2162 let mut buffer = Vec::new();
2163 tlv_stream.write(&mut buffer).unwrap();
2165 match InvoiceRequest::try_from(buffer) {
2166 Ok(_) => panic!("expected error"),
2167 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2172 fn fails_parsing_invoice_request_without_node_id() {
2173 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2176 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2178 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2179 tlv_stream.1.node_id = None;
2181 let mut buffer = Vec::new();
2182 tlv_stream.write(&mut buffer).unwrap();
2184 match InvoiceRequest::try_from(buffer) {
2185 Ok(_) => panic!("expected error"),
2187 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2193 fn fails_parsing_invoice_request_without_signature() {
2194 let mut buffer = Vec::new();
2195 OfferBuilder::new("foo".into(), recipient_pubkey())
2198 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2201 .write(&mut buffer).unwrap();
2203 match InvoiceRequest::try_from(buffer) {
2204 Ok(_) => panic!("expected error"),
2205 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2210 fn fails_parsing_invoice_request_with_invalid_signature() {
2211 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2214 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2216 .sign(payer_sign).unwrap();
2217 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2218 *last_signature_byte = last_signature_byte.wrapping_add(1);
2220 let mut buffer = Vec::new();
2221 invoice_request.write(&mut buffer).unwrap();
2223 match InvoiceRequest::try_from(buffer) {
2224 Ok(_) => panic!("expected error"),
2226 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2232 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2233 let secp_ctx = Secp256k1::new();
2234 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2235 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2238 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2240 .sign(|message: &UnsignedInvoiceRequest|
2241 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2245 let mut encoded_invoice_request = Vec::new();
2246 invoice_request.write(&mut encoded_invoice_request).unwrap();
2247 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2248 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2249 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2251 match InvoiceRequest::try_from(encoded_invoice_request) {
2252 Ok(_) => panic!("expected error"),
2253 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2258 fn copies_verified_invoice_request_fields() {
2259 let desc = "foo".to_string();
2260 let node_id = recipient_pubkey();
2261 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
2262 let entropy = FixedEntropy {};
2263 let secp_ctx = Secp256k1::new();
2266 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
2267 let offer = OfferBuilder
2268 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
2269 .chain(Network::Testnet)
2271 .supported_quantity(Quantity::Unbounded)
2273 assert_eq!(offer.signing_pubkey(), Some(node_id));
2275 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2276 .chain(Network::Testnet).unwrap()
2277 .amount_msats(1001).unwrap()
2278 .quantity(1).unwrap()
2279 .payer_note("0".repeat(PAYER_NOTE_LIMIT * 2))
2281 .sign(payer_sign).unwrap();
2282 match invoice_request.verify(&expanded_key, &secp_ctx) {
2283 Ok(invoice_request) => {
2284 let fields = invoice_request.fields();
2285 assert_eq!(invoice_request.offer_id, offer.id());
2288 InvoiceRequestFields {
2289 payer_id: payer_pubkey(),
2290 amount_msats: Some(1001),
2291 features: InvoiceRequestFeatures::empty(),
2293 payer_note_truncated: Some(UntrustedString("0".repeat(PAYER_NOTE_LIMIT))),
2297 let mut buffer = Vec::new();
2298 fields.write(&mut buffer).unwrap();
2300 let deserialized_fields: InvoiceRequestFields =
2301 Readable::read(&mut buffer.as_slice()).unwrap();
2302 assert_eq!(deserialized_fields, fields);
2304 Err(_) => panic!("unexpected error"),