1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `invoice_request` messages.
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with a [`Bolt12Invoice`].
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
23 //! extern crate bitcoin;
24 //! extern crate lightning;
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
33 //! # fn parse() -> Result<(), lightning::offers::parse::Bolt12ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
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>(
48 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
50 //! .expect("failed verifying signature")
51 //! .write(&mut buffer)
57 use bitcoin::blockdata::constants::ChainHash;
58 use bitcoin::network::constants::Network;
59 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
60 use bitcoin::secp256k1::schnorr::Signature;
61 use core::convert::{AsRef, Infallible, TryFrom};
63 use crate::sign::EntropySource;
65 use crate::blinded_path::BlindedPath;
66 use crate::ln::PaymentHash;
67 use crate::ln::features::InvoiceRequestFeatures;
68 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
69 use crate::ln::msgs::DecodeError;
70 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
71 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
72 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
73 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
74 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
75 use crate::offers::signer::{Metadata, MetadataMaterial};
76 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
77 use crate::util::string::PrintableString;
79 use crate::prelude::*;
81 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
82 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
84 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
86 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
88 /// See [module-level documentation] for usage.
90 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
92 /// [module-level documentation]: self
93 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
95 invoice_request: InvoiceRequestContentsWithoutPayerId,
96 payer_id: Option<PublicKey>,
97 payer_id_strategy: core::marker::PhantomData<P>,
98 secp_ctx: Option<&'b Secp256k1<T>>,
101 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
103 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
104 pub trait PayerIdStrategy {}
106 /// [`InvoiceRequest::payer_id`] will be explicitly set.
108 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
109 pub struct ExplicitPayerId {}
111 /// [`InvoiceRequest::payer_id`] will be derived.
113 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
114 pub struct DerivedPayerId {}
116 impl PayerIdStrategy for ExplicitPayerId {}
117 impl PayerIdStrategy for DerivedPayerId {}
119 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
120 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
123 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
124 payer_id: Some(payer_id),
125 payer_id_strategy: core::marker::PhantomData,
130 pub(super) fn deriving_metadata<ES: Deref>(
131 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
132 ) -> Self where ES::Target: EntropySource {
133 let nonce = Nonce::from_entropy_source(entropy_source);
134 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
135 let metadata = Metadata::Derived(derivation_material);
138 invoice_request: Self::create_contents(offer, metadata),
139 payer_id: Some(payer_id),
140 payer_id_strategy: core::marker::PhantomData,
146 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
147 pub(super) fn deriving_payer_id<ES: Deref>(
148 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
149 ) -> Self where ES::Target: EntropySource {
150 let nonce = Nonce::from_entropy_source(entropy_source);
151 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
152 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
155 invoice_request: Self::create_contents(offer, metadata),
157 payer_id_strategy: core::marker::PhantomData,
158 secp_ctx: Some(secp_ctx),
163 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
164 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
165 let offer = offer.contents.clone();
166 InvoiceRequestContentsWithoutPayerId {
167 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
168 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
172 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
173 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
176 /// Successive calls to this method will override the previous setting.
177 pub fn chain(mut self, network: Network) -> Result<Self, Bolt12SemanticError> {
178 let chain = ChainHash::using_genesis_block(network);
179 if !self.offer.supports_chain(chain) {
180 return Err(Bolt12SemanticError::UnsupportedChain);
183 self.invoice_request.chain = Some(chain);
187 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
188 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
190 /// Successive calls to this method will override the previous setting.
192 /// [`quantity`]: Self::quantity
193 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, Bolt12SemanticError> {
194 self.invoice_request.offer.check_amount_msats_for_quantity(
195 Some(amount_msats), self.invoice_request.quantity
197 self.invoice_request.amount_msats = Some(amount_msats);
201 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
202 /// does not conform to [`Offer::is_valid_quantity`].
204 /// Successive calls to this method will override the previous setting.
205 pub fn quantity(mut self, quantity: u64) -> Result<Self, Bolt12SemanticError> {
206 self.invoice_request.offer.check_quantity(Some(quantity))?;
207 self.invoice_request.quantity = Some(quantity);
211 /// Sets the [`InvoiceRequest::payer_note`].
213 /// Successive calls to this method will override the previous setting.
214 pub fn payer_note(mut self, payer_note: String) -> Self {
215 self.invoice_request.payer_note = Some(payer_note);
219 fn build_with_checks(mut self) -> Result<
220 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
223 #[cfg(feature = "std")] {
224 if self.offer.is_expired() {
225 return Err(Bolt12SemanticError::AlreadyExpired);
229 let chain = self.invoice_request.chain();
230 if !self.offer.supports_chain(chain) {
231 return Err(Bolt12SemanticError::UnsupportedChain);
234 if chain == self.offer.implied_chain() {
235 self.invoice_request.chain = None;
238 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
239 return Err(Bolt12SemanticError::MissingAmount);
242 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
243 self.invoice_request.offer.check_amount_msats_for_quantity(
244 self.invoice_request.amount_msats, self.invoice_request.quantity
247 Ok(self.build_without_checks())
250 fn build_without_checks(mut self) ->
251 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
253 // Create the metadata for stateless verification of a Bolt12Invoice.
255 let secp_ctx = self.secp_ctx.clone();
256 if self.invoice_request.payer.0.has_derivation_material() {
257 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
259 let mut tlv_stream = self.invoice_request.as_tlv_stream();
260 debug_assert!(tlv_stream.2.payer_id.is_none());
261 tlv_stream.0.metadata = None;
262 if !metadata.derives_keys() {
263 tlv_stream.2.payer_id = self.payer_id.as_ref();
266 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
267 metadata = derived_metadata;
269 if let Some(keys) = keys {
270 debug_assert!(self.payer_id.is_none());
271 self.payer_id = Some(keys.public_key());
274 self.invoice_request.payer.0 = metadata;
277 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
278 debug_assert!(self.payer_id.is_some());
279 let payer_id = self.payer_id.unwrap();
281 let invoice_request = InvoiceRequestContents {
282 inner: self.invoice_request,
285 let unsigned_invoice_request = UnsignedInvoiceRequest::new(self.offer, invoice_request);
287 (unsigned_invoice_request, keys, secp_ctx)
291 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
292 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
293 /// by [`UnsignedInvoiceRequest::sign`].
294 pub fn build(self) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
295 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
296 debug_assert!(keys.is_none());
297 Ok(unsigned_invoice_request)
301 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
302 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
303 pub fn build_and_sign(self) -> Result<InvoiceRequest, Bolt12SemanticError> {
304 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
305 debug_assert!(keys.is_some());
307 let secp_ctx = secp_ctx.unwrap();
308 let keys = keys.unwrap();
309 let invoice_request = unsigned_invoice_request
310 .sign::<_, Infallible>(
311 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
319 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
320 fn chain_unchecked(mut self, network: Network) -> Self {
321 let chain = ChainHash::using_genesis_block(network);
322 self.invoice_request.chain = Some(chain);
326 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
327 self.invoice_request.amount_msats = Some(amount_msats);
331 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
332 self.invoice_request.features = features;
336 fn quantity_unchecked(mut self, quantity: u64) -> Self {
337 self.invoice_request.quantity = Some(quantity);
341 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest {
342 self.build_without_checks().0
346 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
350 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
351 /// such, it may include unknown, odd TLV records.
352 pub struct UnsignedInvoiceRequest {
354 contents: InvoiceRequestContents,
355 tagged_hash: TaggedHash,
358 impl UnsignedInvoiceRequest {
359 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
360 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
361 // unknown TLV records, which are not stored in `OfferContents`.
362 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
363 contents.as_tlv_stream();
364 let offer_bytes = WithoutLength(&offer.bytes);
365 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
367 let mut bytes = Vec::new();
368 unsigned_tlv_stream.write(&mut bytes).unwrap();
370 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
372 Self { bytes, contents, tagged_hash }
375 /// Signs the [`TaggedHash`] of the invoice request using the given function.
377 /// Note: The hash computation may have included unknown, odd TLV records.
379 /// This is not exported to bindings users as functions are not yet mapped.
380 pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
382 F: FnOnce(&Self) -> Result<Signature, E>
384 let pubkey = self.contents.payer_id;
385 let signature = merkle::sign_message(sign, &self, pubkey)?;
387 // Append the signature TLV record to the bytes.
388 let signature_tlv_stream = SignatureTlvStreamRef {
389 signature: Some(&signature),
391 signature_tlv_stream.write(&mut self.bytes).unwrap();
395 contents: self.contents,
401 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
402 fn as_ref(&self) -> &TaggedHash {
407 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
409 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
410 /// specifies these such that its recipient can send an invoice for payment.
412 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
413 /// [`Offer`]: crate::offers::offer::Offer
414 #[derive(Clone, Debug)]
415 #[cfg_attr(test, derive(PartialEq))]
416 pub struct InvoiceRequest {
417 pub(super) bytes: Vec<u8>,
418 pub(super) contents: InvoiceRequestContents,
419 signature: Signature,
422 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
424 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
425 #[derive(Clone, Debug)]
426 #[cfg_attr(test, derive(PartialEq))]
427 pub(super) struct InvoiceRequestContents {
428 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
432 #[derive(Clone, Debug)]
433 #[cfg_attr(test, derive(PartialEq))]
434 pub(super) struct InvoiceRequestContentsWithoutPayerId {
435 payer: PayerContents,
436 pub(super) offer: OfferContents,
437 chain: Option<ChainHash>,
438 amount_msats: Option<u64>,
439 features: InvoiceRequestFeatures,
440 quantity: Option<u64>,
441 payer_note: Option<String>,
444 impl InvoiceRequest {
445 /// An unpredictable series of bytes, typically containing information about the derivation of
448 /// [`payer_id`]: Self::payer_id
449 pub fn metadata(&self) -> &[u8] {
450 self.contents.metadata()
453 /// A chain from [`Offer::chains`] that the offer is valid for.
454 pub fn chain(&self) -> ChainHash {
455 self.contents.chain()
458 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
459 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
461 /// [`chain`]: Self::chain
462 pub fn amount_msats(&self) -> Option<u64> {
463 self.contents.amount_msats()
466 /// Features pertaining to requesting an invoice.
467 pub fn features(&self) -> &InvoiceRequestFeatures {
468 &self.contents.features()
471 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
472 pub fn quantity(&self) -> Option<u64> {
473 self.contents.quantity()
476 /// A possibly transient pubkey used to sign the invoice request.
477 pub fn payer_id(&self) -> PublicKey {
478 self.contents.payer_id()
481 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
483 pub fn payer_note(&self) -> Option<PrintableString> {
484 self.contents.payer_note()
487 /// Signature of the invoice request using [`payer_id`].
489 /// [`payer_id`]: Self::payer_id
490 pub fn signature(&self) -> Signature {
494 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
495 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
497 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
498 /// creation time is used for the `created_at` parameter.
500 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
502 /// [`Duration`]: core::time::Duration
503 #[cfg(feature = "std")]
505 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
506 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
507 let created_at = std::time::SystemTime::now()
508 .duration_since(std::time::SystemTime::UNIX_EPOCH)
509 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
511 self.respond_with_no_std(payment_paths, payment_hash, created_at)
514 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
516 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
517 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
518 /// where [`std::time::SystemTime`] is not available.
520 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
523 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
524 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
525 /// a preference. Note, however, that any privacy is lost if a public node id was used for
526 /// [`Offer::signing_pubkey`].
528 /// Errors if the request contains unknown required features.
530 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
532 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
533 pub fn respond_with_no_std(
534 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
535 created_at: core::time::Duration
536 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
537 if self.features().requires_unknown_bits() {
538 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
541 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
544 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
545 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
546 /// the same [`ExpandedKey`] as the one used to create the offer.
548 /// See [`InvoiceRequest::respond_with`] for further details.
550 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
552 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
553 #[cfg(feature = "std")]
554 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
555 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
556 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
557 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
558 let created_at = std::time::SystemTime::now()
559 .duration_since(std::time::SystemTime::UNIX_EPOCH)
560 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
562 self.verify_and_respond_using_derived_keys_no_std(
563 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
567 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
568 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
569 /// the same [`ExpandedKey`] as the one used to create the offer.
571 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
573 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
575 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
576 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
577 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
578 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
579 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
580 if self.features().requires_unknown_bits() {
581 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
584 let keys = match self.verify(expanded_key, secp_ctx) {
585 Err(()) => return Err(Bolt12SemanticError::InvalidMetadata),
586 Ok(None) => return Err(Bolt12SemanticError::InvalidMetadata),
587 Ok(Some(keys)) => keys,
590 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
593 /// Verifies that the request was for an offer created using the given key. Returns the derived
594 /// keys need to sign an [`Bolt12Invoice`] for the request if they could be extracted from the
597 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
598 pub fn verify<T: secp256k1::Signing>(
599 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
600 ) -> Result<Option<KeyPair>, ()> {
601 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
605 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
606 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
607 self.contents.as_tlv_stream();
608 let signature_tlv_stream = SignatureTlvStreamRef {
609 signature: Some(&self.signature),
611 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
615 impl InvoiceRequestContents {
616 pub(super) fn metadata(&self) -> &[u8] {
617 self.inner.metadata()
620 pub(super) fn derives_keys(&self) -> bool {
621 self.inner.payer.0.derives_keys()
624 pub(super) fn chain(&self) -> ChainHash {
628 fn amount_msats(&self) -> Option<u64> {
629 self.inner.amount_msats
632 fn features(&self) -> &InvoiceRequestFeatures {
636 fn quantity(&self) -> Option<u64> {
640 pub(super) fn payer_id(&self) -> PublicKey {
644 fn payer_note(&self) -> Option<PrintableString> {
645 self.inner.payer_note.as_ref()
646 .map(|payer_note| PrintableString(payer_note.as_str()))
649 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
650 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
651 invoice_request.payer_id = Some(&self.payer_id);
652 (payer, offer, invoice_request)
656 impl InvoiceRequestContentsWithoutPayerId {
657 pub(super) fn metadata(&self) -> &[u8] {
658 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
661 pub(super) fn chain(&self) -> ChainHash {
662 self.chain.unwrap_or_else(|| self.offer.implied_chain())
665 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
666 let payer = PayerTlvStreamRef {
667 metadata: self.payer.0.as_bytes(),
670 let offer = self.offer.as_tlv_stream();
673 if self.features == InvoiceRequestFeatures::empty() { None }
674 else { Some(&self.features) }
677 let invoice_request = InvoiceRequestTlvStreamRef {
678 chain: self.chain.as_ref(),
679 amount: self.amount_msats,
681 quantity: self.quantity,
683 payer_note: self.payer_note.as_ref(),
686 (payer, offer, invoice_request)
690 impl Writeable for UnsignedInvoiceRequest {
691 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692 WithoutLength(&self.bytes).write(writer)
696 impl Writeable for InvoiceRequest {
697 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
698 WithoutLength(&self.bytes).write(writer)
702 impl Writeable for InvoiceRequestContents {
703 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
704 self.as_tlv_stream().write(writer)
708 /// Valid type range for invoice_request TLV records.
709 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
711 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
713 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
714 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
716 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
717 (80, chain: ChainHash),
718 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
719 (84, features: (InvoiceRequestFeatures, WithoutLength)),
720 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
721 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
722 (89, payer_note: (String, WithoutLength)),
725 type FullInvoiceRequestTlvStream =
726 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
729 type FullInvoiceRequestTlvStreamRef<'a> = (
730 PayerTlvStreamRef<'a>,
731 OfferTlvStreamRef<'a>,
732 InvoiceRequestTlvStreamRef<'a>,
733 SignatureTlvStreamRef<'a>,
736 impl SeekReadable for FullInvoiceRequestTlvStream {
737 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
738 let payer = SeekReadable::read(r)?;
739 let offer = SeekReadable::read(r)?;
740 let invoice_request = SeekReadable::read(r)?;
741 let signature = SeekReadable::read(r)?;
743 Ok((payer, offer, invoice_request, signature))
747 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
749 type PartialInvoiceRequestTlvStreamRef<'a> = (
750 PayerTlvStreamRef<'a>,
751 OfferTlvStreamRef<'a>,
752 InvoiceRequestTlvStreamRef<'a>,
755 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
756 type Error = Bolt12ParseError;
758 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
759 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
760 let ParsedMessage { bytes, tlv_stream } = invoice_request;
762 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
764 let contents = InvoiceRequestContents::try_from(
765 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
768 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
770 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
774 impl TryFrom<Vec<u8>> for InvoiceRequest {
775 type Error = Bolt12ParseError;
777 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
778 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
779 let ParsedMessage { bytes, tlv_stream } = invoice_request;
781 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
782 SignatureTlvStream { signature },
784 let contents = InvoiceRequestContents::try_from(
785 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
788 let signature = match signature {
789 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
790 Some(signature) => signature,
792 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
794 Ok(InvoiceRequest { bytes, contents, signature })
798 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
799 type Error = Bolt12SemanticError;
801 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
803 PayerTlvStream { metadata },
805 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
808 let payer = match metadata {
809 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
810 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
812 let offer = OfferContents::try_from(offer_tlv_stream)?;
814 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
815 return Err(Bolt12SemanticError::UnsupportedChain);
818 if offer.amount().is_none() && amount.is_none() {
819 return Err(Bolt12SemanticError::MissingAmount);
822 offer.check_quantity(quantity)?;
823 offer.check_amount_msats_for_quantity(amount, quantity)?;
825 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
827 let payer_id = match payer_id {
828 None => return Err(Bolt12SemanticError::MissingPayerId),
829 Some(payer_id) => payer_id,
832 Ok(InvoiceRequestContents {
833 inner: InvoiceRequestContentsWithoutPayerId {
834 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
843 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
845 use bitcoin::blockdata::constants::ChainHash;
846 use bitcoin::network::constants::Network;
847 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
848 use core::convert::{Infallible, TryFrom};
849 use core::num::NonZeroU64;
850 #[cfg(feature = "std")]
851 use core::time::Duration;
852 use crate::sign::KeyMaterial;
853 use crate::ln::features::InvoiceRequestFeatures;
854 use crate::ln::inbound_payment::ExpandedKey;
855 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
856 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
857 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
858 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
859 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
860 use crate::offers::payer::PayerTlvStreamRef;
861 use crate::offers::test_utils::*;
862 use crate::util::ser::{BigSize, Writeable};
863 use crate::util::string::PrintableString;
866 fn builds_invoice_request_with_defaults() {
867 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
870 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
873 let mut buffer = Vec::new();
874 unsigned_invoice_request.write(&mut buffer).unwrap();
876 match UnsignedInvoiceRequest::try_from(buffer) {
877 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
879 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
880 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
884 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
886 let mut buffer = Vec::new();
887 invoice_request.write(&mut buffer).unwrap();
889 assert_eq!(invoice_request.bytes, buffer.as_slice());
890 assert_eq!(invoice_request.metadata(), &[1; 32]);
891 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
892 assert_eq!(invoice_request.amount_msats(), None);
893 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
894 assert_eq!(invoice_request.quantity(), None);
895 assert_eq!(invoice_request.payer_id(), payer_pubkey());
896 assert_eq!(invoice_request.payer_note(), None);
898 merkle::verify_signature(
899 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
904 invoice_request.as_tlv_stream(),
906 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
912 description: Some(&String::from("foo")),
914 absolute_expiry: None,
918 node_id: Some(&recipient_pubkey()),
920 InvoiceRequestTlvStreamRef {
925 payer_id: Some(&payer_pubkey()),
928 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
932 if let Err(e) = InvoiceRequest::try_from(buffer) {
933 panic!("error parsing invoice request: {:?}", e);
937 #[cfg(feature = "std")]
939 fn builds_invoice_request_from_offer_with_expiration() {
940 let future_expiry = Duration::from_secs(u64::max_value());
941 let past_expiry = Duration::from_secs(0);
943 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
945 .absolute_expiry(future_expiry)
947 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
950 panic!("error building invoice_request: {:?}", e);
953 match OfferBuilder::new("foo".into(), recipient_pubkey())
955 .absolute_expiry(past_expiry)
957 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
960 Ok(_) => panic!("expected error"),
961 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
966 fn builds_invoice_request_with_derived_metadata() {
967 let payer_id = payer_pubkey();
968 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
969 let entropy = FixedEntropy {};
970 let secp_ctx = Secp256k1::new();
972 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
975 let invoice_request = offer
976 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
979 .sign(payer_sign).unwrap();
980 assert_eq!(invoice_request.payer_id(), payer_pubkey());
982 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
985 .sign(recipient_sign).unwrap();
986 assert!(invoice.verify(&expanded_key, &secp_ctx));
988 // Fails verification with altered fields
990 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
991 mut invoice_tlv_stream, mut signature_tlv_stream
992 ) = invoice.as_tlv_stream();
993 invoice_request_tlv_stream.amount = Some(2000);
994 invoice_tlv_stream.amount = Some(2000);
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 message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1002 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1003 signature_tlv_stream.signature = Some(&signature);
1005 let mut encoded_invoice = bytes;
1006 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1008 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1009 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1011 // Fails verification with altered metadata
1013 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1014 mut signature_tlv_stream
1015 ) = invoice.as_tlv_stream();
1016 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1017 payer_tlv_stream.metadata = Some(&metadata);
1020 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1021 let mut bytes = Vec::new();
1022 tlv_stream.write(&mut bytes).unwrap();
1024 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1025 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1026 signature_tlv_stream.signature = Some(&signature);
1028 let mut encoded_invoice = bytes;
1029 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1031 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1032 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1036 fn builds_invoice_request_with_derived_payer_id() {
1037 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1038 let entropy = FixedEntropy {};
1039 let secp_ctx = Secp256k1::new();
1041 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1044 let invoice_request = offer
1045 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1050 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1053 .sign(recipient_sign).unwrap();
1054 assert!(invoice.verify(&expanded_key, &secp_ctx));
1056 // Fails verification with altered fields
1058 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1059 mut invoice_tlv_stream, mut signature_tlv_stream
1060 ) = invoice.as_tlv_stream();
1061 invoice_request_tlv_stream.amount = Some(2000);
1062 invoice_tlv_stream.amount = Some(2000);
1065 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1066 let mut bytes = Vec::new();
1067 tlv_stream.write(&mut bytes).unwrap();
1069 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1070 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1071 signature_tlv_stream.signature = Some(&signature);
1073 let mut encoded_invoice = bytes;
1074 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1076 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1077 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1079 // Fails verification with altered payer id
1081 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1082 mut signature_tlv_stream
1083 ) = invoice.as_tlv_stream();
1084 let payer_id = pubkey(1);
1085 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1088 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1089 let mut bytes = Vec::new();
1090 tlv_stream.write(&mut bytes).unwrap();
1092 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1093 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1094 signature_tlv_stream.signature = Some(&signature);
1096 let mut encoded_invoice = bytes;
1097 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1099 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1100 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1104 fn builds_invoice_request_with_chain() {
1105 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1106 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1108 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1111 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1112 .chain(Network::Bitcoin).unwrap()
1114 .sign(payer_sign).unwrap();
1115 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1116 assert_eq!(invoice_request.chain(), mainnet);
1117 assert_eq!(tlv_stream.chain, None);
1119 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1121 .chain(Network::Testnet)
1123 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1124 .chain(Network::Testnet).unwrap()
1126 .sign(payer_sign).unwrap();
1127 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1128 assert_eq!(invoice_request.chain(), testnet);
1129 assert_eq!(tlv_stream.chain, Some(&testnet));
1131 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1133 .chain(Network::Bitcoin)
1134 .chain(Network::Testnet)
1136 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1137 .chain(Network::Bitcoin).unwrap()
1139 .sign(payer_sign).unwrap();
1140 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1141 assert_eq!(invoice_request.chain(), mainnet);
1142 assert_eq!(tlv_stream.chain, None);
1144 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1146 .chain(Network::Bitcoin)
1147 .chain(Network::Testnet)
1149 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1150 .chain(Network::Bitcoin).unwrap()
1151 .chain(Network::Testnet).unwrap()
1153 .sign(payer_sign).unwrap();
1154 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1155 assert_eq!(invoice_request.chain(), testnet);
1156 assert_eq!(tlv_stream.chain, Some(&testnet));
1158 match OfferBuilder::new("foo".into(), recipient_pubkey())
1160 .chain(Network::Testnet)
1162 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1163 .chain(Network::Bitcoin)
1165 Ok(_) => panic!("expected error"),
1166 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1169 match OfferBuilder::new("foo".into(), recipient_pubkey())
1171 .chain(Network::Testnet)
1173 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1176 Ok(_) => panic!("expected error"),
1177 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1182 fn builds_invoice_request_with_amount() {
1183 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1186 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1187 .amount_msats(1000).unwrap()
1189 .sign(payer_sign).unwrap();
1190 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1191 assert_eq!(invoice_request.amount_msats(), Some(1000));
1192 assert_eq!(tlv_stream.amount, Some(1000));
1194 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1197 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1198 .amount_msats(1001).unwrap()
1199 .amount_msats(1000).unwrap()
1201 .sign(payer_sign).unwrap();
1202 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1203 assert_eq!(invoice_request.amount_msats(), Some(1000));
1204 assert_eq!(tlv_stream.amount, Some(1000));
1206 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1209 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1210 .amount_msats(1001).unwrap()
1212 .sign(payer_sign).unwrap();
1213 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1214 assert_eq!(invoice_request.amount_msats(), Some(1001));
1215 assert_eq!(tlv_stream.amount, Some(1001));
1217 match OfferBuilder::new("foo".into(), recipient_pubkey())
1220 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1223 Ok(_) => panic!("expected error"),
1224 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1227 match OfferBuilder::new("foo".into(), recipient_pubkey())
1229 .supported_quantity(Quantity::Unbounded)
1231 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1232 .quantity(2).unwrap()
1235 Ok(_) => panic!("expected error"),
1236 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1239 match OfferBuilder::new("foo".into(), recipient_pubkey())
1242 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1243 .amount_msats(MAX_VALUE_MSAT + 1)
1245 Ok(_) => panic!("expected error"),
1246 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1249 match OfferBuilder::new("foo".into(), recipient_pubkey())
1251 .supported_quantity(Quantity::Unbounded)
1253 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1254 .amount_msats(1000).unwrap()
1255 .quantity(2).unwrap()
1258 Ok(_) => panic!("expected error"),
1259 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1262 match OfferBuilder::new("foo".into(), recipient_pubkey())
1264 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1267 Ok(_) => panic!("expected error"),
1268 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1271 match OfferBuilder::new("foo".into(), recipient_pubkey())
1273 .supported_quantity(Quantity::Unbounded)
1275 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1276 .quantity(u64::max_value()).unwrap()
1279 Ok(_) => panic!("expected error"),
1280 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1285 fn builds_invoice_request_with_features() {
1286 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1289 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1290 .features_unchecked(InvoiceRequestFeatures::unknown())
1292 .sign(payer_sign).unwrap();
1293 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1294 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
1295 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1297 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1300 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1301 .features_unchecked(InvoiceRequestFeatures::unknown())
1302 .features_unchecked(InvoiceRequestFeatures::empty())
1304 .sign(payer_sign).unwrap();
1305 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1306 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
1307 assert_eq!(tlv_stream.features, None);
1311 fn builds_invoice_request_with_quantity() {
1312 let one = NonZeroU64::new(1).unwrap();
1313 let ten = NonZeroU64::new(10).unwrap();
1315 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1317 .supported_quantity(Quantity::One)
1319 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1321 .sign(payer_sign).unwrap();
1322 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1323 assert_eq!(invoice_request.quantity(), None);
1324 assert_eq!(tlv_stream.quantity, None);
1326 match OfferBuilder::new("foo".into(), recipient_pubkey())
1328 .supported_quantity(Quantity::One)
1330 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1331 .amount_msats(2_000).unwrap()
1334 Ok(_) => panic!("expected error"),
1335 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1338 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .supported_quantity(Quantity::Bounded(ten))
1342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1343 .amount_msats(10_000).unwrap()
1344 .quantity(10).unwrap()
1346 .sign(payer_sign).unwrap();
1347 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1348 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1349 assert_eq!(tlv_stream.amount, Some(10_000));
1351 match OfferBuilder::new("foo".into(), recipient_pubkey())
1353 .supported_quantity(Quantity::Bounded(ten))
1355 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1356 .amount_msats(11_000).unwrap()
1359 Ok(_) => panic!("expected error"),
1360 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1363 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1365 .supported_quantity(Quantity::Unbounded)
1367 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1368 .amount_msats(2_000).unwrap()
1369 .quantity(2).unwrap()
1371 .sign(payer_sign).unwrap();
1372 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1373 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1374 assert_eq!(tlv_stream.amount, Some(2_000));
1376 match OfferBuilder::new("foo".into(), recipient_pubkey())
1378 .supported_quantity(Quantity::Unbounded)
1380 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1383 Ok(_) => panic!("expected error"),
1384 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1387 match OfferBuilder::new("foo".into(), recipient_pubkey())
1389 .supported_quantity(Quantity::Bounded(one))
1391 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1394 Ok(_) => panic!("expected error"),
1395 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1400 fn builds_invoice_request_with_payer_note() {
1401 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1404 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .payer_note("bar".into())
1407 .sign(payer_sign).unwrap();
1408 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1409 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1410 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1412 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1415 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1416 .payer_note("bar".into())
1417 .payer_note("baz".into())
1419 .sign(payer_sign).unwrap();
1420 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1421 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1422 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1426 fn fails_signing_invoice_request() {
1427 match OfferBuilder::new("foo".into(), recipient_pubkey())
1430 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1434 Ok(_) => panic!("expected error"),
1435 Err(e) => assert_eq!(e, SignError::Signing(())),
1438 match OfferBuilder::new("foo".into(), recipient_pubkey())
1441 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1443 .sign(recipient_sign)
1445 Ok(_) => panic!("expected error"),
1446 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1451 fn fails_responding_with_unknown_required_features() {
1452 match OfferBuilder::new("foo".into(), recipient_pubkey())
1455 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1456 .features_unchecked(InvoiceRequestFeatures::unknown())
1458 .sign(payer_sign).unwrap()
1459 .respond_with_no_std(payment_paths(), payment_hash(), now())
1461 Ok(_) => panic!("expected error"),
1462 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1467 fn parses_invoice_request_with_metadata() {
1468 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1471 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1473 .sign(payer_sign).unwrap();
1475 let mut buffer = Vec::new();
1476 invoice_request.write(&mut buffer).unwrap();
1478 if let Err(e) = InvoiceRequest::try_from(buffer) {
1479 panic!("error parsing invoice_request: {:?}", e);
1484 fn parses_invoice_request_with_chain() {
1485 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1488 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1489 .chain(Network::Bitcoin).unwrap()
1491 .sign(payer_sign).unwrap();
1493 let mut buffer = Vec::new();
1494 invoice_request.write(&mut buffer).unwrap();
1496 if let Err(e) = InvoiceRequest::try_from(buffer) {
1497 panic!("error parsing invoice_request: {:?}", e);
1500 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1503 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1504 .chain_unchecked(Network::Testnet)
1506 .sign(payer_sign).unwrap();
1508 let mut buffer = Vec::new();
1509 invoice_request.write(&mut buffer).unwrap();
1511 match InvoiceRequest::try_from(buffer) {
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1518 fn parses_invoice_request_with_amount() {
1519 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1522 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1524 .sign(payer_sign).unwrap();
1526 let mut buffer = Vec::new();
1527 invoice_request.write(&mut buffer).unwrap();
1529 if let Err(e) = InvoiceRequest::try_from(buffer) {
1530 panic!("error parsing invoice_request: {:?}", e);
1533 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1535 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1536 .amount_msats(1000).unwrap()
1538 .sign(payer_sign).unwrap();
1540 let mut buffer = Vec::new();
1541 invoice_request.write(&mut buffer).unwrap();
1543 if let Err(e) = InvoiceRequest::try_from(buffer) {
1544 panic!("error parsing invoice_request: {:?}", e);
1547 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1549 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1551 .sign(payer_sign).unwrap();
1553 let mut buffer = Vec::new();
1554 invoice_request.write(&mut buffer).unwrap();
1556 match InvoiceRequest::try_from(buffer) {
1557 Ok(_) => panic!("expected error"),
1558 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1561 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1564 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1565 .amount_msats_unchecked(999)
1567 .sign(payer_sign).unwrap();
1569 let mut buffer = Vec::new();
1570 invoice_request.write(&mut buffer).unwrap();
1572 match InvoiceRequest::try_from(buffer) {
1573 Ok(_) => panic!("expected error"),
1574 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1577 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1578 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1582 .sign(payer_sign).unwrap();
1584 let mut buffer = Vec::new();
1585 invoice_request.write(&mut buffer).unwrap();
1587 match InvoiceRequest::try_from(buffer) {
1588 Ok(_) => panic!("expected error"),
1590 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1594 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1596 .supported_quantity(Quantity::Unbounded)
1598 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1599 .quantity(u64::max_value()).unwrap()
1601 .sign(payer_sign).unwrap();
1603 let mut buffer = Vec::new();
1604 invoice_request.write(&mut buffer).unwrap();
1606 match InvoiceRequest::try_from(buffer) {
1607 Ok(_) => panic!("expected error"),
1608 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1613 fn parses_invoice_request_with_quantity() {
1614 let one = NonZeroU64::new(1).unwrap();
1615 let ten = NonZeroU64::new(10).unwrap();
1617 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1619 .supported_quantity(Quantity::One)
1621 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623 .sign(payer_sign).unwrap();
1625 let mut buffer = Vec::new();
1626 invoice_request.write(&mut buffer).unwrap();
1628 if let Err(e) = InvoiceRequest::try_from(buffer) {
1629 panic!("error parsing invoice_request: {:?}", e);
1632 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1634 .supported_quantity(Quantity::One)
1636 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1637 .amount_msats(2_000).unwrap()
1638 .quantity_unchecked(2)
1640 .sign(payer_sign).unwrap();
1642 let mut buffer = Vec::new();
1643 invoice_request.write(&mut buffer).unwrap();
1645 match InvoiceRequest::try_from(buffer) {
1646 Ok(_) => panic!("expected error"),
1648 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1652 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1654 .supported_quantity(Quantity::Bounded(ten))
1656 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1657 .amount_msats(10_000).unwrap()
1658 .quantity(10).unwrap()
1660 .sign(payer_sign).unwrap();
1662 let mut buffer = Vec::new();
1663 invoice_request.write(&mut buffer).unwrap();
1665 if let Err(e) = InvoiceRequest::try_from(buffer) {
1666 panic!("error parsing invoice_request: {:?}", e);
1669 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1671 .supported_quantity(Quantity::Bounded(ten))
1673 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1674 .amount_msats(11_000).unwrap()
1675 .quantity_unchecked(11)
1677 .sign(payer_sign).unwrap();
1679 let mut buffer = Vec::new();
1680 invoice_request.write(&mut buffer).unwrap();
1682 match InvoiceRequest::try_from(buffer) {
1683 Ok(_) => panic!("expected error"),
1684 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1687 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1689 .supported_quantity(Quantity::Unbounded)
1691 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1692 .amount_msats(2_000).unwrap()
1693 .quantity(2).unwrap()
1695 .sign(payer_sign).unwrap();
1697 let mut buffer = Vec::new();
1698 invoice_request.write(&mut buffer).unwrap();
1700 if let Err(e) = InvoiceRequest::try_from(buffer) {
1701 panic!("error parsing invoice_request: {:?}", e);
1704 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1706 .supported_quantity(Quantity::Unbounded)
1708 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1710 .sign(payer_sign).unwrap();
1712 let mut buffer = Vec::new();
1713 invoice_request.write(&mut buffer).unwrap();
1715 match InvoiceRequest::try_from(buffer) {
1716 Ok(_) => panic!("expected error"),
1717 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1720 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1722 .supported_quantity(Quantity::Bounded(one))
1724 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1726 .sign(payer_sign).unwrap();
1728 let mut buffer = Vec::new();
1729 invoice_request.write(&mut buffer).unwrap();
1731 match InvoiceRequest::try_from(buffer) {
1732 Ok(_) => panic!("expected error"),
1733 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1738 fn fails_parsing_invoice_request_without_metadata() {
1739 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1742 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1744 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1745 tlv_stream.0.metadata = None;
1747 let mut buffer = Vec::new();
1748 tlv_stream.write(&mut buffer).unwrap();
1750 match InvoiceRequest::try_from(buffer) {
1751 Ok(_) => panic!("expected error"),
1753 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1759 fn fails_parsing_invoice_request_without_payer_id() {
1760 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1763 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1765 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1766 tlv_stream.2.payer_id = None;
1768 let mut buffer = Vec::new();
1769 tlv_stream.write(&mut buffer).unwrap();
1771 match InvoiceRequest::try_from(buffer) {
1772 Ok(_) => panic!("expected error"),
1773 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1778 fn fails_parsing_invoice_request_without_node_id() {
1779 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1782 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1784 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1785 tlv_stream.1.node_id = None;
1787 let mut buffer = Vec::new();
1788 tlv_stream.write(&mut buffer).unwrap();
1790 match InvoiceRequest::try_from(buffer) {
1791 Ok(_) => panic!("expected error"),
1793 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1799 fn fails_parsing_invoice_request_without_signature() {
1800 let mut buffer = Vec::new();
1801 OfferBuilder::new("foo".into(), recipient_pubkey())
1804 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .write(&mut buffer).unwrap();
1809 match InvoiceRequest::try_from(buffer) {
1810 Ok(_) => panic!("expected error"),
1811 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1816 fn fails_parsing_invoice_request_with_invalid_signature() {
1817 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1820 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1822 .sign(payer_sign).unwrap();
1823 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1824 *last_signature_byte = last_signature_byte.wrapping_add(1);
1826 let mut buffer = Vec::new();
1827 invoice_request.write(&mut buffer).unwrap();
1829 match InvoiceRequest::try_from(buffer) {
1830 Ok(_) => panic!("expected error"),
1832 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1838 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1839 let secp_ctx = Secp256k1::new();
1840 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1841 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1844 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1846 .sign::<_, Infallible>(
1847 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1851 let mut encoded_invoice_request = Vec::new();
1852 invoice_request.write(&mut encoded_invoice_request).unwrap();
1853 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1854 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1855 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1857 match InvoiceRequest::try_from(encoded_invoice_request) {
1858 Ok(_) => panic!("expected error"),
1859 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),