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` messages.
12 //! A [`Bolt12Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid"
13 //! flow or from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment
14 //! then sends the invoice to the intended payer, who will then pay it.
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
20 //! extern crate bitcoin;
21 //! extern crate lightning;
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::blinded_path::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPayInfo, BlindedPath)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49 .respond_with(payment_paths, payment_hash)?
51 #![cfg_attr(not(feature = "std"), doc = "
52 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
54 //! .relative_expiry(3600)
56 //! .fallback_v0_p2wpkh(&wpubkey_hash)
58 //! .sign::<_, Infallible>(
59 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
61 //! .expect("failed verifying signature")
62 //! .write(&mut buffer)
67 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
68 //! # let payment_paths = create_payment_paths();
69 //! # let payment_hash = create_payment_hash();
70 //! # let secp_ctx = Secp256k1::new();
71 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
72 //! # let pubkey = PublicKey::from(keys);
73 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
74 //! # let mut buffer = Vec::new();
76 //! // Invoice for the "offer for money" flow.
78 //! .parse::<Refund>()?
79 #![cfg_attr(feature = "std", doc = "
80 .respond_with(payment_paths, payment_hash, pubkey)?
82 #![cfg_attr(not(feature = "std"), doc = "
83 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
85 //! .relative_expiry(3600)
87 //! .fallback_v0_p2wpkh(&wpubkey_hash)
89 //! .sign::<_, Infallible>(
90 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
92 //! .expect("failed verifying signature")
93 //! .write(&mut buffer)
100 use bitcoin::blockdata::constants::ChainHash;
101 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
102 use bitcoin::hashes::Hash;
103 use bitcoin::network::constants::Network;
104 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
105 use bitcoin::secp256k1::schnorr::Signature;
106 use bitcoin::util::address::{Address, Payload, WitnessVersion};
107 use bitcoin::util::schnorr::TweakedPublicKey;
108 use core::convert::{AsRef, Infallible, TryFrom};
109 use core::time::Duration;
111 use crate::blinded_path::BlindedPath;
112 use crate::ln::PaymentHash;
113 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
114 use crate::ln::inbound_payment::ExpandedKey;
115 use crate::ln::msgs::DecodeError;
116 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
117 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
118 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
119 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
120 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
121 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
122 use crate::offers::signer;
123 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
124 use crate::util::string::PrintableString;
126 use crate::prelude::*;
128 #[cfg(feature = "std")]
129 use std::time::SystemTime;
131 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
133 /// Tag for the hash function used when signing a [`Bolt12Invoice`]'s merkle root.
134 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
136 /// Builds a [`Bolt12Invoice`] from either:
137 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
138 /// - a [`Refund`] for the "offer for money" flow.
140 /// See [module-level documentation] for usage.
142 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
144 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
145 /// [`Refund`]: crate::offers::refund::Refund
146 /// [module-level documentation]: self
147 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
148 invreq_bytes: &'a Vec<u8>,
149 invoice: InvoiceContents,
150 signing_pubkey_strategy: S,
153 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
155 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
156 pub trait SigningPubkeyStrategy {}
158 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
160 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
161 pub struct ExplicitSigningPubkey {}
163 /// [`Bolt12Invoice::signing_pubkey`] was derived.
165 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
166 pub struct DerivedSigningPubkey(KeyPair);
168 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
169 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
171 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
172 pub(super) fn for_offer(
173 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
174 created_at: Duration, payment_hash: PaymentHash
175 ) -> Result<Self, Bolt12SemanticError> {
176 let amount_msats = Self::check_amount_msats(invoice_request)?;
177 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
178 let contents = InvoiceContents::ForOffer {
179 invoice_request: invoice_request.contents.clone(),
180 fields: Self::fields(
181 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
185 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
188 pub(super) fn for_refund(
189 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
190 payment_hash: PaymentHash, signing_pubkey: PublicKey
191 ) -> Result<Self, Bolt12SemanticError> {
192 let amount_msats = refund.amount_msats();
193 let contents = InvoiceContents::ForRefund {
194 refund: refund.contents.clone(),
195 fields: Self::fields(
196 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
200 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
204 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
205 pub(super) fn for_offer_using_keys(
206 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
207 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
208 ) -> Result<Self, Bolt12SemanticError> {
209 let amount_msats = Self::check_amount_msats(invoice_request)?;
210 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
211 let contents = InvoiceContents::ForOffer {
212 invoice_request: invoice_request.contents.clone(),
213 fields: Self::fields(
214 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
218 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
221 pub(super) fn for_refund_using_keys(
222 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
223 payment_hash: PaymentHash, keys: KeyPair,
224 ) -> Result<Self, Bolt12SemanticError> {
225 let amount_msats = refund.amount_msats();
226 let signing_pubkey = keys.public_key();
227 let contents = InvoiceContents::ForRefund {
228 refund: refund.contents.clone(),
229 fields: Self::fields(
230 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
234 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
238 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
239 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, Bolt12SemanticError> {
240 match invoice_request.amount_msats() {
241 Some(amount_msats) => Ok(amount_msats),
242 None => match invoice_request.contents.inner.offer.amount() {
243 Some(Amount::Bitcoin { amount_msats }) => {
244 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
245 .ok_or(Bolt12SemanticError::InvalidAmount)
247 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
248 None => Err(Bolt12SemanticError::MissingAmount),
254 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
255 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
258 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
259 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
264 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: S
265 ) -> Result<Self, Bolt12SemanticError> {
266 if contents.fields().payment_paths.is_empty() {
267 return Err(Bolt12SemanticError::MissingPaths);
270 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
273 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
274 /// Any expiry that has already passed is valid and can be checked for using
275 /// [`Bolt12Invoice::is_expired`].
277 /// Successive calls to this method will override the previous setting.
278 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
279 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
280 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
284 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
286 /// Successive calls to this method will add another address. Caller is responsible for not
287 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
288 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
289 let address = FallbackAddress {
290 version: WitnessVersion::V0.to_num(),
291 program: Vec::from(&script_hash.into_inner()[..]),
293 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
297 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
299 /// Successive calls to this method will add another address. Caller is responsible for not
300 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
301 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
302 let address = FallbackAddress {
303 version: WitnessVersion::V0.to_num(),
304 program: Vec::from(&pubkey_hash.into_inner()[..]),
306 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
310 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
312 /// Successive calls to this method will add another address. Caller is responsible for not
313 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
314 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
315 let address = FallbackAddress {
316 version: WitnessVersion::V1.to_num(),
317 program: Vec::from(&output_key.serialize()[..]),
319 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
323 /// Sets [`Bolt12Invoice::invoice_features`] to indicate MPP may be used. Otherwise, MPP is
325 pub fn allow_mpp(mut self) -> Self {
326 self.invoice.fields_mut().features.set_basic_mpp_optional();
331 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
332 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
333 /// [`UnsignedBolt12Invoice::sign`].
334 pub fn build(self) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
335 #[cfg(feature = "std")] {
336 if self.invoice.is_offer_or_refund_expired() {
337 return Err(Bolt12SemanticError::AlreadyExpired);
341 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
342 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
346 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
347 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
348 pub fn build_and_sign<T: secp256k1::Signing>(
349 self, secp_ctx: &Secp256k1<T>
350 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
351 #[cfg(feature = "std")] {
352 if self.invoice.is_offer_or_refund_expired() {
353 return Err(Bolt12SemanticError::AlreadyExpired);
358 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
360 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
362 let invoice = unsigned_invoice
363 .sign::<_, Infallible>(
364 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
371 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
375 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
376 /// such, it may include unknown, odd TLV records.
377 pub struct UnsignedBolt12Invoice {
379 contents: InvoiceContents,
380 tagged_hash: TaggedHash,
383 impl UnsignedBolt12Invoice {
384 fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
385 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
386 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
388 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
389 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
390 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
392 let mut bytes = Vec::new();
393 unsigned_tlv_stream.write(&mut bytes).unwrap();
395 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
397 Self { bytes, contents, tagged_hash }
400 /// Signs the [`TaggedHash`] of the invoice using the given function.
402 /// Note: The hash computation may have included unknown, odd TLV records.
404 /// This is not exported to bindings users as functions aren't currently mapped.
405 pub fn sign<F, E>(mut self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
407 F: FnOnce(&Self) -> Result<Signature, E>
409 let pubkey = self.contents.fields().signing_pubkey;
410 let signature = merkle::sign_message(sign, &self, pubkey)?;
412 // Append the signature TLV record to the bytes.
413 let signature_tlv_stream = SignatureTlvStreamRef {
414 signature: Some(&signature),
416 signature_tlv_stream.write(&mut self.bytes).unwrap();
420 contents: self.contents,
426 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
427 fn as_ref(&self) -> &TaggedHash {
432 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
434 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
435 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
437 /// [`Offer`]: crate::offers::offer::Offer
438 /// [`Refund`]: crate::offers::refund::Refund
439 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
440 #[derive(Clone, Debug)]
441 #[cfg_attr(test, derive(PartialEq))]
442 pub struct Bolt12Invoice {
444 contents: InvoiceContents,
445 signature: Signature,
448 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
450 /// [`Offer`]: crate::offers::offer::Offer
451 /// [`Refund`]: crate::offers::refund::Refund
452 #[derive(Clone, Debug)]
453 #[cfg_attr(test, derive(PartialEq))]
454 enum InvoiceContents {
455 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
457 /// [`Offer`]: crate::offers::offer::Offer
459 invoice_request: InvoiceRequestContents,
460 fields: InvoiceFields,
462 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
464 /// [`Refund`]: crate::offers::refund::Refund
466 refund: RefundContents,
467 fields: InvoiceFields,
471 /// Invoice-specific fields for an `invoice` message.
472 #[derive(Clone, Debug, PartialEq)]
473 struct InvoiceFields {
474 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
475 created_at: Duration,
476 relative_expiry: Option<Duration>,
477 payment_hash: PaymentHash,
479 fallbacks: Option<Vec<FallbackAddress>>,
480 features: Bolt12InvoiceFeatures,
481 signing_pubkey: PublicKey,
484 macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
485 /// A complete description of the purpose of the originating offer or refund. Intended to be
486 /// displayed to the user but with the caveat that it has not been verified in any way.
487 pub fn description(&$self) -> PrintableString {
488 $contents.description()
491 /// Paths to the recipient originating from publicly reachable nodes, including information
492 /// needed for routing payments across them.
494 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
495 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
497 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
498 /// matched in another language.
499 pub fn payment_paths(&$self) -> &[(BlindedPayInfo, BlindedPath)] {
500 $contents.payment_paths()
503 /// Duration since the Unix epoch when the invoice was created.
504 pub fn created_at(&$self) -> Duration {
505 $contents.created_at()
508 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
509 /// should no longer be paid.
510 pub fn relative_expiry(&$self) -> Duration {
511 $contents.relative_expiry()
514 /// Whether the invoice has expired.
515 #[cfg(feature = "std")]
516 pub fn is_expired(&$self) -> bool {
517 $contents.is_expired()
520 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
521 pub fn payment_hash(&$self) -> PaymentHash {
522 $contents.payment_hash()
525 /// The minimum amount required for a successful payment of the invoice.
526 pub fn amount_msats(&$self) -> u64 {
527 $contents.amount_msats()
530 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
532 pub fn fallbacks(&$self) -> Vec<Address> {
533 $contents.fallbacks()
536 /// Features pertaining to paying an invoice.
537 pub fn invoice_features(&$self) -> &Bolt12InvoiceFeatures {
541 /// The public key corresponding to the key used to sign the invoice.
542 pub fn signing_pubkey(&$self) -> PublicKey {
543 $contents.signing_pubkey()
547 impl UnsignedBolt12Invoice {
548 invoice_accessors!(self, self.contents);
552 invoice_accessors!(self, self.contents);
554 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
555 pub fn signature(&self) -> Signature {
559 /// Hash that was used for signing the invoice.
560 pub fn signable_hash(&self) -> [u8; 32] {
561 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
564 /// Verifies that the invoice was for a request or refund created using the given key.
565 pub fn verify<T: secp256k1::Signing>(
566 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
568 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
572 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
573 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
574 self.contents.as_tlv_stream();
575 let signature_tlv_stream = SignatureTlvStreamRef {
576 signature: Some(&self.signature),
578 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
579 signature_tlv_stream)
583 impl InvoiceContents {
584 /// Whether the original offer or refund has expired.
585 #[cfg(feature = "std")]
586 fn is_offer_or_refund_expired(&self) -> bool {
588 InvoiceContents::ForOffer { invoice_request, .. } =>
589 invoice_request.inner.offer.is_expired(),
590 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
594 fn chain(&self) -> ChainHash {
596 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
597 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
601 fn description(&self) -> PrintableString {
603 InvoiceContents::ForOffer { invoice_request, .. } => {
604 invoice_request.inner.offer.description()
606 InvoiceContents::ForRefund { refund, .. } => refund.description(),
610 fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
611 &self.fields().payment_paths[..]
614 fn created_at(&self) -> Duration {
615 self.fields().created_at
618 fn relative_expiry(&self) -> Duration {
619 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
622 #[cfg(feature = "std")]
623 fn is_expired(&self) -> bool {
624 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
625 match absolute_expiry {
626 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
627 Ok(elapsed) => elapsed > seconds_from_epoch,
634 fn payment_hash(&self) -> PaymentHash {
635 self.fields().payment_hash
638 fn amount_msats(&self) -> u64 {
639 self.fields().amount_msats
642 fn fallbacks(&self) -> Vec<Address> {
643 let chain = self.chain();
644 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
646 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
648 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
650 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
656 let to_valid_address = |address: &FallbackAddress| {
657 let version = match WitnessVersion::try_from(address.version) {
658 Ok(version) => version,
659 Err(_) => return None,
662 let program = &address.program;
663 if program.len() < 2 || program.len() > 40 {
667 let address = Address {
668 payload: Payload::WitnessProgram {
670 program: program.clone(),
675 if !address.is_standard() && version == WitnessVersion::V0 {
682 self.fields().fallbacks
684 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
685 .unwrap_or_else(Vec::new)
688 fn features(&self) -> &Bolt12InvoiceFeatures {
689 &self.fields().features
692 fn signing_pubkey(&self) -> PublicKey {
693 self.fields().signing_pubkey
696 fn fields(&self) -> &InvoiceFields {
698 InvoiceContents::ForOffer { fields, .. } => fields,
699 InvoiceContents::ForRefund { fields, .. } => fields,
703 fn fields_mut(&mut self) -> &mut InvoiceFields {
705 InvoiceContents::ForOffer { fields, .. } => fields,
706 InvoiceContents::ForRefund { fields, .. } => fields,
710 fn verify<T: secp256k1::Signing>(
711 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
713 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
714 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
715 match record.r#type {
716 PAYER_METADATA_TYPE => false, // Should be outside range
717 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
721 let tlv_stream = offer_records.chain(invreq_records);
723 let (metadata, payer_id, iv_bytes) = match self {
724 InvoiceContents::ForOffer { invoice_request, .. } => {
725 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
727 InvoiceContents::ForRefund { refund, .. } => {
728 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
732 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
738 fn derives_keys(&self) -> bool {
740 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
741 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
745 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
746 let (payer, offer, invoice_request) = match self {
747 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
748 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
750 let invoice = self.fields().as_tlv_stream();
752 (payer, offer, invoice_request, invoice)
757 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
759 if self.features == Bolt12InvoiceFeatures::empty() { None }
760 else { Some(&self.features) }
763 InvoiceTlvStreamRef {
764 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
765 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
766 created_at: Some(self.created_at.as_secs()),
767 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
768 payment_hash: Some(&self.payment_hash),
769 amount: Some(self.amount_msats),
770 fallbacks: self.fallbacks.as_ref(),
772 node_id: Some(&self.signing_pubkey),
777 impl Writeable for UnsignedBolt12Invoice {
778 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
779 WithoutLength(&self.bytes).write(writer)
783 impl Writeable for Bolt12Invoice {
784 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
785 WithoutLength(&self.bytes).write(writer)
789 impl Writeable for InvoiceContents {
790 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
791 self.as_tlv_stream().write(writer)
795 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
796 type Error = Bolt12ParseError;
798 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
799 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
800 let ParsedMessage { bytes, tlv_stream } = invoice;
802 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
804 let contents = InvoiceContents::try_from(
805 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
808 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
810 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
814 impl TryFrom<Vec<u8>> for Bolt12Invoice {
815 type Error = Bolt12ParseError;
817 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
818 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
819 Bolt12Invoice::try_from(parsed_invoice)
823 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
824 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
825 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
826 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
827 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
828 (168, payment_hash: PaymentHash),
829 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
830 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
831 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
832 (176, node_id: PublicKey),
835 type BlindedPathIter<'a> = core::iter::Map<
836 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
837 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
840 type BlindedPayInfoIter<'a> = core::iter::Map<
841 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
842 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
845 /// Information needed to route a payment across a [`BlindedPath`].
846 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
847 pub struct BlindedPayInfo {
848 /// Base fee charged (in millisatoshi) for the entire blinded path.
849 pub fee_base_msat: u32,
851 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
852 /// (i.e., 10,000 is 1%).
853 pub fee_proportional_millionths: u32,
855 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
857 pub cltv_expiry_delta: u16,
859 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
860 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
861 /// seen by the recipient.
862 pub htlc_minimum_msat: u64,
864 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
865 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
866 /// seen by the recipient.
867 pub htlc_maximum_msat: u64,
869 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
871 pub features: BlindedHopFeatures,
874 impl_writeable!(BlindedPayInfo, {
876 fee_proportional_millionths,
883 /// Wire representation for an on-chain fallback address.
884 #[derive(Clone, Debug, PartialEq)]
885 pub(super) struct FallbackAddress {
890 impl_writeable!(FallbackAddress, { version, program });
892 type FullInvoiceTlvStream =
893 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
896 type FullInvoiceTlvStreamRef<'a> = (
897 PayerTlvStreamRef<'a>,
898 OfferTlvStreamRef<'a>,
899 InvoiceRequestTlvStreamRef<'a>,
900 InvoiceTlvStreamRef<'a>,
901 SignatureTlvStreamRef<'a>,
904 impl SeekReadable for FullInvoiceTlvStream {
905 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
906 let payer = SeekReadable::read(r)?;
907 let offer = SeekReadable::read(r)?;
908 let invoice_request = SeekReadable::read(r)?;
909 let invoice = SeekReadable::read(r)?;
910 let signature = SeekReadable::read(r)?;
912 Ok((payer, offer, invoice_request, invoice, signature))
916 type PartialInvoiceTlvStream =
917 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
919 type PartialInvoiceTlvStreamRef<'a> = (
920 PayerTlvStreamRef<'a>,
921 OfferTlvStreamRef<'a>,
922 InvoiceRequestTlvStreamRef<'a>,
923 InvoiceTlvStreamRef<'a>,
926 impl SeekReadable for PartialInvoiceTlvStream {
927 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
928 let payer = SeekReadable::read(r)?;
929 let offer = SeekReadable::read(r)?;
930 let invoice_request = SeekReadable::read(r)?;
931 let invoice = SeekReadable::read(r)?;
933 Ok((payer, offer, invoice_request, invoice))
937 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
938 type Error = Bolt12ParseError;
940 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
941 let ParsedMessage { bytes, tlv_stream } = invoice;
943 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
944 SignatureTlvStream { signature },
946 let contents = InvoiceContents::try_from(
947 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
950 let signature = match signature {
951 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
952 Some(signature) => signature,
954 let pubkey = contents.fields().signing_pubkey;
955 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
957 Ok(Bolt12Invoice { bytes, contents, signature })
961 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
962 type Error = Bolt12SemanticError;
964 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
968 invoice_request_tlv_stream,
970 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
975 let payment_paths = match (blindedpay, paths) {
976 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
977 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
978 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
979 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
980 return Err(Bolt12SemanticError::InvalidPayInfo);
982 (Some(blindedpay), Some(paths)) => {
983 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
987 let created_at = match created_at {
988 None => return Err(Bolt12SemanticError::MissingCreationTime),
989 Some(timestamp) => Duration::from_secs(timestamp),
992 let relative_expiry = relative_expiry
993 .map(Into::<u64>::into)
994 .map(Duration::from_secs);
996 let payment_hash = match payment_hash {
997 None => return Err(Bolt12SemanticError::MissingPaymentHash),
998 Some(payment_hash) => payment_hash,
1001 let amount_msats = match amount {
1002 None => return Err(Bolt12SemanticError::MissingAmount),
1003 Some(amount) => amount,
1006 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1008 let signing_pubkey = match node_id {
1009 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1010 Some(node_id) => node_id,
1013 let fields = InvoiceFields {
1014 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1015 features, signing_pubkey,
1018 match offer_tlv_stream.node_id {
1019 Some(expected_signing_pubkey) => {
1020 if fields.signing_pubkey != expected_signing_pubkey {
1021 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1024 let invoice_request = InvoiceRequestContents::try_from(
1025 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1027 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1030 let refund = RefundContents::try_from(
1031 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1033 Ok(InvoiceContents::ForRefund { refund, fields })
1041 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1043 use bitcoin::blockdata::script::Script;
1044 use bitcoin::hashes::Hash;
1045 use bitcoin::network::constants::Network;
1046 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
1047 use bitcoin::util::address::{Address, Payload, WitnessVersion};
1048 use bitcoin::util::schnorr::TweakedPublicKey;
1049 use core::convert::TryFrom;
1050 use core::time::Duration;
1051 use crate::blinded_path::{BlindedHop, BlindedPath};
1052 use crate::sign::KeyMaterial;
1053 use crate::ln::features::Bolt12InvoiceFeatures;
1054 use crate::ln::inbound_payment::ExpandedKey;
1055 use crate::ln::msgs::DecodeError;
1056 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1057 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
1058 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
1059 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1060 use crate::offers::payer::PayerTlvStreamRef;
1061 use crate::offers::refund::RefundBuilder;
1062 use crate::offers::test_utils::*;
1063 use crate::util::ser::{BigSize, Iterable, Writeable};
1064 use crate::util::string::PrintableString;
1067 fn to_bytes(&self) -> Vec<u8>;
1070 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1071 fn to_bytes(&self) -> Vec<u8> {
1072 let mut buffer = Vec::new();
1073 self.0.write(&mut buffer).unwrap();
1074 self.1.write(&mut buffer).unwrap();
1075 self.2.write(&mut buffer).unwrap();
1076 self.3.write(&mut buffer).unwrap();
1077 self.4.write(&mut buffer).unwrap();
1083 fn builds_invoice_for_offer_with_defaults() {
1084 let payment_paths = payment_paths();
1085 let payment_hash = payment_hash();
1087 let unsigned_invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1090 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1092 .sign(payer_sign).unwrap()
1093 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1096 let mut buffer = Vec::new();
1097 unsigned_invoice.write(&mut buffer).unwrap();
1099 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1100 assert_eq!(unsigned_invoice.description(), PrintableString("foo"));
1101 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1102 assert_eq!(unsigned_invoice.created_at(), now);
1103 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1104 #[cfg(feature = "std")]
1105 assert!(!unsigned_invoice.is_expired());
1106 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1107 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1108 assert_eq!(unsigned_invoice.fallbacks(), vec![]);
1109 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1110 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1112 match UnsignedBolt12Invoice::try_from(buffer) {
1113 Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1115 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1116 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1120 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1122 let mut buffer = Vec::new();
1123 invoice.write(&mut buffer).unwrap();
1125 assert_eq!(invoice.bytes, buffer.as_slice());
1126 assert_eq!(invoice.description(), PrintableString("foo"));
1127 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1128 assert_eq!(invoice.created_at(), now);
1129 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1130 #[cfg(feature = "std")]
1131 assert!(!invoice.is_expired());
1132 assert_eq!(invoice.payment_hash(), payment_hash);
1133 assert_eq!(invoice.amount_msats(), 1000);
1134 assert_eq!(invoice.fallbacks(), vec![]);
1135 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1136 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1138 merkle::verify_signature(
1139 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1143 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1144 let pubkey = recipient_pubkey().into();
1145 let secp_ctx = Secp256k1::verification_only();
1146 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1149 invoice.as_tlv_stream(),
1151 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1157 description: Some(&String::from("foo")),
1159 absolute_expiry: None,
1163 node_id: Some(&recipient_pubkey()),
1165 InvoiceRequestTlvStreamRef {
1170 payer_id: Some(&payer_pubkey()),
1173 InvoiceTlvStreamRef {
1174 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1175 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1176 created_at: Some(now.as_secs()),
1177 relative_expiry: None,
1178 payment_hash: Some(&payment_hash),
1182 node_id: Some(&recipient_pubkey()),
1184 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1188 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1189 panic!("error parsing invoice: {:?}", e);
1194 fn builds_invoice_for_refund_with_defaults() {
1195 let payment_paths = payment_paths();
1196 let payment_hash = payment_hash();
1198 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1200 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1203 .sign(recipient_sign).unwrap();
1205 let mut buffer = Vec::new();
1206 invoice.write(&mut buffer).unwrap();
1208 assert_eq!(invoice.bytes, buffer.as_slice());
1209 assert_eq!(invoice.description(), PrintableString("foo"));
1210 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1211 assert_eq!(invoice.created_at(), now);
1212 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1213 #[cfg(feature = "std")]
1214 assert!(!invoice.is_expired());
1215 assert_eq!(invoice.payment_hash(), payment_hash);
1216 assert_eq!(invoice.amount_msats(), 1000);
1217 assert_eq!(invoice.fallbacks(), vec![]);
1218 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1219 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1221 merkle::verify_signature(
1222 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1227 invoice.as_tlv_stream(),
1229 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1235 description: Some(&String::from("foo")),
1237 absolute_expiry: None,
1243 InvoiceRequestTlvStreamRef {
1248 payer_id: Some(&payer_pubkey()),
1251 InvoiceTlvStreamRef {
1252 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1253 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1254 created_at: Some(now.as_secs()),
1255 relative_expiry: None,
1256 payment_hash: Some(&payment_hash),
1260 node_id: Some(&recipient_pubkey()),
1262 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1266 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1267 panic!("error parsing invoice: {:?}", e);
1271 #[cfg(feature = "std")]
1273 fn builds_invoice_from_offer_with_expiration() {
1274 let future_expiry = Duration::from_secs(u64::max_value());
1275 let past_expiry = Duration::from_secs(0);
1277 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1279 .absolute_expiry(future_expiry)
1281 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1283 .sign(payer_sign).unwrap()
1284 .respond_with(payment_paths(), payment_hash())
1288 panic!("error building invoice: {:?}", e);
1291 match OfferBuilder::new("foo".into(), recipient_pubkey())
1293 .absolute_expiry(past_expiry)
1295 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1297 .sign(payer_sign).unwrap()
1298 .respond_with(payment_paths(), payment_hash())
1302 Ok(_) => panic!("expected error"),
1303 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1307 #[cfg(feature = "std")]
1309 fn builds_invoice_from_refund_with_expiration() {
1310 let future_expiry = Duration::from_secs(u64::max_value());
1311 let past_expiry = Duration::from_secs(0);
1313 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1314 .absolute_expiry(future_expiry)
1316 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1320 panic!("error building invoice: {:?}", e);
1323 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1324 .absolute_expiry(past_expiry)
1326 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1330 Ok(_) => panic!("expected error"),
1331 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1336 fn builds_invoice_from_offer_using_derived_keys() {
1337 let desc = "foo".to_string();
1338 let node_id = recipient_pubkey();
1339 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1340 let entropy = FixedEntropy {};
1341 let secp_ctx = Secp256k1::new();
1343 let blinded_path = BlindedPath {
1344 introduction_node_id: pubkey(40),
1345 blinding_point: pubkey(41),
1347 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1348 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1352 let offer = OfferBuilder
1353 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1357 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359 .sign(payer_sign).unwrap();
1361 if let Err(e) = invoice_request
1362 .verify_and_respond_using_derived_keys_no_std(
1363 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1366 .build_and_sign(&secp_ctx)
1368 panic!("error building invoice: {:?}", e);
1371 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1372 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1373 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1375 Ok(_) => panic!("expected error"),
1376 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1379 let desc = "foo".to_string();
1380 let offer = OfferBuilder
1381 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1384 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1386 .sign(payer_sign).unwrap();
1388 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1389 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1391 Ok(_) => panic!("expected error"),
1392 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1397 fn builds_invoice_from_refund_using_derived_keys() {
1398 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1399 let entropy = FixedEntropy {};
1400 let secp_ctx = Secp256k1::new();
1402 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1405 if let Err(e) = refund
1406 .respond_using_derived_keys_no_std(
1407 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1410 .build_and_sign(&secp_ctx)
1412 panic!("error building invoice: {:?}", e);
1417 fn builds_invoice_with_relative_expiry() {
1419 let one_hour = Duration::from_secs(3600);
1421 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1424 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1426 .sign(payer_sign).unwrap()
1427 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1428 .relative_expiry(one_hour.as_secs() as u32)
1430 .sign(recipient_sign).unwrap();
1431 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1432 #[cfg(feature = "std")]
1433 assert!(!invoice.is_expired());
1434 assert_eq!(invoice.relative_expiry(), one_hour);
1435 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1437 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1440 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442 .sign(payer_sign).unwrap()
1443 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1444 .relative_expiry(one_hour.as_secs() as u32 - 1)
1446 .sign(recipient_sign).unwrap();
1447 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1448 #[cfg(feature = "std")]
1449 assert!(invoice.is_expired());
1450 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1451 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1455 fn builds_invoice_with_amount_from_request() {
1456 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1459 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1460 .amount_msats(1001).unwrap()
1462 .sign(payer_sign).unwrap()
1463 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1465 .sign(recipient_sign).unwrap();
1466 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1467 assert_eq!(invoice.amount_msats(), 1001);
1468 assert_eq!(tlv_stream.amount, Some(1001));
1472 fn builds_invoice_with_quantity_from_request() {
1473 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1475 .supported_quantity(Quantity::Unbounded)
1477 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1478 .quantity(2).unwrap()
1480 .sign(payer_sign).unwrap()
1481 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1483 .sign(recipient_sign).unwrap();
1484 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1485 assert_eq!(invoice.amount_msats(), 2000);
1486 assert_eq!(tlv_stream.amount, Some(2000));
1488 match OfferBuilder::new("foo".into(), recipient_pubkey())
1490 .supported_quantity(Quantity::Unbounded)
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .quantity(u64::max_value()).unwrap()
1495 .sign(payer_sign).unwrap()
1496 .respond_with_no_std(payment_paths(), payment_hash(), now())
1498 Ok(_) => panic!("expected error"),
1499 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1504 fn builds_invoice_with_fallback_address() {
1505 let script = Script::new();
1506 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1507 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1508 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1510 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1513 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1515 .sign(payer_sign).unwrap()
1516 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1517 .fallback_v0_p2wsh(&script.wscript_hash())
1518 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1519 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1521 .sign(recipient_sign).unwrap();
1522 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1524 invoice.fallbacks(),
1526 Address::p2wsh(&script, Network::Bitcoin),
1527 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1528 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1532 tlv_stream.fallbacks,
1535 version: WitnessVersion::V0.to_num(),
1536 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1539 version: WitnessVersion::V0.to_num(),
1540 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1543 version: WitnessVersion::V1.to_num(),
1544 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1551 fn builds_invoice_with_allow_mpp() {
1552 let mut features = Bolt12InvoiceFeatures::empty();
1553 features.set_basic_mpp_optional();
1555 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1558 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1560 .sign(payer_sign).unwrap()
1561 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1564 .sign(recipient_sign).unwrap();
1565 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1566 assert_eq!(invoice.invoice_features(), &features);
1567 assert_eq!(tlv_stream.features, Some(&features));
1571 fn fails_signing_invoice() {
1572 match OfferBuilder::new("foo".into(), recipient_pubkey())
1575 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1577 .sign(payer_sign).unwrap()
1578 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1582 Ok(_) => panic!("expected error"),
1583 Err(e) => assert_eq!(e, SignError::Signing(())),
1586 match OfferBuilder::new("foo".into(), recipient_pubkey())
1589 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1591 .sign(payer_sign).unwrap()
1592 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1596 Ok(_) => panic!("expected error"),
1597 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1602 fn parses_invoice_with_payment_paths() {
1603 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1606 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1608 .sign(payer_sign).unwrap()
1609 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1611 .sign(recipient_sign).unwrap();
1613 let mut buffer = Vec::new();
1614 invoice.write(&mut buffer).unwrap();
1616 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1617 panic!("error parsing invoice: {:?}", e);
1620 let mut tlv_stream = invoice.as_tlv_stream();
1621 tlv_stream.3.paths = None;
1623 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1624 Ok(_) => panic!("expected error"),
1625 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1628 let mut tlv_stream = invoice.as_tlv_stream();
1629 tlv_stream.3.blindedpay = None;
1631 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1632 Ok(_) => panic!("expected error"),
1633 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1636 let empty_payment_paths = vec![];
1637 let mut tlv_stream = invoice.as_tlv_stream();
1638 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1640 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1641 Ok(_) => panic!("expected error"),
1642 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1645 let mut payment_paths = payment_paths();
1646 payment_paths.pop();
1647 let mut tlv_stream = invoice.as_tlv_stream();
1648 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1650 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1651 Ok(_) => panic!("expected error"),
1652 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1657 fn parses_invoice_with_created_at() {
1658 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1661 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1663 .sign(payer_sign).unwrap()
1664 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1666 .sign(recipient_sign).unwrap();
1668 let mut buffer = Vec::new();
1669 invoice.write(&mut buffer).unwrap();
1671 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1672 panic!("error parsing invoice: {:?}", e);
1675 let mut tlv_stream = invoice.as_tlv_stream();
1676 tlv_stream.3.created_at = None;
1678 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1679 Ok(_) => panic!("expected error"),
1681 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1687 fn parses_invoice_with_relative_expiry() {
1688 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1691 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1693 .sign(payer_sign).unwrap()
1694 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1695 .relative_expiry(3600)
1697 .sign(recipient_sign).unwrap();
1699 let mut buffer = Vec::new();
1700 invoice.write(&mut buffer).unwrap();
1702 match Bolt12Invoice::try_from(buffer) {
1703 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1704 Err(e) => panic!("error parsing invoice: {:?}", e),
1709 fn parses_invoice_with_payment_hash() {
1710 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1713 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715 .sign(payer_sign).unwrap()
1716 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1718 .sign(recipient_sign).unwrap();
1720 let mut buffer = Vec::new();
1721 invoice.write(&mut buffer).unwrap();
1723 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1724 panic!("error parsing invoice: {:?}", e);
1727 let mut tlv_stream = invoice.as_tlv_stream();
1728 tlv_stream.3.payment_hash = None;
1730 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1731 Ok(_) => panic!("expected error"),
1733 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1739 fn parses_invoice_with_amount() {
1740 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1743 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1745 .sign(payer_sign).unwrap()
1746 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1748 .sign(recipient_sign).unwrap();
1750 let mut buffer = Vec::new();
1751 invoice.write(&mut buffer).unwrap();
1753 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1754 panic!("error parsing invoice: {:?}", e);
1757 let mut tlv_stream = invoice.as_tlv_stream();
1758 tlv_stream.3.amount = None;
1760 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1761 Ok(_) => panic!("expected error"),
1762 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1767 fn parses_invoice_with_allow_mpp() {
1768 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1771 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1773 .sign(payer_sign).unwrap()
1774 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1777 .sign(recipient_sign).unwrap();
1779 let mut buffer = Vec::new();
1780 invoice.write(&mut buffer).unwrap();
1782 match Bolt12Invoice::try_from(buffer) {
1784 let mut features = Bolt12InvoiceFeatures::empty();
1785 features.set_basic_mpp_optional();
1786 assert_eq!(invoice.invoice_features(), &features);
1788 Err(e) => panic!("error parsing invoice: {:?}", e),
1793 fn parses_invoice_with_fallback_address() {
1794 let script = Script::new();
1795 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1796 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1797 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1799 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1802 let invoice_request = offer
1803 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1805 .sign(payer_sign).unwrap();
1806 let mut invoice_builder = invoice_request
1807 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1808 .fallback_v0_p2wsh(&script.wscript_hash())
1809 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1810 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
1812 // Only standard addresses will be included.
1813 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
1814 // Non-standard addresses
1815 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1816 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1817 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1819 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1820 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1822 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
1823 let mut buffer = Vec::new();
1824 invoice.write(&mut buffer).unwrap();
1826 match Bolt12Invoice::try_from(buffer) {
1829 invoice.fallbacks(),
1831 Address::p2wsh(&script, Network::Bitcoin),
1832 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1833 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1835 payload: Payload::WitnessProgram {
1836 version: WitnessVersion::V1,
1837 program: vec![0u8; 33],
1839 network: Network::Bitcoin,
1842 payload: Payload::WitnessProgram {
1843 version: WitnessVersion::V2,
1844 program: vec![0u8; 40],
1846 network: Network::Bitcoin,
1851 Err(e) => panic!("error parsing invoice: {:?}", e),
1856 fn parses_invoice_with_node_id() {
1857 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1860 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1862 .sign(payer_sign).unwrap()
1863 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1865 .sign(recipient_sign).unwrap();
1867 let mut buffer = Vec::new();
1868 invoice.write(&mut buffer).unwrap();
1870 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1871 panic!("error parsing invoice: {:?}", e);
1874 let mut tlv_stream = invoice.as_tlv_stream();
1875 tlv_stream.3.node_id = None;
1877 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1878 Ok(_) => panic!("expected error"),
1880 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1884 let invalid_pubkey = payer_pubkey();
1885 let mut tlv_stream = invoice.as_tlv_stream();
1886 tlv_stream.3.node_id = Some(&invalid_pubkey);
1888 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1889 Ok(_) => panic!("expected error"),
1891 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1897 fn fails_parsing_invoice_without_signature() {
1898 let mut buffer = Vec::new();
1899 OfferBuilder::new("foo".into(), recipient_pubkey())
1902 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1904 .sign(payer_sign).unwrap()
1905 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1908 .write(&mut buffer).unwrap();
1910 match Bolt12Invoice::try_from(buffer) {
1911 Ok(_) => panic!("expected error"),
1912 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1917 fn fails_parsing_invoice_with_invalid_signature() {
1918 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1921 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1923 .sign(payer_sign).unwrap()
1924 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1926 .sign(recipient_sign).unwrap();
1927 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1928 *last_signature_byte = last_signature_byte.wrapping_add(1);
1930 let mut buffer = Vec::new();
1931 invoice.write(&mut buffer).unwrap();
1933 match Bolt12Invoice::try_from(buffer) {
1934 Ok(_) => panic!("expected error"),
1936 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1942 fn fails_parsing_invoice_with_extra_tlv_records() {
1943 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1946 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1948 .sign(payer_sign).unwrap()
1949 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1951 .sign(recipient_sign).unwrap();
1953 let mut encoded_invoice = Vec::new();
1954 invoice.write(&mut encoded_invoice).unwrap();
1955 BigSize(1002).write(&mut encoded_invoice).unwrap();
1956 BigSize(32).write(&mut encoded_invoice).unwrap();
1957 [42u8; 32].write(&mut encoded_invoice).unwrap();
1959 match Bolt12Invoice::try_from(encoded_invoice) {
1960 Ok(_) => panic!("expected error"),
1961 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),