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 UnsignedInvoiceRequest {
489 offer_accessors!(self, self.contents.inner.offer);
490 invoice_request_accessors!(self, self.contents);
493 impl InvoiceRequest {
494 offer_accessors!(self, self.contents.inner.offer);
495 invoice_request_accessors!(self, self.contents);
497 /// Signature of the invoice request using [`payer_id`].
499 /// [`payer_id`]: Self::payer_id
500 pub fn signature(&self) -> Signature {
504 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
505 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
507 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
508 /// creation time is used for the `created_at` parameter.
510 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
512 /// [`Duration`]: core::time::Duration
513 #[cfg(feature = "std")]
515 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
516 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
517 let created_at = std::time::SystemTime::now()
518 .duration_since(std::time::SystemTime::UNIX_EPOCH)
519 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
521 self.respond_with_no_std(payment_paths, payment_hash, created_at)
524 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
526 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
527 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
528 /// where [`std::time::SystemTime`] is not available.
530 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
533 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
534 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
535 /// a preference. Note, however, that any privacy is lost if a public node id was used for
536 /// [`Offer::signing_pubkey`].
538 /// Errors if the request contains unknown required features.
540 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
542 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
543 pub fn respond_with_no_std(
544 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
545 created_at: core::time::Duration
546 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
547 if self.invoice_request_features().requires_unknown_bits() {
548 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
551 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
554 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
555 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
556 /// the same [`ExpandedKey`] as the one used to create the offer.
558 /// See [`InvoiceRequest::respond_with`] for further details.
560 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
562 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
563 #[cfg(feature = "std")]
564 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
565 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
566 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
567 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
568 let created_at = std::time::SystemTime::now()
569 .duration_since(std::time::SystemTime::UNIX_EPOCH)
570 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
572 self.verify_and_respond_using_derived_keys_no_std(
573 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
577 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
578 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
579 /// the same [`ExpandedKey`] as the one used to create the offer.
581 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
583 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
585 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
586 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
587 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
588 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
589 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
590 if self.invoice_request_features().requires_unknown_bits() {
591 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
594 let keys = match self.verify(expanded_key, secp_ctx) {
595 Err(()) => return Err(Bolt12SemanticError::InvalidMetadata),
596 Ok(None) => return Err(Bolt12SemanticError::InvalidMetadata),
597 Ok(Some(keys)) => keys,
600 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
603 /// Verifies that the request was for an offer created using the given key. Returns the derived
604 /// keys need to sign an [`Bolt12Invoice`] for the request if they could be extracted from the
607 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
608 pub fn verify<T: secp256k1::Signing>(
609 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
610 ) -> Result<Option<KeyPair>, ()> {
611 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
615 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
616 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
617 self.contents.as_tlv_stream();
618 let signature_tlv_stream = SignatureTlvStreamRef {
619 signature: Some(&self.signature),
621 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
625 impl InvoiceRequestContents {
626 pub(super) fn metadata(&self) -> &[u8] {
627 self.inner.metadata()
630 pub(super) fn derives_keys(&self) -> bool {
631 self.inner.payer.0.derives_keys()
634 pub(super) fn chain(&self) -> ChainHash {
638 pub(super) fn amount_msats(&self) -> Option<u64> {
639 self.inner.amount_msats
642 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
646 pub(super) fn quantity(&self) -> Option<u64> {
650 pub(super) fn payer_id(&self) -> PublicKey {
654 pub(super) fn payer_note(&self) -> Option<PrintableString> {
655 self.inner.payer_note.as_ref()
656 .map(|payer_note| PrintableString(payer_note.as_str()))
659 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
660 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
661 invoice_request.payer_id = Some(&self.payer_id);
662 (payer, offer, invoice_request)
666 impl InvoiceRequestContentsWithoutPayerId {
667 pub(super) fn metadata(&self) -> &[u8] {
668 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
671 pub(super) fn chain(&self) -> ChainHash {
672 self.chain.unwrap_or_else(|| self.offer.implied_chain())
675 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
676 let payer = PayerTlvStreamRef {
677 metadata: self.payer.0.as_bytes(),
680 let offer = self.offer.as_tlv_stream();
683 if self.features == InvoiceRequestFeatures::empty() { None }
684 else { Some(&self.features) }
687 let invoice_request = InvoiceRequestTlvStreamRef {
688 chain: self.chain.as_ref(),
689 amount: self.amount_msats,
691 quantity: self.quantity,
693 payer_note: self.payer_note.as_ref(),
696 (payer, offer, invoice_request)
700 impl Writeable for UnsignedInvoiceRequest {
701 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
702 WithoutLength(&self.bytes).write(writer)
706 impl Writeable for InvoiceRequest {
707 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
708 WithoutLength(&self.bytes).write(writer)
712 impl Writeable for InvoiceRequestContents {
713 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
714 self.as_tlv_stream().write(writer)
718 /// Valid type range for invoice_request TLV records.
719 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
721 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
723 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
724 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
726 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
727 (80, chain: ChainHash),
728 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
729 (84, features: (InvoiceRequestFeatures, WithoutLength)),
730 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
731 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
732 (89, payer_note: (String, WithoutLength)),
735 type FullInvoiceRequestTlvStream =
736 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
739 type FullInvoiceRequestTlvStreamRef<'a> = (
740 PayerTlvStreamRef<'a>,
741 OfferTlvStreamRef<'a>,
742 InvoiceRequestTlvStreamRef<'a>,
743 SignatureTlvStreamRef<'a>,
746 impl SeekReadable for FullInvoiceRequestTlvStream {
747 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
748 let payer = SeekReadable::read(r)?;
749 let offer = SeekReadable::read(r)?;
750 let invoice_request = SeekReadable::read(r)?;
751 let signature = SeekReadable::read(r)?;
753 Ok((payer, offer, invoice_request, signature))
757 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
759 type PartialInvoiceRequestTlvStreamRef<'a> = (
760 PayerTlvStreamRef<'a>,
761 OfferTlvStreamRef<'a>,
762 InvoiceRequestTlvStreamRef<'a>,
765 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
766 type Error = Bolt12ParseError;
768 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
769 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
770 let ParsedMessage { bytes, tlv_stream } = invoice_request;
772 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
774 let contents = InvoiceRequestContents::try_from(
775 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
778 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
780 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
784 impl TryFrom<Vec<u8>> for InvoiceRequest {
785 type Error = Bolt12ParseError;
787 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
788 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
789 let ParsedMessage { bytes, tlv_stream } = invoice_request;
791 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
792 SignatureTlvStream { signature },
794 let contents = InvoiceRequestContents::try_from(
795 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
798 let signature = match signature {
799 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
800 Some(signature) => signature,
802 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
804 Ok(InvoiceRequest { bytes, contents, signature })
808 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
809 type Error = Bolt12SemanticError;
811 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
813 PayerTlvStream { metadata },
815 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
818 let payer = match metadata {
819 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
820 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
822 let offer = OfferContents::try_from(offer_tlv_stream)?;
824 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
825 return Err(Bolt12SemanticError::UnsupportedChain);
828 if offer.amount().is_none() && amount.is_none() {
829 return Err(Bolt12SemanticError::MissingAmount);
832 offer.check_quantity(quantity)?;
833 offer.check_amount_msats_for_quantity(amount, quantity)?;
835 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
837 let payer_id = match payer_id {
838 None => return Err(Bolt12SemanticError::MissingPayerId),
839 Some(payer_id) => payer_id,
842 Ok(InvoiceRequestContents {
843 inner: InvoiceRequestContentsWithoutPayerId {
844 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
853 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
855 use bitcoin::blockdata::constants::ChainHash;
856 use bitcoin::network::constants::Network;
857 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
858 use core::convert::{Infallible, TryFrom};
859 use core::num::NonZeroU64;
860 #[cfg(feature = "std")]
861 use core::time::Duration;
862 use crate::sign::KeyMaterial;
863 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
864 use crate::ln::inbound_payment::ExpandedKey;
865 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
866 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
867 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
868 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
869 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
870 use crate::offers::payer::PayerTlvStreamRef;
871 use crate::offers::test_utils::*;
872 use crate::util::ser::{BigSize, Writeable};
873 use crate::util::string::PrintableString;
876 fn builds_invoice_request_with_defaults() {
877 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
880 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
883 let mut buffer = Vec::new();
884 unsigned_invoice_request.write(&mut buffer).unwrap();
886 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
887 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
888 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
889 assert_eq!(unsigned_invoice_request.metadata(), None);
890 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
891 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
892 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
893 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
894 assert_eq!(unsigned_invoice_request.paths(), &[]);
895 assert_eq!(unsigned_invoice_request.issuer(), None);
896 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
897 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
898 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
899 assert_eq!(unsigned_invoice_request.amount_msats(), None);
900 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
901 assert_eq!(unsigned_invoice_request.quantity(), None);
902 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
903 assert_eq!(unsigned_invoice_request.payer_note(), None);
905 match UnsignedInvoiceRequest::try_from(buffer) {
906 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
908 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
909 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
913 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
915 let mut buffer = Vec::new();
916 invoice_request.write(&mut buffer).unwrap();
918 assert_eq!(invoice_request.bytes, buffer.as_slice());
919 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
920 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
921 assert_eq!(invoice_request.metadata(), None);
922 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
923 assert_eq!(invoice_request.description(), PrintableString("foo"));
924 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
925 assert_eq!(invoice_request.absolute_expiry(), None);
926 assert_eq!(invoice_request.paths(), &[]);
927 assert_eq!(invoice_request.issuer(), None);
928 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
929 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
930 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
931 assert_eq!(invoice_request.amount_msats(), None);
932 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
933 assert_eq!(invoice_request.quantity(), None);
934 assert_eq!(invoice_request.payer_id(), payer_pubkey());
935 assert_eq!(invoice_request.payer_note(), None);
937 merkle::verify_signature(
938 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
943 invoice_request.as_tlv_stream(),
945 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
951 description: Some(&String::from("foo")),
953 absolute_expiry: None,
957 node_id: Some(&recipient_pubkey()),
959 InvoiceRequestTlvStreamRef {
964 payer_id: Some(&payer_pubkey()),
967 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
971 if let Err(e) = InvoiceRequest::try_from(buffer) {
972 panic!("error parsing invoice request: {:?}", e);
976 #[cfg(feature = "std")]
978 fn builds_invoice_request_from_offer_with_expiration() {
979 let future_expiry = Duration::from_secs(u64::max_value());
980 let past_expiry = Duration::from_secs(0);
982 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
984 .absolute_expiry(future_expiry)
986 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
989 panic!("error building invoice_request: {:?}", e);
992 match OfferBuilder::new("foo".into(), recipient_pubkey())
994 .absolute_expiry(past_expiry)
996 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
999 Ok(_) => panic!("expected error"),
1000 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1005 fn builds_invoice_request_with_derived_metadata() {
1006 let payer_id = payer_pubkey();
1007 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1008 let entropy = FixedEntropy {};
1009 let secp_ctx = Secp256k1::new();
1011 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1014 let invoice_request = offer
1015 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
1018 .sign(payer_sign).unwrap();
1019 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1021 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1024 .sign(recipient_sign).unwrap();
1025 assert!(invoice.verify(&expanded_key, &secp_ctx));
1027 // Fails verification with altered fields
1029 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1030 mut invoice_tlv_stream, mut signature_tlv_stream
1031 ) = invoice.as_tlv_stream();
1032 invoice_request_tlv_stream.amount = Some(2000);
1033 invoice_tlv_stream.amount = Some(2000);
1036 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1037 let mut bytes = Vec::new();
1038 tlv_stream.write(&mut bytes).unwrap();
1040 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1041 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1042 signature_tlv_stream.signature = Some(&signature);
1044 let mut encoded_invoice = bytes;
1045 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1047 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1048 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1050 // Fails verification with altered metadata
1052 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1053 mut signature_tlv_stream
1054 ) = invoice.as_tlv_stream();
1055 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1056 payer_tlv_stream.metadata = Some(&metadata);
1059 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1060 let mut bytes = Vec::new();
1061 tlv_stream.write(&mut bytes).unwrap();
1063 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1064 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1065 signature_tlv_stream.signature = Some(&signature);
1067 let mut encoded_invoice = bytes;
1068 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1070 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1071 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1075 fn builds_invoice_request_with_derived_payer_id() {
1076 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1077 let entropy = FixedEntropy {};
1078 let secp_ctx = Secp256k1::new();
1080 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1083 let invoice_request = offer
1084 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1089 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1092 .sign(recipient_sign).unwrap();
1093 assert!(invoice.verify(&expanded_key, &secp_ctx));
1095 // Fails verification with altered fields
1097 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1098 mut invoice_tlv_stream, mut signature_tlv_stream
1099 ) = invoice.as_tlv_stream();
1100 invoice_request_tlv_stream.amount = Some(2000);
1101 invoice_tlv_stream.amount = Some(2000);
1104 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1105 let mut bytes = Vec::new();
1106 tlv_stream.write(&mut bytes).unwrap();
1108 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1109 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1110 signature_tlv_stream.signature = Some(&signature);
1112 let mut encoded_invoice = bytes;
1113 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1115 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1116 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1118 // Fails verification with altered payer id
1120 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1121 mut signature_tlv_stream
1122 ) = invoice.as_tlv_stream();
1123 let payer_id = pubkey(1);
1124 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1127 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1128 let mut bytes = Vec::new();
1129 tlv_stream.write(&mut bytes).unwrap();
1131 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1132 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1133 signature_tlv_stream.signature = Some(&signature);
1135 let mut encoded_invoice = bytes;
1136 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1138 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1139 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1143 fn builds_invoice_request_with_chain() {
1144 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1145 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1147 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1150 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151 .chain(Network::Bitcoin).unwrap()
1153 .sign(payer_sign).unwrap();
1154 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1155 assert_eq!(invoice_request.chain(), mainnet);
1156 assert_eq!(tlv_stream.chain, None);
1158 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1160 .chain(Network::Testnet)
1162 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1163 .chain(Network::Testnet).unwrap()
1165 .sign(payer_sign).unwrap();
1166 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1167 assert_eq!(invoice_request.chain(), testnet);
1168 assert_eq!(tlv_stream.chain, Some(&testnet));
1170 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1172 .chain(Network::Bitcoin)
1173 .chain(Network::Testnet)
1175 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1176 .chain(Network::Bitcoin).unwrap()
1178 .sign(payer_sign).unwrap();
1179 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1180 assert_eq!(invoice_request.chain(), mainnet);
1181 assert_eq!(tlv_stream.chain, None);
1183 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1185 .chain(Network::Bitcoin)
1186 .chain(Network::Testnet)
1188 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1189 .chain(Network::Bitcoin).unwrap()
1190 .chain(Network::Testnet).unwrap()
1192 .sign(payer_sign).unwrap();
1193 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1194 assert_eq!(invoice_request.chain(), testnet);
1195 assert_eq!(tlv_stream.chain, Some(&testnet));
1197 match OfferBuilder::new("foo".into(), recipient_pubkey())
1199 .chain(Network::Testnet)
1201 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1202 .chain(Network::Bitcoin)
1204 Ok(_) => panic!("expected error"),
1205 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1208 match OfferBuilder::new("foo".into(), recipient_pubkey())
1210 .chain(Network::Testnet)
1212 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1215 Ok(_) => panic!("expected error"),
1216 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1221 fn builds_invoice_request_with_amount() {
1222 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1225 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1226 .amount_msats(1000).unwrap()
1228 .sign(payer_sign).unwrap();
1229 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1230 assert_eq!(invoice_request.amount_msats(), Some(1000));
1231 assert_eq!(tlv_stream.amount, Some(1000));
1233 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1237 .amount_msats(1001).unwrap()
1238 .amount_msats(1000).unwrap()
1240 .sign(payer_sign).unwrap();
1241 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1242 assert_eq!(invoice_request.amount_msats(), Some(1000));
1243 assert_eq!(tlv_stream.amount, Some(1000));
1245 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1248 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 .amount_msats(1001).unwrap()
1251 .sign(payer_sign).unwrap();
1252 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1253 assert_eq!(invoice_request.amount_msats(), Some(1001));
1254 assert_eq!(tlv_stream.amount, Some(1001));
1256 match OfferBuilder::new("foo".into(), recipient_pubkey())
1259 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1262 Ok(_) => panic!("expected error"),
1263 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1266 match OfferBuilder::new("foo".into(), recipient_pubkey())
1268 .supported_quantity(Quantity::Unbounded)
1270 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271 .quantity(2).unwrap()
1274 Ok(_) => panic!("expected error"),
1275 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1278 match OfferBuilder::new("foo".into(), recipient_pubkey())
1281 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1282 .amount_msats(MAX_VALUE_MSAT + 1)
1284 Ok(_) => panic!("expected error"),
1285 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1288 match OfferBuilder::new("foo".into(), recipient_pubkey())
1290 .supported_quantity(Quantity::Unbounded)
1292 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1293 .amount_msats(1000).unwrap()
1294 .quantity(2).unwrap()
1297 Ok(_) => panic!("expected error"),
1298 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1301 match OfferBuilder::new("foo".into(), recipient_pubkey())
1303 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1306 Ok(_) => panic!("expected error"),
1307 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1310 match OfferBuilder::new("foo".into(), recipient_pubkey())
1312 .supported_quantity(Quantity::Unbounded)
1314 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 .quantity(u64::max_value()).unwrap()
1318 Ok(_) => panic!("expected error"),
1319 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1324 fn builds_invoice_request_with_features() {
1325 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1328 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1329 .features_unchecked(InvoiceRequestFeatures::unknown())
1331 .sign(payer_sign).unwrap();
1332 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1333 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1334 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1336 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1339 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1340 .features_unchecked(InvoiceRequestFeatures::unknown())
1341 .features_unchecked(InvoiceRequestFeatures::empty())
1343 .sign(payer_sign).unwrap();
1344 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1345 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1346 assert_eq!(tlv_stream.features, None);
1350 fn builds_invoice_request_with_quantity() {
1351 let one = NonZeroU64::new(1).unwrap();
1352 let ten = NonZeroU64::new(10).unwrap();
1354 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1356 .supported_quantity(Quantity::One)
1358 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1360 .sign(payer_sign).unwrap();
1361 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1362 assert_eq!(invoice_request.quantity(), None);
1363 assert_eq!(tlv_stream.quantity, None);
1365 match OfferBuilder::new("foo".into(), recipient_pubkey())
1367 .supported_quantity(Quantity::One)
1369 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1370 .amount_msats(2_000).unwrap()
1373 Ok(_) => panic!("expected error"),
1374 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1377 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1379 .supported_quantity(Quantity::Bounded(ten))
1381 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1382 .amount_msats(10_000).unwrap()
1383 .quantity(10).unwrap()
1385 .sign(payer_sign).unwrap();
1386 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1387 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1388 assert_eq!(tlv_stream.amount, Some(10_000));
1390 match OfferBuilder::new("foo".into(), recipient_pubkey())
1392 .supported_quantity(Quantity::Bounded(ten))
1394 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1395 .amount_msats(11_000).unwrap()
1398 Ok(_) => panic!("expected error"),
1399 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1402 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1404 .supported_quantity(Quantity::Unbounded)
1406 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1407 .amount_msats(2_000).unwrap()
1408 .quantity(2).unwrap()
1410 .sign(payer_sign).unwrap();
1411 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1412 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1413 assert_eq!(tlv_stream.amount, Some(2_000));
1415 match OfferBuilder::new("foo".into(), recipient_pubkey())
1417 .supported_quantity(Quantity::Unbounded)
1419 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1422 Ok(_) => panic!("expected error"),
1423 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1426 match OfferBuilder::new("foo".into(), recipient_pubkey())
1428 .supported_quantity(Quantity::Bounded(one))
1430 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1433 Ok(_) => panic!("expected error"),
1434 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1439 fn builds_invoice_request_with_payer_note() {
1440 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1443 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1444 .payer_note("bar".into())
1446 .sign(payer_sign).unwrap();
1447 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1448 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1449 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1451 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1454 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1455 .payer_note("bar".into())
1456 .payer_note("baz".into())
1458 .sign(payer_sign).unwrap();
1459 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1460 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1461 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1465 fn fails_signing_invoice_request() {
1466 match OfferBuilder::new("foo".into(), recipient_pubkey())
1469 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1473 Ok(_) => panic!("expected error"),
1474 Err(e) => assert_eq!(e, SignError::Signing(())),
1477 match OfferBuilder::new("foo".into(), recipient_pubkey())
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1482 .sign(recipient_sign)
1484 Ok(_) => panic!("expected error"),
1485 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1490 fn fails_responding_with_unknown_required_features() {
1491 match OfferBuilder::new("foo".into(), recipient_pubkey())
1494 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1495 .features_unchecked(InvoiceRequestFeatures::unknown())
1497 .sign(payer_sign).unwrap()
1498 .respond_with_no_std(payment_paths(), payment_hash(), now())
1500 Ok(_) => panic!("expected error"),
1501 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1506 fn parses_invoice_request_with_metadata() {
1507 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1510 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1512 .sign(payer_sign).unwrap();
1514 let mut buffer = Vec::new();
1515 invoice_request.write(&mut buffer).unwrap();
1517 if let Err(e) = InvoiceRequest::try_from(buffer) {
1518 panic!("error parsing invoice_request: {:?}", e);
1523 fn parses_invoice_request_with_chain() {
1524 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1527 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1528 .chain(Network::Bitcoin).unwrap()
1530 .sign(payer_sign).unwrap();
1532 let mut buffer = Vec::new();
1533 invoice_request.write(&mut buffer).unwrap();
1535 if let Err(e) = InvoiceRequest::try_from(buffer) {
1536 panic!("error parsing invoice_request: {:?}", e);
1539 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1542 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1543 .chain_unchecked(Network::Testnet)
1545 .sign(payer_sign).unwrap();
1547 let mut buffer = Vec::new();
1548 invoice_request.write(&mut buffer).unwrap();
1550 match InvoiceRequest::try_from(buffer) {
1551 Ok(_) => panic!("expected error"),
1552 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1557 fn parses_invoice_request_with_amount() {
1558 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1561 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1563 .sign(payer_sign).unwrap();
1565 let mut buffer = Vec::new();
1566 invoice_request.write(&mut buffer).unwrap();
1568 if let Err(e) = InvoiceRequest::try_from(buffer) {
1569 panic!("error parsing invoice_request: {:?}", e);
1572 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1574 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1575 .amount_msats(1000).unwrap()
1577 .sign(payer_sign).unwrap();
1579 let mut buffer = Vec::new();
1580 invoice_request.write(&mut buffer).unwrap();
1582 if let Err(e) = InvoiceRequest::try_from(buffer) {
1583 panic!("error parsing invoice_request: {:?}", e);
1586 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1588 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1590 .sign(payer_sign).unwrap();
1592 let mut buffer = Vec::new();
1593 invoice_request.write(&mut buffer).unwrap();
1595 match InvoiceRequest::try_from(buffer) {
1596 Ok(_) => panic!("expected error"),
1597 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1600 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1603 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1604 .amount_msats_unchecked(999)
1606 .sign(payer_sign).unwrap();
1608 let mut buffer = Vec::new();
1609 invoice_request.write(&mut buffer).unwrap();
1611 match InvoiceRequest::try_from(buffer) {
1612 Ok(_) => panic!("expected error"),
1613 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1616 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1617 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1619 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1621 .sign(payer_sign).unwrap();
1623 let mut buffer = Vec::new();
1624 invoice_request.write(&mut buffer).unwrap();
1626 match InvoiceRequest::try_from(buffer) {
1627 Ok(_) => panic!("expected error"),
1629 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1633 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1635 .supported_quantity(Quantity::Unbounded)
1637 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1638 .quantity(u64::max_value()).unwrap()
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"),
1647 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1652 fn parses_invoice_request_with_quantity() {
1653 let one = NonZeroU64::new(1).unwrap();
1654 let ten = NonZeroU64::new(10).unwrap();
1656 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .supported_quantity(Quantity::One)
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1662 .sign(payer_sign).unwrap();
1664 let mut buffer = Vec::new();
1665 invoice_request.write(&mut buffer).unwrap();
1667 if let Err(e) = InvoiceRequest::try_from(buffer) {
1668 panic!("error parsing invoice_request: {:?}", e);
1671 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1673 .supported_quantity(Quantity::One)
1675 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1676 .amount_msats(2_000).unwrap()
1677 .quantity_unchecked(2)
1679 .sign(payer_sign).unwrap();
1681 let mut buffer = Vec::new();
1682 invoice_request.write(&mut buffer).unwrap();
1684 match InvoiceRequest::try_from(buffer) {
1685 Ok(_) => panic!("expected error"),
1687 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1691 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1693 .supported_quantity(Quantity::Bounded(ten))
1695 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1696 .amount_msats(10_000).unwrap()
1697 .quantity(10).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::Bounded(ten))
1712 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1713 .amount_msats(11_000).unwrap()
1714 .quantity_unchecked(11)
1716 .sign(payer_sign).unwrap();
1718 let mut buffer = Vec::new();
1719 invoice_request.write(&mut buffer).unwrap();
1721 match InvoiceRequest::try_from(buffer) {
1722 Ok(_) => panic!("expected error"),
1723 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1726 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1728 .supported_quantity(Quantity::Unbounded)
1730 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1731 .amount_msats(2_000).unwrap()
1732 .quantity(2).unwrap()
1734 .sign(payer_sign).unwrap();
1736 let mut buffer = Vec::new();
1737 invoice_request.write(&mut buffer).unwrap();
1739 if let Err(e) = InvoiceRequest::try_from(buffer) {
1740 panic!("error parsing invoice_request: {:?}", e);
1743 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1745 .supported_quantity(Quantity::Unbounded)
1747 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1749 .sign(payer_sign).unwrap();
1751 let mut buffer = Vec::new();
1752 invoice_request.write(&mut buffer).unwrap();
1754 match InvoiceRequest::try_from(buffer) {
1755 Ok(_) => panic!("expected error"),
1756 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1759 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1761 .supported_quantity(Quantity::Bounded(one))
1763 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1765 .sign(payer_sign).unwrap();
1767 let mut buffer = Vec::new();
1768 invoice_request.write(&mut buffer).unwrap();
1770 match InvoiceRequest::try_from(buffer) {
1771 Ok(_) => panic!("expected error"),
1772 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1777 fn fails_parsing_invoice_request_without_metadata() {
1778 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1781 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1783 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1784 tlv_stream.0.metadata = None;
1786 let mut buffer = Vec::new();
1787 tlv_stream.write(&mut buffer).unwrap();
1789 match InvoiceRequest::try_from(buffer) {
1790 Ok(_) => panic!("expected error"),
1792 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1798 fn fails_parsing_invoice_request_without_payer_id() {
1799 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1802 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1804 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1805 tlv_stream.2.payer_id = None;
1807 let mut buffer = Vec::new();
1808 tlv_stream.write(&mut buffer).unwrap();
1810 match InvoiceRequest::try_from(buffer) {
1811 Ok(_) => panic!("expected error"),
1812 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1817 fn fails_parsing_invoice_request_without_node_id() {
1818 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1821 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1823 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1824 tlv_stream.1.node_id = None;
1826 let mut buffer = Vec::new();
1827 tlv_stream.write(&mut buffer).unwrap();
1829 match InvoiceRequest::try_from(buffer) {
1830 Ok(_) => panic!("expected error"),
1832 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1838 fn fails_parsing_invoice_request_without_signature() {
1839 let mut buffer = Vec::new();
1840 OfferBuilder::new("foo".into(), recipient_pubkey())
1843 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1846 .write(&mut buffer).unwrap();
1848 match InvoiceRequest::try_from(buffer) {
1849 Ok(_) => panic!("expected error"),
1850 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1855 fn fails_parsing_invoice_request_with_invalid_signature() {
1856 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1859 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1861 .sign(payer_sign).unwrap();
1862 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1863 *last_signature_byte = last_signature_byte.wrapping_add(1);
1865 let mut buffer = Vec::new();
1866 invoice_request.write(&mut buffer).unwrap();
1868 match InvoiceRequest::try_from(buffer) {
1869 Ok(_) => panic!("expected error"),
1871 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1877 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1878 let secp_ctx = Secp256k1::new();
1879 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1880 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1883 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1885 .sign::<_, Infallible>(
1886 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1890 let mut encoded_invoice_request = Vec::new();
1891 invoice_request.write(&mut encoded_invoice_request).unwrap();
1892 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1893 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1894 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1896 match InvoiceRequest::try_from(encoded_invoice_request) {
1897 Ok(_) => panic!("expected error"),
1898 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),