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, SeekReadable, WithoutLength, Writeable, Writer};
80 use crate::util::string::PrintableString;
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 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash)
754 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
755 /// Verifies that the request was for an offer created using the given key. Returns the verified
756 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
757 /// if they could be extracted from the metadata.
759 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
761 #[cfg(not(c_bindings))]
762 T: secp256k1::Signing
764 $self: $self_type, key: &ExpandedKey,
765 #[cfg(not(c_bindings))]
766 secp_ctx: &Secp256k1<T>,
768 secp_ctx: &Secp256k1<secp256k1::All>,
769 ) -> Result<VerifiedInvoiceRequest, ()> {
770 let (offer_id, keys) = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
771 Ok(VerifiedInvoiceRequest {
773 #[cfg(not(c_bindings))]
776 inner: $self.clone(),
783 #[cfg(not(c_bindings))]
784 impl InvoiceRequest {
785 offer_accessors!(self, self.contents.inner.offer);
786 invoice_request_accessors!(self, self.contents);
787 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
788 invoice_request_verify_method!(self, Self);
792 impl InvoiceRequest {
793 offer_accessors!(self, self.contents.inner.offer);
794 invoice_request_accessors!(self, self.contents);
795 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
796 invoice_request_verify_method!(self, &Self);
799 impl InvoiceRequest {
800 /// Signature of the invoice request using [`payer_id`].
802 /// [`payer_id`]: Self::payer_id
803 pub fn signature(&self) -> Signature {
807 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
808 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
809 self.contents.as_tlv_stream();
810 let signature_tlv_stream = SignatureTlvStreamRef {
811 signature: Some(&self.signature),
813 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
817 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
818 $self: ident, $contents: expr, $builder: ty
820 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
821 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
822 /// the same [`ExpandedKey`] as the one used to create the offer.
824 /// See [`InvoiceRequest::respond_with`] for further details.
826 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
827 #[cfg(feature = "std")]
828 pub fn respond_using_derived_keys(
829 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
830 ) -> Result<$builder, Bolt12SemanticError> {
831 let created_at = std::time::SystemTime::now()
832 .duration_since(std::time::SystemTime::UNIX_EPOCH)
833 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
835 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
838 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
839 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
840 /// the same [`ExpandedKey`] as the one used to create the offer.
842 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
844 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
845 pub fn respond_using_derived_keys_no_std(
846 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
847 created_at: core::time::Duration
848 ) -> Result<$builder, Bolt12SemanticError> {
849 if $self.inner.invoice_request_features().requires_unknown_bits() {
850 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
853 let keys = match $self.keys {
854 None => return Err(Bolt12SemanticError::InvalidMetadata),
858 <$builder>::for_offer_using_keys(
859 &$self.inner, payment_paths, created_at, payment_hash, keys
864 impl VerifiedInvoiceRequest {
865 offer_accessors!(self, self.inner.contents.inner.offer);
866 invoice_request_accessors!(self, self.inner.contents);
867 #[cfg(not(c_bindings))]
868 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
870 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
871 #[cfg(not(c_bindings))]
872 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
874 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
877 impl InvoiceRequestContents {
878 pub(super) fn metadata(&self) -> &[u8] {
879 self.inner.metadata()
882 pub(super) fn derives_keys(&self) -> bool {
883 self.inner.payer.0.derives_payer_keys()
886 pub(super) fn chain(&self) -> ChainHash {
890 pub(super) fn amount_msats(&self) -> Option<u64> {
891 self.inner.amount_msats
894 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
898 pub(super) fn quantity(&self) -> Option<u64> {
902 pub(super) fn payer_id(&self) -> PublicKey {
906 pub(super) fn payer_note(&self) -> Option<PrintableString> {
907 self.inner.payer_note.as_ref()
908 .map(|payer_note| PrintableString(payer_note.as_str()))
911 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
912 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
913 invoice_request.payer_id = Some(&self.payer_id);
914 (payer, offer, invoice_request)
918 impl InvoiceRequestContentsWithoutPayerId {
919 pub(super) fn metadata(&self) -> &[u8] {
920 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
923 pub(super) fn chain(&self) -> ChainHash {
924 self.chain.unwrap_or_else(|| self.offer.implied_chain())
927 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
928 let payer = PayerTlvStreamRef {
929 metadata: self.payer.0.as_bytes(),
932 let offer = self.offer.as_tlv_stream();
935 if self.features == InvoiceRequestFeatures::empty() { None }
936 else { Some(&self.features) }
939 let invoice_request = InvoiceRequestTlvStreamRef {
940 chain: self.chain.as_ref(),
941 amount: self.amount_msats,
943 quantity: self.quantity,
945 payer_note: self.payer_note.as_ref(),
948 (payer, offer, invoice_request)
952 impl Writeable for UnsignedInvoiceRequest {
953 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
954 WithoutLength(&self.bytes).write(writer)
958 impl Writeable for InvoiceRequest {
959 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
960 WithoutLength(&self.bytes).write(writer)
964 impl Writeable for InvoiceRequestContents {
965 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
966 self.as_tlv_stream().write(writer)
970 /// Valid type range for invoice_request TLV records.
971 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
973 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
975 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
976 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
978 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
979 (80, chain: ChainHash),
980 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
981 (84, features: (InvoiceRequestFeatures, WithoutLength)),
982 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
983 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
984 (89, payer_note: (String, WithoutLength)),
987 type FullInvoiceRequestTlvStream =
988 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
990 type FullInvoiceRequestTlvStreamRef<'a> = (
991 PayerTlvStreamRef<'a>,
992 OfferTlvStreamRef<'a>,
993 InvoiceRequestTlvStreamRef<'a>,
994 SignatureTlvStreamRef<'a>,
997 impl SeekReadable for FullInvoiceRequestTlvStream {
998 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
999 let payer = SeekReadable::read(r)?;
1000 let offer = SeekReadable::read(r)?;
1001 let invoice_request = SeekReadable::read(r)?;
1002 let signature = SeekReadable::read(r)?;
1004 Ok((payer, offer, invoice_request, signature))
1008 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1010 type PartialInvoiceRequestTlvStreamRef<'a> = (
1011 PayerTlvStreamRef<'a>,
1012 OfferTlvStreamRef<'a>,
1013 InvoiceRequestTlvStreamRef<'a>,
1016 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1017 type Error = Bolt12ParseError;
1019 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1020 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1021 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1023 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1025 let contents = InvoiceRequestContents::try_from(
1026 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1029 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1031 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1035 impl TryFrom<Vec<u8>> for InvoiceRequest {
1036 type Error = Bolt12ParseError;
1038 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1039 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1040 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1042 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1043 SignatureTlvStream { signature },
1045 let contents = InvoiceRequestContents::try_from(
1046 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1049 let signature = match signature {
1050 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1051 Some(signature) => signature,
1053 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1054 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1056 Ok(InvoiceRequest { bytes, contents, signature })
1060 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1061 type Error = Bolt12SemanticError;
1063 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1065 PayerTlvStream { metadata },
1067 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1070 let payer = match metadata {
1071 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1072 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1074 let offer = OfferContents::try_from(offer_tlv_stream)?;
1076 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1077 return Err(Bolt12SemanticError::UnsupportedChain);
1080 if offer.amount().is_none() && amount.is_none() {
1081 return Err(Bolt12SemanticError::MissingAmount);
1084 offer.check_quantity(quantity)?;
1085 offer.check_amount_msats_for_quantity(amount, quantity)?;
1087 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1089 let payer_id = match payer_id {
1090 None => return Err(Bolt12SemanticError::MissingPayerId),
1091 Some(payer_id) => payer_id,
1094 Ok(InvoiceRequestContents {
1095 inner: InvoiceRequestContentsWithoutPayerId {
1096 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1105 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1107 use bitcoin::blockdata::constants::ChainHash;
1108 use bitcoin::network::constants::Network;
1109 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1110 use core::num::NonZeroU64;
1111 #[cfg(feature = "std")]
1112 use core::time::Duration;
1113 use crate::sign::KeyMaterial;
1114 use crate::ln::channelmanager::PaymentId;
1115 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1116 use crate::ln::inbound_payment::ExpandedKey;
1117 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1118 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1119 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1120 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1121 #[cfg(not(c_bindings))]
1123 crate::offers::offer::OfferBuilder,
1127 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1129 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1130 use crate::offers::payer::PayerTlvStreamRef;
1131 use crate::offers::test_utils::*;
1132 use crate::util::ser::{BigSize, Writeable};
1133 use crate::util::string::PrintableString;
1136 fn builds_invoice_request_with_defaults() {
1137 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1140 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1143 let mut unsigned_invoice_request = unsigned_invoice_request;
1145 let mut buffer = Vec::new();
1146 unsigned_invoice_request.write(&mut buffer).unwrap();
1148 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1149 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1150 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1151 assert_eq!(unsigned_invoice_request.metadata(), None);
1152 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1153 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1154 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1155 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1156 assert_eq!(unsigned_invoice_request.paths(), &[]);
1157 assert_eq!(unsigned_invoice_request.issuer(), None);
1158 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1159 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1160 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1161 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1162 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1163 assert_eq!(unsigned_invoice_request.quantity(), None);
1164 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1165 assert_eq!(unsigned_invoice_request.payer_note(), None);
1167 match UnsignedInvoiceRequest::try_from(buffer) {
1168 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1170 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1171 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1175 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1177 let mut buffer = Vec::new();
1178 invoice_request.write(&mut buffer).unwrap();
1180 assert_eq!(invoice_request.bytes, buffer.as_slice());
1181 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1182 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1183 assert_eq!(invoice_request.metadata(), None);
1184 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1185 assert_eq!(invoice_request.description(), PrintableString("foo"));
1186 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1187 assert_eq!(invoice_request.absolute_expiry(), None);
1188 assert_eq!(invoice_request.paths(), &[]);
1189 assert_eq!(invoice_request.issuer(), None);
1190 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1191 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1192 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1193 assert_eq!(invoice_request.amount_msats(), None);
1194 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1195 assert_eq!(invoice_request.quantity(), None);
1196 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1197 assert_eq!(invoice_request.payer_note(), None);
1199 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1200 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1203 invoice_request.as_tlv_stream(),
1205 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1211 description: Some(&String::from("foo")),
1213 absolute_expiry: None,
1217 node_id: Some(&recipient_pubkey()),
1219 InvoiceRequestTlvStreamRef {
1224 payer_id: Some(&payer_pubkey()),
1227 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1231 if let Err(e) = InvoiceRequest::try_from(buffer) {
1232 panic!("error parsing invoice request: {:?}", e);
1236 #[cfg(feature = "std")]
1238 fn builds_invoice_request_from_offer_with_expiration() {
1239 let future_expiry = Duration::from_secs(u64::max_value());
1240 let past_expiry = Duration::from_secs(0);
1242 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1244 .absolute_expiry(future_expiry)
1246 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 panic!("error building invoice_request: {:?}", e);
1252 match OfferBuilder::new("foo".into(), recipient_pubkey())
1254 .absolute_expiry(past_expiry)
1256 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1259 Ok(_) => panic!("expected error"),
1260 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1265 fn builds_invoice_request_with_derived_metadata() {
1266 let payer_id = payer_pubkey();
1267 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1268 let entropy = FixedEntropy {};
1269 let secp_ctx = Secp256k1::new();
1270 let payment_id = PaymentId([1; 32]);
1272 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1275 let invoice_request = offer
1276 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1279 .sign(payer_sign).unwrap();
1280 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1282 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1285 .sign(recipient_sign).unwrap();
1286 match invoice.verify(&expanded_key, &secp_ctx) {
1287 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1288 Err(()) => panic!("verification failed"),
1291 // Fails verification with altered fields
1293 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1294 mut invoice_tlv_stream, mut signature_tlv_stream
1295 ) = invoice.as_tlv_stream();
1296 invoice_request_tlv_stream.amount = Some(2000);
1297 invoice_tlv_stream.amount = Some(2000);
1300 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1301 let mut bytes = Vec::new();
1302 tlv_stream.write(&mut bytes).unwrap();
1304 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1305 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1306 signature_tlv_stream.signature = Some(&signature);
1308 let mut encoded_invoice = bytes;
1309 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1311 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1312 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1314 // Fails verification with altered metadata
1316 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1317 mut signature_tlv_stream
1318 ) = invoice.as_tlv_stream();
1319 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1320 payer_tlv_stream.metadata = Some(&metadata);
1323 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1324 let mut bytes = Vec::new();
1325 tlv_stream.write(&mut bytes).unwrap();
1327 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1328 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1329 signature_tlv_stream.signature = Some(&signature);
1331 let mut encoded_invoice = bytes;
1332 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1334 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1335 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1339 fn builds_invoice_request_with_derived_payer_id() {
1340 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1341 let entropy = FixedEntropy {};
1342 let secp_ctx = Secp256k1::new();
1343 let payment_id = PaymentId([1; 32]);
1345 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1348 let invoice_request = offer
1349 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1354 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1357 .sign(recipient_sign).unwrap();
1358 match invoice.verify(&expanded_key, &secp_ctx) {
1359 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1360 Err(()) => panic!("verification failed"),
1363 // Fails verification with altered fields
1365 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1366 mut invoice_tlv_stream, mut signature_tlv_stream
1367 ) = invoice.as_tlv_stream();
1368 invoice_request_tlv_stream.amount = Some(2000);
1369 invoice_tlv_stream.amount = Some(2000);
1372 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1373 let mut bytes = Vec::new();
1374 tlv_stream.write(&mut bytes).unwrap();
1376 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1377 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1378 signature_tlv_stream.signature = Some(&signature);
1380 let mut encoded_invoice = bytes;
1381 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1383 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1384 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1386 // Fails verification with altered payer id
1388 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1389 mut signature_tlv_stream
1390 ) = invoice.as_tlv_stream();
1391 let payer_id = pubkey(1);
1392 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1395 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1396 let mut bytes = Vec::new();
1397 tlv_stream.write(&mut bytes).unwrap();
1399 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1400 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1401 signature_tlv_stream.signature = Some(&signature);
1403 let mut encoded_invoice = bytes;
1404 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1406 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1407 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1411 fn builds_invoice_request_with_chain() {
1412 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1413 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1415 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1418 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1419 .chain(Network::Bitcoin).unwrap()
1421 .sign(payer_sign).unwrap();
1422 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1423 assert_eq!(invoice_request.chain(), mainnet);
1424 assert_eq!(tlv_stream.chain, None);
1426 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1428 .chain(Network::Testnet)
1430 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1431 .chain(Network::Testnet).unwrap()
1433 .sign(payer_sign).unwrap();
1434 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1435 assert_eq!(invoice_request.chain(), testnet);
1436 assert_eq!(tlv_stream.chain, Some(&testnet));
1438 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1440 .chain(Network::Bitcoin)
1441 .chain(Network::Testnet)
1443 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1444 .chain(Network::Bitcoin).unwrap()
1446 .sign(payer_sign).unwrap();
1447 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1448 assert_eq!(invoice_request.chain(), mainnet);
1449 assert_eq!(tlv_stream.chain, None);
1451 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1453 .chain(Network::Bitcoin)
1454 .chain(Network::Testnet)
1456 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1457 .chain(Network::Bitcoin).unwrap()
1458 .chain(Network::Testnet).unwrap()
1460 .sign(payer_sign).unwrap();
1461 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1462 assert_eq!(invoice_request.chain(), testnet);
1463 assert_eq!(tlv_stream.chain, Some(&testnet));
1465 match OfferBuilder::new("foo".into(), recipient_pubkey())
1467 .chain(Network::Testnet)
1469 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1470 .chain(Network::Bitcoin)
1472 Ok(_) => panic!("expected error"),
1473 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1476 match OfferBuilder::new("foo".into(), recipient_pubkey())
1478 .chain(Network::Testnet)
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1483 Ok(_) => panic!("expected error"),
1484 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1489 fn builds_invoice_request_with_amount() {
1490 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1493 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1494 .amount_msats(1000).unwrap()
1496 .sign(payer_sign).unwrap();
1497 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1498 assert_eq!(invoice_request.amount_msats(), Some(1000));
1499 assert_eq!(tlv_stream.amount, Some(1000));
1501 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1504 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1505 .amount_msats(1001).unwrap()
1506 .amount_msats(1000).unwrap()
1508 .sign(payer_sign).unwrap();
1509 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1510 assert_eq!(invoice_request.amount_msats(), Some(1000));
1511 assert_eq!(tlv_stream.amount, Some(1000));
1513 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1516 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1517 .amount_msats(1001).unwrap()
1519 .sign(payer_sign).unwrap();
1520 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1521 assert_eq!(invoice_request.amount_msats(), Some(1001));
1522 assert_eq!(tlv_stream.amount, Some(1001));
1524 match OfferBuilder::new("foo".into(), recipient_pubkey())
1527 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1530 Ok(_) => panic!("expected error"),
1531 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1534 match OfferBuilder::new("foo".into(), recipient_pubkey())
1536 .supported_quantity(Quantity::Unbounded)
1538 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1539 .quantity(2).unwrap()
1542 Ok(_) => panic!("expected error"),
1543 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1546 match OfferBuilder::new("foo".into(), recipient_pubkey())
1549 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1550 .amount_msats(MAX_VALUE_MSAT + 1)
1552 Ok(_) => panic!("expected error"),
1553 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1556 match OfferBuilder::new("foo".into(), recipient_pubkey())
1558 .supported_quantity(Quantity::Unbounded)
1560 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1561 .amount_msats(1000).unwrap()
1562 .quantity(2).unwrap()
1565 Ok(_) => panic!("expected error"),
1566 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1569 match OfferBuilder::new("foo".into(), recipient_pubkey())
1571 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1574 Ok(_) => panic!("expected error"),
1575 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1578 match OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .supported_quantity(Quantity::Unbounded)
1582 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1583 .quantity(u64::max_value()).unwrap()
1586 Ok(_) => panic!("expected error"),
1587 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1592 fn builds_invoice_request_with_features() {
1593 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1596 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1597 .features_unchecked(InvoiceRequestFeatures::unknown())
1599 .sign(payer_sign).unwrap();
1600 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1601 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1602 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1604 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1607 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1608 .features_unchecked(InvoiceRequestFeatures::unknown())
1609 .features_unchecked(InvoiceRequestFeatures::empty())
1611 .sign(payer_sign).unwrap();
1612 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1613 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1614 assert_eq!(tlv_stream.features, None);
1618 fn builds_invoice_request_with_quantity() {
1619 let one = NonZeroU64::new(1).unwrap();
1620 let ten = NonZeroU64::new(10).unwrap();
1622 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1624 .supported_quantity(Quantity::One)
1626 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1628 .sign(payer_sign).unwrap();
1629 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1630 assert_eq!(invoice_request.quantity(), None);
1631 assert_eq!(tlv_stream.quantity, None);
1633 match OfferBuilder::new("foo".into(), recipient_pubkey())
1635 .supported_quantity(Quantity::One)
1637 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1638 .amount_msats(2_000).unwrap()
1641 Ok(_) => panic!("expected error"),
1642 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1645 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1647 .supported_quantity(Quantity::Bounded(ten))
1649 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1650 .amount_msats(10_000).unwrap()
1651 .quantity(10).unwrap()
1653 .sign(payer_sign).unwrap();
1654 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1655 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1656 assert_eq!(tlv_stream.amount, Some(10_000));
1658 match OfferBuilder::new("foo".into(), recipient_pubkey())
1660 .supported_quantity(Quantity::Bounded(ten))
1662 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1663 .amount_msats(11_000).unwrap()
1666 Ok(_) => panic!("expected error"),
1667 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1670 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1672 .supported_quantity(Quantity::Unbounded)
1674 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1675 .amount_msats(2_000).unwrap()
1676 .quantity(2).unwrap()
1678 .sign(payer_sign).unwrap();
1679 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1680 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1681 assert_eq!(tlv_stream.amount, Some(2_000));
1683 match OfferBuilder::new("foo".into(), recipient_pubkey())
1685 .supported_quantity(Quantity::Unbounded)
1687 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1690 Ok(_) => panic!("expected error"),
1691 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1694 match OfferBuilder::new("foo".into(), recipient_pubkey())
1696 .supported_quantity(Quantity::Bounded(one))
1698 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1701 Ok(_) => panic!("expected error"),
1702 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1707 fn builds_invoice_request_with_payer_note() {
1708 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1711 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1712 .payer_note("bar".into())
1714 .sign(payer_sign).unwrap();
1715 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1716 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1717 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1719 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1722 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1723 .payer_note("bar".into())
1724 .payer_note("baz".into())
1726 .sign(payer_sign).unwrap();
1727 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1728 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1729 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1733 fn fails_signing_invoice_request() {
1734 match OfferBuilder::new("foo".into(), recipient_pubkey())
1737 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1741 Ok(_) => panic!("expected error"),
1742 Err(e) => assert_eq!(e, SignError::Signing),
1745 match OfferBuilder::new("foo".into(), recipient_pubkey())
1748 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750 .sign(recipient_sign)
1752 Ok(_) => panic!("expected error"),
1753 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1758 fn fails_responding_with_unknown_required_features() {
1759 match OfferBuilder::new("foo".into(), recipient_pubkey())
1762 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1763 .features_unchecked(InvoiceRequestFeatures::unknown())
1765 .sign(payer_sign).unwrap()
1766 .respond_with_no_std(payment_paths(), payment_hash(), now())
1768 Ok(_) => panic!("expected error"),
1769 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1774 fn parses_invoice_request_with_metadata() {
1775 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1778 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1780 .sign(payer_sign).unwrap();
1782 let mut buffer = Vec::new();
1783 invoice_request.write(&mut buffer).unwrap();
1785 if let Err(e) = InvoiceRequest::try_from(buffer) {
1786 panic!("error parsing invoice_request: {:?}", e);
1791 fn parses_invoice_request_with_chain() {
1792 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1795 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1796 .chain(Network::Bitcoin).unwrap()
1798 .sign(payer_sign).unwrap();
1800 let mut buffer = Vec::new();
1801 invoice_request.write(&mut buffer).unwrap();
1803 if let Err(e) = InvoiceRequest::try_from(buffer) {
1804 panic!("error parsing invoice_request: {:?}", e);
1807 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1810 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1811 .chain_unchecked(Network::Testnet)
1813 .sign(payer_sign).unwrap();
1815 let mut buffer = Vec::new();
1816 invoice_request.write(&mut buffer).unwrap();
1818 match InvoiceRequest::try_from(buffer) {
1819 Ok(_) => panic!("expected error"),
1820 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1825 fn parses_invoice_request_with_amount() {
1826 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1829 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1831 .sign(payer_sign).unwrap();
1833 let mut buffer = Vec::new();
1834 invoice_request.write(&mut buffer).unwrap();
1836 if let Err(e) = InvoiceRequest::try_from(buffer) {
1837 panic!("error parsing invoice_request: {:?}", e);
1840 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1842 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1843 .amount_msats(1000).unwrap()
1845 .sign(payer_sign).unwrap();
1847 let mut buffer = Vec::new();
1848 invoice_request.write(&mut buffer).unwrap();
1850 if let Err(e) = InvoiceRequest::try_from(buffer) {
1851 panic!("error parsing invoice_request: {:?}", e);
1854 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1856 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1858 .sign(payer_sign).unwrap();
1860 let mut buffer = Vec::new();
1861 invoice_request.write(&mut buffer).unwrap();
1863 match InvoiceRequest::try_from(buffer) {
1864 Ok(_) => panic!("expected error"),
1865 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1868 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1871 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1872 .amount_msats_unchecked(999)
1874 .sign(payer_sign).unwrap();
1876 let mut buffer = Vec::new();
1877 invoice_request.write(&mut buffer).unwrap();
1879 match InvoiceRequest::try_from(buffer) {
1880 Ok(_) => panic!("expected error"),
1881 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1884 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1885 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1887 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1889 .sign(payer_sign).unwrap();
1891 let mut buffer = Vec::new();
1892 invoice_request.write(&mut buffer).unwrap();
1894 match InvoiceRequest::try_from(buffer) {
1895 Ok(_) => panic!("expected error"),
1897 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1901 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1903 .supported_quantity(Quantity::Unbounded)
1905 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1906 .quantity(u64::max_value()).unwrap()
1908 .sign(payer_sign).unwrap();
1910 let mut buffer = Vec::new();
1911 invoice_request.write(&mut buffer).unwrap();
1913 match InvoiceRequest::try_from(buffer) {
1914 Ok(_) => panic!("expected error"),
1915 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1920 fn parses_invoice_request_with_quantity() {
1921 let one = NonZeroU64::new(1).unwrap();
1922 let ten = NonZeroU64::new(10).unwrap();
1924 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1926 .supported_quantity(Quantity::One)
1928 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1930 .sign(payer_sign).unwrap();
1932 let mut buffer = Vec::new();
1933 invoice_request.write(&mut buffer).unwrap();
1935 if let Err(e) = InvoiceRequest::try_from(buffer) {
1936 panic!("error parsing invoice_request: {:?}", e);
1939 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1941 .supported_quantity(Quantity::One)
1943 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1944 .amount_msats(2_000).unwrap()
1945 .quantity_unchecked(2)
1947 .sign(payer_sign).unwrap();
1949 let mut buffer = Vec::new();
1950 invoice_request.write(&mut buffer).unwrap();
1952 match InvoiceRequest::try_from(buffer) {
1953 Ok(_) => panic!("expected error"),
1955 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1959 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1961 .supported_quantity(Quantity::Bounded(ten))
1963 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1964 .amount_msats(10_000).unwrap()
1965 .quantity(10).unwrap()
1967 .sign(payer_sign).unwrap();
1969 let mut buffer = Vec::new();
1970 invoice_request.write(&mut buffer).unwrap();
1972 if let Err(e) = InvoiceRequest::try_from(buffer) {
1973 panic!("error parsing invoice_request: {:?}", e);
1976 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1978 .supported_quantity(Quantity::Bounded(ten))
1980 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1981 .amount_msats(11_000).unwrap()
1982 .quantity_unchecked(11)
1984 .sign(payer_sign).unwrap();
1986 let mut buffer = Vec::new();
1987 invoice_request.write(&mut buffer).unwrap();
1989 match InvoiceRequest::try_from(buffer) {
1990 Ok(_) => panic!("expected error"),
1991 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1994 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1996 .supported_quantity(Quantity::Unbounded)
1998 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1999 .amount_msats(2_000).unwrap()
2000 .quantity(2).unwrap()
2002 .sign(payer_sign).unwrap();
2004 let mut buffer = Vec::new();
2005 invoice_request.write(&mut buffer).unwrap();
2007 if let Err(e) = InvoiceRequest::try_from(buffer) {
2008 panic!("error parsing invoice_request: {:?}", e);
2011 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2013 .supported_quantity(Quantity::Unbounded)
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 match InvoiceRequest::try_from(buffer) {
2023 Ok(_) => panic!("expected error"),
2024 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2027 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2029 .supported_quantity(Quantity::Bounded(one))
2031 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2033 .sign(payer_sign).unwrap();
2035 let mut buffer = Vec::new();
2036 invoice_request.write(&mut buffer).unwrap();
2038 match InvoiceRequest::try_from(buffer) {
2039 Ok(_) => panic!("expected error"),
2040 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2045 fn fails_parsing_invoice_request_without_metadata() {
2046 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2049 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2051 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2052 tlv_stream.0.metadata = None;
2054 let mut buffer = Vec::new();
2055 tlv_stream.write(&mut buffer).unwrap();
2057 match InvoiceRequest::try_from(buffer) {
2058 Ok(_) => panic!("expected error"),
2060 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2066 fn fails_parsing_invoice_request_without_payer_id() {
2067 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2070 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2072 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2073 tlv_stream.2.payer_id = None;
2075 let mut buffer = Vec::new();
2076 tlv_stream.write(&mut buffer).unwrap();
2078 match InvoiceRequest::try_from(buffer) {
2079 Ok(_) => panic!("expected error"),
2080 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2085 fn fails_parsing_invoice_request_without_node_id() {
2086 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2089 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2091 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2092 tlv_stream.1.node_id = None;
2094 let mut buffer = Vec::new();
2095 tlv_stream.write(&mut buffer).unwrap();
2097 match InvoiceRequest::try_from(buffer) {
2098 Ok(_) => panic!("expected error"),
2100 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2106 fn fails_parsing_invoice_request_without_signature() {
2107 let mut buffer = Vec::new();
2108 OfferBuilder::new("foo".into(), recipient_pubkey())
2111 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2114 .write(&mut buffer).unwrap();
2116 match InvoiceRequest::try_from(buffer) {
2117 Ok(_) => panic!("expected error"),
2118 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2123 fn fails_parsing_invoice_request_with_invalid_signature() {
2124 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2127 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2129 .sign(payer_sign).unwrap();
2130 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2131 *last_signature_byte = last_signature_byte.wrapping_add(1);
2133 let mut buffer = Vec::new();
2134 invoice_request.write(&mut buffer).unwrap();
2136 match InvoiceRequest::try_from(buffer) {
2137 Ok(_) => panic!("expected error"),
2139 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2145 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2146 let secp_ctx = Secp256k1::new();
2147 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2148 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2151 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2153 .sign(|message: &UnsignedInvoiceRequest|
2154 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2158 let mut encoded_invoice_request = Vec::new();
2159 invoice_request.write(&mut encoded_invoice_request).unwrap();
2160 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2161 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2162 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2164 match InvoiceRequest::try_from(encoded_invoice_request) {
2165 Ok(_) => panic!("expected error"),
2166 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),