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::chain::keysinterface::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 /// This is not exported to bindings users as Signature is not yet mapped.
469 /// [`payer_id`]: Self::payer_id
470 pub fn signature(&self) -> Signature {
474 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
475 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
477 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
478 /// creation time is used for the `created_at` parameter.
480 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
482 /// [`Duration`]: core::time::Duration
483 #[cfg(feature = "std")]
485 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
486 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
487 let created_at = std::time::SystemTime::now()
488 .duration_since(std::time::SystemTime::UNIX_EPOCH)
489 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
491 self.respond_with_no_std(payment_paths, payment_hash, created_at)
494 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
496 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
497 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
498 /// [`std::time::SystemTime`] is not available.
500 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
503 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
504 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
505 /// a preference. Note, however, that any privacy is lost if a public node id was used for
506 /// [`Offer::signing_pubkey`].
508 /// Errors if the request contains unknown required features.
510 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
512 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
513 pub fn respond_with_no_std(
514 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
515 created_at: core::time::Duration
516 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
517 if self.features().requires_unknown_bits() {
518 return Err(SemanticError::UnknownRequiredFeatures);
521 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
524 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
525 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
526 /// same [`ExpandedKey`] as the one used to create the offer.
528 /// See [`InvoiceRequest::respond_with`] for further details.
530 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
532 /// [`Invoice`]: crate::offers::invoice::Invoice
533 #[cfg(feature = "std")]
534 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
535 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
536 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
537 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
538 let created_at = std::time::SystemTime::now()
539 .duration_since(std::time::SystemTime::UNIX_EPOCH)
540 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
542 self.verify_and_respond_using_derived_keys_no_std(
543 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
547 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
548 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
549 /// same [`ExpandedKey`] as the one used to create the offer.
551 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
553 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
555 /// [`Invoice`]: crate::offers::invoice::Invoice
556 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
557 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
558 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
559 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
560 if self.features().requires_unknown_bits() {
561 return Err(SemanticError::UnknownRequiredFeatures);
564 let keys = match self.verify(expanded_key, secp_ctx) {
565 Err(()) => return Err(SemanticError::InvalidMetadata),
566 Ok(None) => return Err(SemanticError::InvalidMetadata),
567 Ok(Some(keys)) => keys,
570 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
573 /// Verifies that the request was for an offer created using the given key. Returns the derived
574 /// keys need to sign an [`Invoice`] for the request if they could be extracted from the
577 /// This is not exported to bindings users as KeyPair is not yet mapped.
579 /// [`Invoice`]: crate::offers::invoice::Invoice
580 pub fn verify<T: secp256k1::Signing>(
581 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
582 ) -> Result<Option<KeyPair>, ()> {
583 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
587 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
588 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
589 self.contents.as_tlv_stream();
590 let signature_tlv_stream = SignatureTlvStreamRef {
591 signature: Some(&self.signature),
593 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
597 impl InvoiceRequestContents {
598 pub fn metadata(&self) -> &[u8] {
599 self.inner.metadata()
602 pub(super) fn derives_keys(&self) -> bool {
603 self.inner.payer.0.derives_keys()
606 pub(super) fn chain(&self) -> ChainHash {
610 pub(super) fn payer_id(&self) -> PublicKey {
614 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
615 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
616 invoice_request.payer_id = Some(&self.payer_id);
617 (payer, offer, invoice_request)
621 impl InvoiceRequestContentsWithoutPayerId {
622 pub(super) fn metadata(&self) -> &[u8] {
623 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
626 pub(super) fn chain(&self) -> ChainHash {
627 self.chain.unwrap_or_else(|| self.offer.implied_chain())
630 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
631 let payer = PayerTlvStreamRef {
632 metadata: self.payer.0.as_bytes(),
635 let offer = self.offer.as_tlv_stream();
638 if self.features == InvoiceRequestFeatures::empty() { None }
639 else { Some(&self.features) }
642 let invoice_request = InvoiceRequestTlvStreamRef {
643 chain: self.chain.as_ref(),
644 amount: self.amount_msats,
646 quantity: self.quantity,
648 payer_note: self.payer_note.as_ref(),
651 (payer, offer, invoice_request)
655 impl Writeable for InvoiceRequest {
656 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
657 WithoutLength(&self.bytes).write(writer)
661 impl Writeable for InvoiceRequestContents {
662 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
663 self.as_tlv_stream().write(writer)
667 /// Valid type range for invoice_request TLV records.
668 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
670 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
672 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
673 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
675 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
676 (80, chain: ChainHash),
677 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
678 (84, features: (InvoiceRequestFeatures, WithoutLength)),
679 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
680 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
681 (89, payer_note: (String, WithoutLength)),
684 type FullInvoiceRequestTlvStream =
685 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
688 type FullInvoiceRequestTlvStreamRef<'a> = (
689 PayerTlvStreamRef<'a>,
690 OfferTlvStreamRef<'a>,
691 InvoiceRequestTlvStreamRef<'a>,
692 SignatureTlvStreamRef<'a>,
695 impl SeekReadable for FullInvoiceRequestTlvStream {
696 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
697 let payer = SeekReadable::read(r)?;
698 let offer = SeekReadable::read(r)?;
699 let invoice_request = SeekReadable::read(r)?;
700 let signature = SeekReadable::read(r)?;
702 Ok((payer, offer, invoice_request, signature))
706 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
708 type PartialInvoiceRequestTlvStreamRef<'a> = (
709 PayerTlvStreamRef<'a>,
710 OfferTlvStreamRef<'a>,
711 InvoiceRequestTlvStreamRef<'a>,
714 impl TryFrom<Vec<u8>> for InvoiceRequest {
715 type Error = ParseError;
717 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
718 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
719 let ParsedMessage { bytes, tlv_stream } = invoice_request;
721 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
722 SignatureTlvStream { signature },
724 let contents = InvoiceRequestContents::try_from(
725 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
728 let signature = match signature {
729 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
730 Some(signature) => signature,
732 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
734 Ok(InvoiceRequest { bytes, contents, signature })
738 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
739 type Error = SemanticError;
741 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
743 PayerTlvStream { metadata },
745 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
748 let payer = match metadata {
749 None => return Err(SemanticError::MissingPayerMetadata),
750 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
752 let offer = OfferContents::try_from(offer_tlv_stream)?;
754 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
755 return Err(SemanticError::UnsupportedChain);
758 if offer.amount().is_none() && amount.is_none() {
759 return Err(SemanticError::MissingAmount);
762 offer.check_quantity(quantity)?;
763 offer.check_amount_msats_for_quantity(amount, quantity)?;
765 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
767 let payer_id = match payer_id {
768 None => return Err(SemanticError::MissingPayerId),
769 Some(payer_id) => payer_id,
772 Ok(InvoiceRequestContents {
773 inner: InvoiceRequestContentsWithoutPayerId {
774 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
783 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
785 use bitcoin::blockdata::constants::ChainHash;
786 use bitcoin::network::constants::Network;
787 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
788 use core::convert::{Infallible, TryFrom};
789 use core::num::NonZeroU64;
790 #[cfg(feature = "std")]
791 use core::time::Duration;
792 use crate::chain::keysinterface::KeyMaterial;
793 use crate::ln::features::InvoiceRequestFeatures;
794 use crate::ln::inbound_payment::ExpandedKey;
795 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
796 use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
797 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
798 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
799 use crate::offers::parse::{ParseError, SemanticError};
800 use crate::offers::payer::PayerTlvStreamRef;
801 use crate::offers::test_utils::*;
802 use crate::util::ser::{BigSize, Writeable};
803 use crate::util::string::PrintableString;
806 fn builds_invoice_request_with_defaults() {
807 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
810 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
812 .sign(payer_sign).unwrap();
814 let mut buffer = Vec::new();
815 invoice_request.write(&mut buffer).unwrap();
817 assert_eq!(invoice_request.bytes, buffer.as_slice());
818 assert_eq!(invoice_request.metadata(), &[1; 32]);
819 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
820 assert_eq!(invoice_request.amount_msats(), None);
821 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
822 assert_eq!(invoice_request.quantity(), None);
823 assert_eq!(invoice_request.payer_id(), payer_pubkey());
824 assert_eq!(invoice_request.payer_note(), None);
826 merkle::verify_signature(
827 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
832 invoice_request.as_tlv_stream(),
834 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
840 description: Some(&String::from("foo")),
842 absolute_expiry: None,
846 node_id: Some(&recipient_pubkey()),
848 InvoiceRequestTlvStreamRef {
853 payer_id: Some(&payer_pubkey()),
856 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
860 if let Err(e) = InvoiceRequest::try_from(buffer) {
861 panic!("error parsing invoice request: {:?}", e);
865 #[cfg(feature = "std")]
867 fn builds_invoice_request_from_offer_with_expiration() {
868 let future_expiry = Duration::from_secs(u64::max_value());
869 let past_expiry = Duration::from_secs(0);
871 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
873 .absolute_expiry(future_expiry)
875 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
878 panic!("error building invoice_request: {:?}", e);
881 match OfferBuilder::new("foo".into(), recipient_pubkey())
883 .absolute_expiry(past_expiry)
885 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
888 Ok(_) => panic!("expected error"),
889 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
894 fn builds_invoice_request_with_derived_metadata() {
895 let payer_id = payer_pubkey();
896 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
897 let entropy = FixedEntropy {};
898 let secp_ctx = Secp256k1::new();
900 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
903 let invoice_request = offer
904 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
907 .sign(payer_sign).unwrap();
908 assert_eq!(invoice_request.payer_id(), payer_pubkey());
910 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
913 .sign(recipient_sign).unwrap();
914 assert!(invoice.verify(&expanded_key, &secp_ctx));
916 // Fails verification with altered fields
918 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
919 mut invoice_tlv_stream, mut signature_tlv_stream
920 ) = invoice.as_tlv_stream();
921 invoice_request_tlv_stream.amount = Some(2000);
922 invoice_tlv_stream.amount = Some(2000);
925 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
926 let mut bytes = Vec::new();
927 tlv_stream.write(&mut bytes).unwrap();
929 let signature = merkle::sign_message(
930 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
932 signature_tlv_stream.signature = Some(&signature);
934 let mut encoded_invoice = bytes;
935 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
937 let invoice = Invoice::try_from(encoded_invoice).unwrap();
938 assert!(!invoice.verify(&expanded_key, &secp_ctx));
940 // Fails verification with altered metadata
942 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
943 mut signature_tlv_stream
944 ) = invoice.as_tlv_stream();
945 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
946 payer_tlv_stream.metadata = Some(&metadata);
949 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
950 let mut bytes = Vec::new();
951 tlv_stream.write(&mut bytes).unwrap();
953 let signature = merkle::sign_message(
954 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
956 signature_tlv_stream.signature = Some(&signature);
958 let mut encoded_invoice = bytes;
959 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
961 let invoice = Invoice::try_from(encoded_invoice).unwrap();
962 assert!(!invoice.verify(&expanded_key, &secp_ctx));
966 fn builds_invoice_request_with_derived_payer_id() {
967 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
968 let entropy = FixedEntropy {};
969 let secp_ctx = Secp256k1::new();
971 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
974 let invoice_request = offer
975 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
980 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
983 .sign(recipient_sign).unwrap();
984 assert!(invoice.verify(&expanded_key, &secp_ctx));
986 // Fails verification with altered fields
988 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
989 mut invoice_tlv_stream, mut signature_tlv_stream
990 ) = invoice.as_tlv_stream();
991 invoice_request_tlv_stream.amount = Some(2000);
992 invoice_tlv_stream.amount = Some(2000);
995 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
996 let mut bytes = Vec::new();
997 tlv_stream.write(&mut bytes).unwrap();
999 let signature = merkle::sign_message(
1000 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1002 signature_tlv_stream.signature = Some(&signature);
1004 let mut encoded_invoice = bytes;
1005 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1007 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1008 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1010 // Fails verification with altered payer id
1012 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1013 mut signature_tlv_stream
1014 ) = invoice.as_tlv_stream();
1015 let payer_id = pubkey(1);
1016 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1019 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1020 let mut bytes = Vec::new();
1021 tlv_stream.write(&mut bytes).unwrap();
1023 let signature = merkle::sign_message(
1024 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1026 signature_tlv_stream.signature = Some(&signature);
1028 let mut encoded_invoice = bytes;
1029 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1031 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1032 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1036 fn builds_invoice_request_with_chain() {
1037 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1038 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1040 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1043 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1044 .chain(Network::Bitcoin).unwrap()
1046 .sign(payer_sign).unwrap();
1047 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1048 assert_eq!(invoice_request.chain(), mainnet);
1049 assert_eq!(tlv_stream.chain, None);
1051 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1053 .chain(Network::Testnet)
1055 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1056 .chain(Network::Testnet).unwrap()
1058 .sign(payer_sign).unwrap();
1059 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1060 assert_eq!(invoice_request.chain(), testnet);
1061 assert_eq!(tlv_stream.chain, Some(&testnet));
1063 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1065 .chain(Network::Bitcoin)
1066 .chain(Network::Testnet)
1068 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1069 .chain(Network::Bitcoin).unwrap()
1071 .sign(payer_sign).unwrap();
1072 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1073 assert_eq!(invoice_request.chain(), mainnet);
1074 assert_eq!(tlv_stream.chain, None);
1076 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1078 .chain(Network::Bitcoin)
1079 .chain(Network::Testnet)
1081 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1082 .chain(Network::Bitcoin).unwrap()
1083 .chain(Network::Testnet).unwrap()
1085 .sign(payer_sign).unwrap();
1086 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1087 assert_eq!(invoice_request.chain(), testnet);
1088 assert_eq!(tlv_stream.chain, Some(&testnet));
1090 match OfferBuilder::new("foo".into(), recipient_pubkey())
1092 .chain(Network::Testnet)
1094 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1095 .chain(Network::Bitcoin)
1097 Ok(_) => panic!("expected error"),
1098 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1101 match OfferBuilder::new("foo".into(), recipient_pubkey())
1103 .chain(Network::Testnet)
1105 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1108 Ok(_) => panic!("expected error"),
1109 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1114 fn builds_invoice_request_with_amount() {
1115 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1118 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1119 .amount_msats(1000).unwrap()
1121 .sign(payer_sign).unwrap();
1122 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1123 assert_eq!(invoice_request.amount_msats(), Some(1000));
1124 assert_eq!(tlv_stream.amount, Some(1000));
1126 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1129 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1130 .amount_msats(1001).unwrap()
1131 .amount_msats(1000).unwrap()
1133 .sign(payer_sign).unwrap();
1134 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1135 assert_eq!(invoice_request.amount_msats(), Some(1000));
1136 assert_eq!(tlv_stream.amount, Some(1000));
1138 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142 .amount_msats(1001).unwrap()
1144 .sign(payer_sign).unwrap();
1145 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1146 assert_eq!(invoice_request.amount_msats(), Some(1001));
1147 assert_eq!(tlv_stream.amount, Some(1001));
1149 match OfferBuilder::new("foo".into(), recipient_pubkey())
1152 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1155 Ok(_) => panic!("expected error"),
1156 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1159 match OfferBuilder::new("foo".into(), recipient_pubkey())
1161 .supported_quantity(Quantity::Unbounded)
1163 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .quantity(2).unwrap()
1167 Ok(_) => panic!("expected error"),
1168 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1171 match OfferBuilder::new("foo".into(), recipient_pubkey())
1174 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1175 .amount_msats(MAX_VALUE_MSAT + 1)
1177 Ok(_) => panic!("expected error"),
1178 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1181 match OfferBuilder::new("foo".into(), recipient_pubkey())
1183 .supported_quantity(Quantity::Unbounded)
1185 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186 .amount_msats(1000).unwrap()
1187 .quantity(2).unwrap()
1190 Ok(_) => panic!("expected error"),
1191 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1194 match OfferBuilder::new("foo".into(), recipient_pubkey())
1196 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1199 Ok(_) => panic!("expected error"),
1200 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1203 match OfferBuilder::new("foo".into(), recipient_pubkey())
1205 .supported_quantity(Quantity::Unbounded)
1207 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1208 .quantity(u64::max_value()).unwrap()
1211 Ok(_) => panic!("expected error"),
1212 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1217 fn builds_invoice_request_with_features() {
1218 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1221 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1222 .features_unchecked(InvoiceRequestFeatures::unknown())
1224 .sign(payer_sign).unwrap();
1225 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1226 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1227 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1229 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1232 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1233 .features_unchecked(InvoiceRequestFeatures::unknown())
1234 .features_unchecked(InvoiceRequestFeatures::empty())
1236 .sign(payer_sign).unwrap();
1237 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1238 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1239 assert_eq!(tlv_stream.features, None);
1243 fn builds_invoice_request_with_quantity() {
1244 let one = NonZeroU64::new(1).unwrap();
1245 let ten = NonZeroU64::new(10).unwrap();
1247 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1249 .supported_quantity(Quantity::One)
1251 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1253 .sign(payer_sign).unwrap();
1254 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1255 assert_eq!(invoice_request.quantity(), None);
1256 assert_eq!(tlv_stream.quantity, None);
1258 match OfferBuilder::new("foo".into(), recipient_pubkey())
1260 .supported_quantity(Quantity::One)
1262 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1263 .amount_msats(2_000).unwrap()
1266 Ok(_) => panic!("expected error"),
1267 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1270 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1272 .supported_quantity(Quantity::Bounded(ten))
1274 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275 .amount_msats(10_000).unwrap()
1276 .quantity(10).unwrap()
1278 .sign(payer_sign).unwrap();
1279 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1280 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1281 assert_eq!(tlv_stream.amount, Some(10_000));
1283 match OfferBuilder::new("foo".into(), recipient_pubkey())
1285 .supported_quantity(Quantity::Bounded(ten))
1287 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288 .amount_msats(11_000).unwrap()
1291 Ok(_) => panic!("expected error"),
1292 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1295 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1297 .supported_quantity(Quantity::Unbounded)
1299 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1300 .amount_msats(2_000).unwrap()
1301 .quantity(2).unwrap()
1303 .sign(payer_sign).unwrap();
1304 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1305 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1306 assert_eq!(tlv_stream.amount, Some(2_000));
1308 match OfferBuilder::new("foo".into(), recipient_pubkey())
1310 .supported_quantity(Quantity::Unbounded)
1312 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 Ok(_) => panic!("expected error"),
1316 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1319 match OfferBuilder::new("foo".into(), recipient_pubkey())
1321 .supported_quantity(Quantity::Bounded(one))
1323 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1326 Ok(_) => panic!("expected error"),
1327 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1332 fn builds_invoice_request_with_payer_note() {
1333 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1336 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1337 .payer_note("bar".into())
1339 .sign(payer_sign).unwrap();
1340 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1341 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1342 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1344 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1347 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1348 .payer_note("bar".into())
1349 .payer_note("baz".into())
1351 .sign(payer_sign).unwrap();
1352 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1353 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1354 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1358 fn fails_signing_invoice_request() {
1359 match OfferBuilder::new("foo".into(), recipient_pubkey())
1362 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1366 Ok(_) => panic!("expected error"),
1367 Err(e) => assert_eq!(e, SignError::Signing(())),
1370 match OfferBuilder::new("foo".into(), recipient_pubkey())
1373 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1375 .sign(recipient_sign)
1377 Ok(_) => panic!("expected error"),
1378 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1383 fn fails_responding_with_unknown_required_features() {
1384 match OfferBuilder::new("foo".into(), recipient_pubkey())
1387 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1388 .features_unchecked(InvoiceRequestFeatures::unknown())
1390 .sign(payer_sign).unwrap()
1391 .respond_with_no_std(payment_paths(), payment_hash(), now())
1393 Ok(_) => panic!("expected error"),
1394 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1399 fn parses_invoice_request_with_metadata() {
1400 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1403 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .sign(payer_sign).unwrap();
1407 let mut buffer = Vec::new();
1408 invoice_request.write(&mut buffer).unwrap();
1410 if let Err(e) = InvoiceRequest::try_from(buffer) {
1411 panic!("error parsing invoice_request: {:?}", e);
1416 fn parses_invoice_request_with_chain() {
1417 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1420 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1421 .chain(Network::Bitcoin).unwrap()
1423 .sign(payer_sign).unwrap();
1425 let mut buffer = Vec::new();
1426 invoice_request.write(&mut buffer).unwrap();
1428 if let Err(e) = InvoiceRequest::try_from(buffer) {
1429 panic!("error parsing invoice_request: {:?}", e);
1432 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1435 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1436 .chain_unchecked(Network::Testnet)
1438 .sign(payer_sign).unwrap();
1440 let mut buffer = Vec::new();
1441 invoice_request.write(&mut buffer).unwrap();
1443 match InvoiceRequest::try_from(buffer) {
1444 Ok(_) => panic!("expected error"),
1445 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1450 fn parses_invoice_request_with_amount() {
1451 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1454 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1456 .sign(payer_sign).unwrap();
1458 let mut buffer = Vec::new();
1459 invoice_request.write(&mut buffer).unwrap();
1461 if let Err(e) = InvoiceRequest::try_from(buffer) {
1462 panic!("error parsing invoice_request: {:?}", e);
1465 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1467 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1468 .amount_msats(1000).unwrap()
1470 .sign(payer_sign).unwrap();
1472 let mut buffer = Vec::new();
1473 invoice_request.write(&mut buffer).unwrap();
1475 if let Err(e) = InvoiceRequest::try_from(buffer) {
1476 panic!("error parsing invoice_request: {:?}", e);
1479 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1481 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1483 .sign(payer_sign).unwrap();
1485 let mut buffer = Vec::new();
1486 invoice_request.write(&mut buffer).unwrap();
1488 match InvoiceRequest::try_from(buffer) {
1489 Ok(_) => panic!("expected error"),
1490 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1493 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1496 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1497 .amount_msats_unchecked(999)
1499 .sign(payer_sign).unwrap();
1501 let mut buffer = Vec::new();
1502 invoice_request.write(&mut buffer).unwrap();
1504 match InvoiceRequest::try_from(buffer) {
1505 Ok(_) => panic!("expected error"),
1506 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1509 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1510 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1512 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1514 .sign(payer_sign).unwrap();
1516 let mut buffer = Vec::new();
1517 invoice_request.write(&mut buffer).unwrap();
1519 match InvoiceRequest::try_from(buffer) {
1520 Ok(_) => panic!("expected error"),
1522 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1526 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1528 .supported_quantity(Quantity::Unbounded)
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531 .quantity(u64::max_value()).unwrap()
1533 .sign(payer_sign).unwrap();
1535 let mut buffer = Vec::new();
1536 invoice_request.write(&mut buffer).unwrap();
1538 match InvoiceRequest::try_from(buffer) {
1539 Ok(_) => panic!("expected error"),
1540 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1545 fn parses_invoice_request_with_quantity() {
1546 let one = NonZeroU64::new(1).unwrap();
1547 let ten = NonZeroU64::new(10).unwrap();
1549 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1551 .supported_quantity(Quantity::One)
1553 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555 .sign(payer_sign).unwrap();
1557 let mut buffer = Vec::new();
1558 invoice_request.write(&mut buffer).unwrap();
1560 if let Err(e) = InvoiceRequest::try_from(buffer) {
1561 panic!("error parsing invoice_request: {:?}", e);
1564 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1566 .supported_quantity(Quantity::One)
1568 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1569 .amount_msats(2_000).unwrap()
1570 .quantity_unchecked(2)
1572 .sign(payer_sign).unwrap();
1574 let mut buffer = Vec::new();
1575 invoice_request.write(&mut buffer).unwrap();
1577 match InvoiceRequest::try_from(buffer) {
1578 Ok(_) => panic!("expected error"),
1580 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1584 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1586 .supported_quantity(Quantity::Bounded(ten))
1588 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1589 .amount_msats(10_000).unwrap()
1590 .quantity(10).unwrap()
1592 .sign(payer_sign).unwrap();
1594 let mut buffer = Vec::new();
1595 invoice_request.write(&mut buffer).unwrap();
1597 if let Err(e) = InvoiceRequest::try_from(buffer) {
1598 panic!("error parsing invoice_request: {:?}", e);
1601 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1603 .supported_quantity(Quantity::Bounded(ten))
1605 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1606 .amount_msats(11_000).unwrap()
1607 .quantity_unchecked(11)
1609 .sign(payer_sign).unwrap();
1611 let mut buffer = Vec::new();
1612 invoice_request.write(&mut buffer).unwrap();
1614 match InvoiceRequest::try_from(buffer) {
1615 Ok(_) => panic!("expected error"),
1616 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1619 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1621 .supported_quantity(Quantity::Unbounded)
1623 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1624 .amount_msats(2_000).unwrap()
1625 .quantity(2).unwrap()
1627 .sign(payer_sign).unwrap();
1629 let mut buffer = Vec::new();
1630 invoice_request.write(&mut buffer).unwrap();
1632 if let Err(e) = InvoiceRequest::try_from(buffer) {
1633 panic!("error parsing invoice_request: {:?}", e);
1636 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1638 .supported_quantity(Quantity::Unbounded)
1640 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1642 .sign(payer_sign).unwrap();
1644 let mut buffer = Vec::new();
1645 invoice_request.write(&mut buffer).unwrap();
1647 match InvoiceRequest::try_from(buffer) {
1648 Ok(_) => panic!("expected error"),
1649 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1652 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1654 .supported_quantity(Quantity::Bounded(one))
1656 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1658 .sign(payer_sign).unwrap();
1660 let mut buffer = Vec::new();
1661 invoice_request.write(&mut buffer).unwrap();
1663 match InvoiceRequest::try_from(buffer) {
1664 Ok(_) => panic!("expected error"),
1665 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1670 fn fails_parsing_invoice_request_without_metadata() {
1671 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1674 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1676 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1677 tlv_stream.0.metadata = None;
1679 let mut buffer = Vec::new();
1680 tlv_stream.write(&mut buffer).unwrap();
1682 match InvoiceRequest::try_from(buffer) {
1683 Ok(_) => panic!("expected error"),
1685 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1691 fn fails_parsing_invoice_request_without_payer_id() {
1692 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1695 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1697 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1698 tlv_stream.2.payer_id = None;
1700 let mut buffer = Vec::new();
1701 tlv_stream.write(&mut buffer).unwrap();
1703 match InvoiceRequest::try_from(buffer) {
1704 Ok(_) => panic!("expected error"),
1705 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1710 fn fails_parsing_invoice_request_without_node_id() {
1711 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1714 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1716 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1717 tlv_stream.1.node_id = None;
1719 let mut buffer = Vec::new();
1720 tlv_stream.write(&mut buffer).unwrap();
1722 match InvoiceRequest::try_from(buffer) {
1723 Ok(_) => panic!("expected error"),
1725 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1731 fn fails_parsing_invoice_request_without_signature() {
1732 let mut buffer = Vec::new();
1733 OfferBuilder::new("foo".into(), recipient_pubkey())
1736 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1739 .write(&mut buffer).unwrap();
1741 match InvoiceRequest::try_from(buffer) {
1742 Ok(_) => panic!("expected error"),
1743 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1748 fn fails_parsing_invoice_request_with_invalid_signature() {
1749 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1752 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1754 .sign(payer_sign).unwrap();
1755 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1756 *last_signature_byte = last_signature_byte.wrapping_add(1);
1758 let mut buffer = Vec::new();
1759 invoice_request.write(&mut buffer).unwrap();
1761 match InvoiceRequest::try_from(buffer) {
1762 Ok(_) => panic!("expected error"),
1764 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1770 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1771 let secp_ctx = Secp256k1::new();
1772 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1773 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1776 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1778 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1781 let mut encoded_invoice_request = Vec::new();
1782 invoice_request.write(&mut encoded_invoice_request).unwrap();
1783 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1784 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1785 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1787 match InvoiceRequest::try_from(encoded_invoice_request) {
1788 Ok(_) => panic!("expected error"),
1789 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),