1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `invoice_request` messages.
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with a [`Bolt12Invoice`].
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
23 //! extern crate bitcoin;
24 //! extern crate lightning;
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
33 //! # fn parse() -> Result<(), lightning::offers::parse::Bolt12ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
39 //! # use lightning::offers::invoice_request::{ExplicitPayerId, InvoiceRequestBuilder};
40 //! # <InvoiceRequestBuilder<ExplicitPayerId, _>>::from(
42 //! .parse::<Offer>()?
43 //! .request_invoice(vec![42; 64], pubkey)?
45 //! .chain(Network::Testnet)?
46 //! .amount_msats(1000)?
48 //! .payer_note("foo".to_string())
50 //! .sign::<_, Infallible>(
51 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
53 //! .expect("failed verifying signature")
54 //! .write(&mut buffer)
60 use bitcoin::blockdata::constants::ChainHash;
61 use bitcoin::network::constants::Network;
62 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
63 use bitcoin::secp256k1::schnorr::Signature;
64 use core::convert::{AsRef, Infallible, TryFrom};
66 use crate::sign::EntropySource;
68 use crate::blinded_path::BlindedPath;
69 use crate::ln::PaymentHash;
70 use crate::ln::channelmanager::PaymentId;
71 use crate::ln::features::InvoiceRequestFeatures;
72 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
73 use crate::ln::msgs::DecodeError;
74 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
75 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
76 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
77 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
78 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
79 use crate::offers::signer::{Metadata, MetadataMaterial};
80 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
81 use crate::util::string::PrintableString;
83 use crate::prelude::*;
85 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
86 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
88 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
90 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
92 /// See [module-level documentation] for usage.
94 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
96 /// [module-level documentation]: self
97 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
99 invoice_request: InvoiceRequestContentsWithoutPayerId,
100 payer_id: Option<PublicKey>,
101 payer_id_strategy: core::marker::PhantomData<P>,
102 secp_ctx: Option<&'b Secp256k1<T>>,
105 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
107 /// See [module-level documentation] for usage.
109 /// [module-level documentation]: self
111 pub struct InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
113 invoice_request: InvoiceRequestContentsWithoutPayerId,
114 payer_id: Option<PublicKey>,
115 payer_id_strategy: core::marker::PhantomData<ExplicitPayerId>,
116 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
119 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
121 /// See [module-level documentation] for usage.
123 /// [module-level documentation]: self
125 pub struct InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
127 invoice_request: InvoiceRequestContentsWithoutPayerId,
128 payer_id: Option<PublicKey>,
129 payer_id_strategy: core::marker::PhantomData<DerivedPayerId>,
130 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
133 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
135 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
136 pub trait PayerIdStrategy {}
138 /// [`InvoiceRequest::payer_id`] will be explicitly set.
140 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
141 pub struct ExplicitPayerId {}
143 /// [`InvoiceRequest::payer_id`] will be derived.
145 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
146 pub struct DerivedPayerId {}
148 impl PayerIdStrategy for ExplicitPayerId {}
149 impl PayerIdStrategy for DerivedPayerId {}
151 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
152 #[cfg_attr(c_bindings, allow(dead_code))]
153 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
156 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
157 payer_id: Some(payer_id),
158 payer_id_strategy: core::marker::PhantomData,
163 #[cfg_attr(c_bindings, allow(dead_code))]
164 pub(super) fn deriving_metadata<ES: Deref>(
165 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
166 payment_id: PaymentId,
167 ) -> Self where ES::Target: EntropySource {
168 let nonce = Nonce::from_entropy_source(entropy_source);
169 let payment_id = Some(payment_id);
170 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
171 let metadata = Metadata::Derived(derivation_material);
174 invoice_request: Self::create_contents(offer, metadata),
175 payer_id: Some(payer_id),
176 payer_id_strategy: core::marker::PhantomData,
181 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
182 /// by [`UnsignedInvoiceRequest::sign`].
183 pub fn build($self: $self_type) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
184 let (unsigned_invoice_request, keys, _) = $self.build_with_checks()?;
185 debug_assert!(keys.is_none());
186 Ok(unsigned_invoice_request)
190 macro_rules! invoice_request_derived_payer_id_builder_methods { (
191 $self: ident, $self_type: ty, $secp_context: ty
193 #[cfg_attr(c_bindings, allow(dead_code))]
194 pub(super) fn deriving_payer_id<ES: Deref>(
195 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
196 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
197 ) -> Self where ES::Target: EntropySource {
198 let nonce = Nonce::from_entropy_source(entropy_source);
199 let payment_id = Some(payment_id);
200 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
201 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
204 invoice_request: Self::create_contents(offer, metadata),
206 payer_id_strategy: core::marker::PhantomData,
207 secp_ctx: Some(secp_ctx),
211 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
212 pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
213 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
215 let mut unsigned_invoice_request = unsigned_invoice_request;
216 debug_assert!(keys.is_some());
218 let secp_ctx = secp_ctx.unwrap();
219 let keys = keys.unwrap();
220 let invoice_request = unsigned_invoice_request
221 .sign::<_, Infallible>(
222 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
229 macro_rules! invoice_request_builder_methods { (
230 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
232 #[cfg_attr(c_bindings, allow(dead_code))]
233 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
234 let offer = offer.contents.clone();
235 InvoiceRequestContentsWithoutPayerId {
236 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
237 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
241 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
242 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
245 /// Successive calls to this method will override the previous setting.
246 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
247 $self.chain_hash(ChainHash::using_genesis_block(network))
250 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
251 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
254 /// Successive calls to this method will override the previous setting.
255 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
256 if !$self.offer.supports_chain(chain) {
257 return Err(Bolt12SemanticError::UnsupportedChain);
260 $self.invoice_request.chain = Some(chain);
264 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
265 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
267 /// Successive calls to this method will override the previous setting.
269 /// [`quantity`]: Self::quantity
270 pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
271 $self.invoice_request.offer.check_amount_msats_for_quantity(
272 Some(amount_msats), $self.invoice_request.quantity
274 $self.invoice_request.amount_msats = Some(amount_msats);
278 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
279 /// does not conform to [`Offer::is_valid_quantity`].
281 /// Successive calls to this method will override the previous setting.
282 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
283 $self.invoice_request.offer.check_quantity(Some(quantity))?;
284 $self.invoice_request.quantity = Some(quantity);
288 /// Sets the [`InvoiceRequest::payer_note`].
290 /// Successive calls to this method will override the previous setting.
291 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
292 $self.invoice_request.payer_note = Some(payer_note);
296 fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
297 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>),
300 #[cfg(feature = "std")] {
301 if $self.offer.is_expired() {
302 return Err(Bolt12SemanticError::AlreadyExpired);
306 let chain = $self.invoice_request.chain();
307 if !$self.offer.supports_chain(chain) {
308 return Err(Bolt12SemanticError::UnsupportedChain);
311 if chain == $self.offer.implied_chain() {
312 $self.invoice_request.chain = None;
315 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
316 return Err(Bolt12SemanticError::MissingAmount);
319 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
320 $self.invoice_request.offer.check_amount_msats_for_quantity(
321 $self.invoice_request.amount_msats, $self.invoice_request.quantity
324 Ok($self.build_without_checks())
327 fn build_without_checks($($self_mut)* $self: $self_type) ->
328 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<$secp_context>>)
330 // Create the metadata for stateless verification of a Bolt12Invoice.
332 let secp_ctx = $self.secp_ctx.clone();
333 if $self.invoice_request.payer.0.has_derivation_material() {
334 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
336 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
337 debug_assert!(tlv_stream.2.payer_id.is_none());
338 tlv_stream.0.metadata = None;
339 if !metadata.derives_payer_keys() {
340 tlv_stream.2.payer_id = $self.payer_id.as_ref();
343 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
344 metadata = derived_metadata;
346 if let Some(keys) = keys {
347 debug_assert!($self.payer_id.is_none());
348 $self.payer_id = Some(keys.public_key());
351 $self.invoice_request.payer.0 = metadata;
354 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
355 debug_assert!($self.payer_id.is_some());
356 let payer_id = $self.payer_id.unwrap();
358 let invoice_request = InvoiceRequestContents {
359 #[cfg(not(c_bindings))]
360 inner: $self.invoice_request,
362 inner: $self.invoice_request.clone(),
365 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
367 (unsigned_invoice_request, keys, secp_ctx)
372 macro_rules! invoice_request_builder_test_methods { (
373 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
375 #[cfg_attr(c_bindings, allow(dead_code))]
376 fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
377 let chain = ChainHash::using_genesis_block(network);
378 $self.invoice_request.chain = Some(chain);
382 #[cfg_attr(c_bindings, allow(dead_code))]
383 fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
384 $self.invoice_request.amount_msats = Some(amount_msats);
388 #[cfg_attr(c_bindings, allow(dead_code))]
389 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
390 $self.invoice_request.features = features;
394 #[cfg_attr(c_bindings, allow(dead_code))]
395 fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
396 $self.invoice_request.quantity = Some(quantity);
400 #[cfg_attr(c_bindings, allow(dead_code))]
401 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
402 $self.build_without_checks().0
406 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
407 invoice_request_explicit_payer_id_builder_methods!(self, Self);
410 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
411 invoice_request_derived_payer_id_builder_methods!(self, Self, T);
414 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
415 invoice_request_builder_methods!(self, Self, Self, self, T, mut);
418 invoice_request_builder_test_methods!(self, Self, Self, self, mut);
421 #[cfg(all(c_bindings, not(test)))]
422 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
423 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
424 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
427 #[cfg(all(c_bindings, test))]
428 impl<'a, 'b> InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b> {
429 invoice_request_explicit_payer_id_builder_methods!(self, &mut Self);
430 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
431 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
434 #[cfg(all(c_bindings, not(test)))]
435 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
436 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
437 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
440 #[cfg(all(c_bindings, test))]
441 impl<'a, 'b> InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b> {
442 invoice_request_derived_payer_id_builder_methods!(self, &mut Self, secp256k1::All);
443 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
444 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
448 impl<'a, 'b> From<InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>>
449 for InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, secp256k1::All> {
450 fn from(builder: InvoiceRequestWithExplicitPayerIdBuilder<'a, 'b>) -> Self {
451 let InvoiceRequestWithExplicitPayerIdBuilder {
452 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
456 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
462 impl<'a, 'b> From<InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>>
463 for InvoiceRequestBuilder<'a, 'b, DerivedPayerId, secp256k1::All> {
464 fn from(builder: InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>) -> Self {
465 let InvoiceRequestWithDerivedPayerIdBuilder {
466 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
470 offer, invoice_request, payer_id, payer_id_strategy, secp_ctx,
475 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
479 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
480 /// such, it may include unknown, odd TLV records.
481 pub struct UnsignedInvoiceRequest {
483 contents: InvoiceRequestContents,
484 tagged_hash: TaggedHash,
487 impl UnsignedInvoiceRequest {
488 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
489 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
490 // unknown TLV records, which are not stored in `OfferContents`.
491 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
492 contents.as_tlv_stream();
493 let offer_bytes = WithoutLength(&offer.bytes);
494 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
496 let mut bytes = Vec::new();
497 unsigned_tlv_stream.write(&mut bytes).unwrap();
499 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
501 Self { bytes, contents, tagged_hash }
504 /// Returns the [`TaggedHash`] of the invoice to sign.
505 pub fn tagged_hash(&self) -> &TaggedHash {
510 macro_rules! unsigned_invoice_request_sign_method { (
511 $self: ident, $self_type: ty $(, $self_mut: tt)?
513 /// Signs the [`TaggedHash`] of the invoice request using the given function.
515 /// Note: The hash computation may have included unknown, odd TLV records.
517 /// This is not exported to bindings users as functions are not yet mapped.
518 pub fn sign<F, E>($($self_mut)* $self: $self_type, sign: F) -> Result<InvoiceRequest, SignError<E>>
520 F: FnOnce(&Self) -> Result<Signature, E>
522 let pubkey = $self.contents.payer_id;
523 let signature = merkle::sign_message(sign, &$self, pubkey)?;
525 // Append the signature TLV record to the bytes.
526 let signature_tlv_stream = SignatureTlvStreamRef {
527 signature: Some(&signature),
529 signature_tlv_stream.write(&mut $self.bytes).unwrap();
532 #[cfg(not(c_bindings))]
535 bytes: $self.bytes.clone(),
536 #[cfg(not(c_bindings))]
537 contents: $self.contents,
539 contents: $self.contents.clone(),
545 #[cfg(not(c_bindings))]
546 impl UnsignedInvoiceRequest {
547 unsigned_invoice_request_sign_method!(self, Self, mut);
551 impl UnsignedInvoiceRequest {
552 unsigned_invoice_request_sign_method!(self, &mut Self);
555 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
556 fn as_ref(&self) -> &TaggedHash {
561 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
563 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
564 /// specifies these such that its recipient can send an invoice for payment.
566 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
567 /// [`Offer`]: crate::offers::offer::Offer
568 #[derive(Clone, Debug)]
569 #[cfg_attr(test, derive(PartialEq))]
570 pub struct InvoiceRequest {
571 pub(super) bytes: Vec<u8>,
572 pub(super) contents: InvoiceRequestContents,
573 signature: Signature,
576 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
577 /// ways to respond depending on whether the signing keys were derived.
578 #[derive(Clone, Debug)]
579 pub struct VerifiedInvoiceRequest {
580 /// The verified request.
581 inner: InvoiceRequest,
583 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
585 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
586 /// [`respond_with`].
588 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
589 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
590 /// [`respond_with`]: Self::respond_with
591 pub keys: Option<KeyPair>,
594 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
596 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
597 #[derive(Clone, Debug)]
598 #[cfg_attr(test, derive(PartialEq))]
599 pub(super) struct InvoiceRequestContents {
600 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
604 #[derive(Clone, Debug)]
605 #[cfg_attr(test, derive(PartialEq))]
606 pub(super) struct InvoiceRequestContentsWithoutPayerId {
607 payer: PayerContents,
608 pub(super) offer: OfferContents,
609 chain: Option<ChainHash>,
610 amount_msats: Option<u64>,
611 features: InvoiceRequestFeatures,
612 quantity: Option<u64>,
613 payer_note: Option<String>,
616 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
617 /// An unpredictable series of bytes, typically containing information about the derivation of
620 /// [`payer_id`]: Self::payer_id
621 pub fn payer_metadata(&$self) -> &[u8] {
625 /// A chain from [`Offer::chains`] that the offer is valid for.
626 pub fn chain(&$self) -> ChainHash {
630 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
631 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
633 /// [`chain`]: Self::chain
634 pub fn amount_msats(&$self) -> Option<u64> {
635 $contents.amount_msats()
638 /// Features pertaining to requesting an invoice.
639 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
640 &$contents.features()
643 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
644 pub fn quantity(&$self) -> Option<u64> {
648 /// A possibly transient pubkey used to sign the invoice request.
649 pub fn payer_id(&$self) -> PublicKey {
653 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
655 pub fn payer_note(&$self) -> Option<PrintableString> {
656 $contents.payer_note()
660 impl UnsignedInvoiceRequest {
661 offer_accessors!(self, self.contents.inner.offer);
662 invoice_request_accessors!(self, self.contents);
665 impl InvoiceRequest {
666 offer_accessors!(self, self.contents.inner.offer);
667 invoice_request_accessors!(self, self.contents);
669 /// Signature of the invoice request using [`payer_id`].
671 /// [`payer_id`]: Self::payer_id
672 pub fn signature(&self) -> Signature {
676 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
677 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
679 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
680 /// creation time is used for the `created_at` parameter.
682 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
684 /// [`Duration`]: core::time::Duration
685 #[cfg(feature = "std")]
687 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
688 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
689 let created_at = std::time::SystemTime::now()
690 .duration_since(std::time::SystemTime::UNIX_EPOCH)
691 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
693 self.respond_with_no_std(payment_paths, payment_hash, created_at)
696 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
698 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
699 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
700 /// where [`std::time::SystemTime`] is not available.
702 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
705 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
706 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
707 /// a preference. Note, however, that any privacy is lost if a public node id was used for
708 /// [`Offer::signing_pubkey`].
710 /// Errors if the request contains unknown required features.
714 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
715 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
717 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
719 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
720 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
721 pub fn respond_with_no_std(
722 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
723 created_at: core::time::Duration
724 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
725 if self.invoice_request_features().requires_unknown_bits() {
726 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
729 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
732 /// Verifies that the request was for an offer created using the given key. Returns the verified
733 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
734 /// if they could be extracted from the metadata.
736 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
737 pub fn verify<T: secp256k1::Signing>(
738 self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
739 ) -> Result<VerifiedInvoiceRequest, ()> {
740 let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
741 Ok(VerifiedInvoiceRequest {
747 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
748 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
749 self.contents.as_tlv_stream();
750 let signature_tlv_stream = SignatureTlvStreamRef {
751 signature: Some(&self.signature),
753 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
757 impl VerifiedInvoiceRequest {
758 offer_accessors!(self, self.inner.contents.inner.offer);
759 invoice_request_accessors!(self, self.inner.contents);
761 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
762 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
764 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
766 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
768 /// [`Duration`]: core::time::Duration
769 #[cfg(feature = "std")]
771 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
772 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
773 self.inner.respond_with(payment_paths, payment_hash)
776 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
778 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
780 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
781 pub fn respond_with_no_std(
782 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
783 created_at: core::time::Duration
784 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
785 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
788 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
789 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
790 /// the same [`ExpandedKey`] as the one used to create the offer.
792 /// See [`InvoiceRequest::respond_with`] for further details.
794 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
796 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
797 #[cfg(feature = "std")]
798 pub fn respond_using_derived_keys(
799 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
800 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
801 let created_at = std::time::SystemTime::now()
802 .duration_since(std::time::SystemTime::UNIX_EPOCH)
803 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
805 self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
808 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
809 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
810 /// the same [`ExpandedKey`] as the one used to create the offer.
812 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
814 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
816 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
817 pub fn respond_using_derived_keys_no_std(
818 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
819 created_at: core::time::Duration
820 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
821 if self.inner.invoice_request_features().requires_unknown_bits() {
822 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
825 let keys = match self.keys {
826 None => return Err(Bolt12SemanticError::InvalidMetadata),
830 InvoiceBuilder::for_offer_using_keys(
831 &self.inner, payment_paths, created_at, payment_hash, keys
836 impl InvoiceRequestContents {
837 pub(super) fn metadata(&self) -> &[u8] {
838 self.inner.metadata()
841 pub(super) fn derives_keys(&self) -> bool {
842 self.inner.payer.0.derives_payer_keys()
845 pub(super) fn chain(&self) -> ChainHash {
849 pub(super) fn amount_msats(&self) -> Option<u64> {
850 self.inner.amount_msats
853 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
857 pub(super) fn quantity(&self) -> Option<u64> {
861 pub(super) fn payer_id(&self) -> PublicKey {
865 pub(super) fn payer_note(&self) -> Option<PrintableString> {
866 self.inner.payer_note.as_ref()
867 .map(|payer_note| PrintableString(payer_note.as_str()))
870 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
871 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
872 invoice_request.payer_id = Some(&self.payer_id);
873 (payer, offer, invoice_request)
877 impl InvoiceRequestContentsWithoutPayerId {
878 pub(super) fn metadata(&self) -> &[u8] {
879 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
882 pub(super) fn chain(&self) -> ChainHash {
883 self.chain.unwrap_or_else(|| self.offer.implied_chain())
886 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
887 let payer = PayerTlvStreamRef {
888 metadata: self.payer.0.as_bytes(),
891 let offer = self.offer.as_tlv_stream();
894 if self.features == InvoiceRequestFeatures::empty() { None }
895 else { Some(&self.features) }
898 let invoice_request = InvoiceRequestTlvStreamRef {
899 chain: self.chain.as_ref(),
900 amount: self.amount_msats,
902 quantity: self.quantity,
904 payer_note: self.payer_note.as_ref(),
907 (payer, offer, invoice_request)
911 impl Writeable for UnsignedInvoiceRequest {
912 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
913 WithoutLength(&self.bytes).write(writer)
917 impl Writeable for InvoiceRequest {
918 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
919 WithoutLength(&self.bytes).write(writer)
923 impl Writeable for InvoiceRequestContents {
924 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
925 self.as_tlv_stream().write(writer)
929 /// Valid type range for invoice_request TLV records.
930 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
932 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
934 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
935 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
937 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
938 (80, chain: ChainHash),
939 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
940 (84, features: (InvoiceRequestFeatures, WithoutLength)),
941 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
942 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
943 (89, payer_note: (String, WithoutLength)),
946 type FullInvoiceRequestTlvStream =
947 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
949 type FullInvoiceRequestTlvStreamRef<'a> = (
950 PayerTlvStreamRef<'a>,
951 OfferTlvStreamRef<'a>,
952 InvoiceRequestTlvStreamRef<'a>,
953 SignatureTlvStreamRef<'a>,
956 impl SeekReadable for FullInvoiceRequestTlvStream {
957 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
958 let payer = SeekReadable::read(r)?;
959 let offer = SeekReadable::read(r)?;
960 let invoice_request = SeekReadable::read(r)?;
961 let signature = SeekReadable::read(r)?;
963 Ok((payer, offer, invoice_request, signature))
967 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
969 type PartialInvoiceRequestTlvStreamRef<'a> = (
970 PayerTlvStreamRef<'a>,
971 OfferTlvStreamRef<'a>,
972 InvoiceRequestTlvStreamRef<'a>,
975 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
976 type Error = Bolt12ParseError;
978 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
979 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
980 let ParsedMessage { bytes, tlv_stream } = invoice_request;
982 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
984 let contents = InvoiceRequestContents::try_from(
985 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
988 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
990 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
994 impl TryFrom<Vec<u8>> for InvoiceRequest {
995 type Error = Bolt12ParseError;
997 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
998 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
999 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1001 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1002 SignatureTlvStream { signature },
1004 let contents = InvoiceRequestContents::try_from(
1005 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1008 let signature = match signature {
1009 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1010 Some(signature) => signature,
1012 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
1013 merkle::verify_signature(&signature, &message, contents.payer_id)?;
1015 Ok(InvoiceRequest { bytes, contents, signature })
1019 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1020 type Error = Bolt12SemanticError;
1022 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1024 PayerTlvStream { metadata },
1026 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
1029 let payer = match metadata {
1030 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1031 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1033 let offer = OfferContents::try_from(offer_tlv_stream)?;
1035 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1036 return Err(Bolt12SemanticError::UnsupportedChain);
1039 if offer.amount().is_none() && amount.is_none() {
1040 return Err(Bolt12SemanticError::MissingAmount);
1043 offer.check_quantity(quantity)?;
1044 offer.check_amount_msats_for_quantity(amount, quantity)?;
1046 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1048 let payer_id = match payer_id {
1049 None => return Err(Bolt12SemanticError::MissingPayerId),
1050 Some(payer_id) => payer_id,
1053 Ok(InvoiceRequestContents {
1054 inner: InvoiceRequestContentsWithoutPayerId {
1055 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1064 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
1066 use bitcoin::blockdata::constants::ChainHash;
1067 use bitcoin::network::constants::Network;
1068 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
1069 use core::convert::{Infallible, TryFrom};
1070 use core::num::NonZeroU64;
1071 #[cfg(feature = "std")]
1072 use core::time::Duration;
1073 use crate::sign::KeyMaterial;
1074 use crate::ln::channelmanager::PaymentId;
1075 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
1076 use crate::ln::inbound_payment::ExpandedKey;
1077 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1078 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1079 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1080 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1081 #[cfg(not(c_bindings))]
1083 crate::offers::offer::OfferBuilder,
1087 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1089 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1090 use crate::offers::payer::PayerTlvStreamRef;
1091 use crate::offers::test_utils::*;
1092 use crate::util::ser::{BigSize, Writeable};
1093 use crate::util::string::PrintableString;
1096 fn builds_invoice_request_with_defaults() {
1097 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1100 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1103 let mut unsigned_invoice_request = unsigned_invoice_request;
1105 let mut buffer = Vec::new();
1106 unsigned_invoice_request.write(&mut buffer).unwrap();
1108 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
1109 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
1110 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1111 assert_eq!(unsigned_invoice_request.metadata(), None);
1112 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1113 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
1114 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
1115 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
1116 assert_eq!(unsigned_invoice_request.paths(), &[]);
1117 assert_eq!(unsigned_invoice_request.issuer(), None);
1118 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1119 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1120 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1121 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1122 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1123 assert_eq!(unsigned_invoice_request.quantity(), None);
1124 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1125 assert_eq!(unsigned_invoice_request.payer_note(), None);
1127 match UnsignedInvoiceRequest::try_from(buffer) {
1128 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1130 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1131 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1135 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1137 let mut buffer = Vec::new();
1138 invoice_request.write(&mut buffer).unwrap();
1140 assert_eq!(invoice_request.bytes, buffer.as_slice());
1141 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1142 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1143 assert_eq!(invoice_request.metadata(), None);
1144 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1145 assert_eq!(invoice_request.description(), PrintableString("foo"));
1146 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1147 assert_eq!(invoice_request.absolute_expiry(), None);
1148 assert_eq!(invoice_request.paths(), &[]);
1149 assert_eq!(invoice_request.issuer(), None);
1150 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1151 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1152 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1153 assert_eq!(invoice_request.amount_msats(), None);
1154 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1155 assert_eq!(invoice_request.quantity(), None);
1156 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1157 assert_eq!(invoice_request.payer_note(), None);
1159 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1160 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1163 invoice_request.as_tlv_stream(),
1165 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1171 description: Some(&String::from("foo")),
1173 absolute_expiry: None,
1177 node_id: Some(&recipient_pubkey()),
1179 InvoiceRequestTlvStreamRef {
1184 payer_id: Some(&payer_pubkey()),
1187 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1191 if let Err(e) = InvoiceRequest::try_from(buffer) {
1192 panic!("error parsing invoice request: {:?}", e);
1196 #[cfg(feature = "std")]
1198 fn builds_invoice_request_from_offer_with_expiration() {
1199 let future_expiry = Duration::from_secs(u64::max_value());
1200 let past_expiry = Duration::from_secs(0);
1202 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1204 .absolute_expiry(future_expiry)
1206 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1209 panic!("error building invoice_request: {:?}", e);
1212 match OfferBuilder::new("foo".into(), recipient_pubkey())
1214 .absolute_expiry(past_expiry)
1216 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1219 Ok(_) => panic!("expected error"),
1220 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1225 fn builds_invoice_request_with_derived_metadata() {
1226 let payer_id = payer_pubkey();
1227 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1228 let entropy = FixedEntropy {};
1229 let secp_ctx = Secp256k1::new();
1230 let payment_id = PaymentId([1; 32]);
1232 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1235 let invoice_request = offer
1236 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1239 .sign(payer_sign).unwrap();
1240 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1242 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1245 .sign(recipient_sign).unwrap();
1246 match invoice.verify(&expanded_key, &secp_ctx) {
1247 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1248 Err(()) => panic!("verification failed"),
1251 // Fails verification with altered fields
1253 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1254 mut invoice_tlv_stream, mut signature_tlv_stream
1255 ) = invoice.as_tlv_stream();
1256 invoice_request_tlv_stream.amount = Some(2000);
1257 invoice_tlv_stream.amount = Some(2000);
1260 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1261 let mut bytes = Vec::new();
1262 tlv_stream.write(&mut bytes).unwrap();
1264 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1265 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1266 signature_tlv_stream.signature = Some(&signature);
1268 let mut encoded_invoice = bytes;
1269 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1271 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1272 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1274 // Fails verification with altered metadata
1276 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1277 mut signature_tlv_stream
1278 ) = invoice.as_tlv_stream();
1279 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1280 payer_tlv_stream.metadata = Some(&metadata);
1283 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1284 let mut bytes = Vec::new();
1285 tlv_stream.write(&mut bytes).unwrap();
1287 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1288 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1289 signature_tlv_stream.signature = Some(&signature);
1291 let mut encoded_invoice = bytes;
1292 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1294 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1295 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1299 fn builds_invoice_request_with_derived_payer_id() {
1300 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1301 let entropy = FixedEntropy {};
1302 let secp_ctx = Secp256k1::new();
1303 let payment_id = PaymentId([1; 32]);
1305 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1308 let invoice_request = offer
1309 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1314 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1317 .sign(recipient_sign).unwrap();
1318 match invoice.verify(&expanded_key, &secp_ctx) {
1319 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1320 Err(()) => panic!("verification failed"),
1323 // Fails verification with altered fields
1325 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1326 mut invoice_tlv_stream, mut signature_tlv_stream
1327 ) = invoice.as_tlv_stream();
1328 invoice_request_tlv_stream.amount = Some(2000);
1329 invoice_tlv_stream.amount = Some(2000);
1332 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1333 let mut bytes = Vec::new();
1334 tlv_stream.write(&mut bytes).unwrap();
1336 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1337 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1338 signature_tlv_stream.signature = Some(&signature);
1340 let mut encoded_invoice = bytes;
1341 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1343 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1344 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1346 // Fails verification with altered payer id
1348 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1349 mut signature_tlv_stream
1350 ) = invoice.as_tlv_stream();
1351 let payer_id = pubkey(1);
1352 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1355 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1356 let mut bytes = Vec::new();
1357 tlv_stream.write(&mut bytes).unwrap();
1359 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1360 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1361 signature_tlv_stream.signature = Some(&signature);
1363 let mut encoded_invoice = bytes;
1364 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1366 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1367 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1371 fn builds_invoice_request_with_chain() {
1372 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1373 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1375 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1378 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1379 .chain(Network::Bitcoin).unwrap()
1381 .sign(payer_sign).unwrap();
1382 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1383 assert_eq!(invoice_request.chain(), mainnet);
1384 assert_eq!(tlv_stream.chain, None);
1386 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1388 .chain(Network::Testnet)
1390 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1391 .chain(Network::Testnet).unwrap()
1393 .sign(payer_sign).unwrap();
1394 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1395 assert_eq!(invoice_request.chain(), testnet);
1396 assert_eq!(tlv_stream.chain, Some(&testnet));
1398 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1400 .chain(Network::Bitcoin)
1401 .chain(Network::Testnet)
1403 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1404 .chain(Network::Bitcoin).unwrap()
1406 .sign(payer_sign).unwrap();
1407 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1408 assert_eq!(invoice_request.chain(), mainnet);
1409 assert_eq!(tlv_stream.chain, None);
1411 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1413 .chain(Network::Bitcoin)
1414 .chain(Network::Testnet)
1416 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1417 .chain(Network::Bitcoin).unwrap()
1418 .chain(Network::Testnet).unwrap()
1420 .sign(payer_sign).unwrap();
1421 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1422 assert_eq!(invoice_request.chain(), testnet);
1423 assert_eq!(tlv_stream.chain, Some(&testnet));
1425 match OfferBuilder::new("foo".into(), recipient_pubkey())
1427 .chain(Network::Testnet)
1429 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1430 .chain(Network::Bitcoin)
1432 Ok(_) => panic!("expected error"),
1433 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1436 match OfferBuilder::new("foo".into(), recipient_pubkey())
1438 .chain(Network::Testnet)
1440 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1443 Ok(_) => panic!("expected error"),
1444 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1449 fn builds_invoice_request_with_amount() {
1450 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1453 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1454 .amount_msats(1000).unwrap()
1456 .sign(payer_sign).unwrap();
1457 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1458 assert_eq!(invoice_request.amount_msats(), Some(1000));
1459 assert_eq!(tlv_stream.amount, Some(1000));
1461 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1464 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1465 .amount_msats(1001).unwrap()
1466 .amount_msats(1000).unwrap()
1468 .sign(payer_sign).unwrap();
1469 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1470 assert_eq!(invoice_request.amount_msats(), Some(1000));
1471 assert_eq!(tlv_stream.amount, Some(1000));
1473 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1476 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 .amount_msats(1001).unwrap()
1479 .sign(payer_sign).unwrap();
1480 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1481 assert_eq!(invoice_request.amount_msats(), Some(1001));
1482 assert_eq!(tlv_stream.amount, Some(1001));
1484 match OfferBuilder::new("foo".into(), recipient_pubkey())
1487 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1490 Ok(_) => panic!("expected error"),
1491 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1494 match OfferBuilder::new("foo".into(), recipient_pubkey())
1496 .supported_quantity(Quantity::Unbounded)
1498 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1499 .quantity(2).unwrap()
1502 Ok(_) => panic!("expected error"),
1503 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1506 match OfferBuilder::new("foo".into(), recipient_pubkey())
1509 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1510 .amount_msats(MAX_VALUE_MSAT + 1)
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1516 match OfferBuilder::new("foo".into(), recipient_pubkey())
1518 .supported_quantity(Quantity::Unbounded)
1520 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1521 .amount_msats(1000).unwrap()
1522 .quantity(2).unwrap()
1525 Ok(_) => panic!("expected error"),
1526 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1529 match OfferBuilder::new("foo".into(), recipient_pubkey())
1531 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534 Ok(_) => panic!("expected error"),
1535 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1538 match OfferBuilder::new("foo".into(), recipient_pubkey())
1540 .supported_quantity(Quantity::Unbounded)
1542 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1543 .quantity(u64::max_value()).unwrap()
1546 Ok(_) => panic!("expected error"),
1547 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1552 fn builds_invoice_request_with_features() {
1553 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1556 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1557 .features_unchecked(InvoiceRequestFeatures::unknown())
1559 .sign(payer_sign).unwrap();
1560 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1561 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1562 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1564 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1567 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1568 .features_unchecked(InvoiceRequestFeatures::unknown())
1569 .features_unchecked(InvoiceRequestFeatures::empty())
1571 .sign(payer_sign).unwrap();
1572 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1573 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1574 assert_eq!(tlv_stream.features, None);
1578 fn builds_invoice_request_with_quantity() {
1579 let one = NonZeroU64::new(1).unwrap();
1580 let ten = NonZeroU64::new(10).unwrap();
1582 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1584 .supported_quantity(Quantity::One)
1586 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1588 .sign(payer_sign).unwrap();
1589 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1590 assert_eq!(invoice_request.quantity(), None);
1591 assert_eq!(tlv_stream.quantity, None);
1593 match OfferBuilder::new("foo".into(), recipient_pubkey())
1595 .supported_quantity(Quantity::One)
1597 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598 .amount_msats(2_000).unwrap()
1601 Ok(_) => panic!("expected error"),
1602 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1605 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1607 .supported_quantity(Quantity::Bounded(ten))
1609 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1610 .amount_msats(10_000).unwrap()
1611 .quantity(10).unwrap()
1613 .sign(payer_sign).unwrap();
1614 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1615 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1616 assert_eq!(tlv_stream.amount, Some(10_000));
1618 match OfferBuilder::new("foo".into(), recipient_pubkey())
1620 .supported_quantity(Quantity::Bounded(ten))
1622 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623 .amount_msats(11_000).unwrap()
1626 Ok(_) => panic!("expected error"),
1627 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1630 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1632 .supported_quantity(Quantity::Unbounded)
1634 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1635 .amount_msats(2_000).unwrap()
1636 .quantity(2).unwrap()
1638 .sign(payer_sign).unwrap();
1639 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1640 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1641 assert_eq!(tlv_stream.amount, Some(2_000));
1643 match OfferBuilder::new("foo".into(), recipient_pubkey())
1645 .supported_quantity(Quantity::Unbounded)
1647 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1650 Ok(_) => panic!("expected error"),
1651 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1654 match OfferBuilder::new("foo".into(), recipient_pubkey())
1656 .supported_quantity(Quantity::Bounded(one))
1658 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 Ok(_) => panic!("expected error"),
1662 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1667 fn builds_invoice_request_with_payer_note() {
1668 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1671 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1672 .payer_note("bar".into())
1674 .sign(payer_sign).unwrap();
1675 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1676 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1677 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1679 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1682 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1683 .payer_note("bar".into())
1684 .payer_note("baz".into())
1686 .sign(payer_sign).unwrap();
1687 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1688 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1689 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1693 fn fails_signing_invoice_request() {
1694 match OfferBuilder::new("foo".into(), recipient_pubkey())
1697 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1701 Ok(_) => panic!("expected error"),
1702 Err(e) => assert_eq!(e, SignError::Signing(())),
1705 match OfferBuilder::new("foo".into(), recipient_pubkey())
1708 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1710 .sign(recipient_sign)
1712 Ok(_) => panic!("expected error"),
1713 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1718 fn fails_responding_with_unknown_required_features() {
1719 match OfferBuilder::new("foo".into(), recipient_pubkey())
1722 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1723 .features_unchecked(InvoiceRequestFeatures::unknown())
1725 .sign(payer_sign).unwrap()
1726 .respond_with_no_std(payment_paths(), payment_hash(), now())
1728 Ok(_) => panic!("expected error"),
1729 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1734 fn parses_invoice_request_with_metadata() {
1735 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1738 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1740 .sign(payer_sign).unwrap();
1742 let mut buffer = Vec::new();
1743 invoice_request.write(&mut buffer).unwrap();
1745 if let Err(e) = InvoiceRequest::try_from(buffer) {
1746 panic!("error parsing invoice_request: {:?}", e);
1751 fn parses_invoice_request_with_chain() {
1752 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1755 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1756 .chain(Network::Bitcoin).unwrap()
1758 .sign(payer_sign).unwrap();
1760 let mut buffer = Vec::new();
1761 invoice_request.write(&mut buffer).unwrap();
1763 if let Err(e) = InvoiceRequest::try_from(buffer) {
1764 panic!("error parsing invoice_request: {:?}", e);
1767 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1770 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1771 .chain_unchecked(Network::Testnet)
1773 .sign(payer_sign).unwrap();
1775 let mut buffer = Vec::new();
1776 invoice_request.write(&mut buffer).unwrap();
1778 match InvoiceRequest::try_from(buffer) {
1779 Ok(_) => panic!("expected error"),
1780 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1785 fn parses_invoice_request_with_amount() {
1786 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1789 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1791 .sign(payer_sign).unwrap();
1793 let mut buffer = Vec::new();
1794 invoice_request.write(&mut buffer).unwrap();
1796 if let Err(e) = InvoiceRequest::try_from(buffer) {
1797 panic!("error parsing invoice_request: {:?}", e);
1800 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1802 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1803 .amount_msats(1000).unwrap()
1805 .sign(payer_sign).unwrap();
1807 let mut buffer = Vec::new();
1808 invoice_request.write(&mut buffer).unwrap();
1810 if let Err(e) = InvoiceRequest::try_from(buffer) {
1811 panic!("error parsing invoice_request: {:?}", e);
1814 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1816 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1818 .sign(payer_sign).unwrap();
1820 let mut buffer = Vec::new();
1821 invoice_request.write(&mut buffer).unwrap();
1823 match InvoiceRequest::try_from(buffer) {
1824 Ok(_) => panic!("expected error"),
1825 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1828 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1831 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1832 .amount_msats_unchecked(999)
1834 .sign(payer_sign).unwrap();
1836 let mut buffer = Vec::new();
1837 invoice_request.write(&mut buffer).unwrap();
1839 match InvoiceRequest::try_from(buffer) {
1840 Ok(_) => panic!("expected error"),
1841 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1844 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1845 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1847 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1849 .sign(payer_sign).unwrap();
1851 let mut buffer = Vec::new();
1852 invoice_request.write(&mut buffer).unwrap();
1854 match InvoiceRequest::try_from(buffer) {
1855 Ok(_) => panic!("expected error"),
1857 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1861 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1863 .supported_quantity(Quantity::Unbounded)
1865 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1866 .quantity(u64::max_value()).unwrap()
1868 .sign(payer_sign).unwrap();
1870 let mut buffer = Vec::new();
1871 invoice_request.write(&mut buffer).unwrap();
1873 match InvoiceRequest::try_from(buffer) {
1874 Ok(_) => panic!("expected error"),
1875 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1880 fn parses_invoice_request_with_quantity() {
1881 let one = NonZeroU64::new(1).unwrap();
1882 let ten = NonZeroU64::new(10).unwrap();
1884 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1886 .supported_quantity(Quantity::One)
1888 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1890 .sign(payer_sign).unwrap();
1892 let mut buffer = Vec::new();
1893 invoice_request.write(&mut buffer).unwrap();
1895 if let Err(e) = InvoiceRequest::try_from(buffer) {
1896 panic!("error parsing invoice_request: {:?}", e);
1899 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1901 .supported_quantity(Quantity::One)
1903 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1904 .amount_msats(2_000).unwrap()
1905 .quantity_unchecked(2)
1907 .sign(payer_sign).unwrap();
1909 let mut buffer = Vec::new();
1910 invoice_request.write(&mut buffer).unwrap();
1912 match InvoiceRequest::try_from(buffer) {
1913 Ok(_) => panic!("expected error"),
1915 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1919 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1921 .supported_quantity(Quantity::Bounded(ten))
1923 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1924 .amount_msats(10_000).unwrap()
1925 .quantity(10).unwrap()
1927 .sign(payer_sign).unwrap();
1929 let mut buffer = Vec::new();
1930 invoice_request.write(&mut buffer).unwrap();
1932 if let Err(e) = InvoiceRequest::try_from(buffer) {
1933 panic!("error parsing invoice_request: {:?}", e);
1936 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1938 .supported_quantity(Quantity::Bounded(ten))
1940 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1941 .amount_msats(11_000).unwrap()
1942 .quantity_unchecked(11)
1944 .sign(payer_sign).unwrap();
1946 let mut buffer = Vec::new();
1947 invoice_request.write(&mut buffer).unwrap();
1949 match InvoiceRequest::try_from(buffer) {
1950 Ok(_) => panic!("expected error"),
1951 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1954 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1956 .supported_quantity(Quantity::Unbounded)
1958 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1959 .amount_msats(2_000).unwrap()
1960 .quantity(2).unwrap()
1962 .sign(payer_sign).unwrap();
1964 let mut buffer = Vec::new();
1965 invoice_request.write(&mut buffer).unwrap();
1967 if let Err(e) = InvoiceRequest::try_from(buffer) {
1968 panic!("error parsing invoice_request: {:?}", e);
1971 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1973 .supported_quantity(Quantity::Unbounded)
1975 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1977 .sign(payer_sign).unwrap();
1979 let mut buffer = Vec::new();
1980 invoice_request.write(&mut buffer).unwrap();
1982 match InvoiceRequest::try_from(buffer) {
1983 Ok(_) => panic!("expected error"),
1984 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1987 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1989 .supported_quantity(Quantity::Bounded(one))
1991 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1993 .sign(payer_sign).unwrap();
1995 let mut buffer = Vec::new();
1996 invoice_request.write(&mut buffer).unwrap();
1998 match InvoiceRequest::try_from(buffer) {
1999 Ok(_) => panic!("expected error"),
2000 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2005 fn fails_parsing_invoice_request_without_metadata() {
2006 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2009 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2011 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2012 tlv_stream.0.metadata = None;
2014 let mut buffer = Vec::new();
2015 tlv_stream.write(&mut buffer).unwrap();
2017 match InvoiceRequest::try_from(buffer) {
2018 Ok(_) => panic!("expected error"),
2020 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2026 fn fails_parsing_invoice_request_without_payer_id() {
2027 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2030 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2032 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2033 tlv_stream.2.payer_id = None;
2035 let mut buffer = Vec::new();
2036 tlv_stream.write(&mut buffer).unwrap();
2038 match InvoiceRequest::try_from(buffer) {
2039 Ok(_) => panic!("expected error"),
2040 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
2045 fn fails_parsing_invoice_request_without_node_id() {
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.1.node_id = 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::MissingSigningPubkey));
2066 fn fails_parsing_invoice_request_without_signature() {
2067 let mut buffer = Vec::new();
2068 OfferBuilder::new("foo".into(), recipient_pubkey())
2071 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2074 .write(&mut buffer).unwrap();
2076 match InvoiceRequest::try_from(buffer) {
2077 Ok(_) => panic!("expected error"),
2078 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2083 fn fails_parsing_invoice_request_with_invalid_signature() {
2084 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
2087 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2089 .sign(payer_sign).unwrap();
2090 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2091 *last_signature_byte = last_signature_byte.wrapping_add(1);
2093 let mut buffer = Vec::new();
2094 invoice_request.write(&mut buffer).unwrap();
2096 match InvoiceRequest::try_from(buffer) {
2097 Ok(_) => panic!("expected error"),
2099 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2105 fn fails_parsing_invoice_request_with_extra_tlv_records() {
2106 let secp_ctx = Secp256k1::new();
2107 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2108 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
2111 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
2113 .sign::<_, Infallible>(
2114 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2118 let mut encoded_invoice_request = Vec::new();
2119 invoice_request.write(&mut encoded_invoice_request).unwrap();
2120 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2121 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2122 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2124 match InvoiceRequest::try_from(encoded_invoice_request) {
2125 Ok(_) => panic!("expected error"),
2126 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),