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 /// [module-level documentation]: self
88 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
90 invoice_request: InvoiceRequestContentsWithoutPayerId,
91 payer_id: Option<PublicKey>,
92 payer_id_strategy: core::marker::PhantomData<P>,
93 secp_ctx: Option<&'b Secp256k1<T>>,
96 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
97 pub trait PayerIdStrategy {}
99 /// [`InvoiceRequest::payer_id`] will be explicitly set.
100 pub struct ExplicitPayerId {}
102 /// [`InvoiceRequest::payer_id`] will be derived.
103 pub struct DerivedPayerId {}
105 impl PayerIdStrategy for ExplicitPayerId {}
106 impl PayerIdStrategy for DerivedPayerId {}
108 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
109 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
112 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
113 payer_id: Some(payer_id),
114 payer_id_strategy: core::marker::PhantomData,
119 pub(super) fn deriving_metadata<ES: Deref>(
120 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
121 ) -> Self where ES::Target: EntropySource {
122 let nonce = Nonce::from_entropy_source(entropy_source);
123 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
124 let metadata = Metadata::Derived(derivation_material);
127 invoice_request: Self::create_contents(offer, metadata),
128 payer_id: Some(payer_id),
129 payer_id_strategy: core::marker::PhantomData,
135 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
136 pub(super) fn deriving_payer_id<ES: Deref>(
137 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
138 ) -> Self where ES::Target: EntropySource {
139 let nonce = Nonce::from_entropy_source(entropy_source);
140 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
141 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
144 invoice_request: Self::create_contents(offer, metadata),
146 payer_id_strategy: core::marker::PhantomData,
147 secp_ctx: Some(secp_ctx),
152 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
153 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
154 let offer = offer.contents.clone();
155 InvoiceRequestContentsWithoutPayerId {
156 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
157 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
161 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
162 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
165 /// Successive calls to this method will override the previous setting.
166 pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
167 let chain = ChainHash::using_genesis_block(network);
168 if !self.offer.supports_chain(chain) {
169 return Err(SemanticError::UnsupportedChain);
172 self.invoice_request.chain = Some(chain);
176 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
177 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
179 /// Successive calls to this method will override the previous setting.
181 /// [`quantity`]: Self::quantity
182 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
183 self.invoice_request.offer.check_amount_msats_for_quantity(
184 Some(amount_msats), self.invoice_request.quantity
186 self.invoice_request.amount_msats = Some(amount_msats);
190 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
191 /// does not conform to [`Offer::is_valid_quantity`].
193 /// Successive calls to this method will override the previous setting.
194 pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
195 self.invoice_request.offer.check_quantity(Some(quantity))?;
196 self.invoice_request.quantity = Some(quantity);
200 /// Sets the [`InvoiceRequest::payer_note`].
202 /// Successive calls to this method will override the previous setting.
203 pub fn payer_note(mut self, payer_note: String) -> Self {
204 self.invoice_request.payer_note = Some(payer_note);
208 fn build_with_checks(mut self) -> Result<
209 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>),
212 #[cfg(feature = "std")] {
213 if self.offer.is_expired() {
214 return Err(SemanticError::AlreadyExpired);
218 let chain = self.invoice_request.chain();
219 if !self.offer.supports_chain(chain) {
220 return Err(SemanticError::UnsupportedChain);
223 if chain == self.offer.implied_chain() {
224 self.invoice_request.chain = None;
227 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
228 return Err(SemanticError::MissingAmount);
231 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
232 self.invoice_request.offer.check_amount_msats_for_quantity(
233 self.invoice_request.amount_msats, self.invoice_request.quantity
236 Ok(self.build_without_checks())
239 fn build_without_checks(mut self) ->
240 (UnsignedInvoiceRequest<'a>, Option<KeyPair>, Option<&'b Secp256k1<T>>)
242 // Create the metadata for stateless verification of an Invoice.
244 let secp_ctx = self.secp_ctx.clone();
245 if self.invoice_request.payer.0.has_derivation_material() {
246 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
248 let mut tlv_stream = self.invoice_request.as_tlv_stream();
249 debug_assert!(tlv_stream.2.payer_id.is_none());
250 tlv_stream.0.metadata = None;
251 if !metadata.derives_keys() {
252 tlv_stream.2.payer_id = self.payer_id.as_ref();
255 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
256 metadata = derived_metadata;
258 if let Some(keys) = keys {
259 debug_assert!(self.payer_id.is_none());
260 self.payer_id = Some(keys.public_key());
263 self.invoice_request.payer.0 = metadata;
266 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
267 debug_assert!(self.payer_id.is_some());
268 let payer_id = self.payer_id.unwrap();
270 let unsigned_invoice = UnsignedInvoiceRequest {
272 invoice_request: InvoiceRequestContents {
273 inner: self.invoice_request,
278 (unsigned_invoice, keys, secp_ctx)
282 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
283 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
284 /// by [`UnsignedInvoiceRequest::sign`].
285 pub fn build(self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
286 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
287 debug_assert!(keys.is_none());
288 Ok(unsigned_invoice_request)
292 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
293 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
294 pub fn build_and_sign(self) -> Result<InvoiceRequest, SemanticError> {
295 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
296 debug_assert!(keys.is_some());
298 let secp_ctx = secp_ctx.unwrap();
299 let keys = keys.unwrap();
300 let invoice_request = unsigned_invoice_request
301 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
308 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
309 fn chain_unchecked(mut self, network: Network) -> Self {
310 let chain = ChainHash::using_genesis_block(network);
311 self.invoice_request.chain = Some(chain);
315 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
316 self.invoice_request.amount_msats = Some(amount_msats);
320 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
321 self.invoice_request.features = features;
325 fn quantity_unchecked(mut self, quantity: u64) -> Self {
326 self.invoice_request.quantity = Some(quantity);
330 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
331 self.build_without_checks().0
335 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
336 pub struct UnsignedInvoiceRequest<'a> {
338 invoice_request: InvoiceRequestContents,
341 impl<'a> UnsignedInvoiceRequest<'a> {
342 /// Signs the invoice request using the given function.
343 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
345 F: FnOnce(&Message) -> Result<Signature, E>
347 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
348 // unknown TLV records, which are not stored in `OfferContents`.
349 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
350 self.invoice_request.as_tlv_stream();
351 let offer_bytes = WithoutLength(&self.offer.bytes);
352 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
354 let mut bytes = Vec::new();
355 unsigned_tlv_stream.write(&mut bytes).unwrap();
357 let pubkey = self.invoice_request.payer_id;
358 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
360 // Append the signature TLV record to the bytes.
361 let signature_tlv_stream = SignatureTlvStreamRef {
362 signature: Some(&signature),
364 signature_tlv_stream.write(&mut bytes).unwrap();
368 contents: self.invoice_request,
374 /// An `InvoiceRequest` is a request for an [`Invoice`] formulated from an [`Offer`].
376 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
377 /// specifies these such that its recipient can send an invoice for payment.
379 /// [`Invoice`]: crate::offers::invoice::Invoice
380 /// [`Offer`]: crate::offers::offer::Offer
381 #[derive(Clone, Debug)]
382 #[cfg_attr(test, derive(PartialEq))]
383 pub struct InvoiceRequest {
384 pub(super) bytes: Vec<u8>,
385 pub(super) contents: InvoiceRequestContents,
386 signature: Signature,
389 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Invoice`].
391 /// [`Invoice`]: crate::offers::invoice::Invoice
392 #[derive(Clone, Debug)]
393 #[cfg_attr(test, derive(PartialEq))]
394 pub(super) struct InvoiceRequestContents {
395 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
399 #[derive(Clone, Debug)]
400 #[cfg_attr(test, derive(PartialEq))]
401 pub(super) struct InvoiceRequestContentsWithoutPayerId {
402 payer: PayerContents,
403 pub(super) offer: OfferContents,
404 chain: Option<ChainHash>,
405 amount_msats: Option<u64>,
406 features: InvoiceRequestFeatures,
407 quantity: Option<u64>,
408 payer_note: Option<String>,
411 impl InvoiceRequest {
412 /// An unpredictable series of bytes, typically containing information about the derivation of
415 /// [`payer_id`]: Self::payer_id
416 pub fn metadata(&self) -> &[u8] {
417 self.contents.metadata()
420 /// A chain from [`Offer::chains`] that the offer is valid for.
421 pub fn chain(&self) -> ChainHash {
422 self.contents.chain()
425 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
426 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
428 /// [`chain`]: Self::chain
429 pub fn amount_msats(&self) -> Option<u64> {
430 self.contents.inner.amount_msats
433 /// Features pertaining to requesting an invoice.
434 pub fn features(&self) -> &InvoiceRequestFeatures {
435 &self.contents.inner.features
438 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
439 pub fn quantity(&self) -> Option<u64> {
440 self.contents.inner.quantity
443 /// A possibly transient pubkey used to sign the invoice request.
444 pub fn payer_id(&self) -> PublicKey {
445 self.contents.payer_id
448 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
450 pub fn payer_note(&self) -> Option<PrintableString> {
451 self.contents.inner.payer_note.as_ref()
452 .map(|payer_note| PrintableString(payer_note.as_str()))
455 /// Signature of the invoice request using [`payer_id`].
457 /// [`payer_id`]: Self::payer_id
458 pub fn signature(&self) -> Signature {
462 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
463 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
465 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
466 /// creation time is used for the `created_at` parameter.
468 /// [`Duration`]: core::time::Duration
469 #[cfg(feature = "std")]
471 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash
472 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
473 let created_at = std::time::SystemTime::now()
474 .duration_since(std::time::SystemTime::UNIX_EPOCH)
475 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
477 self.respond_with_no_std(payment_paths, payment_hash, created_at)
480 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
482 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
483 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
484 /// [`std::time::SystemTime`] is not available.
486 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
489 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
490 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
491 /// a preference. Note, however, that any privacy is lost if a public node id was used for
492 /// [`Offer::signing_pubkey`].
494 /// Errors if the request contains unknown required features.
496 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
497 pub fn respond_with_no_std(
498 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
499 created_at: core::time::Duration
500 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
501 if self.features().requires_unknown_bits() {
502 return Err(SemanticError::UnknownRequiredFeatures);
505 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
508 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
509 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
510 /// same [`ExpandedKey`] as the one used to create the offer.
512 /// See [`InvoiceRequest::respond_with`] for further details.
514 /// [`Invoice`]: crate::offers::invoice::Invoice
515 #[cfg(feature = "std")]
516 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
517 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
518 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
519 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
520 let created_at = std::time::SystemTime::now()
521 .duration_since(std::time::SystemTime::UNIX_EPOCH)
522 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
524 self.verify_and_respond_using_derived_keys_no_std(
525 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
529 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
530 /// derived signing keys from the originating [`Offer`] to sign the [`Invoice`]. Must use the
531 /// same [`ExpandedKey`] as the one used to create the offer.
533 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
535 /// [`Invoice`]: crate::offers::invoice::Invoice
536 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
537 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
538 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
539 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError> {
540 if self.features().requires_unknown_bits() {
541 return Err(SemanticError::UnknownRequiredFeatures);
544 let keys = match self.verify(expanded_key, secp_ctx) {
545 Err(()) => return Err(SemanticError::InvalidMetadata),
546 Ok(None) => return Err(SemanticError::InvalidMetadata),
547 Ok(Some(keys)) => keys,
550 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
553 /// Verifies that the request was for an offer created using the given key. Returns the derived
554 /// keys need to sign an [`Invoice`] for the request if they could be extracted from the
557 /// [`Invoice`]: crate::offers::invoice::Invoice
558 pub fn verify<T: secp256k1::Signing>(
559 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
560 ) -> Result<Option<KeyPair>, ()> {
561 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
565 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
566 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
567 self.contents.as_tlv_stream();
568 let signature_tlv_stream = SignatureTlvStreamRef {
569 signature: Some(&self.signature),
571 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
575 impl InvoiceRequestContents {
576 pub fn metadata(&self) -> &[u8] {
577 self.inner.metadata()
580 pub(super) fn derives_keys(&self) -> bool {
581 self.inner.payer.0.derives_keys()
584 pub(super) fn chain(&self) -> ChainHash {
588 pub(super) fn payer_id(&self) -> PublicKey {
592 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
593 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
594 invoice_request.payer_id = Some(&self.payer_id);
595 (payer, offer, invoice_request)
599 impl InvoiceRequestContentsWithoutPayerId {
600 pub(super) fn metadata(&self) -> &[u8] {
601 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
604 pub(super) fn chain(&self) -> ChainHash {
605 self.chain.unwrap_or_else(|| self.offer.implied_chain())
608 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
609 let payer = PayerTlvStreamRef {
610 metadata: self.payer.0.as_bytes(),
613 let offer = self.offer.as_tlv_stream();
616 if self.features == InvoiceRequestFeatures::empty() { None }
617 else { Some(&self.features) }
620 let invoice_request = InvoiceRequestTlvStreamRef {
621 chain: self.chain.as_ref(),
622 amount: self.amount_msats,
624 quantity: self.quantity,
626 payer_note: self.payer_note.as_ref(),
629 (payer, offer, invoice_request)
633 impl Writeable for InvoiceRequest {
634 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
635 WithoutLength(&self.bytes).write(writer)
639 impl Writeable for InvoiceRequestContents {
640 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
641 self.as_tlv_stream().write(writer)
645 /// Valid type range for invoice_request TLV records.
646 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
648 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
650 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
651 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
653 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
654 (80, chain: ChainHash),
655 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
656 (84, features: (InvoiceRequestFeatures, WithoutLength)),
657 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
658 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
659 (89, payer_note: (String, WithoutLength)),
662 type FullInvoiceRequestTlvStream =
663 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
666 type FullInvoiceRequestTlvStreamRef<'a> = (
667 PayerTlvStreamRef<'a>,
668 OfferTlvStreamRef<'a>,
669 InvoiceRequestTlvStreamRef<'a>,
670 SignatureTlvStreamRef<'a>,
673 impl SeekReadable for FullInvoiceRequestTlvStream {
674 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
675 let payer = SeekReadable::read(r)?;
676 let offer = SeekReadable::read(r)?;
677 let invoice_request = SeekReadable::read(r)?;
678 let signature = SeekReadable::read(r)?;
680 Ok((payer, offer, invoice_request, signature))
684 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
686 type PartialInvoiceRequestTlvStreamRef<'a> = (
687 PayerTlvStreamRef<'a>,
688 OfferTlvStreamRef<'a>,
689 InvoiceRequestTlvStreamRef<'a>,
692 impl TryFrom<Vec<u8>> for InvoiceRequest {
693 type Error = ParseError;
695 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
696 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
697 let ParsedMessage { bytes, tlv_stream } = invoice_request;
699 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
700 SignatureTlvStream { signature },
702 let contents = InvoiceRequestContents::try_from(
703 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
706 let signature = match signature {
707 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
708 Some(signature) => signature,
710 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
712 Ok(InvoiceRequest { bytes, contents, signature })
716 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
717 type Error = SemanticError;
719 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
721 PayerTlvStream { metadata },
723 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
726 let payer = match metadata {
727 None => return Err(SemanticError::MissingPayerMetadata),
728 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
730 let offer = OfferContents::try_from(offer_tlv_stream)?;
732 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
733 return Err(SemanticError::UnsupportedChain);
736 if offer.amount().is_none() && amount.is_none() {
737 return Err(SemanticError::MissingAmount);
740 offer.check_quantity(quantity)?;
741 offer.check_amount_msats_for_quantity(amount, quantity)?;
743 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
745 let payer_id = match payer_id {
746 None => return Err(SemanticError::MissingPayerId),
747 Some(payer_id) => payer_id,
750 Ok(InvoiceRequestContents {
751 inner: InvoiceRequestContentsWithoutPayerId {
752 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
761 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
763 use bitcoin::blockdata::constants::ChainHash;
764 use bitcoin::network::constants::Network;
765 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
766 use core::convert::{Infallible, TryFrom};
767 use core::num::NonZeroU64;
768 #[cfg(feature = "std")]
769 use core::time::Duration;
770 use crate::chain::keysinterface::KeyMaterial;
771 use crate::ln::features::InvoiceRequestFeatures;
772 use crate::ln::inbound_payment::ExpandedKey;
773 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
774 use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
775 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
776 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
777 use crate::offers::parse::{ParseError, SemanticError};
778 use crate::offers::payer::PayerTlvStreamRef;
779 use crate::offers::test_utils::*;
780 use crate::util::ser::{BigSize, Writeable};
781 use crate::util::string::PrintableString;
784 fn builds_invoice_request_with_defaults() {
785 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
788 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
790 .sign(payer_sign).unwrap();
792 let mut buffer = Vec::new();
793 invoice_request.write(&mut buffer).unwrap();
795 assert_eq!(invoice_request.bytes, buffer.as_slice());
796 assert_eq!(invoice_request.metadata(), &[1; 32]);
797 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
798 assert_eq!(invoice_request.amount_msats(), None);
799 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
800 assert_eq!(invoice_request.quantity(), None);
801 assert_eq!(invoice_request.payer_id(), payer_pubkey());
802 assert_eq!(invoice_request.payer_note(), None);
804 merkle::verify_signature(
805 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
810 invoice_request.as_tlv_stream(),
812 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
818 description: Some(&String::from("foo")),
820 absolute_expiry: None,
824 node_id: Some(&recipient_pubkey()),
826 InvoiceRequestTlvStreamRef {
831 payer_id: Some(&payer_pubkey()),
834 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
838 if let Err(e) = InvoiceRequest::try_from(buffer) {
839 panic!("error parsing invoice request: {:?}", e);
843 #[cfg(feature = "std")]
845 fn builds_invoice_request_from_offer_with_expiration() {
846 let future_expiry = Duration::from_secs(u64::max_value());
847 let past_expiry = Duration::from_secs(0);
849 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
851 .absolute_expiry(future_expiry)
853 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
856 panic!("error building invoice_request: {:?}", e);
859 match OfferBuilder::new("foo".into(), recipient_pubkey())
861 .absolute_expiry(past_expiry)
863 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
866 Ok(_) => panic!("expected error"),
867 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
872 fn builds_invoice_request_with_derived_metadata() {
873 let payer_id = payer_pubkey();
874 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
875 let entropy = FixedEntropy {};
876 let secp_ctx = Secp256k1::new();
878 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
881 let invoice_request = offer
882 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
885 .sign(payer_sign).unwrap();
886 assert_eq!(invoice_request.payer_id(), payer_pubkey());
888 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
891 .sign(recipient_sign).unwrap();
892 assert!(invoice.verify(&expanded_key, &secp_ctx));
894 // Fails verification with altered fields
896 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
897 mut invoice_tlv_stream, mut signature_tlv_stream
898 ) = invoice.as_tlv_stream();
899 invoice_request_tlv_stream.amount = Some(2000);
900 invoice_tlv_stream.amount = Some(2000);
903 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
904 let mut bytes = Vec::new();
905 tlv_stream.write(&mut bytes).unwrap();
907 let signature = merkle::sign_message(
908 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
910 signature_tlv_stream.signature = Some(&signature);
912 let mut encoded_invoice = bytes;
913 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
915 let invoice = Invoice::try_from(encoded_invoice).unwrap();
916 assert!(!invoice.verify(&expanded_key, &secp_ctx));
918 // Fails verification with altered metadata
920 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
921 mut signature_tlv_stream
922 ) = invoice.as_tlv_stream();
923 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
924 payer_tlv_stream.metadata = Some(&metadata);
927 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
928 let mut bytes = Vec::new();
929 tlv_stream.write(&mut bytes).unwrap();
931 let signature = merkle::sign_message(
932 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
934 signature_tlv_stream.signature = Some(&signature);
936 let mut encoded_invoice = bytes;
937 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
939 let invoice = Invoice::try_from(encoded_invoice).unwrap();
940 assert!(!invoice.verify(&expanded_key, &secp_ctx));
944 fn builds_invoice_request_with_derived_payer_id() {
945 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
946 let entropy = FixedEntropy {};
947 let secp_ctx = Secp256k1::new();
949 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
952 let invoice_request = offer
953 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
958 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
961 .sign(recipient_sign).unwrap();
962 assert!(invoice.verify(&expanded_key, &secp_ctx));
964 // Fails verification with altered fields
966 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
967 mut invoice_tlv_stream, mut signature_tlv_stream
968 ) = invoice.as_tlv_stream();
969 invoice_request_tlv_stream.amount = Some(2000);
970 invoice_tlv_stream.amount = Some(2000);
973 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
974 let mut bytes = Vec::new();
975 tlv_stream.write(&mut bytes).unwrap();
977 let signature = merkle::sign_message(
978 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
980 signature_tlv_stream.signature = Some(&signature);
982 let mut encoded_invoice = bytes;
983 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
985 let invoice = Invoice::try_from(encoded_invoice).unwrap();
986 assert!(!invoice.verify(&expanded_key, &secp_ctx));
988 // Fails verification with altered payer id
990 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
991 mut signature_tlv_stream
992 ) = invoice.as_tlv_stream();
993 let payer_id = pubkey(1);
994 invoice_request_tlv_stream.payer_id = Some(&payer_id);
997 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
998 let mut bytes = Vec::new();
999 tlv_stream.write(&mut bytes).unwrap();
1001 let signature = merkle::sign_message(
1002 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
1004 signature_tlv_stream.signature = Some(&signature);
1006 let mut encoded_invoice = bytes;
1007 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1009 let invoice = Invoice::try_from(encoded_invoice).unwrap();
1010 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1014 fn builds_invoice_request_with_chain() {
1015 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1016 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1018 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1021 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1022 .chain(Network::Bitcoin).unwrap()
1024 .sign(payer_sign).unwrap();
1025 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1026 assert_eq!(invoice_request.chain(), mainnet);
1027 assert_eq!(tlv_stream.chain, None);
1029 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1031 .chain(Network::Testnet)
1033 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1034 .chain(Network::Testnet).unwrap()
1036 .sign(payer_sign).unwrap();
1037 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1038 assert_eq!(invoice_request.chain(), testnet);
1039 assert_eq!(tlv_stream.chain, Some(&testnet));
1041 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1043 .chain(Network::Bitcoin)
1044 .chain(Network::Testnet)
1046 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1047 .chain(Network::Bitcoin).unwrap()
1049 .sign(payer_sign).unwrap();
1050 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1051 assert_eq!(invoice_request.chain(), mainnet);
1052 assert_eq!(tlv_stream.chain, None);
1054 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1056 .chain(Network::Bitcoin)
1057 .chain(Network::Testnet)
1059 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1060 .chain(Network::Bitcoin).unwrap()
1061 .chain(Network::Testnet).unwrap()
1063 .sign(payer_sign).unwrap();
1064 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1065 assert_eq!(invoice_request.chain(), testnet);
1066 assert_eq!(tlv_stream.chain, Some(&testnet));
1068 match OfferBuilder::new("foo".into(), recipient_pubkey())
1070 .chain(Network::Testnet)
1072 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 .chain(Network::Bitcoin)
1075 Ok(_) => panic!("expected error"),
1076 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1079 match OfferBuilder::new("foo".into(), recipient_pubkey())
1081 .chain(Network::Testnet)
1083 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1086 Ok(_) => panic!("expected error"),
1087 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1092 fn builds_invoice_request_with_amount() {
1093 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1096 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1097 .amount_msats(1000).unwrap()
1099 .sign(payer_sign).unwrap();
1100 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1101 assert_eq!(invoice_request.amount_msats(), Some(1000));
1102 assert_eq!(tlv_stream.amount, Some(1000));
1104 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1107 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1108 .amount_msats(1001).unwrap()
1109 .amount_msats(1000).unwrap()
1111 .sign(payer_sign).unwrap();
1112 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1113 assert_eq!(invoice_request.amount_msats(), Some(1000));
1114 assert_eq!(tlv_stream.amount, Some(1000));
1116 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1119 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1120 .amount_msats(1001).unwrap()
1122 .sign(payer_sign).unwrap();
1123 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1124 assert_eq!(invoice_request.amount_msats(), Some(1001));
1125 assert_eq!(tlv_stream.amount, Some(1001));
1127 match OfferBuilder::new("foo".into(), recipient_pubkey())
1130 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1133 Ok(_) => panic!("expected error"),
1134 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1137 match OfferBuilder::new("foo".into(), recipient_pubkey())
1139 .supported_quantity(Quantity::Unbounded)
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142 .quantity(2).unwrap()
1145 Ok(_) => panic!("expected error"),
1146 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1149 match OfferBuilder::new("foo".into(), recipient_pubkey())
1152 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1153 .amount_msats(MAX_VALUE_MSAT + 1)
1155 Ok(_) => panic!("expected error"),
1156 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1159 match OfferBuilder::new("foo".into(), recipient_pubkey())
1161 .supported_quantity(Quantity::Unbounded)
1163 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .amount_msats(1000).unwrap()
1165 .quantity(2).unwrap()
1168 Ok(_) => panic!("expected error"),
1169 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1172 match OfferBuilder::new("foo".into(), recipient_pubkey())
1174 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1177 Ok(_) => panic!("expected error"),
1178 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1181 match OfferBuilder::new("foo".into(), recipient_pubkey())
1183 .supported_quantity(Quantity::Unbounded)
1185 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186 .quantity(u64::max_value()).unwrap()
1189 Ok(_) => panic!("expected error"),
1190 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1195 fn builds_invoice_request_with_features() {
1196 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1199 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1200 .features_unchecked(InvoiceRequestFeatures::unknown())
1202 .sign(payer_sign).unwrap();
1203 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1204 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1205 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1207 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1210 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1211 .features_unchecked(InvoiceRequestFeatures::unknown())
1212 .features_unchecked(InvoiceRequestFeatures::empty())
1214 .sign(payer_sign).unwrap();
1215 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1216 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1217 assert_eq!(tlv_stream.features, None);
1221 fn builds_invoice_request_with_quantity() {
1222 let one = NonZeroU64::new(1).unwrap();
1223 let ten = NonZeroU64::new(10).unwrap();
1225 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1227 .supported_quantity(Quantity::One)
1229 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231 .sign(payer_sign).unwrap();
1232 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1233 assert_eq!(invoice_request.quantity(), None);
1234 assert_eq!(tlv_stream.quantity, None);
1236 match OfferBuilder::new("foo".into(), recipient_pubkey())
1238 .supported_quantity(Quantity::One)
1240 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1241 .amount_msats(2_000).unwrap()
1244 Ok(_) => panic!("expected error"),
1245 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1248 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1250 .supported_quantity(Quantity::Bounded(ten))
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1253 .amount_msats(10_000).unwrap()
1254 .quantity(10).unwrap()
1256 .sign(payer_sign).unwrap();
1257 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1258 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1259 assert_eq!(tlv_stream.amount, Some(10_000));
1261 match OfferBuilder::new("foo".into(), recipient_pubkey())
1263 .supported_quantity(Quantity::Bounded(ten))
1265 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1266 .amount_msats(11_000).unwrap()
1269 Ok(_) => panic!("expected error"),
1270 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1273 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1275 .supported_quantity(Quantity::Unbounded)
1277 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1278 .amount_msats(2_000).unwrap()
1279 .quantity(2).unwrap()
1281 .sign(payer_sign).unwrap();
1282 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1283 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1284 assert_eq!(tlv_stream.amount, Some(2_000));
1286 match OfferBuilder::new("foo".into(), recipient_pubkey())
1288 .supported_quantity(Quantity::Unbounded)
1290 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1293 Ok(_) => panic!("expected error"),
1294 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1297 match OfferBuilder::new("foo".into(), recipient_pubkey())
1299 .supported_quantity(Quantity::Bounded(one))
1301 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1304 Ok(_) => panic!("expected error"),
1305 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1310 fn builds_invoice_request_with_payer_note() {
1311 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1314 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 .payer_note("bar".into())
1317 .sign(payer_sign).unwrap();
1318 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1319 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1320 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1322 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1325 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1326 .payer_note("bar".into())
1327 .payer_note("baz".into())
1329 .sign(payer_sign).unwrap();
1330 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1331 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1332 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1336 fn fails_signing_invoice_request() {
1337 match OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 Ok(_) => panic!("expected error"),
1345 Err(e) => assert_eq!(e, SignError::Signing(())),
1348 match OfferBuilder::new("foo".into(), recipient_pubkey())
1351 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1353 .sign(recipient_sign)
1355 Ok(_) => panic!("expected error"),
1356 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1361 fn fails_responding_with_unknown_required_features() {
1362 match OfferBuilder::new("foo".into(), recipient_pubkey())
1365 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1366 .features_unchecked(InvoiceRequestFeatures::unknown())
1368 .sign(payer_sign).unwrap()
1369 .respond_with_no_std(payment_paths(), payment_hash(), now())
1371 Ok(_) => panic!("expected error"),
1372 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1377 fn parses_invoice_request_with_metadata() {
1378 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1381 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1383 .sign(payer_sign).unwrap();
1385 let mut buffer = Vec::new();
1386 invoice_request.write(&mut buffer).unwrap();
1388 if let Err(e) = InvoiceRequest::try_from(buffer) {
1389 panic!("error parsing invoice_request: {:?}", e);
1394 fn parses_invoice_request_with_chain() {
1395 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1398 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1399 .chain(Network::Bitcoin).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);
1410 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1413 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1414 .chain_unchecked(Network::Testnet)
1416 .sign(payer_sign).unwrap();
1418 let mut buffer = Vec::new();
1419 invoice_request.write(&mut buffer).unwrap();
1421 match InvoiceRequest::try_from(buffer) {
1422 Ok(_) => panic!("expected error"),
1423 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1428 fn parses_invoice_request_with_amount() {
1429 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1432 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1434 .sign(payer_sign).unwrap();
1436 let mut buffer = Vec::new();
1437 invoice_request.write(&mut buffer).unwrap();
1439 if let Err(e) = InvoiceRequest::try_from(buffer) {
1440 panic!("error parsing invoice_request: {:?}", e);
1443 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446 .amount_msats(1000).unwrap()
1448 .sign(payer_sign).unwrap();
1450 let mut buffer = Vec::new();
1451 invoice_request.write(&mut buffer).unwrap();
1453 if let Err(e) = InvoiceRequest::try_from(buffer) {
1454 panic!("error parsing invoice_request: {:?}", e);
1457 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1459 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1461 .sign(payer_sign).unwrap();
1463 let mut buffer = Vec::new();
1464 invoice_request.write(&mut buffer).unwrap();
1466 match InvoiceRequest::try_from(buffer) {
1467 Ok(_) => panic!("expected error"),
1468 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1471 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1474 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1475 .amount_msats_unchecked(999)
1477 .sign(payer_sign).unwrap();
1479 let mut buffer = Vec::new();
1480 invoice_request.write(&mut buffer).unwrap();
1482 match InvoiceRequest::try_from(buffer) {
1483 Ok(_) => panic!("expected error"),
1484 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1487 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1488 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1490 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1492 .sign(payer_sign).unwrap();
1494 let mut buffer = Vec::new();
1495 invoice_request.write(&mut buffer).unwrap();
1497 match InvoiceRequest::try_from(buffer) {
1498 Ok(_) => panic!("expected error"),
1500 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1504 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1506 .supported_quantity(Quantity::Unbounded)
1508 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1509 .quantity(u64::max_value()).unwrap()
1511 .sign(payer_sign).unwrap();
1513 let mut buffer = Vec::new();
1514 invoice_request.write(&mut buffer).unwrap();
1516 match InvoiceRequest::try_from(buffer) {
1517 Ok(_) => panic!("expected error"),
1518 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1523 fn parses_invoice_request_with_quantity() {
1524 let one = NonZeroU64::new(1).unwrap();
1525 let ten = NonZeroU64::new(10).unwrap();
1527 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1529 .supported_quantity(Quantity::One)
1531 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1533 .sign(payer_sign).unwrap();
1535 let mut buffer = Vec::new();
1536 invoice_request.write(&mut buffer).unwrap();
1538 if let Err(e) = InvoiceRequest::try_from(buffer) {
1539 panic!("error parsing invoice_request: {:?}", e);
1542 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1544 .supported_quantity(Quantity::One)
1546 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1547 .amount_msats(2_000).unwrap()
1548 .quantity_unchecked(2)
1550 .sign(payer_sign).unwrap();
1552 let mut buffer = Vec::new();
1553 invoice_request.write(&mut buffer).unwrap();
1555 match InvoiceRequest::try_from(buffer) {
1556 Ok(_) => panic!("expected error"),
1558 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1562 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1564 .supported_quantity(Quantity::Bounded(ten))
1566 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1567 .amount_msats(10_000).unwrap()
1568 .quantity(10).unwrap()
1570 .sign(payer_sign).unwrap();
1572 let mut buffer = Vec::new();
1573 invoice_request.write(&mut buffer).unwrap();
1575 if let Err(e) = InvoiceRequest::try_from(buffer) {
1576 panic!("error parsing invoice_request: {:?}", e);
1579 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1581 .supported_quantity(Quantity::Bounded(ten))
1583 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1584 .amount_msats(11_000).unwrap()
1585 .quantity_unchecked(11)
1587 .sign(payer_sign).unwrap();
1589 let mut buffer = Vec::new();
1590 invoice_request.write(&mut buffer).unwrap();
1592 match InvoiceRequest::try_from(buffer) {
1593 Ok(_) => panic!("expected error"),
1594 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1597 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1599 .supported_quantity(Quantity::Unbounded)
1601 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1602 .amount_msats(2_000).unwrap()
1603 .quantity(2).unwrap()
1605 .sign(payer_sign).unwrap();
1607 let mut buffer = Vec::new();
1608 invoice_request.write(&mut buffer).unwrap();
1610 if let Err(e) = InvoiceRequest::try_from(buffer) {
1611 panic!("error parsing invoice_request: {:?}", e);
1614 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1616 .supported_quantity(Quantity::Unbounded)
1618 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620 .sign(payer_sign).unwrap();
1622 let mut buffer = Vec::new();
1623 invoice_request.write(&mut buffer).unwrap();
1625 match InvoiceRequest::try_from(buffer) {
1626 Ok(_) => panic!("expected error"),
1627 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1630 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1632 .supported_quantity(Quantity::Bounded(one))
1634 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1636 .sign(payer_sign).unwrap();
1638 let mut buffer = Vec::new();
1639 invoice_request.write(&mut buffer).unwrap();
1641 match InvoiceRequest::try_from(buffer) {
1642 Ok(_) => panic!("expected error"),
1643 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1648 fn fails_parsing_invoice_request_without_metadata() {
1649 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1652 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1654 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1655 tlv_stream.0.metadata = None;
1657 let mut buffer = Vec::new();
1658 tlv_stream.write(&mut buffer).unwrap();
1660 match InvoiceRequest::try_from(buffer) {
1661 Ok(_) => panic!("expected error"),
1663 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1669 fn fails_parsing_invoice_request_without_payer_id() {
1670 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1673 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1675 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1676 tlv_stream.2.payer_id = None;
1678 let mut buffer = Vec::new();
1679 tlv_stream.write(&mut buffer).unwrap();
1681 match InvoiceRequest::try_from(buffer) {
1682 Ok(_) => panic!("expected error"),
1683 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1688 fn fails_parsing_invoice_request_without_node_id() {
1689 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1692 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1694 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1695 tlv_stream.1.node_id = None;
1697 let mut buffer = Vec::new();
1698 tlv_stream.write(&mut buffer).unwrap();
1700 match InvoiceRequest::try_from(buffer) {
1701 Ok(_) => panic!("expected error"),
1703 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1709 fn fails_parsing_invoice_request_without_signature() {
1710 let mut buffer = Vec::new();
1711 OfferBuilder::new("foo".into(), recipient_pubkey())
1714 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1717 .write(&mut buffer).unwrap();
1719 match InvoiceRequest::try_from(buffer) {
1720 Ok(_) => panic!("expected error"),
1721 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1726 fn fails_parsing_invoice_request_with_invalid_signature() {
1727 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1730 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1732 .sign(payer_sign).unwrap();
1733 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1734 *last_signature_byte = last_signature_byte.wrapping_add(1);
1736 let mut buffer = Vec::new();
1737 invoice_request.write(&mut buffer).unwrap();
1739 match InvoiceRequest::try_from(buffer) {
1740 Ok(_) => panic!("expected error"),
1742 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1748 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1749 let secp_ctx = Secp256k1::new();
1750 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1751 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1754 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1756 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1759 let mut encoded_invoice_request = Vec::new();
1760 invoice_request.write(&mut encoded_invoice_request).unwrap();
1761 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1762 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1763 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1765 match InvoiceRequest::try_from(encoded_invoice_request) {
1766 Ok(_) => panic!("expected error"),
1767 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),