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::TryFrom;
26 //! use lightning::offers::invoice::UnsignedBolt12Invoice;
27 //! use lightning::offers::invoice_request::InvoiceRequest;
28 //! use lightning::offers::refund::Refund;
29 //! use lightning::util::ser::Writeable;
31 //! # use lightning::ln::types::PaymentHash;
32 //! # use lightning::offers::invoice::{BlindedPayInfo, ExplicitSigningPubkey, InvoiceBuilder};
33 //! # use lightning::blinded_path::BlindedPath;
35 //! # fn create_payment_paths() -> Vec<(BlindedPayInfo, BlindedPath)> { unimplemented!() }
36 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
38 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
39 //! let payment_paths = create_payment_paths();
40 //! let payment_hash = create_payment_hash();
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
43 //! let pubkey = PublicKey::from(keys);
44 //! let wpubkey_hash = bitcoin::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
45 //! let mut buffer = Vec::new();
47 //! // Invoice for the "offer to be paid" flow.
48 //! # <InvoiceBuilder<ExplicitSigningPubkey>>::from(
49 //! InvoiceRequest::try_from(bytes)?
50 #![cfg_attr(feature = "std", doc = "
51 .respond_with(payment_paths, payment_hash)?
53 #![cfg_attr(not(feature = "std"), doc = "
54 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
57 //! .relative_expiry(3600)
59 //! .fallback_v0_p2wpkh(&wpubkey_hash)
61 //! .sign(|message: &UnsignedBolt12Invoice|
62 //! Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
64 //! .expect("failed verifying signature")
65 //! .write(&mut buffer)
70 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
71 //! # let payment_paths = create_payment_paths();
72 //! # let payment_hash = create_payment_hash();
73 //! # let secp_ctx = Secp256k1::new();
74 //! # let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
75 //! # let pubkey = PublicKey::from(keys);
76 //! # let wpubkey_hash = bitcoin::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
77 //! # let mut buffer = Vec::new();
79 //! // Invoice for the "offer for money" flow.
80 //! # <InvoiceBuilder<ExplicitSigningPubkey>>::from(
82 //! .parse::<Refund>()?
83 #![cfg_attr(feature = "std", doc = "
84 .respond_with(payment_paths, payment_hash, pubkey)?
86 #![cfg_attr(not(feature = "std"), doc = "
87 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
90 //! .relative_expiry(3600)
92 //! .fallback_v0_p2wpkh(&wpubkey_hash)
94 //! .sign(|message: &UnsignedBolt12Invoice|
95 //! Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
97 //! .expect("failed verifying signature")
98 //! .write(&mut buffer)
105 use bitcoin::{WitnessProgram, Network, WitnessVersion};
106 use bitcoin::blockdata::constants::ChainHash;
107 use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, self};
108 use bitcoin::secp256k1::schnorr::Signature;
109 use bitcoin::address::{Address, Payload};
110 use core::time::Duration;
111 use core::hash::{Hash, Hasher};
113 use crate::blinded_path::BlindedPath;
114 use crate::ln::types::PaymentHash;
115 use crate::ln::channelmanager::PaymentId;
116 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
117 use crate::ln::inbound_payment::ExpandedKey;
118 use crate::ln::msgs::DecodeError;
119 use crate::offers::invoice_macros::{invoice_accessors_common, invoice_builder_methods_common};
120 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
121 use crate::offers::merkle::{SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
122 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef, Quantity};
123 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
124 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
125 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
126 use crate::offers::signer;
127 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
128 use crate::util::string::PrintableString;
130 #[allow(unused_imports)]
131 use crate::prelude::*;
133 #[cfg(feature = "std")]
134 use std::time::SystemTime;
136 pub(crate) const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
138 /// Tag for the hash function used when signing a [`Bolt12Invoice`]'s merkle root.
139 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
141 /// Builds a [`Bolt12Invoice`] from either:
142 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
143 /// - a [`Refund`] for the "offer for money" flow.
145 /// See [module-level documentation] for usage.
147 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
149 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
150 /// [`Refund`]: crate::offers::refund::Refund
151 /// [module-level documentation]: self
152 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
153 invreq_bytes: &'a Vec<u8>,
154 invoice: InvoiceContents,
155 signing_pubkey_strategy: S,
158 /// Builds a [`Bolt12Invoice`] from either:
159 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
160 /// - a [`Refund`] for the "offer for money" flow.
162 /// See [module-level documentation] for usage.
164 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
165 /// [`Refund`]: crate::offers::refund::Refund
166 /// [module-level documentation]: self
168 pub struct InvoiceWithExplicitSigningPubkeyBuilder<'a> {
169 invreq_bytes: &'a Vec<u8>,
170 invoice: InvoiceContents,
171 signing_pubkey_strategy: ExplicitSigningPubkey,
174 /// Builds a [`Bolt12Invoice`] from either:
175 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
176 /// - a [`Refund`] for the "offer for money" flow.
178 /// See [module-level documentation] for usage.
180 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
181 /// [`Refund`]: crate::offers::refund::Refund
182 /// [module-level documentation]: self
184 pub struct InvoiceWithDerivedSigningPubkeyBuilder<'a> {
185 invreq_bytes: &'a Vec<u8>,
186 invoice: InvoiceContents,
187 signing_pubkey_strategy: DerivedSigningPubkey,
190 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
192 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
193 pub trait SigningPubkeyStrategy {}
195 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
197 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
198 pub struct ExplicitSigningPubkey {}
200 /// [`Bolt12Invoice::signing_pubkey`] was derived.
202 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
203 pub struct DerivedSigningPubkey(pub(super) Keypair);
205 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
206 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
208 macro_rules! invoice_explicit_signing_pubkey_builder_methods { ($self: ident, $self_type: ty) => {
209 #[cfg_attr(c_bindings, allow(dead_code))]
210 pub(super) fn for_offer(
211 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
212 created_at: Duration, payment_hash: PaymentHash, signing_pubkey: PublicKey
213 ) -> Result<Self, Bolt12SemanticError> {
214 let amount_msats = Self::amount_msats(invoice_request)?;
215 let contents = InvoiceContents::ForOffer {
216 invoice_request: invoice_request.contents.clone(),
217 fields: Self::fields(
218 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
222 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
225 #[cfg_attr(c_bindings, allow(dead_code))]
226 pub(super) fn for_refund(
227 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
228 payment_hash: PaymentHash, signing_pubkey: PublicKey
229 ) -> Result<Self, Bolt12SemanticError> {
230 let amount_msats = refund.amount_msats();
231 let contents = InvoiceContents::ForRefund {
232 refund: refund.contents.clone(),
233 fields: Self::fields(
234 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
238 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
241 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
242 /// [`UnsignedBolt12Invoice::sign`].
243 pub fn build($self: $self_type) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
244 #[cfg(feature = "std")] {
245 if $self.invoice.is_offer_or_refund_expired() {
246 return Err(Bolt12SemanticError::AlreadyExpired);
250 #[cfg(not(feature = "std"))] {
251 if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
252 return Err(Bolt12SemanticError::AlreadyExpired);
256 let Self { invreq_bytes, invoice, .. } = $self;
257 #[cfg(not(c_bindings))] {
258 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
261 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone()))
266 macro_rules! invoice_derived_signing_pubkey_builder_methods { ($self: ident, $self_type: ty) => {
267 #[cfg_attr(c_bindings, allow(dead_code))]
268 pub(super) fn for_offer_using_keys(
269 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
270 created_at: Duration, payment_hash: PaymentHash, keys: Keypair
271 ) -> Result<Self, Bolt12SemanticError> {
272 let amount_msats = Self::amount_msats(invoice_request)?;
273 let signing_pubkey = keys.public_key();
274 let contents = InvoiceContents::ForOffer {
275 invoice_request: invoice_request.contents.clone(),
276 fields: Self::fields(
277 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
281 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
284 #[cfg_attr(c_bindings, allow(dead_code))]
285 pub(super) fn for_refund_using_keys(
286 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
287 payment_hash: PaymentHash, keys: Keypair,
288 ) -> Result<Self, Bolt12SemanticError> {
289 let amount_msats = refund.amount_msats();
290 let signing_pubkey = keys.public_key();
291 let contents = InvoiceContents::ForRefund {
292 refund: refund.contents.clone(),
293 fields: Self::fields(
294 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
298 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
301 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
302 pub fn build_and_sign<T: secp256k1::Signing>(
303 $self: $self_type, secp_ctx: &Secp256k1<T>
304 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
305 #[cfg(feature = "std")] {
306 if $self.invoice.is_offer_or_refund_expired() {
307 return Err(Bolt12SemanticError::AlreadyExpired);
311 #[cfg(not(feature = "std"))] {
312 if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
313 return Err(Bolt12SemanticError::AlreadyExpired);
318 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
320 #[cfg(not(c_bindings))]
321 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
323 let mut unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone());
325 let invoice = unsigned_invoice
326 .sign(|message: &UnsignedBolt12Invoice|
327 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
334 macro_rules! invoice_builder_methods { (
335 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $type_param: ty $(, $self_mut: tt)?
337 pub(crate) fn amount_msats(
338 invoice_request: &InvoiceRequest
339 ) -> Result<u64, Bolt12SemanticError> {
340 match invoice_request.amount_msats() {
341 Some(amount_msats) => Ok(amount_msats),
342 None => match invoice_request.contents.inner.offer.amount() {
343 Some(Amount::Bitcoin { amount_msats }) => {
344 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
345 .ok_or(Bolt12SemanticError::InvalidAmount)
347 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
348 None => Err(Bolt12SemanticError::MissingAmount),
353 #[cfg_attr(c_bindings, allow(dead_code))]
355 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
356 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
359 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
360 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
364 #[cfg_attr(c_bindings, allow(dead_code))]
366 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: $type_param
367 ) -> Result<Self, Bolt12SemanticError> {
368 if contents.fields().payment_paths.is_empty() {
369 return Err(Bolt12SemanticError::MissingPaths);
372 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
376 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
377 invoice_explicit_signing_pubkey_builder_methods!(self, Self);
380 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
381 invoice_derived_signing_pubkey_builder_methods!(self, Self);
384 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
385 invoice_builder_methods!(self, Self, Self, self, S, mut);
386 invoice_builder_methods_common!(self, Self, self.invoice.fields_mut(), Self, self, S, Bolt12Invoice, mut);
389 #[cfg(all(c_bindings, not(test)))]
390 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
391 invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
392 invoice_builder_methods!(self, &mut Self, (), (), ExplicitSigningPubkey);
393 invoice_builder_methods_common!(self, &mut Self, self.invoice.fields_mut(), (), (), ExplicitSigningPubkey, Bolt12Invoice);
396 #[cfg(all(c_bindings, test))]
397 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
398 invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
399 invoice_builder_methods!(self, &mut Self, &mut Self, self, ExplicitSigningPubkey);
400 invoice_builder_methods_common!(self, &mut Self, self.invoice.fields_mut(), &mut Self, self, ExplicitSigningPubkey, Bolt12Invoice);
403 #[cfg(all(c_bindings, not(test)))]
404 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
405 invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
406 invoice_builder_methods!(self, &mut Self, (), (), DerivedSigningPubkey);
407 invoice_builder_methods_common!(self, &mut Self, self.invoice.fields_mut(), (), (), DerivedSigningPubkey, Bolt12Invoice);
410 #[cfg(all(c_bindings, test))]
411 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
412 invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
413 invoice_builder_methods!(self, &mut Self, &mut Self, self, DerivedSigningPubkey);
414 invoice_builder_methods_common!(self, &mut Self, self.invoice.fields_mut(), &mut Self, self, DerivedSigningPubkey, Bolt12Invoice);
418 impl<'a> From<InvoiceWithExplicitSigningPubkeyBuilder<'a>>
419 for InvoiceBuilder<'a, ExplicitSigningPubkey> {
420 fn from(builder: InvoiceWithExplicitSigningPubkeyBuilder<'a>) -> Self {
421 let InvoiceWithExplicitSigningPubkeyBuilder {
422 invreq_bytes, invoice, signing_pubkey_strategy,
426 invreq_bytes, invoice, signing_pubkey_strategy,
432 impl<'a> From<InvoiceWithDerivedSigningPubkeyBuilder<'a>>
433 for InvoiceBuilder<'a, DerivedSigningPubkey> {
434 fn from(builder: InvoiceWithDerivedSigningPubkeyBuilder<'a>) -> Self {
435 let InvoiceWithDerivedSigningPubkeyBuilder {
436 invreq_bytes, invoice, signing_pubkey_strategy,
440 invreq_bytes, invoice, signing_pubkey_strategy,
445 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
449 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
450 /// such, it may include unknown, odd TLV records.
452 pub struct UnsignedBolt12Invoice {
454 contents: InvoiceContents,
455 tagged_hash: TaggedHash,
458 /// A function for signing an [`UnsignedBolt12Invoice`].
459 pub trait SignBolt12InvoiceFn {
460 /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
461 fn sign_invoice(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()>;
464 impl<F> SignBolt12InvoiceFn for F
466 F: Fn(&UnsignedBolt12Invoice) -> Result<Signature, ()>,
468 fn sign_invoice(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()> {
473 impl<F> SignFn<UnsignedBolt12Invoice> for F
475 F: SignBolt12InvoiceFn,
477 fn sign(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()> {
478 self.sign_invoice(message)
482 impl UnsignedBolt12Invoice {
483 fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
484 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
485 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
487 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
488 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
489 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
491 let mut bytes = Vec::new();
492 unsigned_tlv_stream.write(&mut bytes).unwrap();
494 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
496 Self { bytes, contents, tagged_hash }
499 /// Returns the [`TaggedHash`] of the invoice to sign.
500 pub fn tagged_hash(&self) -> &TaggedHash {
505 macro_rules! unsigned_invoice_sign_method { ($self: ident, $self_type: ty $(, $self_mut: tt)?) => {
506 /// Signs the [`TaggedHash`] of the invoice using the given function.
508 /// Note: The hash computation may have included unknown, odd TLV records.
509 pub fn sign<F: SignBolt12InvoiceFn>(
510 $($self_mut)* $self: $self_type, sign: F
511 ) -> Result<Bolt12Invoice, SignError> {
512 let pubkey = $self.contents.fields().signing_pubkey;
513 let signature = merkle::sign_message(sign, &$self, pubkey)?;
515 // Append the signature TLV record to the bytes.
516 let signature_tlv_stream = SignatureTlvStreamRef {
517 signature: Some(&signature),
519 signature_tlv_stream.write(&mut $self.bytes).unwrap();
522 #[cfg(not(c_bindings))]
525 bytes: $self.bytes.clone(),
526 #[cfg(not(c_bindings))]
527 contents: $self.contents,
529 contents: $self.contents.clone(),
531 #[cfg(not(c_bindings))]
532 tagged_hash: $self.tagged_hash,
534 tagged_hash: $self.tagged_hash.clone(),
539 #[cfg(not(c_bindings))]
540 impl UnsignedBolt12Invoice {
541 unsigned_invoice_sign_method!(self, Self, mut);
545 impl UnsignedBolt12Invoice {
546 unsigned_invoice_sign_method!(self, &mut Self);
549 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
550 fn as_ref(&self) -> &TaggedHash {
555 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
557 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
558 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
560 /// [`Offer`]: crate::offers::offer::Offer
561 /// [`Refund`]: crate::offers::refund::Refund
562 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
563 #[derive(Clone, Debug)]
564 pub struct Bolt12Invoice {
566 contents: InvoiceContents,
567 signature: Signature,
568 tagged_hash: TaggedHash,
571 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
573 /// [`Offer`]: crate::offers::offer::Offer
574 /// [`Refund`]: crate::offers::refund::Refund
575 #[derive(Clone, Debug)]
576 #[cfg_attr(test, derive(PartialEq))]
577 enum InvoiceContents {
578 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
580 /// [`Offer`]: crate::offers::offer::Offer
582 invoice_request: InvoiceRequestContents,
583 fields: InvoiceFields,
585 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
587 /// [`Refund`]: crate::offers::refund::Refund
589 refund: RefundContents,
590 fields: InvoiceFields,
594 /// Invoice-specific fields for an `invoice` message.
595 #[derive(Clone, Debug, PartialEq)]
596 struct InvoiceFields {
597 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
598 created_at: Duration,
599 relative_expiry: Option<Duration>,
600 payment_hash: PaymentHash,
602 fallbacks: Option<Vec<FallbackAddress>>,
603 features: Bolt12InvoiceFeatures,
604 signing_pubkey: PublicKey,
607 macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
608 /// The chains that may be used when paying a requested invoice.
610 /// From [`Offer::chains`]; `None` if the invoice was created in response to a [`Refund`].
612 /// [`Offer::chains`]: crate::offers::offer::Offer::chains
613 pub fn offer_chains(&$self) -> Option<Vec<ChainHash>> {
614 $contents.offer_chains()
617 /// The chain that must be used when paying the invoice; selected from [`offer_chains`] if the
618 /// invoice originated from an offer.
620 /// From [`InvoiceRequest::chain`] or [`Refund::chain`].
622 /// [`offer_chains`]: Self::offer_chains
623 /// [`InvoiceRequest::chain`]: crate::offers::invoice_request::InvoiceRequest::chain
624 pub fn chain(&$self) -> ChainHash {
628 /// Opaque bytes set by the originating [`Offer`].
630 /// From [`Offer::metadata`]; `None` if the invoice was created in response to a [`Refund`] or
631 /// if the [`Offer`] did not set it.
633 /// [`Offer`]: crate::offers::offer::Offer
634 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
635 pub fn metadata(&$self) -> Option<&Vec<u8>> {
639 /// The minimum amount required for a successful payment of a single item.
641 /// From [`Offer::amount`]; `None` if the invoice was created in response to a [`Refund`] or if
642 /// the [`Offer`] did not set it.
644 /// [`Offer`]: crate::offers::offer::Offer
645 /// [`Offer::amount`]: crate::offers::offer::Offer::amount
646 pub fn amount(&$self) -> Option<Amount> {
650 /// Features pertaining to the originating [`Offer`].
652 /// From [`Offer::offer_features`]; `None` if the invoice was created in response to a
655 /// [`Offer`]: crate::offers::offer::Offer
656 /// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features
657 pub fn offer_features(&$self) -> Option<&OfferFeatures> {
658 $contents.offer_features()
661 /// A complete description of the purpose of the originating offer or refund.
663 /// From [`Offer::description`] or [`Refund::description`].
665 /// [`Offer::description`]: crate::offers::offer::Offer::description
666 pub fn description(&$self) -> Option<PrintableString> {
667 $contents.description()
670 /// Duration since the Unix epoch when an invoice should no longer be requested.
672 /// From [`Offer::absolute_expiry`] or [`Refund::absolute_expiry`].
674 /// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry
675 pub fn absolute_expiry(&$self) -> Option<Duration> {
676 $contents.absolute_expiry()
679 /// The issuer of the offer or refund.
681 /// From [`Offer::issuer`] or [`Refund::issuer`].
683 /// [`Offer::issuer`]: crate::offers::offer::Offer::issuer
684 pub fn issuer(&$self) -> Option<PrintableString> {
688 /// Paths to the recipient originating from publicly reachable nodes.
690 /// From [`Offer::paths`] or [`Refund::paths`].
692 /// [`Offer::paths`]: crate::offers::offer::Offer::paths
693 pub fn message_paths(&$self) -> &[BlindedPath] {
694 $contents.message_paths()
697 /// The quantity of items supported.
699 /// From [`Offer::supported_quantity`]; `None` if the invoice was created in response to a
702 /// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
703 pub fn supported_quantity(&$self) -> Option<Quantity> {
704 $contents.supported_quantity()
707 /// An unpredictable series of bytes from the payer.
709 /// From [`InvoiceRequest::payer_metadata`] or [`Refund::payer_metadata`].
710 pub fn payer_metadata(&$self) -> &[u8] {
711 $contents.payer_metadata()
714 /// Features pertaining to requesting an invoice.
716 /// From [`InvoiceRequest::invoice_request_features`] or [`Refund::features`].
717 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
718 &$contents.invoice_request_features()
721 /// The quantity of items requested or refunded for.
723 /// From [`InvoiceRequest::quantity`] or [`Refund::quantity`].
724 pub fn quantity(&$self) -> Option<u64> {
728 /// A possibly transient pubkey used to sign the invoice request or to send an invoice for a
729 /// refund in case there are no [`message_paths`].
731 /// [`message_paths`]: Self::message_paths
732 pub fn payer_id(&$self) -> PublicKey {
736 /// A payer-provided note reflected back in the invoice.
738 /// From [`InvoiceRequest::payer_note`] or [`Refund::payer_note`].
739 pub fn payer_note(&$self) -> Option<PrintableString> {
740 $contents.payer_note()
743 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
744 pub fn payment_hash(&$self) -> PaymentHash {
745 $contents.payment_hash()
748 /// The minimum amount required for a successful payment of the invoice.
749 pub fn amount_msats(&$self) -> u64 {
750 $contents.amount_msats()
754 impl UnsignedBolt12Invoice {
755 invoice_accessors_common!(self, self.contents, Bolt12Invoice);
756 invoice_accessors!(self, self.contents);
760 invoice_accessors_common!(self, self.contents, Bolt12Invoice);
761 invoice_accessors!(self, self.contents);
763 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
764 pub fn signature(&self) -> Signature {
768 /// Hash that was used for signing the invoice.
769 pub fn signable_hash(&self) -> [u8; 32] {
770 self.tagged_hash.as_digest().as_ref().clone()
773 /// Verifies that the invoice was for a request or refund created using the given key. Returns
774 /// the associated [`PaymentId`] to use when sending the payment.
775 pub fn verify<T: secp256k1::Signing>(
776 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
777 ) -> Result<PaymentId, ()> {
778 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
781 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
782 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
783 self.contents.as_tlv_stream();
784 let signature_tlv_stream = SignatureTlvStreamRef {
785 signature: Some(&self.signature),
787 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
788 signature_tlv_stream)
792 impl PartialEq for Bolt12Invoice {
793 fn eq(&self, other: &Self) -> bool {
794 self.bytes.eq(&other.bytes)
798 impl Eq for Bolt12Invoice {}
800 impl Hash for Bolt12Invoice {
801 fn hash<H: Hasher>(&self, state: &mut H) {
802 self.bytes.hash(state);
806 impl InvoiceContents {
807 /// Whether the original offer or refund has expired.
808 #[cfg(feature = "std")]
809 fn is_offer_or_refund_expired(&self) -> bool {
811 InvoiceContents::ForOffer { invoice_request, .. } =>
812 invoice_request.inner.offer.is_expired(),
813 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
817 #[cfg(not(feature = "std"))]
818 fn is_offer_or_refund_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
820 InvoiceContents::ForOffer { invoice_request, .. } =>
821 invoice_request.inner.offer.is_expired_no_std(duration_since_epoch),
822 InvoiceContents::ForRefund { refund, .. } =>
823 refund.is_expired_no_std(duration_since_epoch),
827 fn offer_chains(&self) -> Option<Vec<ChainHash>> {
829 InvoiceContents::ForOffer { invoice_request, .. } =>
830 Some(invoice_request.inner.offer.chains()),
831 InvoiceContents::ForRefund { .. } => None,
835 fn chain(&self) -> ChainHash {
837 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
838 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
842 fn metadata(&self) -> Option<&Vec<u8>> {
844 InvoiceContents::ForOffer { invoice_request, .. } =>
845 invoice_request.inner.offer.metadata(),
846 InvoiceContents::ForRefund { .. } => None,
850 fn amount(&self) -> Option<Amount> {
852 InvoiceContents::ForOffer { invoice_request, .. } =>
853 invoice_request.inner.offer.amount(),
854 InvoiceContents::ForRefund { .. } => None,
858 fn description(&self) -> Option<PrintableString> {
860 InvoiceContents::ForOffer { invoice_request, .. } => {
861 invoice_request.inner.offer.description()
863 InvoiceContents::ForRefund { refund, .. } => Some(refund.description()),
867 fn offer_features(&self) -> Option<&OfferFeatures> {
869 InvoiceContents::ForOffer { invoice_request, .. } => {
870 Some(invoice_request.inner.offer.features())
872 InvoiceContents::ForRefund { .. } => None,
876 fn absolute_expiry(&self) -> Option<Duration> {
878 InvoiceContents::ForOffer { invoice_request, .. } => {
879 invoice_request.inner.offer.absolute_expiry()
881 InvoiceContents::ForRefund { refund, .. } => refund.absolute_expiry(),
885 fn issuer(&self) -> Option<PrintableString> {
887 InvoiceContents::ForOffer { invoice_request, .. } => {
888 invoice_request.inner.offer.issuer()
890 InvoiceContents::ForRefund { refund, .. } => refund.issuer(),
894 fn message_paths(&self) -> &[BlindedPath] {
896 InvoiceContents::ForOffer { invoice_request, .. } => {
897 invoice_request.inner.offer.paths()
899 InvoiceContents::ForRefund { refund, .. } => refund.paths(),
903 fn supported_quantity(&self) -> Option<Quantity> {
905 InvoiceContents::ForOffer { invoice_request, .. } => {
906 Some(invoice_request.inner.offer.supported_quantity())
908 InvoiceContents::ForRefund { .. } => None,
912 fn payer_metadata(&self) -> &[u8] {
914 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.metadata(),
915 InvoiceContents::ForRefund { refund, .. } => refund.metadata(),
919 fn invoice_request_features(&self) -> &InvoiceRequestFeatures {
921 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.features(),
922 InvoiceContents::ForRefund { refund, .. } => refund.features(),
926 fn quantity(&self) -> Option<u64> {
928 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.quantity(),
929 InvoiceContents::ForRefund { refund, .. } => refund.quantity(),
933 fn payer_id(&self) -> PublicKey {
935 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_id(),
936 InvoiceContents::ForRefund { refund, .. } => refund.payer_id(),
940 fn payer_note(&self) -> Option<PrintableString> {
942 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_note(),
943 InvoiceContents::ForRefund { refund, .. } => refund.payer_note(),
947 fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
948 &self.fields().payment_paths[..]
951 fn created_at(&self) -> Duration {
952 self.fields().created_at
955 fn relative_expiry(&self) -> Duration {
956 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
959 #[cfg(feature = "std")]
960 fn is_expired(&self) -> bool {
961 is_expired(self.created_at(), self.relative_expiry())
964 fn payment_hash(&self) -> PaymentHash {
965 self.fields().payment_hash
968 fn amount_msats(&self) -> u64 {
969 self.fields().amount_msats
972 fn fallbacks(&self) -> Vec<Address> {
973 self.fields().fallbacks
975 .map(|fallbacks| filter_fallbacks(self.chain(), fallbacks))
976 .unwrap_or_else(Vec::new)
979 fn features(&self) -> &Bolt12InvoiceFeatures {
980 &self.fields().features
983 fn signing_pubkey(&self) -> PublicKey {
984 self.fields().signing_pubkey
987 fn fields(&self) -> &InvoiceFields {
989 InvoiceContents::ForOffer { fields, .. } => fields,
990 InvoiceContents::ForRefund { fields, .. } => fields,
994 fn fields_mut(&mut self) -> &mut InvoiceFields {
996 InvoiceContents::ForOffer { fields, .. } => fields,
997 InvoiceContents::ForRefund { fields, .. } => fields,
1001 fn verify<T: secp256k1::Signing>(
1002 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
1003 ) -> Result<PaymentId, ()> {
1004 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
1005 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
1006 match record.r#type {
1007 PAYER_METADATA_TYPE => false, // Should be outside range
1008 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
1012 let tlv_stream = offer_records.chain(invreq_records);
1014 let (metadata, payer_id, iv_bytes) = match self {
1015 InvoiceContents::ForOffer { invoice_request, .. } => {
1016 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
1018 InvoiceContents::ForRefund { refund, .. } => {
1019 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
1023 signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
1026 fn derives_keys(&self) -> bool {
1028 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
1029 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
1033 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
1034 let (payer, offer, invoice_request) = match self {
1035 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
1036 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
1038 let invoice = self.fields().as_tlv_stream();
1040 (payer, offer, invoice_request, invoice)
1044 #[cfg(feature = "std")]
1045 pub(super) fn is_expired(created_at: Duration, relative_expiry: Duration) -> bool {
1046 let absolute_expiry = created_at.checked_add(relative_expiry);
1047 match absolute_expiry {
1048 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
1049 Ok(elapsed) => elapsed > seconds_from_epoch,
1056 pub(super) fn filter_fallbacks(
1057 chain: ChainHash, fallbacks: &Vec<FallbackAddress>
1059 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
1061 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
1063 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
1065 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
1071 let to_valid_address = |address: &FallbackAddress| {
1072 let version = match WitnessVersion::try_from(address.version) {
1073 Ok(version) => version,
1074 Err(_) => return None,
1077 let program = address.program.clone();
1078 let witness_program = match WitnessProgram::new(version, program) {
1079 Ok(witness_program) => witness_program,
1080 Err(_) => return None,
1082 Some(Address::new(network, Payload::WitnessProgram(witness_program)))
1085 fallbacks.iter().filter_map(to_valid_address).collect()
1088 impl InvoiceFields {
1089 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
1091 if self.features == Bolt12InvoiceFeatures::empty() { None }
1092 else { Some(&self.features) }
1095 InvoiceTlvStreamRef {
1096 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
1097 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
1098 created_at: Some(self.created_at.as_secs()),
1099 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
1100 payment_hash: Some(&self.payment_hash),
1101 amount: Some(self.amount_msats),
1102 fallbacks: self.fallbacks.as_ref(),
1104 node_id: Some(&self.signing_pubkey),
1105 message_paths: None,
1110 impl Writeable for UnsignedBolt12Invoice {
1111 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1112 WithoutLength(&self.bytes).write(writer)
1116 impl Writeable for Bolt12Invoice {
1117 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1118 WithoutLength(&self.bytes).write(writer)
1122 impl Writeable for InvoiceContents {
1123 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1124 self.as_tlv_stream().write(writer)
1128 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
1129 type Error = Bolt12ParseError;
1131 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1132 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
1133 let ParsedMessage { bytes, tlv_stream } = invoice;
1135 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1137 let contents = InvoiceContents::try_from(
1138 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1141 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1143 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
1147 impl TryFrom<Vec<u8>> for Bolt12Invoice {
1148 type Error = Bolt12ParseError;
1150 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1151 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
1152 Bolt12Invoice::try_from(parsed_invoice)
1156 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
1157 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
1158 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
1159 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
1160 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
1161 (168, payment_hash: PaymentHash),
1162 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
1163 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
1164 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
1165 (176, node_id: PublicKey),
1166 // Only present in `StaticInvoice`s.
1167 (238, message_paths: (Vec<BlindedPath>, WithoutLength)),
1170 pub(super) type BlindedPathIter<'a> = core::iter::Map<
1171 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1172 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
1175 pub(super) type BlindedPayInfoIter<'a> = core::iter::Map<
1176 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1177 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
1180 /// Information needed to route a payment across a [`BlindedPath`].
1181 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
1182 pub struct BlindedPayInfo {
1183 /// Base fee charged (in millisatoshi) for the entire blinded path.
1184 pub fee_base_msat: u32,
1186 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
1187 /// (i.e., 10,000 is 1%).
1188 pub fee_proportional_millionths: u32,
1190 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
1192 pub cltv_expiry_delta: u16,
1194 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1195 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1196 /// seen by the recipient.
1197 pub htlc_minimum_msat: u64,
1199 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1200 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1201 /// seen by the recipient.
1202 pub htlc_maximum_msat: u64,
1204 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
1206 pub features: BlindedHopFeatures,
1209 impl_writeable!(BlindedPayInfo, {
1211 fee_proportional_millionths,
1218 /// Wire representation for an on-chain fallback address.
1219 #[derive(Clone, Debug, PartialEq)]
1220 pub(super) struct FallbackAddress {
1221 pub(super) version: u8,
1222 pub(super) program: Vec<u8>,
1225 impl_writeable!(FallbackAddress, { version, program });
1227 type FullInvoiceTlvStream =
1228 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
1230 type FullInvoiceTlvStreamRef<'a> = (
1231 PayerTlvStreamRef<'a>,
1232 OfferTlvStreamRef<'a>,
1233 InvoiceRequestTlvStreamRef<'a>,
1234 InvoiceTlvStreamRef<'a>,
1235 SignatureTlvStreamRef<'a>,
1238 impl SeekReadable for FullInvoiceTlvStream {
1239 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1240 let payer = SeekReadable::read(r)?;
1241 let offer = SeekReadable::read(r)?;
1242 let invoice_request = SeekReadable::read(r)?;
1243 let invoice = SeekReadable::read(r)?;
1244 let signature = SeekReadable::read(r)?;
1246 Ok((payer, offer, invoice_request, invoice, signature))
1250 type PartialInvoiceTlvStream =
1251 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
1253 type PartialInvoiceTlvStreamRef<'a> = (
1254 PayerTlvStreamRef<'a>,
1255 OfferTlvStreamRef<'a>,
1256 InvoiceRequestTlvStreamRef<'a>,
1257 InvoiceTlvStreamRef<'a>,
1260 impl SeekReadable for PartialInvoiceTlvStream {
1261 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1262 let payer = SeekReadable::read(r)?;
1263 let offer = SeekReadable::read(r)?;
1264 let invoice_request = SeekReadable::read(r)?;
1265 let invoice = SeekReadable::read(r)?;
1267 Ok((payer, offer, invoice_request, invoice))
1271 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
1272 type Error = Bolt12ParseError;
1274 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
1275 let ParsedMessage { bytes, tlv_stream } = invoice;
1277 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1278 SignatureTlvStream { signature },
1280 let contents = InvoiceContents::try_from(
1281 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1284 let signature = signature.ok_or(
1285 Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)
1287 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1288 let pubkey = contents.fields().signing_pubkey;
1289 merkle::verify_signature(&signature, &tagged_hash, pubkey)?;
1291 Ok(Bolt12Invoice { bytes, contents, signature, tagged_hash })
1295 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
1296 type Error = Bolt12SemanticError;
1298 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
1302 invoice_request_tlv_stream,
1304 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
1305 features, node_id, message_paths,
1309 if message_paths.is_some() { return Err(Bolt12SemanticError::UnexpectedPaths) }
1311 let payment_paths = construct_payment_paths(blindedpay, paths)?;
1313 let created_at = match created_at {
1314 None => return Err(Bolt12SemanticError::MissingCreationTime),
1315 Some(timestamp) => Duration::from_secs(timestamp),
1318 let relative_expiry = relative_expiry
1319 .map(Into::<u64>::into)
1320 .map(Duration::from_secs);
1322 let payment_hash = payment_hash.ok_or(Bolt12SemanticError::MissingPaymentHash)?;
1324 let amount_msats = amount.ok_or(Bolt12SemanticError::MissingAmount)?;
1326 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1328 let signing_pubkey = node_id.ok_or(Bolt12SemanticError::MissingSigningPubkey)?;
1330 let fields = InvoiceFields {
1331 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1332 features, signing_pubkey,
1335 check_invoice_signing_pubkey(&fields.signing_pubkey, &offer_tlv_stream)?;
1337 if offer_tlv_stream.node_id.is_none() && offer_tlv_stream.paths.is_none() {
1338 let refund = RefundContents::try_from(
1339 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1341 Ok(InvoiceContents::ForRefund { refund, fields })
1343 let invoice_request = InvoiceRequestContents::try_from(
1344 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1346 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1351 pub(super) fn construct_payment_paths(
1352 blinded_payinfos: Option<Vec<BlindedPayInfo>>, blinded_paths: Option<Vec<BlindedPath>>
1353 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, Bolt12SemanticError> {
1354 match (blinded_payinfos, blinded_paths) {
1355 (_, None) => Err(Bolt12SemanticError::MissingPaths),
1356 (None, _) => Err(Bolt12SemanticError::InvalidPayInfo),
1357 (_, Some(paths)) if paths.is_empty() => Err(Bolt12SemanticError::MissingPaths),
1358 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
1359 Err(Bolt12SemanticError::InvalidPayInfo)
1361 (Some(blindedpay), Some(paths)) => {
1362 Ok(blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>())
1367 pub(super) fn check_invoice_signing_pubkey(
1368 invoice_signing_pubkey: &PublicKey, offer_tlv_stream: &OfferTlvStream
1369 ) -> Result<(), Bolt12SemanticError> {
1370 match (&offer_tlv_stream.node_id, &offer_tlv_stream.paths) {
1371 (Some(expected_signing_pubkey), _) => {
1372 if invoice_signing_pubkey != expected_signing_pubkey {
1373 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1376 (None, Some(paths)) => {
1379 .filter_map(|path| path.blinded_hops.last())
1380 .any(|last_hop| invoice_signing_pubkey == &last_hop.blinded_node_id)
1382 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1392 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1394 use bitcoin::{WitnessProgram, WitnessVersion};
1395 use bitcoin::blockdata::constants::ChainHash;
1396 use bitcoin::blockdata::script::ScriptBuf;
1397 use bitcoin::hashes::Hash;
1398 use bitcoin::network::Network;
1399 use bitcoin::secp256k1::{Keypair, Message, Secp256k1, SecretKey, XOnlyPublicKey, self};
1400 use bitcoin::address::{Address, Payload};
1401 use bitcoin::key::TweakedPublicKey;
1403 use core::time::Duration;
1405 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1406 use crate::sign::KeyMaterial;
1407 use crate::ln::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
1408 use crate::ln::inbound_payment::ExpandedKey;
1409 use crate::ln::msgs::DecodeError;
1410 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1411 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1412 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1413 use crate::prelude::*;
1414 #[cfg(not(c_bindings))]
1416 crate::offers::offer::OfferBuilder,
1417 crate::offers::refund::RefundBuilder,
1421 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1422 crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
1424 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1425 use crate::offers::payer::PayerTlvStreamRef;
1426 use crate::offers::test_utils::*;
1427 use crate::util::ser::{BigSize, Iterable, Writeable};
1428 use crate::util::string::PrintableString;
1431 fn to_bytes(&self) -> Vec<u8>;
1434 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1435 fn to_bytes(&self) -> Vec<u8> {
1436 let mut buffer = Vec::new();
1437 self.0.write(&mut buffer).unwrap();
1438 self.1.write(&mut buffer).unwrap();
1439 self.2.write(&mut buffer).unwrap();
1440 self.3.write(&mut buffer).unwrap();
1441 self.4.write(&mut buffer).unwrap();
1447 fn builds_invoice_for_offer_with_defaults() {
1448 let payment_paths = payment_paths();
1449 let payment_hash = payment_hash();
1451 let unsigned_invoice = OfferBuilder::new(recipient_pubkey())
1454 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1456 .sign(payer_sign).unwrap()
1457 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1460 let mut buffer = Vec::new();
1461 unsigned_invoice.write(&mut buffer).unwrap();
1463 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1464 assert_eq!(unsigned_invoice.payer_metadata(), &[1; 32]);
1465 assert_eq!(unsigned_invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1466 assert_eq!(unsigned_invoice.metadata(), None);
1467 assert_eq!(unsigned_invoice.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1468 assert_eq!(unsigned_invoice.description(), Some(PrintableString("")));
1469 assert_eq!(unsigned_invoice.offer_features(), Some(&OfferFeatures::empty()));
1470 assert_eq!(unsigned_invoice.absolute_expiry(), None);
1471 assert_eq!(unsigned_invoice.message_paths(), &[]);
1472 assert_eq!(unsigned_invoice.issuer(), None);
1473 assert_eq!(unsigned_invoice.supported_quantity(), Some(Quantity::One));
1474 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1475 assert_eq!(unsigned_invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1476 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1477 assert_eq!(unsigned_invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1478 assert_eq!(unsigned_invoice.quantity(), None);
1479 assert_eq!(unsigned_invoice.payer_id(), payer_pubkey());
1480 assert_eq!(unsigned_invoice.payer_note(), None);
1481 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1482 assert_eq!(unsigned_invoice.created_at(), now);
1483 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1484 #[cfg(feature = "std")]
1485 assert!(!unsigned_invoice.is_expired());
1486 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1487 assert!(unsigned_invoice.fallbacks().is_empty());
1488 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1490 match UnsignedBolt12Invoice::try_from(buffer) {
1491 Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1493 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1494 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1499 let mut unsigned_invoice = unsigned_invoice;
1500 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1502 let mut buffer = Vec::new();
1503 invoice.write(&mut buffer).unwrap();
1505 assert_eq!(invoice.bytes, buffer.as_slice());
1506 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1507 assert_eq!(invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1508 assert_eq!(invoice.metadata(), None);
1509 assert_eq!(invoice.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1510 assert_eq!(invoice.description(), Some(PrintableString("")));
1511 assert_eq!(invoice.offer_features(), Some(&OfferFeatures::empty()));
1512 assert_eq!(invoice.absolute_expiry(), None);
1513 assert_eq!(invoice.message_paths(), &[]);
1514 assert_eq!(invoice.issuer(), None);
1515 assert_eq!(invoice.supported_quantity(), Some(Quantity::One));
1516 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1517 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1518 assert_eq!(invoice.amount_msats(), 1000);
1519 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1520 assert_eq!(invoice.quantity(), None);
1521 assert_eq!(invoice.payer_id(), payer_pubkey());
1522 assert_eq!(invoice.payer_note(), None);
1523 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1524 assert_eq!(invoice.created_at(), now);
1525 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1526 #[cfg(feature = "std")]
1527 assert!(!invoice.is_expired());
1528 assert_eq!(invoice.payment_hash(), payment_hash);
1529 assert!(invoice.fallbacks().is_empty());
1530 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1532 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice.bytes);
1533 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1535 let digest = Message::from_digest(invoice.signable_hash());
1536 let pubkey = recipient_pubkey().into();
1537 let secp_ctx = Secp256k1::verification_only();
1538 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1541 invoice.as_tlv_stream(),
1543 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1549 description: Some(&String::from("")),
1551 absolute_expiry: None,
1555 node_id: Some(&recipient_pubkey()),
1557 InvoiceRequestTlvStreamRef {
1562 payer_id: Some(&payer_pubkey()),
1566 InvoiceTlvStreamRef {
1567 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1568 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1569 created_at: Some(now.as_secs()),
1570 relative_expiry: None,
1571 payment_hash: Some(&payment_hash),
1575 node_id: Some(&recipient_pubkey()),
1576 message_paths: None,
1578 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1582 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1583 panic!("error parsing invoice: {:?}", e);
1588 fn builds_invoice_for_refund_with_defaults() {
1589 let payment_paths = payment_paths();
1590 let payment_hash = payment_hash();
1592 let invoice = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1594 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1597 .sign(recipient_sign).unwrap();
1599 let mut buffer = Vec::new();
1600 invoice.write(&mut buffer).unwrap();
1602 assert_eq!(invoice.bytes, buffer.as_slice());
1603 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1604 assert_eq!(invoice.offer_chains(), None);
1605 assert_eq!(invoice.metadata(), None);
1606 assert_eq!(invoice.amount(), None);
1607 assert_eq!(invoice.description(), Some(PrintableString("")));
1608 assert_eq!(invoice.offer_features(), None);
1609 assert_eq!(invoice.absolute_expiry(), None);
1610 assert_eq!(invoice.message_paths(), &[]);
1611 assert_eq!(invoice.issuer(), None);
1612 assert_eq!(invoice.supported_quantity(), None);
1613 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1614 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1615 assert_eq!(invoice.amount_msats(), 1000);
1616 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1617 assert_eq!(invoice.quantity(), None);
1618 assert_eq!(invoice.payer_id(), payer_pubkey());
1619 assert_eq!(invoice.payer_note(), None);
1620 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1621 assert_eq!(invoice.created_at(), now);
1622 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1623 #[cfg(feature = "std")]
1624 assert!(!invoice.is_expired());
1625 assert_eq!(invoice.payment_hash(), payment_hash);
1626 assert!(invoice.fallbacks().is_empty());
1627 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1629 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice.bytes);
1630 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1633 invoice.as_tlv_stream(),
1635 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1641 description: Some(&String::from("")),
1643 absolute_expiry: None,
1649 InvoiceRequestTlvStreamRef {
1654 payer_id: Some(&payer_pubkey()),
1658 InvoiceTlvStreamRef {
1659 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1660 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1661 created_at: Some(now.as_secs()),
1662 relative_expiry: None,
1663 payment_hash: Some(&payment_hash),
1667 node_id: Some(&recipient_pubkey()),
1668 message_paths: None,
1670 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1674 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1675 panic!("error parsing invoice: {:?}", e);
1679 #[cfg(feature = "std")]
1681 fn builds_invoice_from_offer_with_expiration() {
1682 let future_expiry = Duration::from_secs(u64::max_value());
1683 let past_expiry = Duration::from_secs(0);
1685 if let Err(e) = OfferBuilder::new(recipient_pubkey())
1687 .absolute_expiry(future_expiry)
1689 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1691 .sign(payer_sign).unwrap()
1692 .respond_with(payment_paths(), payment_hash())
1696 panic!("error building invoice: {:?}", e);
1699 match OfferBuilder::new(recipient_pubkey())
1701 .absolute_expiry(past_expiry)
1703 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1705 .sign(payer_sign).unwrap()
1706 .respond_with(payment_paths(), payment_hash())
1710 Ok(_) => panic!("expected error"),
1711 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1715 #[cfg(feature = "std")]
1717 fn builds_invoice_from_refund_with_expiration() {
1718 let future_expiry = Duration::from_secs(u64::max_value());
1719 let past_expiry = Duration::from_secs(0);
1721 if let Err(e) = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1722 .absolute_expiry(future_expiry)
1724 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1728 panic!("error building invoice: {:?}", e);
1731 match RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1732 .absolute_expiry(past_expiry)
1734 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1738 Ok(_) => panic!("expected error"),
1739 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1744 fn builds_invoice_from_offer_using_derived_keys() {
1745 let node_id = recipient_pubkey();
1746 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1747 let entropy = FixedEntropy {};
1748 let secp_ctx = Secp256k1::new();
1750 let blinded_path = BlindedPath {
1751 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1752 blinding_point: pubkey(41),
1754 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1755 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1760 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
1761 let offer = OfferBuilder
1762 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1766 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1768 .sign(payer_sign).unwrap();
1770 if let Err(e) = invoice_request.clone()
1771 .verify(&expanded_key, &secp_ctx).unwrap()
1772 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
1773 .build_and_sign(&secp_ctx)
1775 panic!("error building invoice: {:?}", e);
1778 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1779 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1781 let offer = OfferBuilder
1782 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1784 // Omit the path so that node_id is used for the signing pubkey instead of deriving
1786 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1788 .sign(payer_sign).unwrap();
1790 match invoice_request
1791 .verify(&expanded_key, &secp_ctx).unwrap()
1792 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
1794 Ok(_) => panic!("expected error"),
1795 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1800 fn builds_invoice_from_refund_using_derived_keys() {
1801 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1802 let entropy = FixedEntropy {};
1803 let secp_ctx = Secp256k1::new();
1805 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1808 if let Err(e) = refund
1809 .respond_using_derived_keys_no_std(
1810 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1813 .build_and_sign(&secp_ctx)
1815 panic!("error building invoice: {:?}", e);
1820 fn builds_invoice_with_relative_expiry() {
1822 let one_hour = Duration::from_secs(3600);
1824 let invoice = OfferBuilder::new(recipient_pubkey())
1827 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1829 .sign(payer_sign).unwrap()
1830 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1831 .relative_expiry(one_hour.as_secs() as u32)
1833 .sign(recipient_sign).unwrap();
1834 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1835 #[cfg(feature = "std")]
1836 assert!(!invoice.is_expired());
1837 assert_eq!(invoice.relative_expiry(), one_hour);
1838 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1840 let invoice = OfferBuilder::new(recipient_pubkey())
1843 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1845 .sign(payer_sign).unwrap()
1846 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1847 .relative_expiry(one_hour.as_secs() as u32 - 1)
1849 .sign(recipient_sign).unwrap();
1850 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1851 #[cfg(feature = "std")]
1852 assert!(invoice.is_expired());
1853 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1854 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1858 fn builds_invoice_with_amount_from_request() {
1859 let invoice = OfferBuilder::new(recipient_pubkey())
1862 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1863 .amount_msats(1001).unwrap()
1865 .sign(payer_sign).unwrap()
1866 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1868 .sign(recipient_sign).unwrap();
1869 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1870 assert_eq!(invoice.amount_msats(), 1001);
1871 assert_eq!(tlv_stream.amount, Some(1001));
1875 fn builds_invoice_with_quantity_from_request() {
1876 let invoice = OfferBuilder::new(recipient_pubkey())
1878 .supported_quantity(Quantity::Unbounded)
1880 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1881 .quantity(2).unwrap()
1883 .sign(payer_sign).unwrap()
1884 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1886 .sign(recipient_sign).unwrap();
1887 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1888 assert_eq!(invoice.amount_msats(), 2000);
1889 assert_eq!(tlv_stream.amount, Some(2000));
1891 match OfferBuilder::new(recipient_pubkey())
1893 .supported_quantity(Quantity::Unbounded)
1895 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1896 .quantity(u64::max_value()).unwrap()
1898 .sign(payer_sign).unwrap()
1899 .respond_with_no_std(payment_paths(), payment_hash(), now())
1901 Ok(_) => panic!("expected error"),
1902 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1907 fn builds_invoice_with_fallback_address() {
1908 let script = ScriptBuf::new();
1909 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
1910 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1911 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1913 let invoice = OfferBuilder::new(recipient_pubkey())
1916 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1918 .sign(payer_sign).unwrap()
1919 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1920 .fallback_v0_p2wsh(&script.wscript_hash())
1921 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1922 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1924 .sign(recipient_sign).unwrap();
1925 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1927 invoice.fallbacks(),
1929 Address::p2wsh(&script, Network::Bitcoin),
1930 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1931 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1935 tlv_stream.fallbacks,
1938 version: WitnessVersion::V0.to_num(),
1939 program: Vec::from(script.wscript_hash().to_byte_array()),
1942 version: WitnessVersion::V0.to_num(),
1943 program: Vec::from(pubkey.wpubkey_hash().unwrap().to_byte_array()),
1946 version: WitnessVersion::V1.to_num(),
1947 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1954 fn builds_invoice_with_allow_mpp() {
1955 let mut features = Bolt12InvoiceFeatures::empty();
1956 features.set_basic_mpp_optional();
1958 let invoice = OfferBuilder::new(recipient_pubkey())
1961 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1963 .sign(payer_sign).unwrap()
1964 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1967 .sign(recipient_sign).unwrap();
1968 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1969 assert_eq!(invoice.invoice_features(), &features);
1970 assert_eq!(tlv_stream.features, Some(&features));
1974 fn fails_signing_invoice() {
1975 match OfferBuilder::new(recipient_pubkey())
1978 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1980 .sign(payer_sign).unwrap()
1981 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1985 Ok(_) => panic!("expected error"),
1986 Err(e) => assert_eq!(e, SignError::Signing),
1989 match OfferBuilder::new(recipient_pubkey())
1992 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1994 .sign(payer_sign).unwrap()
1995 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1999 Ok(_) => panic!("expected error"),
2000 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
2005 fn parses_invoice_with_payment_paths() {
2006 let invoice = OfferBuilder::new(recipient_pubkey())
2009 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2011 .sign(payer_sign).unwrap()
2012 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2014 .sign(recipient_sign).unwrap();
2016 let mut buffer = Vec::new();
2017 invoice.write(&mut buffer).unwrap();
2019 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2020 panic!("error parsing invoice: {:?}", e);
2023 let mut tlv_stream = invoice.as_tlv_stream();
2024 tlv_stream.3.paths = None;
2026 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2027 Ok(_) => panic!("expected error"),
2028 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2031 let mut tlv_stream = invoice.as_tlv_stream();
2032 tlv_stream.3.blindedpay = None;
2034 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2035 Ok(_) => panic!("expected error"),
2036 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2039 let empty_payment_paths = vec![];
2040 let mut tlv_stream = invoice.as_tlv_stream();
2041 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
2043 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2044 Ok(_) => panic!("expected error"),
2045 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2048 let mut payment_paths = payment_paths();
2049 payment_paths.pop();
2050 let mut tlv_stream = invoice.as_tlv_stream();
2051 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
2053 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2054 Ok(_) => panic!("expected error"),
2055 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2060 fn parses_invoice_with_created_at() {
2061 let invoice = OfferBuilder::new(recipient_pubkey())
2064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2066 .sign(payer_sign).unwrap()
2067 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2069 .sign(recipient_sign).unwrap();
2071 let mut buffer = Vec::new();
2072 invoice.write(&mut buffer).unwrap();
2074 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2075 panic!("error parsing invoice: {:?}", e);
2078 let mut tlv_stream = invoice.as_tlv_stream();
2079 tlv_stream.3.created_at = None;
2081 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2082 Ok(_) => panic!("expected error"),
2084 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
2090 fn parses_invoice_with_relative_expiry() {
2091 let invoice = OfferBuilder::new(recipient_pubkey())
2094 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2096 .sign(payer_sign).unwrap()
2097 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2098 .relative_expiry(3600)
2100 .sign(recipient_sign).unwrap();
2102 let mut buffer = Vec::new();
2103 invoice.write(&mut buffer).unwrap();
2105 match Bolt12Invoice::try_from(buffer) {
2106 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
2107 Err(e) => panic!("error parsing invoice: {:?}", e),
2112 fn parses_invoice_with_payment_hash() {
2113 let invoice = OfferBuilder::new(recipient_pubkey())
2116 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2118 .sign(payer_sign).unwrap()
2119 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2121 .sign(recipient_sign).unwrap();
2123 let mut buffer = Vec::new();
2124 invoice.write(&mut buffer).unwrap();
2126 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2127 panic!("error parsing invoice: {:?}", e);
2130 let mut tlv_stream = invoice.as_tlv_stream();
2131 tlv_stream.3.payment_hash = None;
2133 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2134 Ok(_) => panic!("expected error"),
2136 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
2142 fn parses_invoice_with_amount() {
2143 let invoice = OfferBuilder::new(recipient_pubkey())
2146 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2148 .sign(payer_sign).unwrap()
2149 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2151 .sign(recipient_sign).unwrap();
2153 let mut buffer = Vec::new();
2154 invoice.write(&mut buffer).unwrap();
2156 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2157 panic!("error parsing invoice: {:?}", e);
2160 let mut tlv_stream = invoice.as_tlv_stream();
2161 tlv_stream.3.amount = None;
2163 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2164 Ok(_) => panic!("expected error"),
2165 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2170 fn parses_invoice_with_allow_mpp() {
2171 let invoice = OfferBuilder::new(recipient_pubkey())
2174 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2176 .sign(payer_sign).unwrap()
2177 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2180 .sign(recipient_sign).unwrap();
2182 let mut buffer = Vec::new();
2183 invoice.write(&mut buffer).unwrap();
2185 match Bolt12Invoice::try_from(buffer) {
2187 let mut features = Bolt12InvoiceFeatures::empty();
2188 features.set_basic_mpp_optional();
2189 assert_eq!(invoice.invoice_features(), &features);
2191 Err(e) => panic!("error parsing invoice: {:?}", e),
2196 fn parses_invoice_with_fallback_address() {
2197 let script = ScriptBuf::new();
2198 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
2199 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
2200 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
2202 let offer = OfferBuilder::new(recipient_pubkey())
2205 let invoice_request = offer
2206 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2208 .sign(payer_sign).unwrap();
2209 #[cfg(not(c_bindings))]
2210 let invoice_builder = invoice_request
2211 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2213 let mut invoice_builder = invoice_request
2214 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2215 let invoice_builder = invoice_builder
2216 .fallback_v0_p2wsh(&script.wscript_hash())
2217 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
2218 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
2219 #[cfg(not(c_bindings))]
2220 let mut invoice_builder = invoice_builder;
2222 // Only standard addresses will be included.
2223 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
2224 // Non-standard addresses
2225 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
2226 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
2227 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
2229 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
2230 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
2232 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
2233 let mut buffer = Vec::new();
2234 invoice.write(&mut buffer).unwrap();
2236 match Bolt12Invoice::try_from(buffer) {
2238 let v1_witness_program = WitnessProgram::new(WitnessVersion::V1, vec![0u8; 33]).unwrap();
2239 let v2_witness_program = WitnessProgram::new(WitnessVersion::V2, vec![0u8; 40]).unwrap();
2241 invoice.fallbacks(),
2243 Address::p2wsh(&script, Network::Bitcoin),
2244 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
2245 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
2246 Address::new(Network::Bitcoin, Payload::WitnessProgram(v1_witness_program)),
2247 Address::new(Network::Bitcoin, Payload::WitnessProgram(v2_witness_program)),
2251 Err(e) => panic!("error parsing invoice: {:?}", e),
2256 fn parses_invoice_with_node_id() {
2257 let invoice = OfferBuilder::new(recipient_pubkey())
2260 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2262 .sign(payer_sign).unwrap()
2263 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2265 .sign(recipient_sign).unwrap();
2267 let mut buffer = Vec::new();
2268 invoice.write(&mut buffer).unwrap();
2270 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2271 panic!("error parsing invoice: {:?}", e);
2274 let mut tlv_stream = invoice.as_tlv_stream();
2275 tlv_stream.3.node_id = None;
2277 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2278 Ok(_) => panic!("expected error"),
2280 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2284 let invalid_pubkey = payer_pubkey();
2285 let mut tlv_stream = invoice.as_tlv_stream();
2286 tlv_stream.3.node_id = Some(&invalid_pubkey);
2288 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2289 Ok(_) => panic!("expected error"),
2291 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
2297 fn parses_invoice_with_node_id_from_blinded_path() {
2300 introduction_node: IntroductionNode::NodeId(pubkey(40)),
2301 blinding_point: pubkey(41),
2303 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
2304 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
2308 introduction_node: IntroductionNode::NodeId(pubkey(40)),
2309 blinding_point: pubkey(41),
2311 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
2312 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
2317 let blinded_node_id_sign = |message: &UnsignedBolt12Invoice| {
2318 let secp_ctx = Secp256k1::new();
2319 let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap());
2320 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2323 let invoice = OfferBuilder::new(recipient_pubkey())
2324 .clear_signing_pubkey()
2326 .path(paths[0].clone())
2327 .path(paths[1].clone())
2329 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2331 .sign(payer_sign).unwrap()
2332 .respond_with_no_std_using_signing_pubkey(
2333 payment_paths(), payment_hash(), now(), pubkey(46)
2336 .sign(blinded_node_id_sign).unwrap();
2338 let mut buffer = Vec::new();
2339 invoice.write(&mut buffer).unwrap();
2341 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2342 panic!("error parsing invoice: {:?}", e);
2345 let invoice = OfferBuilder::new(recipient_pubkey())
2346 .clear_signing_pubkey()
2348 .path(paths[0].clone())
2349 .path(paths[1].clone())
2351 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2353 .sign(payer_sign).unwrap()
2354 .respond_with_no_std_using_signing_pubkey(
2355 payment_paths(), payment_hash(), now(), recipient_pubkey()
2358 .sign(recipient_sign).unwrap();
2360 let mut buffer = Vec::new();
2361 invoice.write(&mut buffer).unwrap();
2363 match Bolt12Invoice::try_from(buffer) {
2364 Ok(_) => panic!("expected error"),
2366 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
2372 fn fails_parsing_invoice_without_signature() {
2373 let mut buffer = Vec::new();
2374 OfferBuilder::new(recipient_pubkey())
2377 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2379 .sign(payer_sign).unwrap()
2380 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2383 .write(&mut buffer).unwrap();
2385 match Bolt12Invoice::try_from(buffer) {
2386 Ok(_) => panic!("expected error"),
2387 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2392 fn fails_parsing_invoice_with_invalid_signature() {
2393 let mut invoice = OfferBuilder::new(recipient_pubkey())
2396 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2398 .sign(payer_sign).unwrap()
2399 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2401 .sign(recipient_sign).unwrap();
2402 let last_signature_byte = invoice.bytes.last_mut().unwrap();
2403 *last_signature_byte = last_signature_byte.wrapping_add(1);
2405 let mut buffer = Vec::new();
2406 invoice.write(&mut buffer).unwrap();
2408 match Bolt12Invoice::try_from(buffer) {
2409 Ok(_) => panic!("expected error"),
2411 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2417 fn fails_parsing_invoice_with_extra_tlv_records() {
2418 let invoice = OfferBuilder::new(recipient_pubkey())
2421 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2423 .sign(payer_sign).unwrap()
2424 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2426 .sign(recipient_sign).unwrap();
2428 let mut encoded_invoice = Vec::new();
2429 invoice.write(&mut encoded_invoice).unwrap();
2430 BigSize(1002).write(&mut encoded_invoice).unwrap();
2431 BigSize(32).write(&mut encoded_invoice).unwrap();
2432 [42u8; 32].write(&mut encoded_invoice).unwrap();
2434 match Bolt12Invoice::try_from(encoded_invoice) {
2435 Ok(_) => panic!("expected error"),
2436 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2441 fn fails_parsing_invoice_with_message_paths() {
2442 let invoice = OfferBuilder::new(recipient_pubkey())
2445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2447 .sign(payer_sign).unwrap()
2448 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2450 .sign(recipient_sign).unwrap();
2452 let blinded_path = BlindedPath {
2453 introduction_node: IntroductionNode::NodeId(pubkey(40)),
2454 blinding_point: pubkey(41),
2456 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
2457 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 44] },
2461 let mut tlv_stream = invoice.as_tlv_stream();
2462 let message_paths = vec![blinded_path];
2463 tlv_stream.3.message_paths = Some(&message_paths);
2465 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2466 Ok(_) => panic!("expected error"),
2467 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedPaths)),