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 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
445 /// An unpredictable series of bytes, typically containing information about the derivation of
448 /// [`payer_id`]: Self::payer_id
449 pub fn payer_metadata(&$self) -> &[u8] {
453 /// A chain from [`Offer::chains`] that the offer is valid for.
454 pub fn chain(&$self) -> ChainHash {
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 $contents.amount_msats()
466 /// Features pertaining to requesting an invoice.
467 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
468 &$contents.features()
471 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
472 pub fn quantity(&$self) -> Option<u64> {
476 /// A possibly transient pubkey used to sign the invoice request.
477 pub fn payer_id(&$self) -> PublicKey {
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 $contents.payer_note()
488 impl InvoiceRequest {
489 invoice_request_accessors!(self, self.contents);
491 /// Signature of the invoice request using [`payer_id`].
493 /// [`payer_id`]: Self::payer_id
494 pub fn signature(&self) -> Signature {
498 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
499 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
501 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
502 /// creation time is used for the `created_at` parameter.
504 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
506 /// [`Duration`]: core::time::Duration
507 #[cfg(feature = "std")]
509 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
510 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
511 let created_at = std::time::SystemTime::now()
512 .duration_since(std::time::SystemTime::UNIX_EPOCH)
513 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
515 self.respond_with_no_std(payment_paths, payment_hash, created_at)
518 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
520 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
521 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
522 /// where [`std::time::SystemTime`] is not available.
524 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
527 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
528 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
529 /// a preference. Note, however, that any privacy is lost if a public node id was used for
530 /// [`Offer::signing_pubkey`].
532 /// Errors if the request contains unknown required features.
534 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
536 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
537 pub fn respond_with_no_std(
538 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
539 created_at: core::time::Duration
540 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
541 if self.invoice_request_features().requires_unknown_bits() {
542 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
545 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
548 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
549 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
550 /// the same [`ExpandedKey`] as the one used to create the offer.
552 /// See [`InvoiceRequest::respond_with`] for further details.
554 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
556 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
557 #[cfg(feature = "std")]
558 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
559 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
560 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
561 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
562 let created_at = std::time::SystemTime::now()
563 .duration_since(std::time::SystemTime::UNIX_EPOCH)
564 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
566 self.verify_and_respond_using_derived_keys_no_std(
567 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
571 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
572 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
573 /// the same [`ExpandedKey`] as the one used to create the offer.
575 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
577 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
579 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
580 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
581 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
582 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
583 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
584 if self.invoice_request_features().requires_unknown_bits() {
585 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
588 let keys = match self.verify(expanded_key, secp_ctx) {
589 Err(()) => return Err(Bolt12SemanticError::InvalidMetadata),
590 Ok(None) => return Err(Bolt12SemanticError::InvalidMetadata),
591 Ok(Some(keys)) => keys,
594 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
597 /// Verifies that the request was for an offer created using the given key. Returns the derived
598 /// keys need to sign an [`Bolt12Invoice`] for the request if they could be extracted from the
601 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
602 pub fn verify<T: secp256k1::Signing>(
603 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
604 ) -> Result<Option<KeyPair>, ()> {
605 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
609 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
610 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
611 self.contents.as_tlv_stream();
612 let signature_tlv_stream = SignatureTlvStreamRef {
613 signature: Some(&self.signature),
615 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
619 impl InvoiceRequestContents {
620 pub(super) fn metadata(&self) -> &[u8] {
621 self.inner.metadata()
624 pub(super) fn derives_keys(&self) -> bool {
625 self.inner.payer.0.derives_keys()
628 pub(super) fn chain(&self) -> ChainHash {
632 fn amount_msats(&self) -> Option<u64> {
633 self.inner.amount_msats
636 fn features(&self) -> &InvoiceRequestFeatures {
640 fn quantity(&self) -> Option<u64> {
644 pub(super) fn payer_id(&self) -> PublicKey {
648 fn payer_note(&self) -> Option<PrintableString> {
649 self.inner.payer_note.as_ref()
650 .map(|payer_note| PrintableString(payer_note.as_str()))
653 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
654 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
655 invoice_request.payer_id = Some(&self.payer_id);
656 (payer, offer, invoice_request)
660 impl InvoiceRequestContentsWithoutPayerId {
661 pub(super) fn metadata(&self) -> &[u8] {
662 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
665 pub(super) fn chain(&self) -> ChainHash {
666 self.chain.unwrap_or_else(|| self.offer.implied_chain())
669 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
670 let payer = PayerTlvStreamRef {
671 metadata: self.payer.0.as_bytes(),
674 let offer = self.offer.as_tlv_stream();
677 if self.features == InvoiceRequestFeatures::empty() { None }
678 else { Some(&self.features) }
681 let invoice_request = InvoiceRequestTlvStreamRef {
682 chain: self.chain.as_ref(),
683 amount: self.amount_msats,
685 quantity: self.quantity,
687 payer_note: self.payer_note.as_ref(),
690 (payer, offer, invoice_request)
694 impl Writeable for UnsignedInvoiceRequest {
695 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
696 WithoutLength(&self.bytes).write(writer)
700 impl Writeable for InvoiceRequest {
701 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
702 WithoutLength(&self.bytes).write(writer)
706 impl Writeable for InvoiceRequestContents {
707 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
708 self.as_tlv_stream().write(writer)
712 /// Valid type range for invoice_request TLV records.
713 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
715 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
717 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
718 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
720 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
721 (80, chain: ChainHash),
722 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
723 (84, features: (InvoiceRequestFeatures, WithoutLength)),
724 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
725 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
726 (89, payer_note: (String, WithoutLength)),
729 type FullInvoiceRequestTlvStream =
730 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
733 type FullInvoiceRequestTlvStreamRef<'a> = (
734 PayerTlvStreamRef<'a>,
735 OfferTlvStreamRef<'a>,
736 InvoiceRequestTlvStreamRef<'a>,
737 SignatureTlvStreamRef<'a>,
740 impl SeekReadable for FullInvoiceRequestTlvStream {
741 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
742 let payer = SeekReadable::read(r)?;
743 let offer = SeekReadable::read(r)?;
744 let invoice_request = SeekReadable::read(r)?;
745 let signature = SeekReadable::read(r)?;
747 Ok((payer, offer, invoice_request, signature))
751 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
753 type PartialInvoiceRequestTlvStreamRef<'a> = (
754 PayerTlvStreamRef<'a>,
755 OfferTlvStreamRef<'a>,
756 InvoiceRequestTlvStreamRef<'a>,
759 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
760 type Error = Bolt12ParseError;
762 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
763 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
764 let ParsedMessage { bytes, tlv_stream } = invoice_request;
766 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
768 let contents = InvoiceRequestContents::try_from(
769 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
772 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
774 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
778 impl TryFrom<Vec<u8>> for InvoiceRequest {
779 type Error = Bolt12ParseError;
781 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
782 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
783 let ParsedMessage { bytes, tlv_stream } = invoice_request;
785 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
786 SignatureTlvStream { signature },
788 let contents = InvoiceRequestContents::try_from(
789 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
792 let signature = match signature {
793 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
794 Some(signature) => signature,
796 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
798 Ok(InvoiceRequest { bytes, contents, signature })
802 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
803 type Error = Bolt12SemanticError;
805 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
807 PayerTlvStream { metadata },
809 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
812 let payer = match metadata {
813 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
814 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
816 let offer = OfferContents::try_from(offer_tlv_stream)?;
818 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
819 return Err(Bolt12SemanticError::UnsupportedChain);
822 if offer.amount().is_none() && amount.is_none() {
823 return Err(Bolt12SemanticError::MissingAmount);
826 offer.check_quantity(quantity)?;
827 offer.check_amount_msats_for_quantity(amount, quantity)?;
829 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
831 let payer_id = match payer_id {
832 None => return Err(Bolt12SemanticError::MissingPayerId),
833 Some(payer_id) => payer_id,
836 Ok(InvoiceRequestContents {
837 inner: InvoiceRequestContentsWithoutPayerId {
838 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
847 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
849 use bitcoin::blockdata::constants::ChainHash;
850 use bitcoin::network::constants::Network;
851 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
852 use core::convert::{Infallible, TryFrom};
853 use core::num::NonZeroU64;
854 #[cfg(feature = "std")]
855 use core::time::Duration;
856 use crate::sign::KeyMaterial;
857 use crate::ln::features::InvoiceRequestFeatures;
858 use crate::ln::inbound_payment::ExpandedKey;
859 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
860 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
861 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
862 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
863 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
864 use crate::offers::payer::PayerTlvStreamRef;
865 use crate::offers::test_utils::*;
866 use crate::util::ser::{BigSize, Writeable};
867 use crate::util::string::PrintableString;
870 fn builds_invoice_request_with_defaults() {
871 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
874 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
877 let mut buffer = Vec::new();
878 unsigned_invoice_request.write(&mut buffer).unwrap();
880 match UnsignedInvoiceRequest::try_from(buffer) {
881 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
883 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
884 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
888 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
890 let mut buffer = Vec::new();
891 invoice_request.write(&mut buffer).unwrap();
893 assert_eq!(invoice_request.bytes, buffer.as_slice());
894 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
895 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
896 assert_eq!(invoice_request.amount_msats(), None);
897 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
898 assert_eq!(invoice_request.quantity(), None);
899 assert_eq!(invoice_request.payer_id(), payer_pubkey());
900 assert_eq!(invoice_request.payer_note(), None);
902 merkle::verify_signature(
903 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
908 invoice_request.as_tlv_stream(),
910 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
916 description: Some(&String::from("foo")),
918 absolute_expiry: None,
922 node_id: Some(&recipient_pubkey()),
924 InvoiceRequestTlvStreamRef {
929 payer_id: Some(&payer_pubkey()),
932 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
936 if let Err(e) = InvoiceRequest::try_from(buffer) {
937 panic!("error parsing invoice request: {:?}", e);
941 #[cfg(feature = "std")]
943 fn builds_invoice_request_from_offer_with_expiration() {
944 let future_expiry = Duration::from_secs(u64::max_value());
945 let past_expiry = Duration::from_secs(0);
947 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
949 .absolute_expiry(future_expiry)
951 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
954 panic!("error building invoice_request: {:?}", e);
957 match OfferBuilder::new("foo".into(), recipient_pubkey())
959 .absolute_expiry(past_expiry)
961 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
964 Ok(_) => panic!("expected error"),
965 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
970 fn builds_invoice_request_with_derived_metadata() {
971 let payer_id = payer_pubkey();
972 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
973 let entropy = FixedEntropy {};
974 let secp_ctx = Secp256k1::new();
976 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
979 let invoice_request = offer
980 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
983 .sign(payer_sign).unwrap();
984 assert_eq!(invoice_request.payer_id(), payer_pubkey());
986 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
989 .sign(recipient_sign).unwrap();
990 assert!(invoice.verify(&expanded_key, &secp_ctx));
992 // Fails verification with altered fields
994 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
995 mut invoice_tlv_stream, mut signature_tlv_stream
996 ) = invoice.as_tlv_stream();
997 invoice_request_tlv_stream.amount = Some(2000);
998 invoice_tlv_stream.amount = Some(2000);
1001 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1002 let mut bytes = Vec::new();
1003 tlv_stream.write(&mut bytes).unwrap();
1005 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1006 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1007 signature_tlv_stream.signature = Some(&signature);
1009 let mut encoded_invoice = bytes;
1010 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1012 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1013 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1015 // Fails verification with altered metadata
1017 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1018 mut signature_tlv_stream
1019 ) = invoice.as_tlv_stream();
1020 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1021 payer_tlv_stream.metadata = Some(&metadata);
1024 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1025 let mut bytes = Vec::new();
1026 tlv_stream.write(&mut bytes).unwrap();
1028 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1029 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1030 signature_tlv_stream.signature = Some(&signature);
1032 let mut encoded_invoice = bytes;
1033 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1035 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1036 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1040 fn builds_invoice_request_with_derived_payer_id() {
1041 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1042 let entropy = FixedEntropy {};
1043 let secp_ctx = Secp256k1::new();
1045 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1048 let invoice_request = offer
1049 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1054 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1057 .sign(recipient_sign).unwrap();
1058 assert!(invoice.verify(&expanded_key, &secp_ctx));
1060 // Fails verification with altered fields
1062 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1063 mut invoice_tlv_stream, mut signature_tlv_stream
1064 ) = invoice.as_tlv_stream();
1065 invoice_request_tlv_stream.amount = Some(2000);
1066 invoice_tlv_stream.amount = Some(2000);
1069 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1070 let mut bytes = Vec::new();
1071 tlv_stream.write(&mut bytes).unwrap();
1073 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1074 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1075 signature_tlv_stream.signature = Some(&signature);
1077 let mut encoded_invoice = bytes;
1078 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1080 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1081 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1083 // Fails verification with altered payer id
1085 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1086 mut signature_tlv_stream
1087 ) = invoice.as_tlv_stream();
1088 let payer_id = pubkey(1);
1089 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1092 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1093 let mut bytes = Vec::new();
1094 tlv_stream.write(&mut bytes).unwrap();
1096 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1097 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1098 signature_tlv_stream.signature = Some(&signature);
1100 let mut encoded_invoice = bytes;
1101 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1103 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1104 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1108 fn builds_invoice_request_with_chain() {
1109 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1110 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1112 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1115 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1116 .chain(Network::Bitcoin).unwrap()
1118 .sign(payer_sign).unwrap();
1119 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1120 assert_eq!(invoice_request.chain(), mainnet);
1121 assert_eq!(tlv_stream.chain, None);
1123 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1125 .chain(Network::Testnet)
1127 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1128 .chain(Network::Testnet).unwrap()
1130 .sign(payer_sign).unwrap();
1131 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1132 assert_eq!(invoice_request.chain(), testnet);
1133 assert_eq!(tlv_stream.chain, Some(&testnet));
1135 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1137 .chain(Network::Bitcoin)
1138 .chain(Network::Testnet)
1140 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1141 .chain(Network::Bitcoin).unwrap()
1143 .sign(payer_sign).unwrap();
1144 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1145 assert_eq!(invoice_request.chain(), mainnet);
1146 assert_eq!(tlv_stream.chain, None);
1148 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1150 .chain(Network::Bitcoin)
1151 .chain(Network::Testnet)
1153 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1154 .chain(Network::Bitcoin).unwrap()
1155 .chain(Network::Testnet).unwrap()
1157 .sign(payer_sign).unwrap();
1158 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1159 assert_eq!(invoice_request.chain(), testnet);
1160 assert_eq!(tlv_stream.chain, Some(&testnet));
1162 match OfferBuilder::new("foo".into(), recipient_pubkey())
1164 .chain(Network::Testnet)
1166 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1167 .chain(Network::Bitcoin)
1169 Ok(_) => panic!("expected error"),
1170 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1173 match OfferBuilder::new("foo".into(), recipient_pubkey())
1175 .chain(Network::Testnet)
1177 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1180 Ok(_) => panic!("expected error"),
1181 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1186 fn builds_invoice_request_with_amount() {
1187 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1190 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1191 .amount_msats(1000).unwrap()
1193 .sign(payer_sign).unwrap();
1194 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1195 assert_eq!(invoice_request.amount_msats(), Some(1000));
1196 assert_eq!(tlv_stream.amount, Some(1000));
1198 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1201 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1202 .amount_msats(1001).unwrap()
1203 .amount_msats(1000).unwrap()
1205 .sign(payer_sign).unwrap();
1206 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1207 assert_eq!(invoice_request.amount_msats(), Some(1000));
1208 assert_eq!(tlv_stream.amount, Some(1000));
1210 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1213 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1214 .amount_msats(1001).unwrap()
1216 .sign(payer_sign).unwrap();
1217 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1218 assert_eq!(invoice_request.amount_msats(), Some(1001));
1219 assert_eq!(tlv_stream.amount, Some(1001));
1221 match OfferBuilder::new("foo".into(), recipient_pubkey())
1224 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1227 Ok(_) => panic!("expected error"),
1228 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1231 match OfferBuilder::new("foo".into(), recipient_pubkey())
1233 .supported_quantity(Quantity::Unbounded)
1235 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236 .quantity(2).unwrap()
1239 Ok(_) => panic!("expected error"),
1240 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1243 match OfferBuilder::new("foo".into(), recipient_pubkey())
1246 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1247 .amount_msats(MAX_VALUE_MSAT + 1)
1249 Ok(_) => panic!("expected error"),
1250 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1253 match OfferBuilder::new("foo".into(), recipient_pubkey())
1255 .supported_quantity(Quantity::Unbounded)
1257 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258 .amount_msats(1000).unwrap()
1259 .quantity(2).unwrap()
1262 Ok(_) => panic!("expected error"),
1263 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1266 match OfferBuilder::new("foo".into(), recipient_pubkey())
1268 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271 Ok(_) => panic!("expected error"),
1272 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1275 match OfferBuilder::new("foo".into(), recipient_pubkey())
1277 .supported_quantity(Quantity::Unbounded)
1279 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1280 .quantity(u64::max_value()).unwrap()
1283 Ok(_) => panic!("expected error"),
1284 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1289 fn builds_invoice_request_with_features() {
1290 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1293 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1294 .features_unchecked(InvoiceRequestFeatures::unknown())
1296 .sign(payer_sign).unwrap();
1297 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1298 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1299 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1301 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1304 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1305 .features_unchecked(InvoiceRequestFeatures::unknown())
1306 .features_unchecked(InvoiceRequestFeatures::empty())
1308 .sign(payer_sign).unwrap();
1309 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1310 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1311 assert_eq!(tlv_stream.features, None);
1315 fn builds_invoice_request_with_quantity() {
1316 let one = NonZeroU64::new(1).unwrap();
1317 let ten = NonZeroU64::new(10).unwrap();
1319 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1321 .supported_quantity(Quantity::One)
1323 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1325 .sign(payer_sign).unwrap();
1326 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1327 assert_eq!(invoice_request.quantity(), None);
1328 assert_eq!(tlv_stream.quantity, None);
1330 match OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .supported_quantity(Quantity::One)
1334 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1335 .amount_msats(2_000).unwrap()
1338 Ok(_) => panic!("expected error"),
1339 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1342 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1344 .supported_quantity(Quantity::Bounded(ten))
1346 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .amount_msats(10_000).unwrap()
1348 .quantity(10).unwrap()
1350 .sign(payer_sign).unwrap();
1351 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1352 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1353 assert_eq!(tlv_stream.amount, Some(10_000));
1355 match OfferBuilder::new("foo".into(), recipient_pubkey())
1357 .supported_quantity(Quantity::Bounded(ten))
1359 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1360 .amount_msats(11_000).unwrap()
1363 Ok(_) => panic!("expected error"),
1364 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1367 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1369 .supported_quantity(Quantity::Unbounded)
1371 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1372 .amount_msats(2_000).unwrap()
1373 .quantity(2).unwrap()
1375 .sign(payer_sign).unwrap();
1376 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1377 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1378 assert_eq!(tlv_stream.amount, Some(2_000));
1380 match OfferBuilder::new("foo".into(), recipient_pubkey())
1382 .supported_quantity(Quantity::Unbounded)
1384 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1387 Ok(_) => panic!("expected error"),
1388 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1391 match OfferBuilder::new("foo".into(), recipient_pubkey())
1393 .supported_quantity(Quantity::Bounded(one))
1395 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1398 Ok(_) => panic!("expected error"),
1399 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1404 fn builds_invoice_request_with_payer_note() {
1405 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1408 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1409 .payer_note("bar".into())
1411 .sign(payer_sign).unwrap();
1412 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1413 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1414 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1416 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1419 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1420 .payer_note("bar".into())
1421 .payer_note("baz".into())
1423 .sign(payer_sign).unwrap();
1424 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1425 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1426 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1430 fn fails_signing_invoice_request() {
1431 match OfferBuilder::new("foo".into(), recipient_pubkey())
1434 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1438 Ok(_) => panic!("expected error"),
1439 Err(e) => assert_eq!(e, SignError::Signing(())),
1442 match OfferBuilder::new("foo".into(), recipient_pubkey())
1445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1447 .sign(recipient_sign)
1449 Ok(_) => panic!("expected error"),
1450 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1455 fn fails_responding_with_unknown_required_features() {
1456 match OfferBuilder::new("foo".into(), recipient_pubkey())
1459 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1460 .features_unchecked(InvoiceRequestFeatures::unknown())
1462 .sign(payer_sign).unwrap()
1463 .respond_with_no_std(payment_paths(), payment_hash(), now())
1465 Ok(_) => panic!("expected error"),
1466 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1471 fn parses_invoice_request_with_metadata() {
1472 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1475 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 .sign(payer_sign).unwrap();
1479 let mut buffer = Vec::new();
1480 invoice_request.write(&mut buffer).unwrap();
1482 if let Err(e) = InvoiceRequest::try_from(buffer) {
1483 panic!("error parsing invoice_request: {:?}", e);
1488 fn parses_invoice_request_with_chain() {
1489 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .chain(Network::Bitcoin).unwrap()
1495 .sign(payer_sign).unwrap();
1497 let mut buffer = Vec::new();
1498 invoice_request.write(&mut buffer).unwrap();
1500 if let Err(e) = InvoiceRequest::try_from(buffer) {
1501 panic!("error parsing invoice_request: {:?}", e);
1504 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1507 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1508 .chain_unchecked(Network::Testnet)
1510 .sign(payer_sign).unwrap();
1512 let mut buffer = Vec::new();
1513 invoice_request.write(&mut buffer).unwrap();
1515 match InvoiceRequest::try_from(buffer) {
1516 Ok(_) => panic!("expected error"),
1517 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1522 fn parses_invoice_request_with_amount() {
1523 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1526 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1528 .sign(payer_sign).unwrap();
1530 let mut buffer = Vec::new();
1531 invoice_request.write(&mut buffer).unwrap();
1533 if let Err(e) = InvoiceRequest::try_from(buffer) {
1534 panic!("error parsing invoice_request: {:?}", e);
1537 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1539 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1540 .amount_msats(1000).unwrap()
1542 .sign(payer_sign).unwrap();
1544 let mut buffer = Vec::new();
1545 invoice_request.write(&mut buffer).unwrap();
1547 if let Err(e) = InvoiceRequest::try_from(buffer) {
1548 panic!("error parsing invoice_request: {:?}", e);
1551 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1553 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555 .sign(payer_sign).unwrap();
1557 let mut buffer = Vec::new();
1558 invoice_request.write(&mut buffer).unwrap();
1560 match InvoiceRequest::try_from(buffer) {
1561 Ok(_) => panic!("expected error"),
1562 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1565 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1568 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1569 .amount_msats_unchecked(999)
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, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1581 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1582 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1584 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1586 .sign(payer_sign).unwrap();
1588 let mut buffer = Vec::new();
1589 invoice_request.write(&mut buffer).unwrap();
1591 match InvoiceRequest::try_from(buffer) {
1592 Ok(_) => panic!("expected error"),
1594 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1598 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1600 .supported_quantity(Quantity::Unbounded)
1602 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1603 .quantity(u64::max_value()).unwrap()
1605 .sign(payer_sign).unwrap();
1607 let mut buffer = Vec::new();
1608 invoice_request.write(&mut buffer).unwrap();
1610 match InvoiceRequest::try_from(buffer) {
1611 Ok(_) => panic!("expected error"),
1612 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1617 fn parses_invoice_request_with_quantity() {
1618 let one = NonZeroU64::new(1).unwrap();
1619 let ten = NonZeroU64::new(10).unwrap();
1621 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1623 .supported_quantity(Quantity::One)
1625 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1627 .sign(payer_sign).unwrap();
1629 let mut buffer = Vec::new();
1630 invoice_request.write(&mut buffer).unwrap();
1632 if let Err(e) = InvoiceRequest::try_from(buffer) {
1633 panic!("error parsing invoice_request: {:?}", e);
1636 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1638 .supported_quantity(Quantity::One)
1640 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1641 .amount_msats(2_000).unwrap()
1642 .quantity_unchecked(2)
1644 .sign(payer_sign).unwrap();
1646 let mut buffer = Vec::new();
1647 invoice_request.write(&mut buffer).unwrap();
1649 match InvoiceRequest::try_from(buffer) {
1650 Ok(_) => panic!("expected error"),
1652 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1656 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .supported_quantity(Quantity::Bounded(ten))
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 .amount_msats(10_000).unwrap()
1662 .quantity(10).unwrap()
1664 .sign(payer_sign).unwrap();
1666 let mut buffer = Vec::new();
1667 invoice_request.write(&mut buffer).unwrap();
1669 if let Err(e) = InvoiceRequest::try_from(buffer) {
1670 panic!("error parsing invoice_request: {:?}", e);
1673 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1675 .supported_quantity(Quantity::Bounded(ten))
1677 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1678 .amount_msats(11_000).unwrap()
1679 .quantity_unchecked(11)
1681 .sign(payer_sign).unwrap();
1683 let mut buffer = Vec::new();
1684 invoice_request.write(&mut buffer).unwrap();
1686 match InvoiceRequest::try_from(buffer) {
1687 Ok(_) => panic!("expected error"),
1688 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1691 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1693 .supported_quantity(Quantity::Unbounded)
1695 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1696 .amount_msats(2_000).unwrap()
1697 .quantity(2).unwrap()
1699 .sign(payer_sign).unwrap();
1701 let mut buffer = Vec::new();
1702 invoice_request.write(&mut buffer).unwrap();
1704 if let Err(e) = InvoiceRequest::try_from(buffer) {
1705 panic!("error parsing invoice_request: {:?}", e);
1708 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1710 .supported_quantity(Quantity::Unbounded)
1712 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1714 .sign(payer_sign).unwrap();
1716 let mut buffer = Vec::new();
1717 invoice_request.write(&mut buffer).unwrap();
1719 match InvoiceRequest::try_from(buffer) {
1720 Ok(_) => panic!("expected error"),
1721 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1724 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1726 .supported_quantity(Quantity::Bounded(one))
1728 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1730 .sign(payer_sign).unwrap();
1732 let mut buffer = Vec::new();
1733 invoice_request.write(&mut buffer).unwrap();
1735 match InvoiceRequest::try_from(buffer) {
1736 Ok(_) => panic!("expected error"),
1737 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1742 fn fails_parsing_invoice_request_without_metadata() {
1743 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1746 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1748 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1749 tlv_stream.0.metadata = None;
1751 let mut buffer = Vec::new();
1752 tlv_stream.write(&mut buffer).unwrap();
1754 match InvoiceRequest::try_from(buffer) {
1755 Ok(_) => panic!("expected error"),
1757 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1763 fn fails_parsing_invoice_request_without_payer_id() {
1764 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1767 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1769 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1770 tlv_stream.2.payer_id = None;
1772 let mut buffer = Vec::new();
1773 tlv_stream.write(&mut buffer).unwrap();
1775 match InvoiceRequest::try_from(buffer) {
1776 Ok(_) => panic!("expected error"),
1777 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1782 fn fails_parsing_invoice_request_without_node_id() {
1783 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1786 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1788 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1789 tlv_stream.1.node_id = None;
1791 let mut buffer = Vec::new();
1792 tlv_stream.write(&mut buffer).unwrap();
1794 match InvoiceRequest::try_from(buffer) {
1795 Ok(_) => panic!("expected error"),
1797 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1803 fn fails_parsing_invoice_request_without_signature() {
1804 let mut buffer = Vec::new();
1805 OfferBuilder::new("foo".into(), recipient_pubkey())
1808 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1811 .write(&mut buffer).unwrap();
1813 match InvoiceRequest::try_from(buffer) {
1814 Ok(_) => panic!("expected error"),
1815 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1820 fn fails_parsing_invoice_request_with_invalid_signature() {
1821 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1824 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1826 .sign(payer_sign).unwrap();
1827 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1828 *last_signature_byte = last_signature_byte.wrapping_add(1);
1830 let mut buffer = Vec::new();
1831 invoice_request.write(&mut buffer).unwrap();
1833 match InvoiceRequest::try_from(buffer) {
1834 Ok(_) => panic!("expected error"),
1836 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1842 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1843 let secp_ctx = Secp256k1::new();
1844 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1845 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1848 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1850 .sign::<_, Infallible>(
1851 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1855 let mut encoded_invoice_request = Vec::new();
1856 invoice_request.write(&mut encoded_invoice_request).unwrap();
1857 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1858 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1859 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1861 match InvoiceRequest::try_from(encoded_invoice_request) {
1862 Ok(_) => panic!("expected error"),
1863 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),