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 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
803 merkle::verify_signature(&signature, message, contents.payer_id)?;
805 Ok(InvoiceRequest { bytes, contents, signature })
809 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
810 type Error = Bolt12SemanticError;
812 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
814 PayerTlvStream { metadata },
816 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
819 let payer = match metadata {
820 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
821 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
823 let offer = OfferContents::try_from(offer_tlv_stream)?;
825 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
826 return Err(Bolt12SemanticError::UnsupportedChain);
829 if offer.amount().is_none() && amount.is_none() {
830 return Err(Bolt12SemanticError::MissingAmount);
833 offer.check_quantity(quantity)?;
834 offer.check_amount_msats_for_quantity(amount, quantity)?;
836 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
838 let payer_id = match payer_id {
839 None => return Err(Bolt12SemanticError::MissingPayerId),
840 Some(payer_id) => payer_id,
843 Ok(InvoiceRequestContents {
844 inner: InvoiceRequestContentsWithoutPayerId {
845 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
854 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
856 use bitcoin::blockdata::constants::ChainHash;
857 use bitcoin::network::constants::Network;
858 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
859 use core::convert::{Infallible, TryFrom};
860 use core::num::NonZeroU64;
861 #[cfg(feature = "std")]
862 use core::time::Duration;
863 use crate::sign::KeyMaterial;
864 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
865 use crate::ln::inbound_payment::ExpandedKey;
866 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
867 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
868 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
869 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
870 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
871 use crate::offers::payer::PayerTlvStreamRef;
872 use crate::offers::test_utils::*;
873 use crate::util::ser::{BigSize, Writeable};
874 use crate::util::string::PrintableString;
877 fn builds_invoice_request_with_defaults() {
878 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
881 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
884 let mut buffer = Vec::new();
885 unsigned_invoice_request.write(&mut buffer).unwrap();
887 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
888 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
889 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
890 assert_eq!(unsigned_invoice_request.metadata(), None);
891 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
892 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
893 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
894 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
895 assert_eq!(unsigned_invoice_request.paths(), &[]);
896 assert_eq!(unsigned_invoice_request.issuer(), None);
897 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
898 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
899 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
900 assert_eq!(unsigned_invoice_request.amount_msats(), None);
901 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
902 assert_eq!(unsigned_invoice_request.quantity(), None);
903 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
904 assert_eq!(unsigned_invoice_request.payer_note(), None);
906 match UnsignedInvoiceRequest::try_from(buffer) {
907 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
909 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
910 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
914 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
916 let mut buffer = Vec::new();
917 invoice_request.write(&mut buffer).unwrap();
919 assert_eq!(invoice_request.bytes, buffer.as_slice());
920 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
921 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
922 assert_eq!(invoice_request.metadata(), None);
923 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
924 assert_eq!(invoice_request.description(), PrintableString("foo"));
925 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
926 assert_eq!(invoice_request.absolute_expiry(), None);
927 assert_eq!(invoice_request.paths(), &[]);
928 assert_eq!(invoice_request.issuer(), None);
929 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
930 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
931 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
932 assert_eq!(invoice_request.amount_msats(), None);
933 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
934 assert_eq!(invoice_request.quantity(), None);
935 assert_eq!(invoice_request.payer_id(), payer_pubkey());
936 assert_eq!(invoice_request.payer_note(), None);
938 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
939 assert!(merkle::verify_signature(&invoice_request.signature, message, payer_pubkey()).is_ok());
942 invoice_request.as_tlv_stream(),
944 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
950 description: Some(&String::from("foo")),
952 absolute_expiry: None,
956 node_id: Some(&recipient_pubkey()),
958 InvoiceRequestTlvStreamRef {
963 payer_id: Some(&payer_pubkey()),
966 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
970 if let Err(e) = InvoiceRequest::try_from(buffer) {
971 panic!("error parsing invoice request: {:?}", e);
975 #[cfg(feature = "std")]
977 fn builds_invoice_request_from_offer_with_expiration() {
978 let future_expiry = Duration::from_secs(u64::max_value());
979 let past_expiry = Duration::from_secs(0);
981 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
983 .absolute_expiry(future_expiry)
985 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
988 panic!("error building invoice_request: {:?}", e);
991 match OfferBuilder::new("foo".into(), recipient_pubkey())
993 .absolute_expiry(past_expiry)
995 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
998 Ok(_) => panic!("expected error"),
999 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1004 fn builds_invoice_request_with_derived_metadata() {
1005 let payer_id = payer_pubkey();
1006 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1007 let entropy = FixedEntropy {};
1008 let secp_ctx = Secp256k1::new();
1010 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1013 let invoice_request = offer
1014 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
1017 .sign(payer_sign).unwrap();
1018 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1020 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1023 .sign(recipient_sign).unwrap();
1024 assert!(invoice.verify(&expanded_key, &secp_ctx));
1026 // Fails verification with altered fields
1028 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1029 mut invoice_tlv_stream, mut signature_tlv_stream
1030 ) = invoice.as_tlv_stream();
1031 invoice_request_tlv_stream.amount = Some(2000);
1032 invoice_tlv_stream.amount = Some(2000);
1035 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1036 let mut bytes = Vec::new();
1037 tlv_stream.write(&mut bytes).unwrap();
1039 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1040 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1041 signature_tlv_stream.signature = Some(&signature);
1043 let mut encoded_invoice = bytes;
1044 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1046 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1047 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1049 // Fails verification with altered metadata
1051 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1052 mut signature_tlv_stream
1053 ) = invoice.as_tlv_stream();
1054 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1055 payer_tlv_stream.metadata = Some(&metadata);
1058 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1059 let mut bytes = Vec::new();
1060 tlv_stream.write(&mut bytes).unwrap();
1062 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1063 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1064 signature_tlv_stream.signature = Some(&signature);
1066 let mut encoded_invoice = bytes;
1067 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1069 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1070 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1074 fn builds_invoice_request_with_derived_payer_id() {
1075 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1076 let entropy = FixedEntropy {};
1077 let secp_ctx = Secp256k1::new();
1079 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1082 let invoice_request = offer
1083 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1088 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1091 .sign(recipient_sign).unwrap();
1092 assert!(invoice.verify(&expanded_key, &secp_ctx));
1094 // Fails verification with altered fields
1096 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1097 mut invoice_tlv_stream, mut signature_tlv_stream
1098 ) = invoice.as_tlv_stream();
1099 invoice_request_tlv_stream.amount = Some(2000);
1100 invoice_tlv_stream.amount = Some(2000);
1103 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1104 let mut bytes = Vec::new();
1105 tlv_stream.write(&mut bytes).unwrap();
1107 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1108 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1109 signature_tlv_stream.signature = Some(&signature);
1111 let mut encoded_invoice = bytes;
1112 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1114 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1115 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1117 // Fails verification with altered payer id
1119 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1120 mut signature_tlv_stream
1121 ) = invoice.as_tlv_stream();
1122 let payer_id = pubkey(1);
1123 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1126 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1127 let mut bytes = Vec::new();
1128 tlv_stream.write(&mut bytes).unwrap();
1130 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1131 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1132 signature_tlv_stream.signature = Some(&signature);
1134 let mut encoded_invoice = bytes;
1135 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1137 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1138 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1142 fn builds_invoice_request_with_chain() {
1143 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1144 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1146 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1149 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1150 .chain(Network::Bitcoin).unwrap()
1152 .sign(payer_sign).unwrap();
1153 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1154 assert_eq!(invoice_request.chain(), mainnet);
1155 assert_eq!(tlv_stream.chain, None);
1157 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1159 .chain(Network::Testnet)
1161 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1162 .chain(Network::Testnet).unwrap()
1164 .sign(payer_sign).unwrap();
1165 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1166 assert_eq!(invoice_request.chain(), testnet);
1167 assert_eq!(tlv_stream.chain, Some(&testnet));
1169 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1171 .chain(Network::Bitcoin)
1172 .chain(Network::Testnet)
1174 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1175 .chain(Network::Bitcoin).unwrap()
1177 .sign(payer_sign).unwrap();
1178 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1179 assert_eq!(invoice_request.chain(), mainnet);
1180 assert_eq!(tlv_stream.chain, None);
1182 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1184 .chain(Network::Bitcoin)
1185 .chain(Network::Testnet)
1187 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1188 .chain(Network::Bitcoin).unwrap()
1189 .chain(Network::Testnet).unwrap()
1191 .sign(payer_sign).unwrap();
1192 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1193 assert_eq!(invoice_request.chain(), testnet);
1194 assert_eq!(tlv_stream.chain, Some(&testnet));
1196 match OfferBuilder::new("foo".into(), recipient_pubkey())
1198 .chain(Network::Testnet)
1200 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1201 .chain(Network::Bitcoin)
1203 Ok(_) => panic!("expected error"),
1204 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1207 match OfferBuilder::new("foo".into(), recipient_pubkey())
1209 .chain(Network::Testnet)
1211 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1214 Ok(_) => panic!("expected error"),
1215 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1220 fn builds_invoice_request_with_amount() {
1221 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1224 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225 .amount_msats(1000).unwrap()
1227 .sign(payer_sign).unwrap();
1228 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1229 assert_eq!(invoice_request.amount_msats(), Some(1000));
1230 assert_eq!(tlv_stream.amount, Some(1000));
1232 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1235 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236 .amount_msats(1001).unwrap()
1237 .amount_msats(1000).unwrap()
1239 .sign(payer_sign).unwrap();
1240 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1241 assert_eq!(invoice_request.amount_msats(), Some(1000));
1242 assert_eq!(tlv_stream.amount, Some(1000));
1244 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1247 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248 .amount_msats(1001).unwrap()
1250 .sign(payer_sign).unwrap();
1251 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1252 assert_eq!(invoice_request.amount_msats(), Some(1001));
1253 assert_eq!(tlv_stream.amount, Some(1001));
1255 match OfferBuilder::new("foo".into(), recipient_pubkey())
1258 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1261 Ok(_) => panic!("expected error"),
1262 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1265 match OfferBuilder::new("foo".into(), recipient_pubkey())
1267 .supported_quantity(Quantity::Unbounded)
1269 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1270 .quantity(2).unwrap()
1273 Ok(_) => panic!("expected error"),
1274 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1277 match OfferBuilder::new("foo".into(), recipient_pubkey())
1280 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1281 .amount_msats(MAX_VALUE_MSAT + 1)
1283 Ok(_) => panic!("expected error"),
1284 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1287 match OfferBuilder::new("foo".into(), recipient_pubkey())
1289 .supported_quantity(Quantity::Unbounded)
1291 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1292 .amount_msats(1000).unwrap()
1293 .quantity(2).unwrap()
1296 Ok(_) => panic!("expected error"),
1297 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1300 match OfferBuilder::new("foo".into(), recipient_pubkey())
1302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1305 Ok(_) => panic!("expected error"),
1306 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1309 match OfferBuilder::new("foo".into(), recipient_pubkey())
1311 .supported_quantity(Quantity::Unbounded)
1313 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1314 .quantity(u64::max_value()).unwrap()
1317 Ok(_) => panic!("expected error"),
1318 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1323 fn builds_invoice_request_with_features() {
1324 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1327 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1328 .features_unchecked(InvoiceRequestFeatures::unknown())
1330 .sign(payer_sign).unwrap();
1331 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1332 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1333 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1335 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1338 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1339 .features_unchecked(InvoiceRequestFeatures::unknown())
1340 .features_unchecked(InvoiceRequestFeatures::empty())
1342 .sign(payer_sign).unwrap();
1343 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1344 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1345 assert_eq!(tlv_stream.features, None);
1349 fn builds_invoice_request_with_quantity() {
1350 let one = NonZeroU64::new(1).unwrap();
1351 let ten = NonZeroU64::new(10).unwrap();
1353 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1355 .supported_quantity(Quantity::One)
1357 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359 .sign(payer_sign).unwrap();
1360 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1361 assert_eq!(invoice_request.quantity(), None);
1362 assert_eq!(tlv_stream.quantity, None);
1364 match OfferBuilder::new("foo".into(), recipient_pubkey())
1366 .supported_quantity(Quantity::One)
1368 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1369 .amount_msats(2_000).unwrap()
1372 Ok(_) => panic!("expected error"),
1373 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1376 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1378 .supported_quantity(Quantity::Bounded(ten))
1380 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1381 .amount_msats(10_000).unwrap()
1382 .quantity(10).unwrap()
1384 .sign(payer_sign).unwrap();
1385 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1386 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1387 assert_eq!(tlv_stream.amount, Some(10_000));
1389 match OfferBuilder::new("foo".into(), recipient_pubkey())
1391 .supported_quantity(Quantity::Bounded(ten))
1393 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1394 .amount_msats(11_000).unwrap()
1397 Ok(_) => panic!("expected error"),
1398 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1401 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1403 .supported_quantity(Quantity::Unbounded)
1405 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1406 .amount_msats(2_000).unwrap()
1407 .quantity(2).unwrap()
1409 .sign(payer_sign).unwrap();
1410 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1411 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1412 assert_eq!(tlv_stream.amount, Some(2_000));
1414 match OfferBuilder::new("foo".into(), recipient_pubkey())
1416 .supported_quantity(Quantity::Unbounded)
1418 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1421 Ok(_) => panic!("expected error"),
1422 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1425 match OfferBuilder::new("foo".into(), recipient_pubkey())
1427 .supported_quantity(Quantity::Bounded(one))
1429 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1432 Ok(_) => panic!("expected error"),
1433 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1438 fn builds_invoice_request_with_payer_note() {
1439 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1442 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1443 .payer_note("bar".into())
1445 .sign(payer_sign).unwrap();
1446 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1447 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1448 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1450 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1453 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1454 .payer_note("bar".into())
1455 .payer_note("baz".into())
1457 .sign(payer_sign).unwrap();
1458 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1459 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1460 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1464 fn fails_signing_invoice_request() {
1465 match OfferBuilder::new("foo".into(), recipient_pubkey())
1468 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1472 Ok(_) => panic!("expected error"),
1473 Err(e) => assert_eq!(e, SignError::Signing(())),
1476 match OfferBuilder::new("foo".into(), recipient_pubkey())
1479 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1481 .sign(recipient_sign)
1483 Ok(_) => panic!("expected error"),
1484 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1489 fn fails_responding_with_unknown_required_features() {
1490 match OfferBuilder::new("foo".into(), recipient_pubkey())
1493 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1494 .features_unchecked(InvoiceRequestFeatures::unknown())
1496 .sign(payer_sign).unwrap()
1497 .respond_with_no_std(payment_paths(), payment_hash(), now())
1499 Ok(_) => panic!("expected error"),
1500 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1505 fn parses_invoice_request_with_metadata() {
1506 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1509 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1511 .sign(payer_sign).unwrap();
1513 let mut buffer = Vec::new();
1514 invoice_request.write(&mut buffer).unwrap();
1516 if let Err(e) = InvoiceRequest::try_from(buffer) {
1517 panic!("error parsing invoice_request: {:?}", e);
1522 fn parses_invoice_request_with_chain() {
1523 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1526 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1527 .chain(Network::Bitcoin).unwrap()
1529 .sign(payer_sign).unwrap();
1531 let mut buffer = Vec::new();
1532 invoice_request.write(&mut buffer).unwrap();
1534 if let Err(e) = InvoiceRequest::try_from(buffer) {
1535 panic!("error parsing invoice_request: {:?}", e);
1538 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1541 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1542 .chain_unchecked(Network::Testnet)
1544 .sign(payer_sign).unwrap();
1546 let mut buffer = Vec::new();
1547 invoice_request.write(&mut buffer).unwrap();
1549 match InvoiceRequest::try_from(buffer) {
1550 Ok(_) => panic!("expected error"),
1551 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1556 fn parses_invoice_request_with_amount() {
1557 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1560 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1562 .sign(payer_sign).unwrap();
1564 let mut buffer = Vec::new();
1565 invoice_request.write(&mut buffer).unwrap();
1567 if let Err(e) = InvoiceRequest::try_from(buffer) {
1568 panic!("error parsing invoice_request: {:?}", e);
1571 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1573 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1574 .amount_msats(1000).unwrap()
1576 .sign(payer_sign).unwrap();
1578 let mut buffer = Vec::new();
1579 invoice_request.write(&mut buffer).unwrap();
1581 if let Err(e) = InvoiceRequest::try_from(buffer) {
1582 panic!("error parsing invoice_request: {:?}", e);
1585 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1587 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1589 .sign(payer_sign).unwrap();
1591 let mut buffer = Vec::new();
1592 invoice_request.write(&mut buffer).unwrap();
1594 match InvoiceRequest::try_from(buffer) {
1595 Ok(_) => panic!("expected error"),
1596 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1599 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1602 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1603 .amount_msats_unchecked(999)
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::InsufficientAmount)),
1615 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1616 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1618 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620 .sign(payer_sign).unwrap();
1622 let mut buffer = Vec::new();
1623 invoice_request.write(&mut buffer).unwrap();
1625 match InvoiceRequest::try_from(buffer) {
1626 Ok(_) => panic!("expected error"),
1628 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1632 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1634 .supported_quantity(Quantity::Unbounded)
1636 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1637 .quantity(u64::max_value()).unwrap()
1639 .sign(payer_sign).unwrap();
1641 let mut buffer = Vec::new();
1642 invoice_request.write(&mut buffer).unwrap();
1644 match InvoiceRequest::try_from(buffer) {
1645 Ok(_) => panic!("expected error"),
1646 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1651 fn parses_invoice_request_with_quantity() {
1652 let one = NonZeroU64::new(1).unwrap();
1653 let ten = NonZeroU64::new(10).unwrap();
1655 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1657 .supported_quantity(Quantity::One)
1659 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 .sign(payer_sign).unwrap();
1663 let mut buffer = Vec::new();
1664 invoice_request.write(&mut buffer).unwrap();
1666 if let Err(e) = InvoiceRequest::try_from(buffer) {
1667 panic!("error parsing invoice_request: {:?}", e);
1670 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1672 .supported_quantity(Quantity::One)
1674 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1675 .amount_msats(2_000).unwrap()
1676 .quantity_unchecked(2)
1678 .sign(payer_sign).unwrap();
1680 let mut buffer = Vec::new();
1681 invoice_request.write(&mut buffer).unwrap();
1683 match InvoiceRequest::try_from(buffer) {
1684 Ok(_) => panic!("expected error"),
1686 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1690 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1692 .supported_quantity(Quantity::Bounded(ten))
1694 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1695 .amount_msats(10_000).unwrap()
1696 .quantity(10).unwrap()
1698 .sign(payer_sign).unwrap();
1700 let mut buffer = Vec::new();
1701 invoice_request.write(&mut buffer).unwrap();
1703 if let Err(e) = InvoiceRequest::try_from(buffer) {
1704 panic!("error parsing invoice_request: {:?}", e);
1707 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1709 .supported_quantity(Quantity::Bounded(ten))
1711 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1712 .amount_msats(11_000).unwrap()
1713 .quantity_unchecked(11)
1715 .sign(payer_sign).unwrap();
1717 let mut buffer = Vec::new();
1718 invoice_request.write(&mut buffer).unwrap();
1720 match InvoiceRequest::try_from(buffer) {
1721 Ok(_) => panic!("expected error"),
1722 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1725 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1727 .supported_quantity(Quantity::Unbounded)
1729 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1730 .amount_msats(2_000).unwrap()
1731 .quantity(2).unwrap()
1733 .sign(payer_sign).unwrap();
1735 let mut buffer = Vec::new();
1736 invoice_request.write(&mut buffer).unwrap();
1738 if let Err(e) = InvoiceRequest::try_from(buffer) {
1739 panic!("error parsing invoice_request: {:?}", e);
1742 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1744 .supported_quantity(Quantity::Unbounded)
1746 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1748 .sign(payer_sign).unwrap();
1750 let mut buffer = Vec::new();
1751 invoice_request.write(&mut buffer).unwrap();
1753 match InvoiceRequest::try_from(buffer) {
1754 Ok(_) => panic!("expected error"),
1755 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1758 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1760 .supported_quantity(Quantity::Bounded(one))
1762 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1764 .sign(payer_sign).unwrap();
1766 let mut buffer = Vec::new();
1767 invoice_request.write(&mut buffer).unwrap();
1769 match InvoiceRequest::try_from(buffer) {
1770 Ok(_) => panic!("expected error"),
1771 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1776 fn fails_parsing_invoice_request_without_metadata() {
1777 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1780 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1782 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1783 tlv_stream.0.metadata = None;
1785 let mut buffer = Vec::new();
1786 tlv_stream.write(&mut buffer).unwrap();
1788 match InvoiceRequest::try_from(buffer) {
1789 Ok(_) => panic!("expected error"),
1791 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1797 fn fails_parsing_invoice_request_without_payer_id() {
1798 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1801 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1803 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1804 tlv_stream.2.payer_id = None;
1806 let mut buffer = Vec::new();
1807 tlv_stream.write(&mut buffer).unwrap();
1809 match InvoiceRequest::try_from(buffer) {
1810 Ok(_) => panic!("expected error"),
1811 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1816 fn fails_parsing_invoice_request_without_node_id() {
1817 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1820 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1822 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1823 tlv_stream.1.node_id = None;
1825 let mut buffer = Vec::new();
1826 tlv_stream.write(&mut buffer).unwrap();
1828 match InvoiceRequest::try_from(buffer) {
1829 Ok(_) => panic!("expected error"),
1831 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1837 fn fails_parsing_invoice_request_without_signature() {
1838 let mut buffer = Vec::new();
1839 OfferBuilder::new("foo".into(), recipient_pubkey())
1842 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1845 .write(&mut buffer).unwrap();
1847 match InvoiceRequest::try_from(buffer) {
1848 Ok(_) => panic!("expected error"),
1849 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1854 fn fails_parsing_invoice_request_with_invalid_signature() {
1855 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1858 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1860 .sign(payer_sign).unwrap();
1861 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1862 *last_signature_byte = last_signature_byte.wrapping_add(1);
1864 let mut buffer = Vec::new();
1865 invoice_request.write(&mut buffer).unwrap();
1867 match InvoiceRequest::try_from(buffer) {
1868 Ok(_) => panic!("expected error"),
1870 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1876 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1877 let secp_ctx = Secp256k1::new();
1878 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1879 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1882 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1884 .sign::<_, Infallible>(
1885 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1889 let mut encoded_invoice_request = Vec::new();
1890 invoice_request.write(&mut encoded_invoice_request).unwrap();
1891 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1892 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1893 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1895 match InvoiceRequest::try_from(encoded_invoice_request) {
1896 Ok(_) => panic!("expected error"),
1897 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),