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 /// Returns the [`TaggedHash`] of the invoice to sign.
376 pub fn tagged_hash(&self) -> &TaggedHash {
380 /// Signs the [`TaggedHash`] of the invoice request using the given function.
382 /// Note: The hash computation may have included unknown, odd TLV records.
384 /// This is not exported to bindings users as functions are not yet mapped.
385 pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
387 F: FnOnce(&Self) -> Result<Signature, E>
389 let pubkey = self.contents.payer_id;
390 let signature = merkle::sign_message(sign, &self, pubkey)?;
392 // Append the signature TLV record to the bytes.
393 let signature_tlv_stream = SignatureTlvStreamRef {
394 signature: Some(&signature),
396 signature_tlv_stream.write(&mut self.bytes).unwrap();
400 contents: self.contents,
406 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
407 fn as_ref(&self) -> &TaggedHash {
412 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
414 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
415 /// specifies these such that its recipient can send an invoice for payment.
417 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
418 /// [`Offer`]: crate::offers::offer::Offer
419 #[derive(Clone, Debug)]
420 #[cfg_attr(test, derive(PartialEq))]
421 pub struct InvoiceRequest {
422 pub(super) bytes: Vec<u8>,
423 pub(super) contents: InvoiceRequestContents,
424 signature: Signature,
427 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
429 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
430 #[derive(Clone, Debug)]
431 #[cfg_attr(test, derive(PartialEq))]
432 pub(super) struct InvoiceRequestContents {
433 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
437 #[derive(Clone, Debug)]
438 #[cfg_attr(test, derive(PartialEq))]
439 pub(super) struct InvoiceRequestContentsWithoutPayerId {
440 payer: PayerContents,
441 pub(super) offer: OfferContents,
442 chain: Option<ChainHash>,
443 amount_msats: Option<u64>,
444 features: InvoiceRequestFeatures,
445 quantity: Option<u64>,
446 payer_note: Option<String>,
449 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
450 /// An unpredictable series of bytes, typically containing information about the derivation of
453 /// [`payer_id`]: Self::payer_id
454 pub fn payer_metadata(&$self) -> &[u8] {
458 /// A chain from [`Offer::chains`] that the offer is valid for.
459 pub fn chain(&$self) -> ChainHash {
463 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
464 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
466 /// [`chain`]: Self::chain
467 pub fn amount_msats(&$self) -> Option<u64> {
468 $contents.amount_msats()
471 /// Features pertaining to requesting an invoice.
472 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
473 &$contents.features()
476 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
477 pub fn quantity(&$self) -> Option<u64> {
481 /// A possibly transient pubkey used to sign the invoice request.
482 pub fn payer_id(&$self) -> PublicKey {
486 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
488 pub fn payer_note(&$self) -> Option<PrintableString> {
489 $contents.payer_note()
493 impl UnsignedInvoiceRequest {
494 offer_accessors!(self, self.contents.inner.offer);
495 invoice_request_accessors!(self, self.contents);
498 impl InvoiceRequest {
499 offer_accessors!(self, self.contents.inner.offer);
500 invoice_request_accessors!(self, self.contents);
502 /// Signature of the invoice request using [`payer_id`].
504 /// [`payer_id`]: Self::payer_id
505 pub fn signature(&self) -> Signature {
509 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
510 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
512 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
513 /// creation time is used for the `created_at` parameter.
515 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
517 /// [`Duration`]: core::time::Duration
518 #[cfg(feature = "std")]
520 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
521 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
522 let created_at = std::time::SystemTime::now()
523 .duration_since(std::time::SystemTime::UNIX_EPOCH)
524 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
526 self.respond_with_no_std(payment_paths, payment_hash, created_at)
529 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
531 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
532 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
533 /// where [`std::time::SystemTime`] is not available.
535 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
538 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
539 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
540 /// a preference. Note, however, that any privacy is lost if a public node id was used for
541 /// [`Offer::signing_pubkey`].
543 /// Errors if the request contains unknown required features.
545 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
547 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
548 pub fn respond_with_no_std(
549 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
550 created_at: core::time::Duration
551 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
552 if self.invoice_request_features().requires_unknown_bits() {
553 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
556 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
559 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
560 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
561 /// the same [`ExpandedKey`] as the one used to create the offer.
563 /// See [`InvoiceRequest::respond_with`] for further details.
565 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
567 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
568 #[cfg(feature = "std")]
569 pub fn verify_and_respond_using_derived_keys<T: secp256k1::Signing>(
570 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
571 expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
572 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
573 let created_at = std::time::SystemTime::now()
574 .duration_since(std::time::SystemTime::UNIX_EPOCH)
575 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
577 self.verify_and_respond_using_derived_keys_no_std(
578 payment_paths, payment_hash, created_at, expanded_key, secp_ctx
582 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
583 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
584 /// the same [`ExpandedKey`] as the one used to create the offer.
586 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
588 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
590 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
591 pub fn verify_and_respond_using_derived_keys_no_std<T: secp256k1::Signing>(
592 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
593 created_at: core::time::Duration, expanded_key: &ExpandedKey, secp_ctx: &Secp256k1<T>
594 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
595 if self.invoice_request_features().requires_unknown_bits() {
596 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
599 let keys = match self.verify(expanded_key, secp_ctx) {
600 Err(()) => return Err(Bolt12SemanticError::InvalidMetadata),
601 Ok(None) => return Err(Bolt12SemanticError::InvalidMetadata),
602 Ok(Some(keys)) => keys,
605 InvoiceBuilder::for_offer_using_keys(self, payment_paths, created_at, payment_hash, keys)
608 /// Verifies that the request was for an offer created using the given key. Returns the derived
609 /// keys need to sign an [`Bolt12Invoice`] for the request if they could be extracted from the
612 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
613 pub fn verify<T: secp256k1::Signing>(
614 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
615 ) -> Result<Option<KeyPair>, ()> {
616 self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)
620 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
621 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
622 self.contents.as_tlv_stream();
623 let signature_tlv_stream = SignatureTlvStreamRef {
624 signature: Some(&self.signature),
626 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
630 impl InvoiceRequestContents {
631 pub(super) fn metadata(&self) -> &[u8] {
632 self.inner.metadata()
635 pub(super) fn derives_keys(&self) -> bool {
636 self.inner.payer.0.derives_keys()
639 pub(super) fn chain(&self) -> ChainHash {
643 pub(super) fn amount_msats(&self) -> Option<u64> {
644 self.inner.amount_msats
647 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
651 pub(super) fn quantity(&self) -> Option<u64> {
655 pub(super) fn payer_id(&self) -> PublicKey {
659 pub(super) fn payer_note(&self) -> Option<PrintableString> {
660 self.inner.payer_note.as_ref()
661 .map(|payer_note| PrintableString(payer_note.as_str()))
664 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
665 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
666 invoice_request.payer_id = Some(&self.payer_id);
667 (payer, offer, invoice_request)
671 impl InvoiceRequestContentsWithoutPayerId {
672 pub(super) fn metadata(&self) -> &[u8] {
673 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
676 pub(super) fn chain(&self) -> ChainHash {
677 self.chain.unwrap_or_else(|| self.offer.implied_chain())
680 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
681 let payer = PayerTlvStreamRef {
682 metadata: self.payer.0.as_bytes(),
685 let offer = self.offer.as_tlv_stream();
688 if self.features == InvoiceRequestFeatures::empty() { None }
689 else { Some(&self.features) }
692 let invoice_request = InvoiceRequestTlvStreamRef {
693 chain: self.chain.as_ref(),
694 amount: self.amount_msats,
696 quantity: self.quantity,
698 payer_note: self.payer_note.as_ref(),
701 (payer, offer, invoice_request)
705 impl Writeable for UnsignedInvoiceRequest {
706 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
707 WithoutLength(&self.bytes).write(writer)
711 impl Writeable for InvoiceRequest {
712 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
713 WithoutLength(&self.bytes).write(writer)
717 impl Writeable for InvoiceRequestContents {
718 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
719 self.as_tlv_stream().write(writer)
723 /// Valid type range for invoice_request TLV records.
724 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
726 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
728 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
729 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
731 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
732 (80, chain: ChainHash),
733 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
734 (84, features: (InvoiceRequestFeatures, WithoutLength)),
735 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
736 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
737 (89, payer_note: (String, WithoutLength)),
740 type FullInvoiceRequestTlvStream =
741 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
744 type FullInvoiceRequestTlvStreamRef<'a> = (
745 PayerTlvStreamRef<'a>,
746 OfferTlvStreamRef<'a>,
747 InvoiceRequestTlvStreamRef<'a>,
748 SignatureTlvStreamRef<'a>,
751 impl SeekReadable for FullInvoiceRequestTlvStream {
752 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
753 let payer = SeekReadable::read(r)?;
754 let offer = SeekReadable::read(r)?;
755 let invoice_request = SeekReadable::read(r)?;
756 let signature = SeekReadable::read(r)?;
758 Ok((payer, offer, invoice_request, signature))
762 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
764 type PartialInvoiceRequestTlvStreamRef<'a> = (
765 PayerTlvStreamRef<'a>,
766 OfferTlvStreamRef<'a>,
767 InvoiceRequestTlvStreamRef<'a>,
770 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
771 type Error = Bolt12ParseError;
773 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
774 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
775 let ParsedMessage { bytes, tlv_stream } = invoice_request;
777 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
779 let contents = InvoiceRequestContents::try_from(
780 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
783 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
785 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
789 impl TryFrom<Vec<u8>> for InvoiceRequest {
790 type Error = Bolt12ParseError;
792 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
793 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
794 let ParsedMessage { bytes, tlv_stream } = invoice_request;
796 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
797 SignatureTlvStream { signature },
799 let contents = InvoiceRequestContents::try_from(
800 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
803 let signature = match signature {
804 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
805 Some(signature) => signature,
807 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
808 merkle::verify_signature(&signature, message, contents.payer_id)?;
810 Ok(InvoiceRequest { bytes, contents, signature })
814 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
815 type Error = Bolt12SemanticError;
817 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
819 PayerTlvStream { metadata },
821 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
824 let payer = match metadata {
825 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
826 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
828 let offer = OfferContents::try_from(offer_tlv_stream)?;
830 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
831 return Err(Bolt12SemanticError::UnsupportedChain);
834 if offer.amount().is_none() && amount.is_none() {
835 return Err(Bolt12SemanticError::MissingAmount);
838 offer.check_quantity(quantity)?;
839 offer.check_amount_msats_for_quantity(amount, quantity)?;
841 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
843 let payer_id = match payer_id {
844 None => return Err(Bolt12SemanticError::MissingPayerId),
845 Some(payer_id) => payer_id,
848 Ok(InvoiceRequestContents {
849 inner: InvoiceRequestContentsWithoutPayerId {
850 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
859 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
861 use bitcoin::blockdata::constants::ChainHash;
862 use bitcoin::network::constants::Network;
863 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
864 use core::convert::{Infallible, TryFrom};
865 use core::num::NonZeroU64;
866 #[cfg(feature = "std")]
867 use core::time::Duration;
868 use crate::sign::KeyMaterial;
869 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
870 use crate::ln::inbound_payment::ExpandedKey;
871 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
872 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
873 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
874 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
875 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
876 use crate::offers::payer::PayerTlvStreamRef;
877 use crate::offers::test_utils::*;
878 use crate::util::ser::{BigSize, Writeable};
879 use crate::util::string::PrintableString;
882 fn builds_invoice_request_with_defaults() {
883 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
886 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
889 let mut buffer = Vec::new();
890 unsigned_invoice_request.write(&mut buffer).unwrap();
892 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
893 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
894 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
895 assert_eq!(unsigned_invoice_request.metadata(), None);
896 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
897 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
898 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
899 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
900 assert_eq!(unsigned_invoice_request.paths(), &[]);
901 assert_eq!(unsigned_invoice_request.issuer(), None);
902 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
903 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
904 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
905 assert_eq!(unsigned_invoice_request.amount_msats(), None);
906 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
907 assert_eq!(unsigned_invoice_request.quantity(), None);
908 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
909 assert_eq!(unsigned_invoice_request.payer_note(), None);
911 match UnsignedInvoiceRequest::try_from(buffer) {
912 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
914 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
915 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
919 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
921 let mut buffer = Vec::new();
922 invoice_request.write(&mut buffer).unwrap();
924 assert_eq!(invoice_request.bytes, buffer.as_slice());
925 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
926 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
927 assert_eq!(invoice_request.metadata(), None);
928 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
929 assert_eq!(invoice_request.description(), PrintableString("foo"));
930 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
931 assert_eq!(invoice_request.absolute_expiry(), None);
932 assert_eq!(invoice_request.paths(), &[]);
933 assert_eq!(invoice_request.issuer(), None);
934 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
935 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
936 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
937 assert_eq!(invoice_request.amount_msats(), None);
938 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
939 assert_eq!(invoice_request.quantity(), None);
940 assert_eq!(invoice_request.payer_id(), payer_pubkey());
941 assert_eq!(invoice_request.payer_note(), None);
943 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
944 assert!(merkle::verify_signature(&invoice_request.signature, message, payer_pubkey()).is_ok());
947 invoice_request.as_tlv_stream(),
949 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
955 description: Some(&String::from("foo")),
957 absolute_expiry: None,
961 node_id: Some(&recipient_pubkey()),
963 InvoiceRequestTlvStreamRef {
968 payer_id: Some(&payer_pubkey()),
971 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
975 if let Err(e) = InvoiceRequest::try_from(buffer) {
976 panic!("error parsing invoice request: {:?}", e);
980 #[cfg(feature = "std")]
982 fn builds_invoice_request_from_offer_with_expiration() {
983 let future_expiry = Duration::from_secs(u64::max_value());
984 let past_expiry = Duration::from_secs(0);
986 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
988 .absolute_expiry(future_expiry)
990 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
993 panic!("error building invoice_request: {:?}", e);
996 match OfferBuilder::new("foo".into(), recipient_pubkey())
998 .absolute_expiry(past_expiry)
1000 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1003 Ok(_) => panic!("expected error"),
1004 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1009 fn builds_invoice_request_with_derived_metadata() {
1010 let payer_id = payer_pubkey();
1011 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1012 let entropy = FixedEntropy {};
1013 let secp_ctx = Secp256k1::new();
1015 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1018 let invoice_request = offer
1019 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy)
1022 .sign(payer_sign).unwrap();
1023 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1025 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1028 .sign(recipient_sign).unwrap();
1029 assert!(invoice.verify(&expanded_key, &secp_ctx));
1031 // Fails verification with altered fields
1033 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1034 mut invoice_tlv_stream, mut signature_tlv_stream
1035 ) = invoice.as_tlv_stream();
1036 invoice_request_tlv_stream.amount = Some(2000);
1037 invoice_tlv_stream.amount = Some(2000);
1040 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1041 let mut bytes = Vec::new();
1042 tlv_stream.write(&mut bytes).unwrap();
1044 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1045 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1046 signature_tlv_stream.signature = Some(&signature);
1048 let mut encoded_invoice = bytes;
1049 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1051 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1052 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1054 // Fails verification with altered metadata
1056 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1057 mut signature_tlv_stream
1058 ) = invoice.as_tlv_stream();
1059 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1060 payer_tlv_stream.metadata = Some(&metadata);
1063 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1064 let mut bytes = Vec::new();
1065 tlv_stream.write(&mut bytes).unwrap();
1067 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1068 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1069 signature_tlv_stream.signature = Some(&signature);
1071 let mut encoded_invoice = bytes;
1072 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1074 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1075 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1079 fn builds_invoice_request_with_derived_payer_id() {
1080 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1081 let entropy = FixedEntropy {};
1082 let secp_ctx = Secp256k1::new();
1084 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1087 let invoice_request = offer
1088 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx)
1093 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1096 .sign(recipient_sign).unwrap();
1097 assert!(invoice.verify(&expanded_key, &secp_ctx));
1099 // Fails verification with altered fields
1101 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1102 mut invoice_tlv_stream, mut signature_tlv_stream
1103 ) = invoice.as_tlv_stream();
1104 invoice_request_tlv_stream.amount = Some(2000);
1105 invoice_tlv_stream.amount = Some(2000);
1108 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1109 let mut bytes = Vec::new();
1110 tlv_stream.write(&mut bytes).unwrap();
1112 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1113 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1114 signature_tlv_stream.signature = Some(&signature);
1116 let mut encoded_invoice = bytes;
1117 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1119 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1120 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1122 // Fails verification with altered payer id
1124 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1125 mut signature_tlv_stream
1126 ) = invoice.as_tlv_stream();
1127 let payer_id = pubkey(1);
1128 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1131 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1132 let mut bytes = Vec::new();
1133 tlv_stream.write(&mut bytes).unwrap();
1135 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1136 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1137 signature_tlv_stream.signature = Some(&signature);
1139 let mut encoded_invoice = bytes;
1140 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1142 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1143 assert!(!invoice.verify(&expanded_key, &secp_ctx));
1147 fn builds_invoice_request_with_chain() {
1148 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1149 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1151 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1154 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1155 .chain(Network::Bitcoin).unwrap()
1157 .sign(payer_sign).unwrap();
1158 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1159 assert_eq!(invoice_request.chain(), mainnet);
1160 assert_eq!(tlv_stream.chain, None);
1162 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1164 .chain(Network::Testnet)
1166 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1167 .chain(Network::Testnet).unwrap()
1169 .sign(payer_sign).unwrap();
1170 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1171 assert_eq!(invoice_request.chain(), testnet);
1172 assert_eq!(tlv_stream.chain, Some(&testnet));
1174 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1176 .chain(Network::Bitcoin)
1177 .chain(Network::Testnet)
1179 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1180 .chain(Network::Bitcoin).unwrap()
1182 .sign(payer_sign).unwrap();
1183 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1184 assert_eq!(invoice_request.chain(), mainnet);
1185 assert_eq!(tlv_stream.chain, None);
1187 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1189 .chain(Network::Bitcoin)
1190 .chain(Network::Testnet)
1192 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1193 .chain(Network::Bitcoin).unwrap()
1194 .chain(Network::Testnet).unwrap()
1196 .sign(payer_sign).unwrap();
1197 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1198 assert_eq!(invoice_request.chain(), testnet);
1199 assert_eq!(tlv_stream.chain, Some(&testnet));
1201 match OfferBuilder::new("foo".into(), recipient_pubkey())
1203 .chain(Network::Testnet)
1205 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1206 .chain(Network::Bitcoin)
1208 Ok(_) => panic!("expected error"),
1209 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1212 match OfferBuilder::new("foo".into(), recipient_pubkey())
1214 .chain(Network::Testnet)
1216 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1219 Ok(_) => panic!("expected error"),
1220 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1225 fn builds_invoice_request_with_amount() {
1226 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1229 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1230 .amount_msats(1000).unwrap()
1232 .sign(payer_sign).unwrap();
1233 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1234 assert_eq!(invoice_request.amount_msats(), Some(1000));
1235 assert_eq!(tlv_stream.amount, Some(1000));
1237 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1240 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1241 .amount_msats(1001).unwrap()
1242 .amount_msats(1000).unwrap()
1244 .sign(payer_sign).unwrap();
1245 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1246 assert_eq!(invoice_request.amount_msats(), Some(1000));
1247 assert_eq!(tlv_stream.amount, Some(1000));
1249 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1253 .amount_msats(1001).unwrap()
1255 .sign(payer_sign).unwrap();
1256 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1257 assert_eq!(invoice_request.amount_msats(), Some(1001));
1258 assert_eq!(tlv_stream.amount, Some(1001));
1260 match OfferBuilder::new("foo".into(), recipient_pubkey())
1263 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1266 Ok(_) => panic!("expected error"),
1267 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1270 match OfferBuilder::new("foo".into(), recipient_pubkey())
1272 .supported_quantity(Quantity::Unbounded)
1274 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275 .quantity(2).unwrap()
1278 Ok(_) => panic!("expected error"),
1279 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1282 match OfferBuilder::new("foo".into(), recipient_pubkey())
1285 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1286 .amount_msats(MAX_VALUE_MSAT + 1)
1288 Ok(_) => panic!("expected error"),
1289 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1292 match OfferBuilder::new("foo".into(), recipient_pubkey())
1294 .supported_quantity(Quantity::Unbounded)
1296 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1297 .amount_msats(1000).unwrap()
1298 .quantity(2).unwrap()
1301 Ok(_) => panic!("expected error"),
1302 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1305 match OfferBuilder::new("foo".into(), recipient_pubkey())
1307 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1310 Ok(_) => panic!("expected error"),
1311 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1314 match OfferBuilder::new("foo".into(), recipient_pubkey())
1316 .supported_quantity(Quantity::Unbounded)
1318 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1319 .quantity(u64::max_value()).unwrap()
1322 Ok(_) => panic!("expected error"),
1323 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1328 fn builds_invoice_request_with_features() {
1329 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1333 .features_unchecked(InvoiceRequestFeatures::unknown())
1335 .sign(payer_sign).unwrap();
1336 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1337 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1338 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1340 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 .features_unchecked(InvoiceRequestFeatures::unknown())
1345 .features_unchecked(InvoiceRequestFeatures::empty())
1347 .sign(payer_sign).unwrap();
1348 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1349 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1350 assert_eq!(tlv_stream.features, None);
1354 fn builds_invoice_request_with_quantity() {
1355 let one = NonZeroU64::new(1).unwrap();
1356 let ten = NonZeroU64::new(10).unwrap();
1358 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1360 .supported_quantity(Quantity::One)
1362 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1364 .sign(payer_sign).unwrap();
1365 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1366 assert_eq!(invoice_request.quantity(), None);
1367 assert_eq!(tlv_stream.quantity, None);
1369 match OfferBuilder::new("foo".into(), recipient_pubkey())
1371 .supported_quantity(Quantity::One)
1373 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1374 .amount_msats(2_000).unwrap()
1377 Ok(_) => panic!("expected error"),
1378 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1381 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1383 .supported_quantity(Quantity::Bounded(ten))
1385 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1386 .amount_msats(10_000).unwrap()
1387 .quantity(10).unwrap()
1389 .sign(payer_sign).unwrap();
1390 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1391 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1392 assert_eq!(tlv_stream.amount, Some(10_000));
1394 match OfferBuilder::new("foo".into(), recipient_pubkey())
1396 .supported_quantity(Quantity::Bounded(ten))
1398 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1399 .amount_msats(11_000).unwrap()
1402 Ok(_) => panic!("expected error"),
1403 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1406 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1408 .supported_quantity(Quantity::Unbounded)
1410 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1411 .amount_msats(2_000).unwrap()
1412 .quantity(2).unwrap()
1414 .sign(payer_sign).unwrap();
1415 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1416 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1417 assert_eq!(tlv_stream.amount, Some(2_000));
1419 match OfferBuilder::new("foo".into(), recipient_pubkey())
1421 .supported_quantity(Quantity::Unbounded)
1423 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1426 Ok(_) => panic!("expected error"),
1427 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1430 match OfferBuilder::new("foo".into(), recipient_pubkey())
1432 .supported_quantity(Quantity::Bounded(one))
1434 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1437 Ok(_) => panic!("expected error"),
1438 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1443 fn builds_invoice_request_with_payer_note() {
1444 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1447 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1448 .payer_note("bar".into())
1450 .sign(payer_sign).unwrap();
1451 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1452 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1453 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1455 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1458 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1459 .payer_note("bar".into())
1460 .payer_note("baz".into())
1462 .sign(payer_sign).unwrap();
1463 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1464 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1465 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1469 fn fails_signing_invoice_request() {
1470 match OfferBuilder::new("foo".into(), recipient_pubkey())
1473 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 Ok(_) => panic!("expected error"),
1478 Err(e) => assert_eq!(e, SignError::Signing(())),
1481 match OfferBuilder::new("foo".into(), recipient_pubkey())
1484 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1486 .sign(recipient_sign)
1488 Ok(_) => panic!("expected error"),
1489 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1494 fn fails_responding_with_unknown_required_features() {
1495 match OfferBuilder::new("foo".into(), recipient_pubkey())
1498 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1499 .features_unchecked(InvoiceRequestFeatures::unknown())
1501 .sign(payer_sign).unwrap()
1502 .respond_with_no_std(payment_paths(), payment_hash(), now())
1504 Ok(_) => panic!("expected error"),
1505 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1510 fn parses_invoice_request_with_metadata() {
1511 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1514 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1516 .sign(payer_sign).unwrap();
1518 let mut buffer = Vec::new();
1519 invoice_request.write(&mut buffer).unwrap();
1521 if let Err(e) = InvoiceRequest::try_from(buffer) {
1522 panic!("error parsing invoice_request: {:?}", e);
1527 fn parses_invoice_request_with_chain() {
1528 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1531 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1532 .chain(Network::Bitcoin).unwrap()
1534 .sign(payer_sign).unwrap();
1536 let mut buffer = Vec::new();
1537 invoice_request.write(&mut buffer).unwrap();
1539 if let Err(e) = InvoiceRequest::try_from(buffer) {
1540 panic!("error parsing invoice_request: {:?}", e);
1543 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1546 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1547 .chain_unchecked(Network::Testnet)
1549 .sign(payer_sign).unwrap();
1551 let mut buffer = Vec::new();
1552 invoice_request.write(&mut buffer).unwrap();
1554 match InvoiceRequest::try_from(buffer) {
1555 Ok(_) => panic!("expected error"),
1556 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1561 fn parses_invoice_request_with_amount() {
1562 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1565 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1567 .sign(payer_sign).unwrap();
1569 let mut buffer = Vec::new();
1570 invoice_request.write(&mut buffer).unwrap();
1572 if let Err(e) = InvoiceRequest::try_from(buffer) {
1573 panic!("error parsing invoice_request: {:?}", e);
1576 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1578 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1579 .amount_msats(1000).unwrap()
1581 .sign(payer_sign).unwrap();
1583 let mut buffer = Vec::new();
1584 invoice_request.write(&mut buffer).unwrap();
1586 if let Err(e) = InvoiceRequest::try_from(buffer) {
1587 panic!("error parsing invoice_request: {:?}", e);
1590 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1592 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594 .sign(payer_sign).unwrap();
1596 let mut buffer = Vec::new();
1597 invoice_request.write(&mut buffer).unwrap();
1599 match InvoiceRequest::try_from(buffer) {
1600 Ok(_) => panic!("expected error"),
1601 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1604 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1607 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1608 .amount_msats_unchecked(999)
1610 .sign(payer_sign).unwrap();
1612 let mut buffer = Vec::new();
1613 invoice_request.write(&mut buffer).unwrap();
1615 match InvoiceRequest::try_from(buffer) {
1616 Ok(_) => panic!("expected error"),
1617 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1620 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1621 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1623 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1625 .sign(payer_sign).unwrap();
1627 let mut buffer = Vec::new();
1628 invoice_request.write(&mut buffer).unwrap();
1630 match InvoiceRequest::try_from(buffer) {
1631 Ok(_) => panic!("expected error"),
1633 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1637 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1639 .supported_quantity(Quantity::Unbounded)
1641 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1642 .quantity(u64::max_value()).unwrap()
1644 .sign(payer_sign).unwrap();
1646 let mut buffer = Vec::new();
1647 invoice_request.write(&mut buffer).unwrap();
1649 match InvoiceRequest::try_from(buffer) {
1650 Ok(_) => panic!("expected error"),
1651 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1656 fn parses_invoice_request_with_quantity() {
1657 let one = NonZeroU64::new(1).unwrap();
1658 let ten = NonZeroU64::new(10).unwrap();
1660 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1662 .supported_quantity(Quantity::One)
1664 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1666 .sign(payer_sign).unwrap();
1668 let mut buffer = Vec::new();
1669 invoice_request.write(&mut buffer).unwrap();
1671 if let Err(e) = InvoiceRequest::try_from(buffer) {
1672 panic!("error parsing invoice_request: {:?}", e);
1675 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1677 .supported_quantity(Quantity::One)
1679 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1680 .amount_msats(2_000).unwrap()
1681 .quantity_unchecked(2)
1683 .sign(payer_sign).unwrap();
1685 let mut buffer = Vec::new();
1686 invoice_request.write(&mut buffer).unwrap();
1688 match InvoiceRequest::try_from(buffer) {
1689 Ok(_) => panic!("expected error"),
1691 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1695 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1697 .supported_quantity(Quantity::Bounded(ten))
1699 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1700 .amount_msats(10_000).unwrap()
1701 .quantity(10).unwrap()
1703 .sign(payer_sign).unwrap();
1705 let mut buffer = Vec::new();
1706 invoice_request.write(&mut buffer).unwrap();
1708 if let Err(e) = InvoiceRequest::try_from(buffer) {
1709 panic!("error parsing invoice_request: {:?}", e);
1712 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1714 .supported_quantity(Quantity::Bounded(ten))
1716 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1717 .amount_msats(11_000).unwrap()
1718 .quantity_unchecked(11)
1720 .sign(payer_sign).unwrap();
1722 let mut buffer = Vec::new();
1723 invoice_request.write(&mut buffer).unwrap();
1725 match InvoiceRequest::try_from(buffer) {
1726 Ok(_) => panic!("expected error"),
1727 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1730 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1732 .supported_quantity(Quantity::Unbounded)
1734 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1735 .amount_msats(2_000).unwrap()
1736 .quantity(2).unwrap()
1738 .sign(payer_sign).unwrap();
1740 let mut buffer = Vec::new();
1741 invoice_request.write(&mut buffer).unwrap();
1743 if let Err(e) = InvoiceRequest::try_from(buffer) {
1744 panic!("error parsing invoice_request: {:?}", e);
1747 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1749 .supported_quantity(Quantity::Unbounded)
1751 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1753 .sign(payer_sign).unwrap();
1755 let mut buffer = Vec::new();
1756 invoice_request.write(&mut buffer).unwrap();
1758 match InvoiceRequest::try_from(buffer) {
1759 Ok(_) => panic!("expected error"),
1760 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1763 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1765 .supported_quantity(Quantity::Bounded(one))
1767 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1769 .sign(payer_sign).unwrap();
1771 let mut buffer = Vec::new();
1772 invoice_request.write(&mut buffer).unwrap();
1774 match InvoiceRequest::try_from(buffer) {
1775 Ok(_) => panic!("expected error"),
1776 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1781 fn fails_parsing_invoice_request_without_metadata() {
1782 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1785 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1787 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1788 tlv_stream.0.metadata = None;
1790 let mut buffer = Vec::new();
1791 tlv_stream.write(&mut buffer).unwrap();
1793 match InvoiceRequest::try_from(buffer) {
1794 Ok(_) => panic!("expected error"),
1796 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1802 fn fails_parsing_invoice_request_without_payer_id() {
1803 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1806 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1808 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1809 tlv_stream.2.payer_id = None;
1811 let mut buffer = Vec::new();
1812 tlv_stream.write(&mut buffer).unwrap();
1814 match InvoiceRequest::try_from(buffer) {
1815 Ok(_) => panic!("expected error"),
1816 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1821 fn fails_parsing_invoice_request_without_node_id() {
1822 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1825 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1827 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1828 tlv_stream.1.node_id = None;
1830 let mut buffer = Vec::new();
1831 tlv_stream.write(&mut buffer).unwrap();
1833 match InvoiceRequest::try_from(buffer) {
1834 Ok(_) => panic!("expected error"),
1836 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1842 fn fails_parsing_invoice_request_without_signature() {
1843 let mut buffer = Vec::new();
1844 OfferBuilder::new("foo".into(), recipient_pubkey())
1847 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1850 .write(&mut buffer).unwrap();
1852 match InvoiceRequest::try_from(buffer) {
1853 Ok(_) => panic!("expected error"),
1854 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1859 fn fails_parsing_invoice_request_with_invalid_signature() {
1860 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1863 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1865 .sign(payer_sign).unwrap();
1866 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1867 *last_signature_byte = last_signature_byte.wrapping_add(1);
1869 let mut buffer = Vec::new();
1870 invoice_request.write(&mut buffer).unwrap();
1872 match InvoiceRequest::try_from(buffer) {
1873 Ok(_) => panic!("expected error"),
1875 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1881 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1882 let secp_ctx = Secp256k1::new();
1883 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1884 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1887 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1889 .sign::<_, Infallible>(
1890 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1894 let mut encoded_invoice_request = Vec::new();
1895 invoice_request.write(&mut encoded_invoice_request).unwrap();
1896 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1897 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1898 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1900 match InvoiceRequest::try_from(encoded_invoice_request) {
1901 Ok(_) => panic!("expected error"),
1902 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),