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;
64 use core::convert::{AsRef, TryFrom};
66 use crate::sign::EntropySource;
68 use crate::blinded_path::BlindedPath;
69 use crate::ln::PaymentHash;
70 use crate::ln::channelmanager::PaymentId;
71 use crate::ln::features::InvoiceRequestFeatures;
72 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
73 use crate::ln::msgs::DecodeError;
74 use crate::offers::invoice::BlindedPayInfo;
75 use crate::offers::merkle::{SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
76 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
77 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
78 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
79 use crate::offers::signer::{Metadata, MetadataMaterial};
80 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
81 use crate::util::string::PrintableString;
83 #[cfg(not(c_bindings))]
85 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
89 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
92 #[allow(unused_imports)]
93 use crate::prelude::*;
95 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
96 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
98 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
100 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
102 /// See [module-level documentation] for usage.
104 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
106 /// [module-level documentation]: self
107 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
109 invoice_request: InvoiceRequestContentsWithoutPayerId,
110 payer_id: Option<PublicKey>,
111 payer_id_strategy: core::marker::PhantomData<P>,
112 secp_ctx: Option<&'b Secp256k1<T>>,
115 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
117 /// See [module-level documentation] for usage.
119 /// [module-level documentation]: self
121 pub struct InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
123 invoice_request: InvoiceRequestContentsWithoutPayerId,
124 payer_id: Option<PublicKey>,
125 payer_id_strategy: core::marker::PhantomData<ExplicitPayerId>,
126 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
129 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
131 /// See [module-level documentation] for usage.
133 /// [module-level documentation]: self
135 pub struct InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
137 invoice_request: InvoiceRequestContentsWithoutPayerId,
138 payer_id: Option<PublicKey>,
139 payer_id_strategy: core::marker::PhantomData<DerivedPayerId>,
140 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
143 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
145 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
146 pub trait PayerIdStrategy {}
148 /// [`InvoiceRequest::payer_id`] will be explicitly set.
150 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
151 pub struct ExplicitPayerId {}
153 /// [`InvoiceRequest::payer_id`] will be derived.
155 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
156 pub struct DerivedPayerId {}
158 impl PayerIdStrategy for ExplicitPayerId {}
159 impl PayerIdStrategy for DerivedPayerId {}
161 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
162 #[cfg_attr(c_bindings, allow(dead_code))]
163 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
166 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
167 payer_id: Some(payer_id),
168 payer_id_strategy: core::marker::PhantomData,
173 #[cfg_attr(c_bindings, allow(dead_code))]
174 pub(super) fn deriving_metadata<ES: Deref>(
175 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
176 payment_id: PaymentId,
177 ) -> Self where ES::Target: EntropySource {
178 let nonce = Nonce::from_entropy_source(entropy_source);
179 let payment_id = Some(payment_id);
180 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
181 let metadata = Metadata::Derived(derivation_material);
184 invoice_request: Self::create_contents(offer, metadata),
185 payer_id: Some(payer_id),
186 payer_id_strategy: core::marker::PhantomData,
191 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
192 /// by [`UnsignedInvoiceRequest::sign`].
193 pub fn build($self: $self_type) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
194 let (unsigned_invoice_request, keys, _) = $self.build_with_checks()?;
195 debug_assert!(keys.is_none());
196 Ok(unsigned_invoice_request)
200 macro_rules! invoice_request_derived_payer_id_builder_methods { (
201 $self: ident, $self_type: ty, $secp_context: ty
203 #[cfg_attr(c_bindings, allow(dead_code))]
204 pub(super) fn deriving_payer_id<ES: Deref>(
205 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
206 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
207 ) -> Self where ES::Target: EntropySource {
208 let nonce = Nonce::from_entropy_source(entropy_source);
209 let payment_id = Some(payment_id);
210 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
211 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
214 invoice_request: Self::create_contents(offer, metadata),
216 payer_id_strategy: core::marker::PhantomData,
217 secp_ctx: Some(secp_ctx),
221 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
222 pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
223 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
225 let mut unsigned_invoice_request = unsigned_invoice_request;
226 debug_assert!(keys.is_some());
228 let secp_ctx = secp_ctx.unwrap();
229 let keys = keys.unwrap();
230 let invoice_request = unsigned_invoice_request
231 .sign(|message: &UnsignedInvoiceRequest|
232 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
239 macro_rules! invoice_request_builder_methods { (
240 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
242 #[cfg_attr(c_bindings, allow(dead_code))]
243 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
244 let offer = offer.contents.clone();
245 InvoiceRequestContentsWithoutPayerId {
246 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
247 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
251 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
252 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
255 /// Successive calls to this method will override the previous setting.
256 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
257 $self.chain_hash(ChainHash::using_genesis_block(network))
260 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
261 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
264 /// Successive calls to this method will override the previous setting.
265 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
266 if !$self.offer.supports_chain(chain) {
267 return Err(Bolt12SemanticError::UnsupportedChain);
270 $self.invoice_request.chain = Some(chain);
274 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
275 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
277 /// Successive calls to this method will override the previous setting.
279 /// [`quantity`]: Self::quantity
280 pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
281 $self.invoice_request.offer.check_amount_msats_for_quantity(
282 Some(amount_msats), $self.invoice_request.quantity
284 $self.invoice_request.amount_msats = Some(amount_msats);
288 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
289 /// does not conform to [`Offer::is_valid_quantity`].
291 /// Successive calls to this method will override the previous setting.
292 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
293 $self.invoice_request.offer.check_quantity(Some(quantity))?;
294 $self.invoice_request.quantity = Some(quantity);
298 /// Sets the [`InvoiceRequest::payer_note`].
300 /// Successive calls to this method will override the previous setting.
301 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
302 $self.invoice_request.payer_note = Some(payer_note);
306 fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
307 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>),
310 #[cfg(feature = "std")] {
311 if $self.offer.is_expired() {
312 return Err(Bolt12SemanticError::AlreadyExpired);
316 let chain = $self.invoice_request.chain();
317 if !$self.offer.supports_chain(chain) {
318 return Err(Bolt12SemanticError::UnsupportedChain);
321 if chain == $self.offer.implied_chain() {
322 $self.invoice_request.chain = None;
325 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
326 return Err(Bolt12SemanticError::MissingAmount);
329 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
330 $self.invoice_request.offer.check_amount_msats_for_quantity(
331 $self.invoice_request.amount_msats, $self.invoice_request.quantity
334 Ok($self.build_without_checks())
337 fn build_without_checks($($self_mut)* $self: $self_type) ->
338 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>)
340 // Create the metadata for stateless verification of a Bolt12Invoice.
342 let secp_ctx = $self.secp_ctx.clone();
343 if $self.invoice_request.payer.0.has_derivation_material() {
344 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
346 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
347 debug_assert!(tlv_stream.2.payer_id.is_none());
348 tlv_stream.0.metadata = None;
349 if !metadata.derives_payer_keys() {
350 tlv_stream.2.payer_id = $self.payer_id.as_ref();
353 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
354 metadata = derived_metadata;
356 if let Some(keys) = keys {
357 debug_assert!($self.payer_id.is_none());
358 $self.payer_id = Some(keys.public_key());
361 $self.invoice_request.payer.0 = metadata;
364 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
365 debug_assert!($self.payer_id.is_some());
366 let payer_id = $self.payer_id.unwrap();
368 let invoice_request = InvoiceRequestContents {
369 #[cfg(not(c_bindings))]
370 inner: $self.invoice_request,
372 inner: $self.invoice_request.clone(),
375 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
377 (unsigned_invoice_request, keys, secp_ctx)
382 macro_rules! invoice_request_builder_test_methods { (
383 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
385 #[cfg_attr(c_bindings, allow(dead_code))]
386 fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
387 let chain = ChainHash::using_genesis_block(network);
388 $self.invoice_request.chain = Some(chain);
392 #[cfg_attr(c_bindings, allow(dead_code))]
393 fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
394 $self.invoice_request.amount_msats = Some(amount_msats);
398 #[cfg_attr(c_bindings, allow(dead_code))]
399 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
400 $self.invoice_request.features = features;
404 #[cfg_attr(c_bindings, allow(dead_code))]
405 fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
406 $self.invoice_request.quantity = Some(quantity);
410 #[cfg_attr(c_bindings, allow(dead_code))]
411 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
412 $self.build_without_checks().0
416 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
417 invoice_request_explicit_payer_id_builder_methods!(self, Self);
420 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
421 invoice_request_derived_payer_id_builder_methods!(self, Self, T);
424 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
425 invoice_request_builder_methods!(self, Self, Self, self, T, mut);
428 invoice_request_builder_test_methods!(self, Self, Self, self, mut);
431 #[cfg(all(c_bindings, not(test)))]
432 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
433 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
434 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
437 #[cfg(all(c_bindings, test))]
438 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
439 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
440 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
441 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
444 #[cfg(all(c_bindings, not(test)))]
445 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
446 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
447 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
450 #[cfg(all(c_bindings, test))]
451 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
452 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
453 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
454 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
458 impl<'a, 'b> From<InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>>
459 for InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, secp256k1::All> {
460 fn from(builder: InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>) -> Self {
461 let InvoiceRequestWithExplicitPayerIdBuilder {
462 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
466 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
472 impl<'a, 'b> From<InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>>
473 for InvoiceRequestBuilder<'a, 'b, DerivedPayerId, secp256k1::All> {
474 fn from(builder: InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>) -> Self {
475 let InvoiceRequestWithDerivedPayerIdBuilder {
476 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
480 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
485 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
489 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
490 /// such, it may include unknown, odd TLV records.
491 pub struct UnsignedInvoiceRequest {
493 contents: InvoiceRequestContents,
494 tagged_hash: TaggedHash,
497 /// A function for signing an [`UnsignedInvoiceRequest`].
498 pub trait SignInvoiceRequestFn {
499 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
500 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()>;
503 impl<F> SignInvoiceRequestFn for F
505 F: Fn(&UnsignedInvoiceRequest) -> Result<Signature, ()>,
507 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
512 impl<F> SignFn<UnsignedInvoiceRequest> for F
514 F: SignInvoiceRequestFn,
516 fn sign(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
517 self.sign_invoice_request(message)
521 impl UnsignedInvoiceRequest {
522 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
523 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
524 // unknown TLV records, which are not stored in `OfferContents`.
525 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
526 contents.as_tlv_stream();
527 let offer_bytes = WithoutLength(&offer.bytes);
528 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
530 let mut bytes = Vec::new();
531 unsigned_tlv_stream.write(&mut bytes).unwrap();
533 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
535 Self { bytes, contents, tagged_hash }
538 /// Returns the [`TaggedHash`] of the invoice to sign.
539 pub fn tagged_hash(&self) -> &TaggedHash {
544 macro_rules! unsigned_invoice_request_sign_method { (
545 $self: ident, $self_type: ty $(, $self_mut: tt)?
547 /// Signs the [`TaggedHash`] of the invoice request using the given function.
549 /// Note: The hash computation may have included unknown, odd TLV records.
550 pub fn sign<F: SignInvoiceRequestFn>(
551 $($self_mut)* $self: $self_type, sign: F
552 ) -> Result<InvoiceRequest, SignError> {
553 let pubkey = $self.contents.payer_id;
554 let signature = merkle::sign_message(sign, &$self, pubkey)?;
556 // Append the signature TLV record to the bytes.
557 let signature_tlv_stream = SignatureTlvStreamRef {
558 signature: Some(&signature),
560 signature_tlv_stream.write(&mut $self.bytes).unwrap();
563 #[cfg(not(c_bindings))]
566 bytes: $self.bytes.clone(),
567 #[cfg(not(c_bindings))]
568 contents: $self.contents,
570 contents: $self.contents.clone(),
576 #[cfg(not(c_bindings))]
577 impl UnsignedInvoiceRequest {
578 unsigned_invoice_request_sign_method!(self, Self, mut);
582 impl UnsignedInvoiceRequest {
583 unsigned_invoice_request_sign_method!(self, &mut Self);
586 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
587 fn as_ref(&self) -> &TaggedHash {
592 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
594 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
595 /// specifies these such that its recipient can send an invoice for payment.
597 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
598 /// [`Offer`]: crate::offers::offer::Offer
599 #[derive(Clone, Debug)]
600 #[cfg_attr(test, derive(PartialEq))]
601 pub struct InvoiceRequest {
602 pub(super) bytes: Vec<u8>,
603 pub(super) contents: InvoiceRequestContents,
604 signature: Signature,
607 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
608 /// ways to respond depending on whether the signing keys were derived.
609 #[derive(Clone, Debug)]
610 pub struct VerifiedInvoiceRequest {
611 /// The verified request.
612 inner: InvoiceRequest,
614 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
616 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
617 /// [`respond_with`].
619 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
620 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
621 /// [`respond_with`]: Self::respond_with
622 pub keys: Option<KeyPair>,
625 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
627 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
628 #[derive(Clone, Debug)]
629 #[cfg_attr(test, derive(PartialEq))]
630 pub(super) struct InvoiceRequestContents {
631 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
635 #[derive(Clone, Debug)]
636 #[cfg_attr(test, derive(PartialEq))]
637 pub(super) struct InvoiceRequestContentsWithoutPayerId {
638 payer: PayerContents,
639 pub(super) offer: OfferContents,
640 chain: Option<ChainHash>,
641 amount_msats: Option<u64>,
642 features: InvoiceRequestFeatures,
643 quantity: Option<u64>,
644 payer_note: Option<String>,
647 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
648 /// An unpredictable series of bytes, typically containing information about the derivation of
651 /// [`payer_id`]: Self::payer_id
652 pub fn payer_metadata(&$self) -> &[u8] {
656 /// A chain from [`Offer::chains`] that the offer is valid for.
657 pub fn chain(&$self) -> ChainHash {
661 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
662 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
664 /// [`chain`]: Self::chain
665 pub fn amount_msats(&$self) -> Option<u64> {
666 $contents.amount_msats()
669 /// Features pertaining to requesting an invoice.
670 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
671 &$contents.features()
674 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
675 pub fn quantity(&$self) -> Option<u64> {
679 /// A possibly transient pubkey used to sign the invoice request.
680 pub fn payer_id(&$self) -> PublicKey {
684 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
686 pub fn payer_note(&$self) -> Option<PrintableString> {
687 $contents.payer_note()
691 impl UnsignedInvoiceRequest {
692 offer_accessors!(self, self.contents.inner.offer);
693 invoice_request_accessors!(self, self.contents);
696 macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
697 $self: ident, $contents: expr, $builder: ty
699 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
700 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
702 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
703 /// creation time is used for the `created_at` parameter.
705 /// [`Duration`]: core::time::Duration
706 #[cfg(feature = "std")]
708 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
709 ) -> Result<$builder, Bolt12SemanticError> {
710 let created_at = std::time::SystemTime::now()
711 .duration_since(std::time::SystemTime::UNIX_EPOCH)
712 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
714 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
717 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
719 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
720 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
721 /// where [`std::time::SystemTime`] is not available.
723 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
726 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
727 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
728 /// a preference. Note, however, that any privacy is lost if a public node id was used for
729 /// [`Offer::signing_pubkey`].
731 /// Errors if the request contains unknown required features.
735 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
736 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
738 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
739 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
740 pub fn respond_with_no_std(
741 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
742 created_at: core::time::Duration
743 ) -> Result<$builder, Bolt12SemanticError> {
744 if $contents.invoice_request_features().requires_unknown_bits() {
745 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
748 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash)
752 macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
753 /// Verifies that the request was for an offer created using the given key. Returns the verified
754 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
755 /// if they could be extracted from the metadata.
757 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
759 #[cfg(not(c_bindings))]
760 T: secp256k1::Signing
762 $self: $self_type, key: &ExpandedKey,
763 #[cfg(not(c_bindings))]
764 secp_ctx: &Secp256k1<T>,
766 secp_ctx: &Secp256k1<secp256k1::All>,
767 ) -> Result<VerifiedInvoiceRequest, ()> {
768 let keys = $self.contents.inner.offer.verify(&$self.bytes, key, secp_ctx)?;
769 Ok(VerifiedInvoiceRequest {
770 #[cfg(not(c_bindings))]
773 inner: $self.clone(),
780 #[cfg(not(c_bindings))]
781 impl InvoiceRequest {
782 offer_accessors!(self, self.contents.inner.offer);
783 invoice_request_accessors!(self, self.contents);
784 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
785 invoice_request_verify_method!(self, Self);
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, InvoiceWithExplicitSigningPubkeyBuilder);
793 invoice_request_verify_method!(self, &Self);
796 impl InvoiceRequest {
797 /// Signature of the invoice request using [`payer_id`].
799 /// [`payer_id`]: Self::payer_id
800 pub fn signature(&self) -> Signature {
804 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
805 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
806 self.contents.as_tlv_stream();
807 let signature_tlv_stream = SignatureTlvStreamRef {
808 signature: Some(&self.signature),
810 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
814 macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
815 $self: ident, $contents: expr, $builder: ty
817 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
818 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
819 /// the same [`ExpandedKey`] as the one used to create the offer.
821 /// See [`InvoiceRequest::respond_with`] for further details.
823 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
824 #[cfg(feature = "std")]
825 pub fn respond_using_derived_keys(
826 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
827 ) -> Result<$builder, Bolt12SemanticError> {
828 let created_at = std::time::SystemTime::now()
829 .duration_since(std::time::SystemTime::UNIX_EPOCH)
830 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
832 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
835 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
836 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
837 /// the same [`ExpandedKey`] as the one used to create the offer.
839 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
841 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
842 pub fn respond_using_derived_keys_no_std(
843 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
844 created_at: core::time::Duration
845 ) -> Result<$builder, Bolt12SemanticError> {
846 if $self.inner.invoice_request_features().requires_unknown_bits() {
847 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
850 let keys = match $self.keys {
851 None => return Err(Bolt12SemanticError::InvalidMetadata),
855 <$builder>::for_offer_using_keys(
856 &$self.inner, payment_paths, created_at, payment_hash, keys
861 impl VerifiedInvoiceRequest {
862 offer_accessors!(self, self.inner.contents.inner.offer);
863 invoice_request_accessors!(self, self.inner.contents);
864 #[cfg(not(c_bindings))]
865 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
867 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
868 #[cfg(not(c_bindings))]
869 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
871 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
874 impl InvoiceRequestContents {
875 pub(super) fn metadata(&self) -> &[u8] {
876 self.inner.metadata()
879 pub(super) fn derives_keys(&self) -> bool {
880 self.inner.payer.0.derives_payer_keys()
883 pub(super) fn chain(&self) -> ChainHash {
887 pub(super) fn amount_msats(&self) -> Option<u64> {
888 self.inner.amount_msats
891 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
895 pub(super) fn quantity(&self) -> Option<u64> {
899 pub(super) fn payer_id(&self) -> PublicKey {
903 pub(super) fn payer_note(&self) -> Option<PrintableString> {
904 self.inner.payer_note.as_ref()
905 .map(|payer_note| PrintableString(payer_note.as_str()))
908 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
909 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
910 invoice_request.payer_id = Some(&self.payer_id);
911 (payer, offer, invoice_request)
915 impl InvoiceRequestContentsWithoutPayerId {
916 pub(super) fn metadata(&self) -> &[u8] {
917 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
920 pub(super) fn chain(&self) -> ChainHash {
921 self.chain.unwrap_or_else(|| self.offer.implied_chain())
924 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
925 let payer = PayerTlvStreamRef {
926 metadata: self.payer.0.as_bytes(),
929 let offer = self.offer.as_tlv_stream();
932 if self.features == InvoiceRequestFeatures::empty() { None }
933 else { Some(&self.features) }
936 let invoice_request = InvoiceRequestTlvStreamRef {
937 chain: self.chain.as_ref(),
938 amount: self.amount_msats,
940 quantity: self.quantity,
942 payer_note: self.payer_note.as_ref(),
945 (payer, offer, invoice_request)
949 impl Writeable for UnsignedInvoiceRequest {
950 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
951 WithoutLength(&self.bytes).write(writer)
955 impl Writeable for InvoiceRequest {
956 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
957 WithoutLength(&self.bytes).write(writer)
961 impl Writeable for InvoiceRequestContents {
962 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
963 self.as_tlv_stream().write(writer)
967 /// Valid type range for invoice_request TLV records.
968 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
970 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
972 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
973 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
975 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
976 (80, chain: ChainHash),
977 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
978 (84, features: (InvoiceRequestFeatures, WithoutLength)),
979 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
980 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
981 (89, payer_note: (String, WithoutLength)),
984 type FullInvoiceRequestTlvStream =
985 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
987 type FullInvoiceRequestTlvStreamRef<'a> = (
988 PayerTlvStreamRef<'a>,
989 OfferTlvStreamRef<'a>,
990 InvoiceRequestTlvStreamRef<'a>,
991 SignatureTlvStreamRef<'a>,
994 impl SeekReadable for FullInvoiceRequestTlvStream {
995 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
996 let payer = SeekReadable::read(r)?;
997 let offer = SeekReadable::read(r)?;
998 let invoice_request = SeekReadable::read(r)?;
999 let signature = SeekReadable::read(r)?;
1001 Ok((payer, offer, invoice_request, signature))
1005 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
1007 type PartialInvoiceRequestTlvStreamRef<'a> = (
1008 PayerTlvStreamRef<'a>,
1009 OfferTlvStreamRef<'a>,
1010 InvoiceRequestTlvStreamRef<'a>,
1013 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1014 type Error = Bolt12ParseError;
1016 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1017 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1018 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1020 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1022 let contents = InvoiceRequestContents::try_from(
1023 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1026 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1028 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
1032 impl TryFrom<Vec<u8>> for InvoiceRequest {
1033 type Error = Bolt12ParseError;
1035 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1036 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1037 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1039 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1040 SignatureTlvStream { signature },
1042 let contents = InvoiceRequestContents::try_from(
1043 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1046 let signature = match signature {
1047 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1048 Some(signature) => signature,
1050 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
1051 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1053 Ok(InvoiceRequest { bytes, contents, signature })
1057 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1058 type Error = Bolt12SemanticError;
1060 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1062 PayerTlvStream { metadata },
1064 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1067 let payer = match metadata {
1068 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1069 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1071 let offer = OfferContents::try_from(offer_tlv_stream)?;
1073 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1074 return Err(Bolt12SemanticError::UnsupportedChain);
1077 if offer.amount().is_none() && amount.is_none() {
1078 return Err(Bolt12SemanticError::MissingAmount);
1081 offer.check_quantity(quantity)?;
1082 offer.check_amount_msats_for_quantity(amount, quantity)?;
1084 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1086 let payer_id = match payer_id {
1087 None => return Err(Bolt12SemanticError::MissingPayerId),
1088 Some(payer_id) => payer_id,
1091 Ok(InvoiceRequestContents {
1092 inner: InvoiceRequestContentsWithoutPayerId {
1093 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1102 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1104 use bitcoin::blockdata::constants::ChainHash;
1105 use bitcoin::network::constants::Network;
1106 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1107 use core::convert::TryFrom;
1108 use core::num::NonZeroU64;
1109 #[cfg(feature = "std")]
1110 use core::time::Duration;
1111 use crate::sign::KeyMaterial;
1112 use crate::ln::channelmanager::PaymentId;
1113 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1114 use crate::ln::inbound_payment::ExpandedKey;
1115 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1116 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1117 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1118 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1119 #[cfg(not(c_bindings))]
1121 crate::offers::offer::OfferBuilder,
1125 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1127 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1128 use crate::offers::payer::PayerTlvStreamRef;
1129 use crate::offers::test_utils::*;
1130 use crate::util::ser::{BigSize, Writeable};
1131 use crate::util::string::PrintableString;
1134 fn builds_invoice_request_with_defaults() {
1135 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1138 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1141 let mut unsigned_invoice_request = unsigned_invoice_request;
1143 let mut buffer = Vec::new();
1144 unsigned_invoice_request.write(&mut buffer).unwrap();
1146 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1147 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1148 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1149 assert_eq!(unsigned_invoice_request.metadata(), None);
1150 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1151 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1152 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1153 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1154 assert_eq!(unsigned_invoice_request.paths(), &[]);
1155 assert_eq!(unsigned_invoice_request.issuer(), None);
1156 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1157 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1158 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1159 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1160 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1161 assert_eq!(unsigned_invoice_request.quantity(), None);
1162 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1163 assert_eq!(unsigned_invoice_request.payer_note(), None);
1165 match UnsignedInvoiceRequest::try_from(buffer) {
1166 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1168 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1169 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1173 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1175 let mut buffer = Vec::new();
1176 invoice_request.write(&mut buffer).unwrap();
1178 assert_eq!(invoice_request.bytes, buffer.as_slice());
1179 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1180 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1181 assert_eq!(invoice_request.metadata(), None);
1182 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1183 assert_eq!(invoice_request.description(), PrintableString("foo"));
1184 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1185 assert_eq!(invoice_request.absolute_expiry(), None);
1186 assert_eq!(invoice_request.paths(), &[]);
1187 assert_eq!(invoice_request.issuer(), None);
1188 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1189 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1190 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1191 assert_eq!(invoice_request.amount_msats(), None);
1192 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1193 assert_eq!(invoice_request.quantity(), None);
1194 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1195 assert_eq!(invoice_request.payer_note(), None);
1197 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1198 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1201 invoice_request.as_tlv_stream(),
1203 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1209 description: Some(&String::from("foo")),
1211 absolute_expiry: None,
1215 node_id: Some(&recipient_pubkey()),
1217 InvoiceRequestTlvStreamRef {
1222 payer_id: Some(&payer_pubkey()),
1225 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1229 if let Err(e) = InvoiceRequest::try_from(buffer) {
1230 panic!("error parsing invoice request: {:?}", e);
1234 #[cfg(feature = "std")]
1236 fn builds_invoice_request_from_offer_with_expiration() {
1237 let future_expiry = Duration::from_secs(u64::max_value());
1238 let past_expiry = Duration::from_secs(0);
1240 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1242 .absolute_expiry(future_expiry)
1244 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1247 panic!("error building invoice_request: {:?}", e);
1250 match OfferBuilder::new("foo".into(), recipient_pubkey())
1252 .absolute_expiry(past_expiry)
1254 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1257 Ok(_) => panic!("expected error"),
1258 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1263 fn builds_invoice_request_with_derived_metadata() {
1264 let payer_id = payer_pubkey();
1265 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1266 let entropy = FixedEntropy {};
1267 let secp_ctx = Secp256k1::new();
1268 let payment_id = PaymentId([1; 32]);
1270 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1273 let invoice_request = offer
1274 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1277 .sign(payer_sign).unwrap();
1278 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1280 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1283 .sign(recipient_sign).unwrap();
1284 match invoice.verify(&expanded_key, &secp_ctx) {
1285 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1286 Err(()) => panic!("verification failed"),
1289 // Fails verification with altered fields
1291 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1292 mut invoice_tlv_stream, mut signature_tlv_stream
1293 ) = invoice.as_tlv_stream();
1294 invoice_request_tlv_stream.amount = Some(2000);
1295 invoice_tlv_stream.amount = Some(2000);
1298 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1299 let mut bytes = Vec::new();
1300 tlv_stream.write(&mut bytes).unwrap();
1302 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1303 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1304 signature_tlv_stream.signature = Some(&signature);
1306 let mut encoded_invoice = bytes;
1307 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1309 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1310 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1312 // Fails verification with altered metadata
1314 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1315 mut signature_tlv_stream
1316 ) = invoice.as_tlv_stream();
1317 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1318 payer_tlv_stream.metadata = Some(&metadata);
1321 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1322 let mut bytes = Vec::new();
1323 tlv_stream.write(&mut bytes).unwrap();
1325 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1326 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1327 signature_tlv_stream.signature = Some(&signature);
1329 let mut encoded_invoice = bytes;
1330 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1332 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1333 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1337 fn builds_invoice_request_with_derived_payer_id() {
1338 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1339 let entropy = FixedEntropy {};
1340 let secp_ctx = Secp256k1::new();
1341 let payment_id = PaymentId([1; 32]);
1343 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1346 let invoice_request = offer
1347 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1352 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1355 .sign(recipient_sign).unwrap();
1356 match invoice.verify(&expanded_key, &secp_ctx) {
1357 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1358 Err(()) => panic!("verification failed"),
1361 // Fails verification with altered fields
1363 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1364 mut invoice_tlv_stream, mut signature_tlv_stream
1365 ) = invoice.as_tlv_stream();
1366 invoice_request_tlv_stream.amount = Some(2000);
1367 invoice_tlv_stream.amount = Some(2000);
1370 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1371 let mut bytes = Vec::new();
1372 tlv_stream.write(&mut bytes).unwrap();
1374 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1375 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1376 signature_tlv_stream.signature = Some(&signature);
1378 let mut encoded_invoice = bytes;
1379 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1381 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1382 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1384 // Fails verification with altered payer id
1386 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1387 mut signature_tlv_stream
1388 ) = invoice.as_tlv_stream();
1389 let payer_id = pubkey(1);
1390 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1393 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1394 let mut bytes = Vec::new();
1395 tlv_stream.write(&mut bytes).unwrap();
1397 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1398 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1399 signature_tlv_stream.signature = Some(&signature);
1401 let mut encoded_invoice = bytes;
1402 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1404 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1405 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1409 fn builds_invoice_request_with_chain() {
1410 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1411 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1413 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1416 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1417 .chain(Network::Bitcoin).unwrap()
1419 .sign(payer_sign).unwrap();
1420 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1421 assert_eq!(invoice_request.chain(), mainnet);
1422 assert_eq!(tlv_stream.chain, None);
1424 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1426 .chain(Network::Testnet)
1428 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1429 .chain(Network::Testnet).unwrap()
1431 .sign(payer_sign).unwrap();
1432 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1433 assert_eq!(invoice_request.chain(), testnet);
1434 assert_eq!(tlv_stream.chain, Some(&testnet));
1436 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1438 .chain(Network::Bitcoin)
1439 .chain(Network::Testnet)
1441 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442 .chain(Network::Bitcoin).unwrap()
1444 .sign(payer_sign).unwrap();
1445 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1446 assert_eq!(invoice_request.chain(), mainnet);
1447 assert_eq!(tlv_stream.chain, None);
1449 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1451 .chain(Network::Bitcoin)
1452 .chain(Network::Testnet)
1454 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1455 .chain(Network::Bitcoin).unwrap()
1456 .chain(Network::Testnet).unwrap()
1458 .sign(payer_sign).unwrap();
1459 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1460 assert_eq!(invoice_request.chain(), testnet);
1461 assert_eq!(tlv_stream.chain, Some(&testnet));
1463 match OfferBuilder::new("foo".into(), recipient_pubkey())
1465 .chain(Network::Testnet)
1467 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1468 .chain(Network::Bitcoin)
1470 Ok(_) => panic!("expected error"),
1471 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1474 match OfferBuilder::new("foo".into(), recipient_pubkey())
1476 .chain(Network::Testnet)
1478 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1481 Ok(_) => panic!("expected error"),
1482 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1487 fn builds_invoice_request_with_amount() {
1488 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1491 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1492 .amount_msats(1000).unwrap()
1494 .sign(payer_sign).unwrap();
1495 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1496 assert_eq!(invoice_request.amount_msats(), Some(1000));
1497 assert_eq!(tlv_stream.amount, Some(1000));
1499 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1502 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1503 .amount_msats(1001).unwrap()
1504 .amount_msats(1000).unwrap()
1506 .sign(payer_sign).unwrap();
1507 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1508 assert_eq!(invoice_request.amount_msats(), Some(1000));
1509 assert_eq!(tlv_stream.amount, Some(1000));
1511 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1514 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1515 .amount_msats(1001).unwrap()
1517 .sign(payer_sign).unwrap();
1518 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1519 assert_eq!(invoice_request.amount_msats(), Some(1001));
1520 assert_eq!(tlv_stream.amount, Some(1001));
1522 match OfferBuilder::new("foo".into(), recipient_pubkey())
1525 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1528 Ok(_) => panic!("expected error"),
1529 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1532 match OfferBuilder::new("foo".into(), recipient_pubkey())
1534 .supported_quantity(Quantity::Unbounded)
1536 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1537 .quantity(2).unwrap()
1540 Ok(_) => panic!("expected error"),
1541 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1544 match OfferBuilder::new("foo".into(), recipient_pubkey())
1547 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1548 .amount_msats(MAX_VALUE_MSAT + 1)
1550 Ok(_) => panic!("expected error"),
1551 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1554 match OfferBuilder::new("foo".into(), recipient_pubkey())
1556 .supported_quantity(Quantity::Unbounded)
1558 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1559 .amount_msats(1000).unwrap()
1560 .quantity(2).unwrap()
1563 Ok(_) => panic!("expected error"),
1564 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1567 match OfferBuilder::new("foo".into(), recipient_pubkey())
1569 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1572 Ok(_) => panic!("expected error"),
1573 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1576 match OfferBuilder::new("foo".into(), recipient_pubkey())
1578 .supported_quantity(Quantity::Unbounded)
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1581 .quantity(u64::max_value()).unwrap()
1584 Ok(_) => panic!("expected error"),
1585 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1590 fn builds_invoice_request_with_features() {
1591 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1594 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1595 .features_unchecked(InvoiceRequestFeatures::unknown())
1597 .sign(payer_sign).unwrap();
1598 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1599 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1600 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1602 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1605 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1606 .features_unchecked(InvoiceRequestFeatures::unknown())
1607 .features_unchecked(InvoiceRequestFeatures::empty())
1609 .sign(payer_sign).unwrap();
1610 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1611 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1612 assert_eq!(tlv_stream.features, None);
1616 fn builds_invoice_request_with_quantity() {
1617 let one = NonZeroU64::new(1).unwrap();
1618 let ten = NonZeroU64::new(10).unwrap();
1620 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1622 .supported_quantity(Quantity::One)
1624 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 .sign(payer_sign).unwrap();
1627 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1628 assert_eq!(invoice_request.quantity(), None);
1629 assert_eq!(tlv_stream.quantity, None);
1631 match OfferBuilder::new("foo".into(), recipient_pubkey())
1633 .supported_quantity(Quantity::One)
1635 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1636 .amount_msats(2_000).unwrap()
1639 Ok(_) => panic!("expected error"),
1640 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1643 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1645 .supported_quantity(Quantity::Bounded(ten))
1647 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1648 .amount_msats(10_000).unwrap()
1649 .quantity(10).unwrap()
1651 .sign(payer_sign).unwrap();
1652 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1653 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1654 assert_eq!(tlv_stream.amount, Some(10_000));
1656 match OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .supported_quantity(Quantity::Bounded(ten))
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 .amount_msats(11_000).unwrap()
1664 Ok(_) => panic!("expected error"),
1665 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1668 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1670 .supported_quantity(Quantity::Unbounded)
1672 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1673 .amount_msats(2_000).unwrap()
1674 .quantity(2).unwrap()
1676 .sign(payer_sign).unwrap();
1677 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1678 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1679 assert_eq!(tlv_stream.amount, Some(2_000));
1681 match OfferBuilder::new("foo".into(), recipient_pubkey())
1683 .supported_quantity(Quantity::Unbounded)
1685 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1688 Ok(_) => panic!("expected error"),
1689 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1692 match OfferBuilder::new("foo".into(), recipient_pubkey())
1694 .supported_quantity(Quantity::Bounded(one))
1696 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1699 Ok(_) => panic!("expected error"),
1700 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1705 fn builds_invoice_request_with_payer_note() {
1706 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1709 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1710 .payer_note("bar".into())
1712 .sign(payer_sign).unwrap();
1713 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1714 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1715 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1717 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1720 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1721 .payer_note("bar".into())
1722 .payer_note("baz".into())
1724 .sign(payer_sign).unwrap();
1725 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1726 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1727 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1731 fn fails_signing_invoice_request() {
1732 match OfferBuilder::new("foo".into(), recipient_pubkey())
1735 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1739 Ok(_) => panic!("expected error"),
1740 Err(e) => assert_eq!(e, SignError::Signing),
1743 match OfferBuilder::new("foo".into(), recipient_pubkey())
1746 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1748 .sign(recipient_sign)
1750 Ok(_) => panic!("expected error"),
1751 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1756 fn fails_responding_with_unknown_required_features() {
1757 match OfferBuilder::new("foo".into(), recipient_pubkey())
1760 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1761 .features_unchecked(InvoiceRequestFeatures::unknown())
1763 .sign(payer_sign).unwrap()
1764 .respond_with_no_std(payment_paths(), payment_hash(), now())
1766 Ok(_) => panic!("expected error"),
1767 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1772 fn parses_invoice_request_with_metadata() {
1773 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1776 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1778 .sign(payer_sign).unwrap();
1780 let mut buffer = Vec::new();
1781 invoice_request.write(&mut buffer).unwrap();
1783 if let Err(e) = InvoiceRequest::try_from(buffer) {
1784 panic!("error parsing invoice_request: {:?}", e);
1789 fn parses_invoice_request_with_chain() {
1790 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1793 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1794 .chain(Network::Bitcoin).unwrap()
1796 .sign(payer_sign).unwrap();
1798 let mut buffer = Vec::new();
1799 invoice_request.write(&mut buffer).unwrap();
1801 if let Err(e) = InvoiceRequest::try_from(buffer) {
1802 panic!("error parsing invoice_request: {:?}", e);
1805 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1808 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1809 .chain_unchecked(Network::Testnet)
1811 .sign(payer_sign).unwrap();
1813 let mut buffer = Vec::new();
1814 invoice_request.write(&mut buffer).unwrap();
1816 match InvoiceRequest::try_from(buffer) {
1817 Ok(_) => panic!("expected error"),
1818 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1823 fn parses_invoice_request_with_amount() {
1824 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1827 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1829 .sign(payer_sign).unwrap();
1831 let mut buffer = Vec::new();
1832 invoice_request.write(&mut buffer).unwrap();
1834 if let Err(e) = InvoiceRequest::try_from(buffer) {
1835 panic!("error parsing invoice_request: {:?}", e);
1838 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1840 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1841 .amount_msats(1000).unwrap()
1843 .sign(payer_sign).unwrap();
1845 let mut buffer = Vec::new();
1846 invoice_request.write(&mut buffer).unwrap();
1848 if let Err(e) = InvoiceRequest::try_from(buffer) {
1849 panic!("error parsing invoice_request: {:?}", e);
1852 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1854 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1856 .sign(payer_sign).unwrap();
1858 let mut buffer = Vec::new();
1859 invoice_request.write(&mut buffer).unwrap();
1861 match InvoiceRequest::try_from(buffer) {
1862 Ok(_) => panic!("expected error"),
1863 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1866 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1869 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1870 .amount_msats_unchecked(999)
1872 .sign(payer_sign).unwrap();
1874 let mut buffer = Vec::new();
1875 invoice_request.write(&mut buffer).unwrap();
1877 match InvoiceRequest::try_from(buffer) {
1878 Ok(_) => panic!("expected error"),
1879 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1882 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1883 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1885 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1887 .sign(payer_sign).unwrap();
1889 let mut buffer = Vec::new();
1890 invoice_request.write(&mut buffer).unwrap();
1892 match InvoiceRequest::try_from(buffer) {
1893 Ok(_) => panic!("expected error"),
1895 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1899 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1901 .supported_quantity(Quantity::Unbounded)
1903 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1904 .quantity(u64::max_value()).unwrap()
1906 .sign(payer_sign).unwrap();
1908 let mut buffer = Vec::new();
1909 invoice_request.write(&mut buffer).unwrap();
1911 match InvoiceRequest::try_from(buffer) {
1912 Ok(_) => panic!("expected error"),
1913 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1918 fn parses_invoice_request_with_quantity() {
1919 let one = NonZeroU64::new(1).unwrap();
1920 let ten = NonZeroU64::new(10).unwrap();
1922 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1924 .supported_quantity(Quantity::One)
1926 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1928 .sign(payer_sign).unwrap();
1930 let mut buffer = Vec::new();
1931 invoice_request.write(&mut buffer).unwrap();
1933 if let Err(e) = InvoiceRequest::try_from(buffer) {
1934 panic!("error parsing invoice_request: {:?}", e);
1937 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1939 .supported_quantity(Quantity::One)
1941 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1942 .amount_msats(2_000).unwrap()
1943 .quantity_unchecked(2)
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"),
1953 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1957 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1959 .supported_quantity(Quantity::Bounded(ten))
1961 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1962 .amount_msats(10_000).unwrap()
1963 .quantity(10).unwrap()
1965 .sign(payer_sign).unwrap();
1967 let mut buffer = Vec::new();
1968 invoice_request.write(&mut buffer).unwrap();
1970 if let Err(e) = InvoiceRequest::try_from(buffer) {
1971 panic!("error parsing invoice_request: {:?}", e);
1974 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1976 .supported_quantity(Quantity::Bounded(ten))
1978 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1979 .amount_msats(11_000).unwrap()
1980 .quantity_unchecked(11)
1982 .sign(payer_sign).unwrap();
1984 let mut buffer = Vec::new();
1985 invoice_request.write(&mut buffer).unwrap();
1987 match InvoiceRequest::try_from(buffer) {
1988 Ok(_) => panic!("expected error"),
1989 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1992 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1994 .supported_quantity(Quantity::Unbounded)
1996 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1997 .amount_msats(2_000).unwrap()
1998 .quantity(2).unwrap()
2000 .sign(payer_sign).unwrap();
2002 let mut buffer = Vec::new();
2003 invoice_request.write(&mut buffer).unwrap();
2005 if let Err(e) = InvoiceRequest::try_from(buffer) {
2006 panic!("error parsing invoice_request: {:?}", e);
2009 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2011 .supported_quantity(Quantity::Unbounded)
2013 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2015 .sign(payer_sign).unwrap();
2017 let mut buffer = Vec::new();
2018 invoice_request.write(&mut buffer).unwrap();
2020 match InvoiceRequest::try_from(buffer) {
2021 Ok(_) => panic!("expected error"),
2022 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2025 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2027 .supported_quantity(Quantity::Bounded(one))
2029 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2031 .sign(payer_sign).unwrap();
2033 let mut buffer = Vec::new();
2034 invoice_request.write(&mut buffer).unwrap();
2036 match InvoiceRequest::try_from(buffer) {
2037 Ok(_) => panic!("expected error"),
2038 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2043 fn fails_parsing_invoice_request_without_metadata() {
2044 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2047 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2049 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2050 tlv_stream.0.metadata = None;
2052 let mut buffer = Vec::new();
2053 tlv_stream.write(&mut buffer).unwrap();
2055 match InvoiceRequest::try_from(buffer) {
2056 Ok(_) => panic!("expected error"),
2058 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2064 fn fails_parsing_invoice_request_without_payer_id() {
2065 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2068 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2070 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2071 tlv_stream.2.payer_id = None;
2073 let mut buffer = Vec::new();
2074 tlv_stream.write(&mut buffer).unwrap();
2076 match InvoiceRequest::try_from(buffer) {
2077 Ok(_) => panic!("expected error"),
2078 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2083 fn fails_parsing_invoice_request_without_node_id() {
2084 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2087 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2089 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2090 tlv_stream.1.node_id = None;
2092 let mut buffer = Vec::new();
2093 tlv_stream.write(&mut buffer).unwrap();
2095 match InvoiceRequest::try_from(buffer) {
2096 Ok(_) => panic!("expected error"),
2098 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2104 fn fails_parsing_invoice_request_without_signature() {
2105 let mut buffer = Vec::new();
2106 OfferBuilder::new("foo".into(), recipient_pubkey())
2109 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2112 .write(&mut buffer).unwrap();
2114 match InvoiceRequest::try_from(buffer) {
2115 Ok(_) => panic!("expected error"),
2116 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2121 fn fails_parsing_invoice_request_with_invalid_signature() {
2122 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2125 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2127 .sign(payer_sign).unwrap();
2128 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2129 *last_signature_byte = last_signature_byte.wrapping_add(1);
2131 let mut buffer = Vec::new();
2132 invoice_request.write(&mut buffer).unwrap();
2134 match InvoiceRequest::try_from(buffer) {
2135 Ok(_) => panic!("expected error"),
2137 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2143 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2144 let secp_ctx = Secp256k1::new();
2145 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2146 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2149 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2151 .sign(|message: &UnsignedInvoiceRequest|
2152 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2156 let mut encoded_invoice_request = Vec::new();
2157 invoice_request.write(&mut encoded_invoice_request).unwrap();
2158 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2159 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2160 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2162 match InvoiceRequest::try_from(encoded_invoice_request) {
2163 Ok(_) => panic!("expected error"),
2164 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),