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::ln::PaymentHash;
64 use crate::ln::features::InvoiceRequestFeatures;
65 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
66 use crate::ln::msgs::DecodeError;
67 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
68 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, self};
69 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
70 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
71 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
72 use crate::offers::signer::{Metadata, MetadataMaterial};
73 use crate::onion_message::BlindedPath;
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, 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, 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 /// Verifies that the request was for an offer created using the given key.
509 pub fn verify<T: secp256k1::Signing>(
510 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
512 self.contents.inner.offer.verify(TlvStream::new(&self.bytes), key, secp_ctx)
516 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
517 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
518 self.contents.as_tlv_stream();
519 let signature_tlv_stream = SignatureTlvStreamRef {
520 signature: Some(&self.signature),
522 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
526 impl InvoiceRequestContents {
527 pub fn metadata(&self) -> &[u8] {
528 self.inner.metadata()
531 pub(super) fn derives_keys(&self) -> bool {
532 self.inner.payer.0.derives_keys()
535 pub(super) fn chain(&self) -> ChainHash {
539 pub(super) fn payer_id(&self) -> PublicKey {
543 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
544 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
545 invoice_request.payer_id = Some(&self.payer_id);
546 (payer, offer, invoice_request)
550 impl InvoiceRequestContentsWithoutPayerId {
551 pub(super) fn metadata(&self) -> &[u8] {
552 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
555 pub(super) fn chain(&self) -> ChainHash {
556 self.chain.unwrap_or_else(|| self.offer.implied_chain())
559 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
560 let payer = PayerTlvStreamRef {
561 metadata: self.payer.0.as_bytes(),
564 let offer = self.offer.as_tlv_stream();
567 if self.features == InvoiceRequestFeatures::empty() { None }
568 else { Some(&self.features) }
571 let invoice_request = InvoiceRequestTlvStreamRef {
572 chain: self.chain.as_ref(),
573 amount: self.amount_msats,
575 quantity: self.quantity,
577 payer_note: self.payer_note.as_ref(),
580 (payer, offer, invoice_request)
584 impl Writeable for InvoiceRequest {
585 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
586 WithoutLength(&self.bytes).write(writer)
590 impl Writeable for InvoiceRequestContents {
591 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
592 self.as_tlv_stream().write(writer)
596 /// Valid type range for invoice_request TLV records.
597 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
599 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
601 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
602 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
604 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
605 (80, chain: ChainHash),
606 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
607 (84, features: (InvoiceRequestFeatures, WithoutLength)),
608 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
609 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
610 (89, payer_note: (String, WithoutLength)),
613 type FullInvoiceRequestTlvStream =
614 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
617 type FullInvoiceRequestTlvStreamRef<'a> = (
618 PayerTlvStreamRef<'a>,
619 OfferTlvStreamRef<'a>,
620 InvoiceRequestTlvStreamRef<'a>,
621 SignatureTlvStreamRef<'a>,
624 impl SeekReadable for FullInvoiceRequestTlvStream {
625 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
626 let payer = SeekReadable::read(r)?;
627 let offer = SeekReadable::read(r)?;
628 let invoice_request = SeekReadable::read(r)?;
629 let signature = SeekReadable::read(r)?;
631 Ok((payer, offer, invoice_request, signature))
635 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
637 type PartialInvoiceRequestTlvStreamRef<'a> = (
638 PayerTlvStreamRef<'a>,
639 OfferTlvStreamRef<'a>,
640 InvoiceRequestTlvStreamRef<'a>,
643 impl TryFrom<Vec<u8>> for InvoiceRequest {
644 type Error = ParseError;
646 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
647 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
648 let ParsedMessage { bytes, tlv_stream } = invoice_request;
650 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
651 SignatureTlvStream { signature },
653 let contents = InvoiceRequestContents::try_from(
654 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
657 let signature = match signature {
658 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
659 Some(signature) => signature,
661 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
663 Ok(InvoiceRequest { bytes, contents, signature })
667 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
668 type Error = SemanticError;
670 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
672 PayerTlvStream { metadata },
674 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
677 let payer = match metadata {
678 None => return Err(SemanticError::MissingPayerMetadata),
679 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
681 let offer = OfferContents::try_from(offer_tlv_stream)?;
683 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
684 return Err(SemanticError::UnsupportedChain);
687 if offer.amount().is_none() && amount.is_none() {
688 return Err(SemanticError::MissingAmount);
691 offer.check_quantity(quantity)?;
692 offer.check_amount_msats_for_quantity(amount, quantity)?;
694 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
696 let payer_id = match payer_id {
697 None => return Err(SemanticError::MissingPayerId),
698 Some(payer_id) => payer_id,
701 Ok(InvoiceRequestContents {
702 inner: InvoiceRequestContentsWithoutPayerId {
703 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
712 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
714 use bitcoin::blockdata::constants::ChainHash;
715 use bitcoin::network::constants::Network;
716 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
717 use core::convert::{Infallible, TryFrom};
718 use core::num::NonZeroU64;
719 #[cfg(feature = "std")]
720 use core::time::Duration;
721 use crate::chain::keysinterface::KeyMaterial;
722 use crate::ln::features::InvoiceRequestFeatures;
723 use crate::ln::inbound_payment::ExpandedKey;
724 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
725 use crate::offers::invoice::{Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
726 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
727 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
728 use crate::offers::parse::{ParseError, SemanticError};
729 use crate::offers::payer::PayerTlvStreamRef;
730 use crate::offers::test_utils::*;
731 use crate::util::ser::{BigSize, Writeable};
732 use crate::util::string::PrintableString;
735 fn builds_invoice_request_with_defaults() {
736 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
739 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
741 .sign(payer_sign).unwrap();
743 let mut buffer = Vec::new();
744 invoice_request.write(&mut buffer).unwrap();
746 assert_eq!(invoice_request.bytes, buffer.as_slice());
747 assert_eq!(invoice_request.metadata(), &[1; 32]);
748 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
749 assert_eq!(invoice_request.amount_msats(), None);
750 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
751 assert_eq!(invoice_request.quantity(), None);
752 assert_eq!(invoice_request.payer_id(), payer_pubkey());
753 assert_eq!(invoice_request.payer_note(), None);
755 merkle::verify_signature(
756 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
761 invoice_request.as_tlv_stream(),
763 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
769 description: Some(&String::from("foo")),
771 absolute_expiry: None,
775 node_id: Some(&recipient_pubkey()),
777 InvoiceRequestTlvStreamRef {
782 payer_id: Some(&payer_pubkey()),
785 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
789 if let Err(e) = InvoiceRequest::try_from(buffer) {
790 panic!("error parsing invoice request: {:?}", e);
794 #[cfg(feature = "std")]
796 fn builds_invoice_request_from_offer_with_expiration() {
797 let future_expiry = Duration::from_secs(u64::max_value());
798 let past_expiry = Duration::from_secs(0);
800 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
802 .absolute_expiry(future_expiry)
804 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
807 panic!("error building invoice_request: {:?}", e);
810 match OfferBuilder::new("foo".into(), recipient_pubkey())
812 .absolute_expiry(past_expiry)
814 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
817 Ok(_) => panic!("expected error"),
818 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
823 fn builds_invoice_request_with_derived_metadata() {
824 let payer_id = payer_pubkey();
825 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
826 let entropy = FixedEntropy {};
827 let secp_ctx = Secp256k1::new();
829 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
832 let invoice_request = offer
833 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
836 .sign(payer_sign).unwrap();
837 assert_eq!(invoice_request.payer_id(), payer_pubkey());
839 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
842 .sign(recipient_sign).unwrap();
843 assert!(invoice.verify(&expanded_key, &secp_ctx));
845 // Fails verification with altered fields
847 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
848 mut invoice_tlv_stream, mut signature_tlv_stream
849 ) = invoice.as_tlv_stream();
850 invoice_request_tlv_stream.amount = Some(2000);
851 invoice_tlv_stream.amount = Some(2000);
854 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
855 let mut bytes = Vec::new();
856 tlv_stream.write(&mut bytes).unwrap();
858 let signature = merkle::sign_message(
859 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
861 signature_tlv_stream.signature = Some(&signature);
863 let mut encoded_invoice = bytes;
864 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
866 let invoice = Invoice::try_from(encoded_invoice).unwrap();
867 assert!(!invoice.verify(&expanded_key, &secp_ctx));
869 // Fails verification with altered metadata
871 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
872 mut signature_tlv_stream
873 ) = invoice.as_tlv_stream();
874 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
875 payer_tlv_stream.metadata = Some(&metadata);
878 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
879 let mut bytes = Vec::new();
880 tlv_stream.write(&mut bytes).unwrap();
882 let signature = merkle::sign_message(
883 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
885 signature_tlv_stream.signature = Some(&signature);
887 let mut encoded_invoice = bytes;
888 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
890 let invoice = Invoice::try_from(encoded_invoice).unwrap();
891 assert!(!invoice.verify(&expanded_key, &secp_ctx));
895 fn builds_invoice_request_with_derived_payer_id() {
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_payer_id(&expanded_key, &entropy, &secp_ctx)
909 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
912 .sign(recipient_sign).unwrap();
913 assert!(invoice.verify(&expanded_key, &secp_ctx));
915 // Fails verification with altered fields
917 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
918 mut invoice_tlv_stream, mut signature_tlv_stream
919 ) = invoice.as_tlv_stream();
920 invoice_request_tlv_stream.amount = Some(2000);
921 invoice_tlv_stream.amount = Some(2000);
924 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
925 let mut bytes = Vec::new();
926 tlv_stream.write(&mut bytes).unwrap();
928 let signature = merkle::sign_message(
929 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
931 signature_tlv_stream.signature = Some(&signature);
933 let mut encoded_invoice = bytes;
934 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
936 let invoice = Invoice::try_from(encoded_invoice).unwrap();
937 assert!(!invoice.verify(&expanded_key, &secp_ctx));
939 // Fails verification with altered payer id
941 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
942 mut signature_tlv_stream
943 ) = invoice.as_tlv_stream();
944 let payer_id = pubkey(1);
945 invoice_request_tlv_stream.payer_id = Some(&payer_id);
948 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
949 let mut bytes = Vec::new();
950 tlv_stream.write(&mut bytes).unwrap();
952 let signature = merkle::sign_message(
953 recipient_sign, INVOICE_SIGNATURE_TAG, &bytes, recipient_pubkey()
955 signature_tlv_stream.signature = Some(&signature);
957 let mut encoded_invoice = bytes;
958 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
960 let invoice = Invoice::try_from(encoded_invoice).unwrap();
961 assert!(!invoice.verify(&expanded_key, &secp_ctx));
965 fn builds_invoice_request_with_chain() {
966 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
967 let testnet = ChainHash::using_genesis_block(Network::Testnet);
969 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
972 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
973 .chain(Network::Bitcoin).unwrap()
975 .sign(payer_sign).unwrap();
976 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
977 assert_eq!(invoice_request.chain(), mainnet);
978 assert_eq!(tlv_stream.chain, None);
980 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
982 .chain(Network::Testnet)
984 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
985 .chain(Network::Testnet).unwrap()
987 .sign(payer_sign).unwrap();
988 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
989 assert_eq!(invoice_request.chain(), testnet);
990 assert_eq!(tlv_stream.chain, Some(&testnet));
992 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
994 .chain(Network::Bitcoin)
995 .chain(Network::Testnet)
997 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
998 .chain(Network::Bitcoin).unwrap()
1000 .sign(payer_sign).unwrap();
1001 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1002 assert_eq!(invoice_request.chain(), mainnet);
1003 assert_eq!(tlv_stream.chain, None);
1005 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1007 .chain(Network::Bitcoin)
1008 .chain(Network::Testnet)
1010 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1011 .chain(Network::Bitcoin).unwrap()
1012 .chain(Network::Testnet).unwrap()
1014 .sign(payer_sign).unwrap();
1015 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1016 assert_eq!(invoice_request.chain(), testnet);
1017 assert_eq!(tlv_stream.chain, Some(&testnet));
1019 match OfferBuilder::new("foo".into(), recipient_pubkey())
1021 .chain(Network::Testnet)
1023 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1024 .chain(Network::Bitcoin)
1026 Ok(_) => panic!("expected error"),
1027 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1030 match OfferBuilder::new("foo".into(), recipient_pubkey())
1032 .chain(Network::Testnet)
1034 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1037 Ok(_) => panic!("expected error"),
1038 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
1043 fn builds_invoice_request_with_amount() {
1044 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1047 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1048 .amount_msats(1000).unwrap()
1050 .sign(payer_sign).unwrap();
1051 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1052 assert_eq!(invoice_request.amount_msats(), Some(1000));
1053 assert_eq!(tlv_stream.amount, Some(1000));
1055 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1058 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1059 .amount_msats(1001).unwrap()
1060 .amount_msats(1000).unwrap()
1062 .sign(payer_sign).unwrap();
1063 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1064 assert_eq!(invoice_request.amount_msats(), Some(1000));
1065 assert_eq!(tlv_stream.amount, Some(1000));
1067 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1070 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 .amount_msats(1001).unwrap()
1073 .sign(payer_sign).unwrap();
1074 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1075 assert_eq!(invoice_request.amount_msats(), Some(1001));
1076 assert_eq!(tlv_stream.amount, Some(1001));
1078 match OfferBuilder::new("foo".into(), recipient_pubkey())
1081 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1084 Ok(_) => panic!("expected error"),
1085 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1088 match OfferBuilder::new("foo".into(), recipient_pubkey())
1090 .supported_quantity(Quantity::Unbounded)
1092 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1093 .quantity(2).unwrap()
1096 Ok(_) => panic!("expected error"),
1097 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1100 match OfferBuilder::new("foo".into(), recipient_pubkey())
1103 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1104 .amount_msats(MAX_VALUE_MSAT + 1)
1106 Ok(_) => panic!("expected error"),
1107 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1110 match OfferBuilder::new("foo".into(), recipient_pubkey())
1112 .supported_quantity(Quantity::Unbounded)
1114 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1115 .amount_msats(1000).unwrap()
1116 .quantity(2).unwrap()
1119 Ok(_) => panic!("expected error"),
1120 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
1123 match OfferBuilder::new("foo".into(), recipient_pubkey())
1125 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1128 Ok(_) => panic!("expected error"),
1129 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
1132 match OfferBuilder::new("foo".into(), recipient_pubkey())
1134 .supported_quantity(Quantity::Unbounded)
1136 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1137 .quantity(u64::max_value()).unwrap()
1140 Ok(_) => panic!("expected error"),
1141 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1146 fn builds_invoice_request_with_features() {
1147 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1150 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151 .features_unchecked(InvoiceRequestFeatures::unknown())
1153 .sign(payer_sign).unwrap();
1154 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1155 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1156 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1158 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1161 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1162 .features_unchecked(InvoiceRequestFeatures::unknown())
1163 .features_unchecked(InvoiceRequestFeatures::empty())
1165 .sign(payer_sign).unwrap();
1166 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1167 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1168 assert_eq!(tlv_stream.features, None);
1172 fn builds_invoice_request_with_quantity() {
1173 let one = NonZeroU64::new(1).unwrap();
1174 let ten = NonZeroU64::new(10).unwrap();
1176 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1178 .supported_quantity(Quantity::One)
1180 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1182 .sign(payer_sign).unwrap();
1183 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1184 assert_eq!(invoice_request.quantity(), None);
1185 assert_eq!(tlv_stream.quantity, None);
1187 match OfferBuilder::new("foo".into(), recipient_pubkey())
1189 .supported_quantity(Quantity::One)
1191 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1192 .amount_msats(2_000).unwrap()
1195 Ok(_) => panic!("expected error"),
1196 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
1199 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1201 .supported_quantity(Quantity::Bounded(ten))
1203 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1204 .amount_msats(10_000).unwrap()
1205 .quantity(10).unwrap()
1207 .sign(payer_sign).unwrap();
1208 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1209 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1210 assert_eq!(tlv_stream.amount, Some(10_000));
1212 match OfferBuilder::new("foo".into(), recipient_pubkey())
1214 .supported_quantity(Quantity::Bounded(ten))
1216 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1217 .amount_msats(11_000).unwrap()
1220 Ok(_) => panic!("expected error"),
1221 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
1224 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1226 .supported_quantity(Quantity::Unbounded)
1228 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229 .amount_msats(2_000).unwrap()
1230 .quantity(2).unwrap()
1232 .sign(payer_sign).unwrap();
1233 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1234 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1235 assert_eq!(tlv_stream.amount, Some(2_000));
1237 match OfferBuilder::new("foo".into(), recipient_pubkey())
1239 .supported_quantity(Quantity::Unbounded)
1241 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1244 Ok(_) => panic!("expected error"),
1245 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1248 match OfferBuilder::new("foo".into(), recipient_pubkey())
1250 .supported_quantity(Quantity::Bounded(one))
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1255 Ok(_) => panic!("expected error"),
1256 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
1261 fn builds_invoice_request_with_payer_note() {
1262 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1265 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1266 .payer_note("bar".into())
1268 .sign(payer_sign).unwrap();
1269 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1270 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1271 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1273 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1276 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1277 .payer_note("bar".into())
1278 .payer_note("baz".into())
1280 .sign(payer_sign).unwrap();
1281 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1282 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1283 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1287 fn fails_signing_invoice_request() {
1288 match OfferBuilder::new("foo".into(), recipient_pubkey())
1291 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1295 Ok(_) => panic!("expected error"),
1296 Err(e) => assert_eq!(e, SignError::Signing(())),
1299 match OfferBuilder::new("foo".into(), recipient_pubkey())
1302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1304 .sign(recipient_sign)
1306 Ok(_) => panic!("expected error"),
1307 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1312 fn fails_responding_with_unknown_required_features() {
1313 match OfferBuilder::new("foo".into(), recipient_pubkey())
1316 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1317 .features_unchecked(InvoiceRequestFeatures::unknown())
1319 .sign(payer_sign).unwrap()
1320 .respond_with_no_std(payment_paths(), payment_hash(), now())
1322 Ok(_) => panic!("expected error"),
1323 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1328 fn parses_invoice_request_with_metadata() {
1329 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1334 .sign(payer_sign).unwrap();
1336 let mut buffer = Vec::new();
1337 invoice_request.write(&mut buffer).unwrap();
1339 if let Err(e) = InvoiceRequest::try_from(buffer) {
1340 panic!("error parsing invoice_request: {:?}", e);
1345 fn parses_invoice_request_with_chain() {
1346 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1349 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1350 .chain(Network::Bitcoin).unwrap()
1352 .sign(payer_sign).unwrap();
1354 let mut buffer = Vec::new();
1355 invoice_request.write(&mut buffer).unwrap();
1357 if let Err(e) = InvoiceRequest::try_from(buffer) {
1358 panic!("error parsing invoice_request: {:?}", e);
1361 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1364 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1365 .chain_unchecked(Network::Testnet)
1367 .sign(payer_sign).unwrap();
1369 let mut buffer = Vec::new();
1370 invoice_request.write(&mut buffer).unwrap();
1372 match InvoiceRequest::try_from(buffer) {
1373 Ok(_) => panic!("expected error"),
1374 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1379 fn parses_invoice_request_with_amount() {
1380 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1383 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1385 .sign(payer_sign).unwrap();
1387 let mut buffer = Vec::new();
1388 invoice_request.write(&mut buffer).unwrap();
1390 if let Err(e) = InvoiceRequest::try_from(buffer) {
1391 panic!("error parsing invoice_request: {:?}", e);
1394 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1396 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1397 .amount_msats(1000).unwrap()
1399 .sign(payer_sign).unwrap();
1401 let mut buffer = Vec::new();
1402 invoice_request.write(&mut buffer).unwrap();
1404 if let Err(e) = InvoiceRequest::try_from(buffer) {
1405 panic!("error parsing invoice_request: {:?}", e);
1408 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1410 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1412 .sign(payer_sign).unwrap();
1414 let mut buffer = Vec::new();
1415 invoice_request.write(&mut buffer).unwrap();
1417 match InvoiceRequest::try_from(buffer) {
1418 Ok(_) => panic!("expected error"),
1419 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1422 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1425 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1426 .amount_msats_unchecked(999)
1428 .sign(payer_sign).unwrap();
1430 let mut buffer = Vec::new();
1431 invoice_request.write(&mut buffer).unwrap();
1433 match InvoiceRequest::try_from(buffer) {
1434 Ok(_) => panic!("expected error"),
1435 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1438 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1439 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1441 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1443 .sign(payer_sign).unwrap();
1445 let mut buffer = Vec::new();
1446 invoice_request.write(&mut buffer).unwrap();
1448 match InvoiceRequest::try_from(buffer) {
1449 Ok(_) => panic!("expected error"),
1451 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1455 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1457 .supported_quantity(Quantity::Unbounded)
1459 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1460 .quantity(u64::max_value()).unwrap()
1462 .sign(payer_sign).unwrap();
1464 let mut buffer = Vec::new();
1465 invoice_request.write(&mut buffer).unwrap();
1467 match InvoiceRequest::try_from(buffer) {
1468 Ok(_) => panic!("expected error"),
1469 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1474 fn parses_invoice_request_with_quantity() {
1475 let one = NonZeroU64::new(1).unwrap();
1476 let ten = NonZeroU64::new(10).unwrap();
1478 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1480 .supported_quantity(Quantity::One)
1482 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1484 .sign(payer_sign).unwrap();
1486 let mut buffer = Vec::new();
1487 invoice_request.write(&mut buffer).unwrap();
1489 if let Err(e) = InvoiceRequest::try_from(buffer) {
1490 panic!("error parsing invoice_request: {:?}", e);
1493 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1495 .supported_quantity(Quantity::One)
1497 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1498 .amount_msats(2_000).unwrap()
1499 .quantity_unchecked(2)
1501 .sign(payer_sign).unwrap();
1503 let mut buffer = Vec::new();
1504 invoice_request.write(&mut buffer).unwrap();
1506 match InvoiceRequest::try_from(buffer) {
1507 Ok(_) => panic!("expected error"),
1509 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1513 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1515 .supported_quantity(Quantity::Bounded(ten))
1517 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1518 .amount_msats(10_000).unwrap()
1519 .quantity(10).unwrap()
1521 .sign(payer_sign).unwrap();
1523 let mut buffer = Vec::new();
1524 invoice_request.write(&mut buffer).unwrap();
1526 if let Err(e) = InvoiceRequest::try_from(buffer) {
1527 panic!("error parsing invoice_request: {:?}", e);
1530 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1532 .supported_quantity(Quantity::Bounded(ten))
1534 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1535 .amount_msats(11_000).unwrap()
1536 .quantity_unchecked(11)
1538 .sign(payer_sign).unwrap();
1540 let mut buffer = Vec::new();
1541 invoice_request.write(&mut buffer).unwrap();
1543 match InvoiceRequest::try_from(buffer) {
1544 Ok(_) => panic!("expected error"),
1545 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1548 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1550 .supported_quantity(Quantity::Unbounded)
1552 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1553 .amount_msats(2_000).unwrap()
1554 .quantity(2).unwrap()
1556 .sign(payer_sign).unwrap();
1558 let mut buffer = Vec::new();
1559 invoice_request.write(&mut buffer).unwrap();
1561 if let Err(e) = InvoiceRequest::try_from(buffer) {
1562 panic!("error parsing invoice_request: {:?}", e);
1565 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1567 .supported_quantity(Quantity::Unbounded)
1569 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1571 .sign(payer_sign).unwrap();
1573 let mut buffer = Vec::new();
1574 invoice_request.write(&mut buffer).unwrap();
1576 match InvoiceRequest::try_from(buffer) {
1577 Ok(_) => panic!("expected error"),
1578 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1581 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1583 .supported_quantity(Quantity::Bounded(one))
1585 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
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::MissingQuantity)),
1599 fn fails_parsing_invoice_request_without_metadata() {
1600 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1603 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1605 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1606 tlv_stream.0.metadata = None;
1608 let mut buffer = Vec::new();
1609 tlv_stream.write(&mut buffer).unwrap();
1611 match InvoiceRequest::try_from(buffer) {
1612 Ok(_) => panic!("expected error"),
1614 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1620 fn fails_parsing_invoice_request_without_payer_id() {
1621 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1624 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1627 tlv_stream.2.payer_id = None;
1629 let mut buffer = Vec::new();
1630 tlv_stream.write(&mut buffer).unwrap();
1632 match InvoiceRequest::try_from(buffer) {
1633 Ok(_) => panic!("expected error"),
1634 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1639 fn fails_parsing_invoice_request_without_node_id() {
1640 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1643 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1645 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1646 tlv_stream.1.node_id = None;
1648 let mut buffer = Vec::new();
1649 tlv_stream.write(&mut buffer).unwrap();
1651 match InvoiceRequest::try_from(buffer) {
1652 Ok(_) => panic!("expected error"),
1654 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1660 fn fails_parsing_invoice_request_without_signature() {
1661 let mut buffer = Vec::new();
1662 OfferBuilder::new("foo".into(), recipient_pubkey())
1665 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1668 .write(&mut buffer).unwrap();
1670 match InvoiceRequest::try_from(buffer) {
1671 Ok(_) => panic!("expected error"),
1672 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1677 fn fails_parsing_invoice_request_with_invalid_signature() {
1678 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1681 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1683 .sign(payer_sign).unwrap();
1684 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1685 *last_signature_byte = last_signature_byte.wrapping_add(1);
1687 let mut buffer = Vec::new();
1688 invoice_request.write(&mut buffer).unwrap();
1690 match InvoiceRequest::try_from(buffer) {
1691 Ok(_) => panic!("expected error"),
1693 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1699 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1700 let secp_ctx = Secp256k1::new();
1701 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1702 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1705 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1707 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1710 let mut encoded_invoice_request = Vec::new();
1711 invoice_request.write(&mut encoded_invoice_request).unwrap();
1712 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1713 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1714 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1716 match InvoiceRequest::try_from(encoded_invoice_request) {
1717 Ok(_) => panic!("expected error"),
1718 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),