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 an [`Invoice`].
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Invoice`]: crate::offers::invoice::Invoice
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::ParseError> {
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();
40 //! .parse::<Offer>()?
41 //! .request_invoice(vec![42; 64], pubkey)?
42 //! .chain(Network::Testnet)?
43 //! .amount_msats(1000)?
45 //! .payer_note("foo".to_string())
47 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
48 //! .expect("failed verifying signature")
49 //! .write(&mut buffer)
55 use bitcoin::blockdata::constants::ChainHash;
56 use bitcoin::network::constants::Network;
57 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, self};
58 use bitcoin::secp256k1::schnorr::Signature;
59 use core::convert::{Infallible, TryFrom};
61 use crate::sign::EntropySource;
63 use crate::blinded_path::BlindedPath;
64 use crate::ln::PaymentHash;
65 use crate::ln::features::InvoiceRequestFeatures;
66 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
67 use crate::ln::msgs::DecodeError;
68 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
69 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
70 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
71 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
72 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
73 use crate::offers::signer::{Metadata, MetadataMaterial};
74 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
75 use crate::util::string::PrintableString;
77 use crate::prelude::*;
79 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
81 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
83 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
85 /// See [module-level documentation] for usage.
87 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
89 /// [module-level documentation]: self
90 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
92 invoice_request: InvoiceRequestContentsWithoutPayerId,
93 payer_id: Option<PublicKey>,
94 payer_id_strategy: core::marker::PhantomData<P>,
95 secp_ctx: Option<&'b Secp256k1<T>>,
98 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
100 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
101 pub trait PayerIdStrategy {}
103 /// [`InvoiceRequest::payer_id`] will be explicitly set.
105 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
106 pub struct ExplicitPayerId {}
108 /// [`InvoiceRequest::payer_id`] will be derived.
110 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
111 pub struct DerivedPayerId {}
113 impl PayerIdStrategy for ExplicitPayerId {}
114 impl PayerIdStrategy for DerivedPayerId {}
116 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
117 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
120 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
121 payer_id: Some(payer_id),
122 payer_id_strategy: core::marker::PhantomData,
127 pub(super) fn deriving_metadata<ES: Deref>(
128 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
129 ) -> Self where ES::Target: EntropySource {
130 let nonce = Nonce::from_entropy_source(entropy_source);
131 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
132 let metadata = Metadata::Derived(derivation_material);
135 invoice_request: Self::create_contents(offer, metadata),
136 payer_id: Some(payer_id),
137 payer_id_strategy: core::marker::PhantomData,
143 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
144 pub(super) fn deriving_payer_id<ES: Deref>(
145 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
146 ) -> Self where ES::Target: EntropySource {
147 let nonce = Nonce::from_entropy_source(entropy_source);
148 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
149 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
152 invoice_request: Self::create_contents(offer, metadata),
154 payer_id_strategy: core::marker::PhantomData,
155 secp_ctx: Some(secp_ctx),
160 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
161 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
162 let offer = offer.contents.clone();
163 InvoiceRequestContentsWithoutPayerId {
164 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
165 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
169 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
170 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
173 /// Successive calls to this method will override the previous setting.
174 pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
175 let chain = ChainHash::using_genesis_block(network);
176 if !self.offer.supports_chain(chain) {
177 return Err(SemanticError::UnsupportedChain);
180 self.invoice_request.chain = Some(chain);
184 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
185 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
187 /// Successive calls to this method will override the previous setting.
189 /// [`quantity`]: Self::quantity
190 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
191 self.invoice_request.offer.check_amount_msats_for_quantity(
192 Some(amount_msats), self.invoice_request.quantity
194 self.invoice_request.amount_msats = Some(amount_msats);
198 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
199 /// does not conform to [`Offer::is_valid_quantity`].
201 /// Successive calls to this method will override the previous setting.
202 pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
203 self.invoice_request.offer.check_quantity(Some(quantity))?;
204 self.invoice_request.quantity = Some(quantity);
208 /// Sets the [`InvoiceRequest::payer_note`].
210 /// Successive calls to this method will override the previous setting.
211 pub fn payer_note(mut self, payer_note: String) -> Self {
212 self.invoice_request.payer_note = Some(payer_note);
216 fn build_with_checks(mut self) -> Result<
217 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>),
220 #[cfg(feature = "std")] {
221 if self.offer.is_expired() {
222 return Err(SemanticError::AlreadyExpired);
226 let chain = self.invoice_request.chain();
227 if !self.offer.supports_chain(chain) {
228 return Err(SemanticError::UnsupportedChain);
231 if chain == self.offer.implied_chain() {
232 self.invoice_request.chain = None;
235 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
236 return Err(SemanticError::MissingAmount);
239 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
240 self.invoice_request.offer.check_amount_msats_for_quantity(
241 self.invoice_request.amount_msats, self.invoice_request.quantity
244 Ok(self.build_without_checks())
247 fn build_without_checks(mut self) ->
248 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>)
250 // Create the metadata for stateless verification of an Invoice.
252 let secp_ctx = self.secp_ctx.clone();
253 if self.invoice_request.payer.0.has_derivation_material() {
254 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
256 let mut tlv_stream = self.invoice_request.as_tlv_stream();
257 debug_assert!(tlv_stream.2.payer_id.is_none());
258 tlv_stream.0.metadata = None;
259 if !metadata.derives_keys() {
260 tlv_stream.2.payer_id = self.payer_id.as_ref();
263 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
264 metadata = derived_metadata;
266 if let Some(keys) = keys {
267 debug_assert!(self.payer_id.is_none());
268 self.payer_id = Some(keys.public_key());
271 self.invoice_request.payer.0 = metadata;
274 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
275 debug_assert!(self.payer_id.is_some());
276 let payer_id = self.payer_id.unwrap();
278 let unsigned_invoice = UnsignedInvoiceRequest {
280 invoice_request: InvoiceRequestContents {
281 inner: self.invoice_request,
286 (unsigned_invoice, keys, secp_ctx)
290 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
291 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
292 /// by [`UnsignedInvoiceRequest::sign`].
293 pub fn build(self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
294 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
295 debug_assert!(keys.is_none());
296 Ok(unsigned_invoice_request)
300 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
301 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
302 pub fn build_and_sign(self) -> Result<InvoiceRequest, SemanticError> {
303 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
304 debug_assert!(keys.is_some());
306 let secp_ctx = secp_ctx.unwrap();
307 let keys = keys.unwrap();
308 let invoice_request = unsigned_invoice_request
309 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
316 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
317 fn chain_unchecked(mut self, network: Network) -> Self {
318 let chain = ChainHash::using_genesis_block(network);
319 self.invoice_request.chain = Some(chain);
323 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
324 self.invoice_request.amount_msats = Some(amount_msats);
328 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
329 self.invoice_request.features = features;
333 fn quantity_unchecked(mut self, quantity: u64) -> Self {
334 self.invoice_request.quantity = Some(quantity);
338 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
339 self.build_without_checks().0
343 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
344 pub struct UnsignedInvoiceRequest<'a> {
346 invoice_request: InvoiceRequestContents,
349 impl<'a> UnsignedInvoiceRequest<'a> {
350 /// Signs the invoice request using the given function.
352 /// This is not exported to bindings users as functions are not yet mapped.
353 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
355 F: FnOnce(&Message) -> Result<Signature, E>
357 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
358 // unknown TLV records, which are not stored in `OfferContents`.
359 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
360 self.invoice_request.as_tlv_stream();
361 let offer_bytes = WithoutLength(&self.offer.bytes);
362 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
364 let mut bytes = Vec::new();
365 unsigned_tlv_stream.write(&mut bytes).unwrap();
367 let pubkey = self.invoice_request.payer_id;
368 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
370 // Append the signature TLV record to the bytes.
371 let signature_tlv_stream = SignatureTlvStreamRef {
372 signature: Some(&signature),
374 signature_tlv_stream.write(&mut bytes).unwrap();
378 contents: self.invoice_request,
384 /// An `InvoiceRequest` is a request for an [`Invoice`] formulated from an [`Offer`].
386 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
387 /// specifies these such that its recipient can send an invoice for payment.
389 /// [`Invoice`]: crate::offers::invoice::Invoice
390 /// [`Offer`]: crate::offers::offer::Offer
391 #[derive(Clone, Debug)]
392 #[cfg_attr(test, derive(PartialEq))]
393 pub struct InvoiceRequest {
394 pub(super) bytes: Vec<u8>,
395 pub(super) contents: InvoiceRequestContents,
396 signature: Signature,
399 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Invoice`].
401 /// [`Invoice`]: crate::offers::invoice::Invoice
402 #[derive(Clone, Debug)]
403 #[cfg_attr(test, derive(PartialEq))]
404 pub(super) struct InvoiceRequestContents {
405 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
409 #[derive(Clone, Debug)]
410 #[cfg_attr(test, derive(PartialEq))]
411 pub(super) struct InvoiceRequestContentsWithoutPayerId {
412 payer: PayerContents,
413 pub(super) offer: OfferContents,
414 chain: Option<ChainHash>,
415 amount_msats: Option<u64>,
416 features: InvoiceRequestFeatures,
417 quantity: Option<u64>,
418 payer_note: Option<String>,
421 impl InvoiceRequest {
422 /// An unpredictable series of bytes, typically containing information about the derivation of
425 /// [`payer_id`]: Self::payer_id
426 pub fn metadata(&self) -> &[u8] {
427 self.contents.metadata()
430 /// A chain from [`Offer::chains`] that the offer is valid for.
431 pub fn chain(&self) -> ChainHash {
432 self.contents.chain()
435 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
436 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
438 /// [`chain`]: Self::chain
439 pub fn amount_msats(&self) -> Option<u64> {
440 self.contents.inner.amount_msats
443 /// Features pertaining to requesting an invoice.
444 pub fn features(&self) -> &InvoiceRequestFeatures {
445 &self.contents.inner.features
448 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
449 pub fn quantity(&self) -> Option<u64> {
450 self.contents.inner.quantity
453 /// A possibly transient pubkey used to sign the invoice request.
454 pub fn payer_id(&self) -> PublicKey {
455 self.contents.payer_id
458 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
460 pub fn payer_note(&self) -> Option<PrintableString> {
461 self.contents.inner.payer_note.as_ref()
462 .map(|payer_note| PrintableString(payer_note.as_str()))
465 /// Signature of the invoice request using [`payer_id`].
467 /// [`payer_id`]: Self::payer_id
468 pub fn signature(&self) -> Signature {
472 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
473 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
475 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
476 /// creation time is used for the `created_at` parameter.
478 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
480 /// [`Duration`]: core::time::Duration
481 #[cfg(feature = "std")]
483 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
484 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
485 let created_at = std::time::SystemTime::now()
486 .duration_since(std::time::SystemTime::UNIX_EPOCH)
487 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
489 self.respond_with_no_std(payment_paths, payment_hash, created_at)
492 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
494 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
495 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
496 /// [`std::time::SystemTime`] is not available.
498 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
501 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
502 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
503 /// a preference. Note, however, that any privacy is lost if a public node id was used for
504 /// [`Offer::signing_pubkey`].
506 /// Errors if the request contains unknown required features.
508 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
510 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
511 pub fn respond_with_no_std(
512 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
513 created_at: core::time::Duration
514 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
515 if self.features().requires_unknown_bits() {
516 return Err(SemanticError::UnknownRequiredFeatures);
519 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
522 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
523 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
524 /// same [`ExpandedKey`] as the one used to create the offer.
526 /// See [`InvoiceRequest::respond_with`] for further details.
528 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
530 /// [`Invoice`]: crate::offers::invoice::Invoice
531 #[cfg(feature = "std")]
532 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
533 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
534 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
535 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
536 let created_at = std::time::SystemTime::now()
537 .duration_since(std::time::SystemTime::UNIX_EPOCH)
538 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
540 self.verify_and_respond_using_derived_keys_no_std(
541 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
545 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
546 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
547 /// same [`ExpandedKey`] as the one used to create the offer.
549 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
551 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
553 /// [`Invoice`]: crate::offers::invoice::Invoice
554 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
555 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
556 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
557 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
558 if self.features().requires_unknown_bits() {
559 return Err(SemanticError::UnknownRequiredFeatures);
562 let keys = match self.verify(expanded_key, secp_ctx) {
563 Err(()) => return Err(SemanticError::InvalidMetadata),
564 Ok(None) => return Err(SemanticError::InvalidMetadata),
565 Ok(Some(keys)) => keys,
568 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
571 /// Verifies that the request was for an offer created using the given key. Returns the derived
572 /// keys need to sign an [`Invoice`] for the request if they could be extracted from the
575 /// [`Invoice`]: crate::offers::invoice::Invoice
576 pub fn verify<T: secp256k1::Signing>(
577 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
578 ) -> Result<Option<KeyPair>, ()> {
579 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
583 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
584 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
585 self.contents.as_tlv_stream();
586 let signature_tlv_stream = SignatureTlvStreamRef {
587 signature: Some(&self.signature),
589 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
593 impl InvoiceRequestContents {
594 pub fn metadata(&self) -> &[u8] {
595 self.inner.metadata()
598 pub(super) fn derives_keys(&self) -> bool {
599 self.inner.payer.0.derives_keys()
602 pub(super) fn chain(&self) -> ChainHash {
606 pub(super) fn payer_id(&self) -> PublicKey {
610 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
611 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
612 invoice_request.payer_id = Some(&self.payer_id);
613 (payer, offer, invoice_request)
617 impl InvoiceRequestContentsWithoutPayerId {
618 pub(super) fn metadata(&self) -> &[u8] {
619 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
622 pub(super) fn chain(&self) -> ChainHash {
623 self.chain.unwrap_or_else(|| self.offer.implied_chain())
626 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
627 let payer = PayerTlvStreamRef {
628 metadata: self.payer.0.as_bytes(),
631 let offer = self.offer.as_tlv_stream();
634 if self.features == InvoiceRequestFeatures::empty() { None }
635 else { Some(&self.features) }
638 let invoice_request = InvoiceRequestTlvStreamRef {
639 chain: self.chain.as_ref(),
640 amount: self.amount_msats,
642 quantity: self.quantity,
644 payer_note: self.payer_note.as_ref(),
647 (payer, offer, invoice_request)
651 impl Writeable for InvoiceRequest {
652 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
653 WithoutLength(&self.bytes).write(writer)
657 impl Writeable for InvoiceRequestContents {
658 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
659 self.as_tlv_stream().write(writer)
663 /// Valid type range for invoice_request TLV records.
664 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
666 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
668 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
669 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
671 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
672 (80, chain: ChainHash),
673 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
674 (84, features: (InvoiceRequestFeatures, WithoutLength)),
675 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
676 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
677 (89, payer_note: (String, WithoutLength)),
680 type FullInvoiceRequestTlvStream =
681 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
684 type FullInvoiceRequestTlvStreamRef<'a> = (
685 PayerTlvStreamRef<'a>,
686 OfferTlvStreamRef<'a>,
687 InvoiceRequestTlvStreamRef<'a>,
688 SignatureTlvStreamRef<'a>,
691 impl SeekReadable for FullInvoiceRequestTlvStream {
692 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
693 let payer = SeekReadable::read(r)?;
694 let offer = SeekReadable::read(r)?;
695 let invoice_request = SeekReadable::read(r)?;
696 let signature = SeekReadable::read(r)?;
698 Ok((payer, offer, invoice_request, signature))
702 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
704 type PartialInvoiceRequestTlvStreamRef<'a> = (
705 PayerTlvStreamRef<'a>,
706 OfferTlvStreamRef<'a>,
707 InvoiceRequestTlvStreamRef<'a>,
710 impl TryFrom<Vec<u8>> for InvoiceRequest {
711 type Error = ParseError;
713 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
714 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
715 let ParsedMessage { bytes, tlv_stream } = invoice_request;
717 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
718 SignatureTlvStream { signature },
720 let contents = InvoiceRequestContents::try_from(
721 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
724 let signature = match signature {
725 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
726 Some(signature) => signature,
728 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
730 Ok(InvoiceRequest { bytes, contents, signature })
734 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
735 type Error = SemanticError;
737 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
739 PayerTlvStream { metadata },
741 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
744 let payer = match metadata {
745 None => return Err(SemanticError::MissingPayerMetadata),
746 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
748 let offer = OfferContents::try_from(offer_tlv_stream)?;
750 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
751 return Err(SemanticError::UnsupportedChain);
754 if offer.amount().is_none() && amount.is_none() {
755 return Err(SemanticError::MissingAmount);
758 offer.check_quantity(quantity)?;
759 offer.check_amount_msats_for_quantity(amount, quantity)?;
761 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
763 let payer_id = match payer_id {
764 None => return Err(SemanticError::MissingPayerId),
765 Some(payer_id) => payer_id,
768 Ok(InvoiceRequestContents {
769 inner: InvoiceRequestContentsWithoutPayerId {
770 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
779 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
781 use bitcoin::blockdata::constants::ChainHash;
782 use bitcoin::network::constants::Network;
783 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
784 use core::convert::{Infallible, TryFrom};
785 use core::num::NonZeroU64;
786 #[cfg(feature = "std")]
787 use core::time::Duration;
788 use crate::sign::KeyMaterial;
789 use crate::ln::features::InvoiceRequestFeatures;
790 use crate::ln::inbound_payment::ExpandedKey;
791 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
792 use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
793 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
794 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
795 use crate::offers::parse::{ParseError, SemanticError};
796 use crate::offers::payer::PayerTlvStreamRef;
797 use crate::offers::test_utils::*;
798 use crate::util::ser::{BigSize, Writeable};
799 use crate::util::string::PrintableString;
802 fn builds_invoice_request_with_defaults() {
803 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
806 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
808 .sign(payer_sign).unwrap();
810 let mut buffer = Vec::new();
811 invoice_request.write(&mut buffer).unwrap();
813 assert_eq!(invoice_request.bytes, buffer.as_slice());
814 assert_eq!(invoice_request.metadata(), &[1; 32]);
815 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
816 assert_eq!(invoice_request.amount_msats(), None);
817 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
818 assert_eq!(invoice_request.quantity(), None);
819 assert_eq!(invoice_request.payer_id(), payer_pubkey());
820 assert_eq!(invoice_request.payer_note(), None);
822 merkle::verify_signature(
823 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
828 invoice_request.as_tlv_stream(),
830 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
836 description: Some(&String::from("foo")),
838 absolute_expiry: None,
842 node_id: Some(&recipient_pubkey()),
844 InvoiceRequestTlvStreamRef {
849 payer_id: Some(&payer_pubkey()),
852 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
856 if let Err(e) = InvoiceRequest::try_from(buffer) {
857 panic!("error parsing invoice request: {:?}", e);
861 #[cfg(feature = "std")]
863 fn builds_invoice_request_from_offer_with_expiration() {
864 let future_expiry = Duration::from_secs(u64::max_value());
865 let past_expiry = Duration::from_secs(0);
867 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
869 .absolute_expiry(future_expiry)
871 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
874 panic!("error building invoice_request: {:?}", e);
877 match OfferBuilder::new("foo".into(), recipient_pubkey())
879 .absolute_expiry(past_expiry)
881 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
884 Ok(_) => panic!("expected error"),
885 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
890 fn builds_invoice_request_with_derived_metadata() {
891 let payer_id = payer_pubkey();
892 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
893 let entropy = FixedEntropy {};
894 let secp_ctx = Secp256k1::new();
896 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
899 let invoice_request = offer
900 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
903 .sign(payer_sign).unwrap();
904 assert_eq!(invoice_request.payer_id(), payer_pubkey());
906 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
909 .sign(recipient_sign).unwrap();
910 assert!(invoice.verify(&expanded_key, &secp_ctx));
912 // Fails verification with altered fields
914 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
915 mut invoice_tlv_stream, mut signature_tlv_stream
916 ) = invoice.as_tlv_stream();
917 invoice_request_tlv_stream.amount = Some(2000);
918 invoice_tlv_stream.amount = Some(2000);
921 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
922 let mut bytes = Vec::new();
923 tlv_stream.write(&mut bytes).unwrap();
925 let signature = merkle::sign_message(
926 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
928 signature_tlv_stream.signature = Some(&signature);
930 let mut encoded_invoice = bytes;
931 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
933 let invoice = Invoice::try_from(encoded_invoice).unwrap();
934 assert!(!invoice.verify(&expanded_key, &secp_ctx));
936 // Fails verification with altered metadata
938 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
939 mut signature_tlv_stream
940 ) = invoice.as_tlv_stream();
941 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
942 payer_tlv_stream.metadata = Some(&metadata);
945 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
946 let mut bytes = Vec::new();
947 tlv_stream.write(&mut bytes).unwrap();
949 let signature = merkle::sign_message(
950 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
952 signature_tlv_stream.signature = Some(&signature);
954 let mut encoded_invoice = bytes;
955 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
957 let invoice = Invoice::try_from(encoded_invoice).unwrap();
958 assert!(!invoice.verify(&expanded_key, &secp_ctx));
962 fn builds_invoice_request_with_derived_payer_id() {
963 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
964 let entropy = FixedEntropy {};
965 let secp_ctx = Secp256k1::new();
967 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
970 let invoice_request = offer
971 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
976 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
979 .sign(recipient_sign).unwrap();
980 assert!(invoice.verify(&expanded_key, &secp_ctx));
982 // Fails verification with altered fields
984 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
985 mut invoice_tlv_stream, mut signature_tlv_stream
986 ) = invoice.as_tlv_stream();
987 invoice_request_tlv_stream.amount = Some(2000);
988 invoice_tlv_stream.amount = Some(2000);
991 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
992 let mut bytes = Vec::new();
993 tlv_stream.write(&mut bytes).unwrap();
995 let signature = merkle::sign_message(
996 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
998 signature_tlv_stream.signature = Some(&signature);
1000 let mut encoded_invoice = bytes;
1001 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1003 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1004 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1006 // Fails verification with altered payer id
1008 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1009 mut signature_tlv_stream
1010 ) = invoice.as_tlv_stream();
1011 let payer_id = pubkey(1);
1012 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1015 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1016 let mut bytes = Vec::new();
1017 tlv_stream.write(&mut bytes).unwrap();
1019 let signature = merkle::sign_message(
1020 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1022 signature_tlv_stream.signature = Some(&signature);
1024 let mut encoded_invoice = bytes;
1025 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1027 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1028 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1032 fn builds_invoice_request_with_chain() {
1033 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1034 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1036 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1039 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1040 .chain(Network::Bitcoin).unwrap()
1042 .sign(payer_sign).unwrap();
1043 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1044 assert_eq!(invoice_request.chain(), mainnet);
1045 assert_eq!(tlv_stream.chain, None);
1047 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1049 .chain(Network::Testnet)
1051 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1052 .chain(Network::Testnet).unwrap()
1054 .sign(payer_sign).unwrap();
1055 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1056 assert_eq!(invoice_request.chain(), testnet);
1057 assert_eq!(tlv_stream.chain, Some(&testnet));
1059 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1061 .chain(Network::Bitcoin)
1062 .chain(Network::Testnet)
1064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1065 .chain(Network::Bitcoin).unwrap()
1067 .sign(payer_sign).unwrap();
1068 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1069 assert_eq!(invoice_request.chain(), mainnet);
1070 assert_eq!(tlv_stream.chain, None);
1072 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1074 .chain(Network::Bitcoin)
1075 .chain(Network::Testnet)
1077 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1078 .chain(Network::Bitcoin).unwrap()
1079 .chain(Network::Testnet).unwrap()
1081 .sign(payer_sign).unwrap();
1082 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1083 assert_eq!(invoice_request.chain(), testnet);
1084 assert_eq!(tlv_stream.chain, Some(&testnet));
1086 match OfferBuilder::new("foo".into(), recipient_pubkey())
1088 .chain(Network::Testnet)
1090 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1091 .chain(Network::Bitcoin)
1093 Ok(_) => panic!("expected error"),
1094 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1097 match OfferBuilder::new("foo".into(), recipient_pubkey())
1099 .chain(Network::Testnet)
1101 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1104 Ok(_) => panic!("expected error"),
1105 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1110 fn builds_invoice_request_with_amount() {
1111 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1114 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1115 .amount_msats(1000).unwrap()
1117 .sign(payer_sign).unwrap();
1118 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1119 assert_eq!(invoice_request.amount_msats(), Some(1000));
1120 assert_eq!(tlv_stream.amount, Some(1000));
1122 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1125 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1126 .amount_msats(1001).unwrap()
1127 .amount_msats(1000).unwrap()
1129 .sign(payer_sign).unwrap();
1130 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1131 assert_eq!(invoice_request.amount_msats(), Some(1000));
1132 assert_eq!(tlv_stream.amount, Some(1000));
1134 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1137 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1138 .amount_msats(1001).unwrap()
1140 .sign(payer_sign).unwrap();
1141 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1142 assert_eq!(invoice_request.amount_msats(), Some(1001));
1143 assert_eq!(tlv_stream.amount, Some(1001));
1145 match OfferBuilder::new("foo".into(), recipient_pubkey())
1148 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151 Ok(_) => panic!("expected error"),
1152 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1155 match OfferBuilder::new("foo".into(), recipient_pubkey())
1157 .supported_quantity(Quantity::Unbounded)
1159 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1160 .quantity(2).unwrap()
1163 Ok(_) => panic!("expected error"),
1164 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1167 match OfferBuilder::new("foo".into(), recipient_pubkey())
1170 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1171 .amount_msats(MAX_VALUE_MSAT + 1)
1173 Ok(_) => panic!("expected error"),
1174 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1177 match OfferBuilder::new("foo".into(), recipient_pubkey())
1179 .supported_quantity(Quantity::Unbounded)
1181 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1182 .amount_msats(1000).unwrap()
1183 .quantity(2).unwrap()
1186 Ok(_) => panic!("expected error"),
1187 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1190 match OfferBuilder::new("foo".into(), recipient_pubkey())
1192 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1195 Ok(_) => panic!("expected error"),
1196 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1199 match OfferBuilder::new("foo".into(), recipient_pubkey())
1201 .supported_quantity(Quantity::Unbounded)
1203 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1204 .quantity(u64::max_value()).unwrap()
1207 Ok(_) => panic!("expected error"),
1208 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1213 fn builds_invoice_request_with_features() {
1214 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1217 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1218 .features_unchecked(InvoiceRequestFeatures::unknown())
1220 .sign(payer_sign).unwrap();
1221 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1222 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1223 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1225 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1228 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229 .features_unchecked(InvoiceRequestFeatures::unknown())
1230 .features_unchecked(InvoiceRequestFeatures::empty())
1232 .sign(payer_sign).unwrap();
1233 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1234 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1235 assert_eq!(tlv_stream.features, None);
1239 fn builds_invoice_request_with_quantity() {
1240 let one = NonZeroU64::new(1).unwrap();
1241 let ten = NonZeroU64::new(10).unwrap();
1243 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1245 .supported_quantity(Quantity::One)
1247 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 .sign(payer_sign).unwrap();
1250 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1251 assert_eq!(invoice_request.quantity(), None);
1252 assert_eq!(tlv_stream.quantity, None);
1254 match OfferBuilder::new("foo".into(), recipient_pubkey())
1256 .supported_quantity(Quantity::One)
1258 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1259 .amount_msats(2_000).unwrap()
1262 Ok(_) => panic!("expected error"),
1263 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1266 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1268 .supported_quantity(Quantity::Bounded(ten))
1270 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271 .amount_msats(10_000).unwrap()
1272 .quantity(10).unwrap()
1274 .sign(payer_sign).unwrap();
1275 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1276 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1277 assert_eq!(tlv_stream.amount, Some(10_000));
1279 match OfferBuilder::new("foo".into(), recipient_pubkey())
1281 .supported_quantity(Quantity::Bounded(ten))
1283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1284 .amount_msats(11_000).unwrap()
1287 Ok(_) => panic!("expected error"),
1288 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1291 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1293 .supported_quantity(Quantity::Unbounded)
1295 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1296 .amount_msats(2_000).unwrap()
1297 .quantity(2).unwrap()
1299 .sign(payer_sign).unwrap();
1300 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1301 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1302 assert_eq!(tlv_stream.amount, Some(2_000));
1304 match OfferBuilder::new("foo".into(), recipient_pubkey())
1306 .supported_quantity(Quantity::Unbounded)
1308 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1311 Ok(_) => panic!("expected error"),
1312 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1315 match OfferBuilder::new("foo".into(), recipient_pubkey())
1317 .supported_quantity(Quantity::Bounded(one))
1319 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1322 Ok(_) => panic!("expected error"),
1323 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1328 fn builds_invoice_request_with_payer_note() {
1329 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1333 .payer_note("bar".into())
1335 .sign(payer_sign).unwrap();
1336 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1337 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1338 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1340 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 .payer_note("bar".into())
1345 .payer_note("baz".into())
1347 .sign(payer_sign).unwrap();
1348 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1349 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1350 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1354 fn fails_signing_invoice_request() {
1355 match OfferBuilder::new("foo".into(), recipient_pubkey())
1358 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1362 Ok(_) => panic!("expected error"),
1363 Err(e) => assert_eq!(e, SignError::Signing(())),
1366 match OfferBuilder::new("foo".into(), recipient_pubkey())
1369 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1371 .sign(recipient_sign)
1373 Ok(_) => panic!("expected error"),
1374 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1379 fn fails_responding_with_unknown_required_features() {
1380 match OfferBuilder::new("foo".into(), recipient_pubkey())
1383 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1384 .features_unchecked(InvoiceRequestFeatures::unknown())
1386 .sign(payer_sign).unwrap()
1387 .respond_with_no_std(payment_paths(), payment_hash(), now())
1389 Ok(_) => panic!("expected error"),
1390 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1395 fn parses_invoice_request_with_metadata() {
1396 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1399 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1401 .sign(payer_sign).unwrap();
1403 let mut buffer = Vec::new();
1404 invoice_request.write(&mut buffer).unwrap();
1406 if let Err(e) = InvoiceRequest::try_from(buffer) {
1407 panic!("error parsing invoice_request: {:?}", e);
1412 fn parses_invoice_request_with_chain() {
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();
1421 let mut buffer = Vec::new();
1422 invoice_request.write(&mut buffer).unwrap();
1424 if let Err(e) = InvoiceRequest::try_from(buffer) {
1425 panic!("error parsing invoice_request: {:?}", e);
1428 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1431 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1432 .chain_unchecked(Network::Testnet)
1434 .sign(payer_sign).unwrap();
1436 let mut buffer = Vec::new();
1437 invoice_request.write(&mut buffer).unwrap();
1439 match InvoiceRequest::try_from(buffer) {
1440 Ok(_) => panic!("expected error"),
1441 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1446 fn parses_invoice_request_with_amount() {
1447 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1450 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1452 .sign(payer_sign).unwrap();
1454 let mut buffer = Vec::new();
1455 invoice_request.write(&mut buffer).unwrap();
1457 if let Err(e) = InvoiceRequest::try_from(buffer) {
1458 panic!("error parsing invoice_request: {:?}", e);
1461 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1463 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1464 .amount_msats(1000).unwrap()
1466 .sign(payer_sign).unwrap();
1468 let mut buffer = Vec::new();
1469 invoice_request.write(&mut buffer).unwrap();
1471 if let Err(e) = InvoiceRequest::try_from(buffer) {
1472 panic!("error parsing invoice_request: {:?}", e);
1475 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1477 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1479 .sign(payer_sign).unwrap();
1481 let mut buffer = Vec::new();
1482 invoice_request.write(&mut buffer).unwrap();
1484 match InvoiceRequest::try_from(buffer) {
1485 Ok(_) => panic!("expected error"),
1486 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1489 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .amount_msats_unchecked(999)
1495 .sign(payer_sign).unwrap();
1497 let mut buffer = Vec::new();
1498 invoice_request.write(&mut buffer).unwrap();
1500 match InvoiceRequest::try_from(buffer) {
1501 Ok(_) => panic!("expected error"),
1502 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1505 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1506 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1508 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1510 .sign(payer_sign).unwrap();
1512 let mut buffer = Vec::new();
1513 invoice_request.write(&mut buffer).unwrap();
1515 match InvoiceRequest::try_from(buffer) {
1516 Ok(_) => panic!("expected error"),
1518 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1522 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1524 .supported_quantity(Quantity::Unbounded)
1526 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1527 .quantity(u64::max_value()).unwrap()
1529 .sign(payer_sign).unwrap();
1531 let mut buffer = Vec::new();
1532 invoice_request.write(&mut buffer).unwrap();
1534 match InvoiceRequest::try_from(buffer) {
1535 Ok(_) => panic!("expected error"),
1536 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1541 fn parses_invoice_request_with_quantity() {
1542 let one = NonZeroU64::new(1).unwrap();
1543 let ten = NonZeroU64::new(10).unwrap();
1545 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1547 .supported_quantity(Quantity::One)
1549 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1551 .sign(payer_sign).unwrap();
1553 let mut buffer = Vec::new();
1554 invoice_request.write(&mut buffer).unwrap();
1556 if let Err(e) = InvoiceRequest::try_from(buffer) {
1557 panic!("error parsing invoice_request: {:?}", e);
1560 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1562 .supported_quantity(Quantity::One)
1564 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1565 .amount_msats(2_000).unwrap()
1566 .quantity_unchecked(2)
1568 .sign(payer_sign).unwrap();
1570 let mut buffer = Vec::new();
1571 invoice_request.write(&mut buffer).unwrap();
1573 match InvoiceRequest::try_from(buffer) {
1574 Ok(_) => panic!("expected error"),
1576 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1580 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1582 .supported_quantity(Quantity::Bounded(ten))
1584 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1585 .amount_msats(10_000).unwrap()
1586 .quantity(10).unwrap()
1588 .sign(payer_sign).unwrap();
1590 let mut buffer = Vec::new();
1591 invoice_request.write(&mut buffer).unwrap();
1593 if let Err(e) = InvoiceRequest::try_from(buffer) {
1594 panic!("error parsing invoice_request: {:?}", e);
1597 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1599 .supported_quantity(Quantity::Bounded(ten))
1601 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1602 .amount_msats(11_000).unwrap()
1603 .quantity_unchecked(11)
1605 .sign(payer_sign).unwrap();
1607 let mut buffer = Vec::new();
1608 invoice_request.write(&mut buffer).unwrap();
1610 match InvoiceRequest::try_from(buffer) {
1611 Ok(_) => panic!("expected error"),
1612 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1615 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1617 .supported_quantity(Quantity::Unbounded)
1619 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620 .amount_msats(2_000).unwrap()
1621 .quantity(2).unwrap()
1623 .sign(payer_sign).unwrap();
1625 let mut buffer = Vec::new();
1626 invoice_request.write(&mut buffer).unwrap();
1628 if let Err(e) = InvoiceRequest::try_from(buffer) {
1629 panic!("error parsing invoice_request: {:?}", e);
1632 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1634 .supported_quantity(Quantity::Unbounded)
1636 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1638 .sign(payer_sign).unwrap();
1640 let mut buffer = Vec::new();
1641 invoice_request.write(&mut buffer).unwrap();
1643 match InvoiceRequest::try_from(buffer) {
1644 Ok(_) => panic!("expected error"),
1645 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1648 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1650 .supported_quantity(Quantity::Bounded(one))
1652 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1654 .sign(payer_sign).unwrap();
1656 let mut buffer = Vec::new();
1657 invoice_request.write(&mut buffer).unwrap();
1659 match InvoiceRequest::try_from(buffer) {
1660 Ok(_) => panic!("expected error"),
1661 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1666 fn fails_parsing_invoice_request_without_metadata() {
1667 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1670 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1672 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1673 tlv_stream.0.metadata = None;
1675 let mut buffer = Vec::new();
1676 tlv_stream.write(&mut buffer).unwrap();
1678 match InvoiceRequest::try_from(buffer) {
1679 Ok(_) => panic!("expected error"),
1681 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1687 fn fails_parsing_invoice_request_without_payer_id() {
1688 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1691 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1693 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1694 tlv_stream.2.payer_id = None;
1696 let mut buffer = Vec::new();
1697 tlv_stream.write(&mut buffer).unwrap();
1699 match InvoiceRequest::try_from(buffer) {
1700 Ok(_) => panic!("expected error"),
1701 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1706 fn fails_parsing_invoice_request_without_node_id() {
1707 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1710 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1712 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1713 tlv_stream.1.node_id = None;
1715 let mut buffer = Vec::new();
1716 tlv_stream.write(&mut buffer).unwrap();
1718 match InvoiceRequest::try_from(buffer) {
1719 Ok(_) => panic!("expected error"),
1721 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1727 fn fails_parsing_invoice_request_without_signature() {
1728 let mut buffer = Vec::new();
1729 OfferBuilder::new("foo".into(), recipient_pubkey())
1732 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1735 .write(&mut buffer).unwrap();
1737 match InvoiceRequest::try_from(buffer) {
1738 Ok(_) => panic!("expected error"),
1739 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1744 fn fails_parsing_invoice_request_with_invalid_signature() {
1745 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1748 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750 .sign(payer_sign).unwrap();
1751 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1752 *last_signature_byte = last_signature_byte.wrapping_add(1);
1754 let mut buffer = Vec::new();
1755 invoice_request.write(&mut buffer).unwrap();
1757 match InvoiceRequest::try_from(buffer) {
1758 Ok(_) => panic!("expected error"),
1760 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1766 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1767 let secp_ctx = Secp256k1::new();
1768 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1769 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1772 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1774 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1777 let mut encoded_invoice_request = Vec::new();
1778 invoice_request.write(&mut encoded_invoice_request).unwrap();
1779 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1780 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1781 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1783 match InvoiceRequest::try_from(encoded_invoice_request) {
1784 Ok(_) => panic!("expected error"),
1785 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),