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, ExplicitSigningPubkey, InvoiceBuilder};
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::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
46 //! // Invoice for the "offer to be paid" flow.
47 //! # <InvoiceBuilder<ExplicitSigningPubkey>>::from(
48 //! InvoiceRequest::try_from(bytes)?
49 #![cfg_attr(feature = "std", doc = "
50 .respond_with(payment_paths, payment_hash)?
52 #![cfg_attr(not(feature = "std"), doc = "
53 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
56 //! .relative_expiry(3600)
58 //! .fallback_v0_p2wpkh(&wpubkey_hash)
60 //! .sign::<_, Infallible>(
61 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
63 //! .expect("failed verifying signature")
64 //! .write(&mut buffer)
69 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
70 //! # let payment_paths = create_payment_paths();
71 //! # let payment_hash = create_payment_hash();
72 //! # let secp_ctx = Secp256k1::new();
73 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
74 //! # let pubkey = PublicKey::from(keys);
75 //! # let wpubkey_hash = bitcoin::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
76 //! # let mut buffer = Vec::new();
78 //! // Invoice for the "offer for money" flow.
79 //! # <InvoiceBuilder<ExplicitSigningPubkey>>::from(
81 //! .parse::<Refund>()?
82 #![cfg_attr(feature = "std", doc = "
83 .respond_with(payment_paths, payment_hash, pubkey)?
85 #![cfg_attr(not(feature = "std"), doc = "
86 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
89 //! .relative_expiry(3600)
91 //! .fallback_v0_p2wpkh(&wpubkey_hash)
93 //! .sign::<_, Infallible>(
94 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
96 //! .expect("failed verifying signature")
97 //! .write(&mut buffer)
104 use bitcoin::blockdata::constants::ChainHash;
105 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
106 use bitcoin::hashes::Hash;
107 use bitcoin::network::constants::Network;
108 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
109 use bitcoin::secp256k1::schnorr::Signature;
110 use bitcoin::address::{Address, Payload, WitnessProgram, WitnessVersion};
111 use bitcoin::key::TweakedPublicKey;
112 use core::convert::{AsRef, Infallible, TryFrom};
113 use core::time::Duration;
115 use crate::blinded_path::BlindedPath;
116 use crate::ln::PaymentHash;
117 use crate::ln::channelmanager::PaymentId;
118 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
119 use crate::ln::inbound_payment::ExpandedKey;
120 use crate::ln::msgs::DecodeError;
121 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
122 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
123 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef, Quantity};
124 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
125 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
126 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
127 use crate::offers::signer;
128 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
129 use crate::util::string::PrintableString;
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(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
213 ) -> Result<Self, Bolt12SemanticError> {
214 let amount_msats = Self::amount_msats(invoice_request)?;
215 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
216 let contents = InvoiceContents::ForOffer {
217 invoice_request: invoice_request.contents.clone(),
218 fields: Self::fields(
219 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
223 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
226 #[cfg_attr(c_bindings, allow(dead_code))]
227 pub(super) fn for_refund(
228 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
229 payment_hash: PaymentHash, signing_pubkey: PublicKey
230 ) -> Result<Self, Bolt12SemanticError> {
231 let amount_msats = refund.amount_msats();
232 let contents = InvoiceContents::ForRefund {
233 refund: refund.contents.clone(),
234 fields: Self::fields(
235 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
239 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
242 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
243 /// [`UnsignedBolt12Invoice::sign`].
244 pub fn build($self: $self_type) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
245 #[cfg(feature = "std")] {
246 if $self.invoice.is_offer_or_refund_expired() {
247 return Err(Bolt12SemanticError::AlreadyExpired);
251 #[cfg(not(feature = "std"))] {
252 if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
253 return Err(Bolt12SemanticError::AlreadyExpired);
257 let Self { invreq_bytes, invoice, .. } = $self;
258 #[cfg(not(c_bindings))] {
259 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
262 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone()))
267 macro_rules! invoice_derived_signing_pubkey_builder_methods { ($self: ident, $self_type: ty) => {
268 #[cfg_attr(c_bindings, allow(dead_code))]
269 pub(super) fn for_offer_using_keys(
270 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
271 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
272 ) -> Result<Self, Bolt12SemanticError> {
273 let amount_msats = Self::amount_msats(invoice_request)?;
274 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
275 let contents = InvoiceContents::ForOffer {
276 invoice_request: invoice_request.contents.clone(),
277 fields: Self::fields(
278 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
282 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
285 #[cfg_attr(c_bindings, allow(dead_code))]
286 pub(super) fn for_refund_using_keys(
287 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
288 payment_hash: PaymentHash, keys: KeyPair,
289 ) -> Result<Self, Bolt12SemanticError> {
290 let amount_msats = refund.amount_msats();
291 let signing_pubkey = keys.public_key();
292 let contents = InvoiceContents::ForRefund {
293 refund: refund.contents.clone(),
294 fields: Self::fields(
295 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
299 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
302 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
303 pub fn build_and_sign<T: secp256k1::Signing>(
304 $self: $self_type, secp_ctx: &Secp256k1<T>
305 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
306 #[cfg(feature = "std")] {
307 if $self.invoice.is_offer_or_refund_expired() {
308 return Err(Bolt12SemanticError::AlreadyExpired);
312 #[cfg(not(feature = "std"))] {
313 if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
314 return Err(Bolt12SemanticError::AlreadyExpired);
319 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
321 #[cfg(not(c_bindings))]
322 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
324 let mut unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone());
326 let invoice = unsigned_invoice
327 .sign::<_, Infallible>(
328 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
335 macro_rules! invoice_builder_methods { (
336 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $type_param: ty $(, $self_mut: tt)?
338 pub(crate) fn amount_msats(
339 invoice_request: &InvoiceRequest
340 ) -> Result<u64, Bolt12SemanticError> {
341 match invoice_request.amount_msats() {
342 Some(amount_msats) => Ok(amount_msats),
343 None => match invoice_request.contents.inner.offer.amount() {
344 Some(Amount::Bitcoin { amount_msats }) => {
345 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
346 .ok_or(Bolt12SemanticError::InvalidAmount)
348 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
349 None => Err(Bolt12SemanticError::MissingAmount),
354 #[cfg_attr(c_bindings, allow(dead_code))]
356 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
357 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
360 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
361 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
365 #[cfg_attr(c_bindings, allow(dead_code))]
367 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: $type_param
368 ) -> Result<Self, Bolt12SemanticError> {
369 if contents.fields().payment_paths.is_empty() {
370 return Err(Bolt12SemanticError::MissingPaths);
373 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
376 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
377 /// Any expiry that has already passed is valid and can be checked for using
378 /// [`Bolt12Invoice::is_expired`].
380 /// Successive calls to this method will override the previous setting.
381 pub fn relative_expiry($($self_mut)* $self: $self_type, relative_expiry_secs: u32) -> $return_type {
382 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
383 $self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
387 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
389 /// Successive calls to this method will add another address. Caller is responsible for not
390 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
391 pub fn fallback_v0_p2wsh($($self_mut)* $self: $self_type, script_hash: &WScriptHash) -> $return_type {
392 let address = FallbackAddress {
393 version: WitnessVersion::V0.to_num(),
394 program: Vec::from(script_hash.to_byte_array()),
396 $self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
400 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
402 /// Successive calls to this method will add another address. Caller is responsible for not
403 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
404 pub fn fallback_v0_p2wpkh($($self_mut)* $self: $self_type, pubkey_hash: &WPubkeyHash) -> $return_type {
405 let address = FallbackAddress {
406 version: WitnessVersion::V0.to_num(),
407 program: Vec::from(pubkey_hash.to_byte_array()),
409 $self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
413 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
415 /// Successive calls to this method will add another address. Caller is responsible for not
416 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
417 pub fn fallback_v1_p2tr_tweaked($($self_mut)* $self: $self_type, output_key: &TweakedPublicKey) -> $return_type {
418 let address = FallbackAddress {
419 version: WitnessVersion::V1.to_num(),
420 program: Vec::from(&output_key.serialize()[..]),
422 $self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
426 /// Sets [`Bolt12Invoice::invoice_features`] to indicate MPP may be used. Otherwise, MPP is
428 pub fn allow_mpp($($self_mut)* $self: $self_type) -> $return_type {
429 $self.invoice.fields_mut().features.set_basic_mpp_optional();
434 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
435 invoice_explicit_signing_pubkey_builder_methods!(self, Self);
438 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
439 invoice_derived_signing_pubkey_builder_methods!(self, Self);
442 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
443 invoice_builder_methods!(self, Self, Self, self, S, mut);
446 #[cfg(all(c_bindings, not(test)))]
447 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
448 invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
449 invoice_builder_methods!(self, &mut Self, (), (), ExplicitSigningPubkey);
452 #[cfg(all(c_bindings, test))]
453 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
454 invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
455 invoice_builder_methods!(self, &mut Self, &mut Self, self, ExplicitSigningPubkey);
458 #[cfg(all(c_bindings, not(test)))]
459 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
460 invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
461 invoice_builder_methods!(self, &mut Self, (), (), DerivedSigningPubkey);
464 #[cfg(all(c_bindings, test))]
465 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
466 invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
467 invoice_builder_methods!(self, &mut Self, &mut Self, self, DerivedSigningPubkey);
471 impl<'a> From<InvoiceWithExplicitSigningPubkeyBuilder<'a>>
472 for InvoiceBuilder<'a, ExplicitSigningPubkey> {
473 fn from(builder: InvoiceWithExplicitSigningPubkeyBuilder<'a>) -> Self {
474 let InvoiceWithExplicitSigningPubkeyBuilder {
475 invreq_bytes, invoice, signing_pubkey_strategy,
479 invreq_bytes, invoice, signing_pubkey_strategy,
485 impl<'a> From<InvoiceWithDerivedSigningPubkeyBuilder<'a>>
486 for InvoiceBuilder<'a, DerivedSigningPubkey> {
487 fn from(builder: InvoiceWithDerivedSigningPubkeyBuilder<'a>) -> Self {
488 let InvoiceWithDerivedSigningPubkeyBuilder {
489 invreq_bytes, invoice, signing_pubkey_strategy,
493 invreq_bytes, invoice, signing_pubkey_strategy,
498 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
502 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
503 /// such, it may include unknown, odd TLV records.
504 pub struct UnsignedBolt12Invoice {
506 contents: InvoiceContents,
507 tagged_hash: TaggedHash,
510 impl UnsignedBolt12Invoice {
511 fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
512 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
513 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
515 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
516 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
517 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
519 let mut bytes = Vec::new();
520 unsigned_tlv_stream.write(&mut bytes).unwrap();
522 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
524 Self { bytes, contents, tagged_hash }
527 /// Returns the [`TaggedHash`] of the invoice to sign.
528 pub fn tagged_hash(&self) -> &TaggedHash {
533 macro_rules! unsigned_invoice_sign_method { ($self: ident, $self_type: ty $(, $self_mut: tt)?) => {
534 /// Signs the [`TaggedHash`] of the invoice using the given function.
536 /// Note: The hash computation may have included unknown, odd TLV records.
538 /// This is not exported to bindings users as functions aren't currently mapped.
539 pub fn sign<F, E>($($self_mut)* $self: $self_type, sign: F) -> Result<Bolt12Invoice, SignError<E>>
541 F: FnOnce(&Self) -> Result<Signature, E>
543 let pubkey = $self.contents.fields().signing_pubkey;
544 let signature = merkle::sign_message(sign, &$self, pubkey)?;
546 // Append the signature TLV record to the bytes.
547 let signature_tlv_stream = SignatureTlvStreamRef {
548 signature: Some(&signature),
550 signature_tlv_stream.write(&mut $self.bytes).unwrap();
553 #[cfg(not(c_bindings))]
556 bytes: $self.bytes.clone(),
557 #[cfg(not(c_bindings))]
558 contents: $self.contents,
560 contents: $self.contents.clone(),
562 #[cfg(not(c_bindings))]
563 tagged_hash: $self.tagged_hash,
565 tagged_hash: $self.tagged_hash.clone(),
570 #[cfg(not(c_bindings))]
571 impl UnsignedBolt12Invoice {
572 unsigned_invoice_sign_method!(self, Self, mut);
576 impl UnsignedBolt12Invoice {
577 unsigned_invoice_sign_method!(self, &mut Self);
580 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
581 fn as_ref(&self) -> &TaggedHash {
586 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
588 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
589 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
591 /// [`Offer`]: crate::offers::offer::Offer
592 /// [`Refund`]: crate::offers::refund::Refund
593 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
594 #[derive(Clone, Debug)]
595 #[cfg_attr(test, derive(PartialEq))]
596 pub struct Bolt12Invoice {
598 contents: InvoiceContents,
599 signature: Signature,
600 tagged_hash: TaggedHash,
603 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
605 /// [`Offer`]: crate::offers::offer::Offer
606 /// [`Refund`]: crate::offers::refund::Refund
607 #[derive(Clone, Debug)]
608 #[cfg_attr(test, derive(PartialEq))]
609 enum InvoiceContents {
610 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
612 /// [`Offer`]: crate::offers::offer::Offer
614 invoice_request: InvoiceRequestContents,
615 fields: InvoiceFields,
617 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
619 /// [`Refund`]: crate::offers::refund::Refund
621 refund: RefundContents,
622 fields: InvoiceFields,
626 /// Invoice-specific fields for an `invoice` message.
627 #[derive(Clone, Debug, PartialEq)]
628 struct InvoiceFields {
629 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
630 created_at: Duration,
631 relative_expiry: Option<Duration>,
632 payment_hash: PaymentHash,
634 fallbacks: Option<Vec<FallbackAddress>>,
635 features: Bolt12InvoiceFeatures,
636 signing_pubkey: PublicKey,
639 macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
640 /// The chains that may be used when paying a requested invoice.
642 /// From [`Offer::chains`]; `None` if the invoice was created in response to a [`Refund`].
644 /// [`Offer::chains`]: crate::offers::offer::Offer::chains
645 pub fn offer_chains(&$self) -> Option<Vec<ChainHash>> {
646 $contents.offer_chains()
649 /// The chain that must be used when paying the invoice; selected from [`offer_chains`] if the
650 /// invoice originated from an offer.
652 /// From [`InvoiceRequest::chain`] or [`Refund::chain`].
654 /// [`offer_chains`]: Self::offer_chains
655 /// [`InvoiceRequest::chain`]: crate::offers::invoice_request::InvoiceRequest::chain
656 pub fn chain(&$self) -> ChainHash {
660 /// Opaque bytes set by the originating [`Offer`].
662 /// From [`Offer::metadata`]; `None` if the invoice was created in response to a [`Refund`] or
663 /// if the [`Offer`] did not set it.
665 /// [`Offer`]: crate::offers::offer::Offer
666 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
667 pub fn metadata(&$self) -> Option<&Vec<u8>> {
671 /// The minimum amount required for a successful payment of a single item.
673 /// From [`Offer::amount`]; `None` if the invoice was created in response to a [`Refund`] or if
674 /// the [`Offer`] did not set it.
676 /// [`Offer`]: crate::offers::offer::Offer
677 /// [`Offer::amount`]: crate::offers::offer::Offer::amount
678 pub fn amount(&$self) -> Option<&Amount> {
682 /// Features pertaining to the originating [`Offer`].
684 /// From [`Offer::offer_features`]; `None` if the invoice was created in response to a
687 /// [`Offer`]: crate::offers::offer::Offer
688 /// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features
689 pub fn offer_features(&$self) -> Option<&OfferFeatures> {
690 $contents.offer_features()
693 /// A complete description of the purpose of the originating offer or refund.
695 /// From [`Offer::description`] or [`Refund::description`].
697 /// [`Offer::description`]: crate::offers::offer::Offer::description
698 pub fn description(&$self) -> PrintableString {
699 $contents.description()
702 /// Duration since the Unix epoch when an invoice should no longer be requested.
704 /// From [`Offer::absolute_expiry`] or [`Refund::absolute_expiry`].
706 /// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry
707 pub fn absolute_expiry(&$self) -> Option<Duration> {
708 $contents.absolute_expiry()
711 /// The issuer of the offer or refund.
713 /// From [`Offer::issuer`] or [`Refund::issuer`].
715 /// [`Offer::issuer`]: crate::offers::offer::Offer::issuer
716 pub fn issuer(&$self) -> Option<PrintableString> {
720 /// Paths to the recipient originating from publicly reachable nodes.
722 /// From [`Offer::paths`] or [`Refund::paths`].
724 /// [`Offer::paths`]: crate::offers::offer::Offer::paths
725 pub fn message_paths(&$self) -> &[BlindedPath] {
726 $contents.message_paths()
729 /// The quantity of items supported.
731 /// From [`Offer::supported_quantity`]; `None` if the invoice was created in response to a
734 /// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
735 pub fn supported_quantity(&$self) -> Option<Quantity> {
736 $contents.supported_quantity()
739 /// An unpredictable series of bytes from the payer.
741 /// From [`InvoiceRequest::payer_metadata`] or [`Refund::payer_metadata`].
742 pub fn payer_metadata(&$self) -> &[u8] {
743 $contents.payer_metadata()
746 /// Features pertaining to requesting an invoice.
748 /// From [`InvoiceRequest::invoice_request_features`] or [`Refund::features`].
749 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
750 &$contents.invoice_request_features()
753 /// The quantity of items requested or refunded for.
755 /// From [`InvoiceRequest::quantity`] or [`Refund::quantity`].
756 pub fn quantity(&$self) -> Option<u64> {
760 /// A possibly transient pubkey used to sign the invoice request or to send an invoice for a
761 /// refund in case there are no [`message_paths`].
763 /// [`message_paths`]: Self::message_paths
764 pub fn payer_id(&$self) -> PublicKey {
768 /// A payer-provided note reflected back in the invoice.
770 /// From [`InvoiceRequest::payer_note`] or [`Refund::payer_note`].
771 pub fn payer_note(&$self) -> Option<PrintableString> {
772 $contents.payer_note()
775 /// Paths to the recipient originating from publicly reachable nodes, including information
776 /// needed for routing payments across them.
778 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
779 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
781 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
782 /// matched in another language.
783 pub fn payment_paths(&$self) -> &[(BlindedPayInfo, BlindedPath)] {
784 $contents.payment_paths()
787 /// Duration since the Unix epoch when the invoice was created.
788 pub fn created_at(&$self) -> Duration {
789 $contents.created_at()
792 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
793 /// should no longer be paid.
794 pub fn relative_expiry(&$self) -> Duration {
795 $contents.relative_expiry()
798 /// Whether the invoice has expired.
799 #[cfg(feature = "std")]
800 pub fn is_expired(&$self) -> bool {
801 $contents.is_expired()
804 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
805 pub fn payment_hash(&$self) -> PaymentHash {
806 $contents.payment_hash()
809 /// The minimum amount required for a successful payment of the invoice.
810 pub fn amount_msats(&$self) -> u64 {
811 $contents.amount_msats()
814 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
816 pub fn fallbacks(&$self) -> Vec<Address> {
817 $contents.fallbacks()
820 /// Features pertaining to paying an invoice.
821 pub fn invoice_features(&$self) -> &Bolt12InvoiceFeatures {
825 /// The public key corresponding to the key used to sign the invoice.
826 pub fn signing_pubkey(&$self) -> PublicKey {
827 $contents.signing_pubkey()
831 impl UnsignedBolt12Invoice {
832 invoice_accessors!(self, self.contents);
836 invoice_accessors!(self, self.contents);
838 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
839 pub fn signature(&self) -> Signature {
843 /// Hash that was used for signing the invoice.
844 pub fn signable_hash(&self) -> [u8; 32] {
845 self.tagged_hash.as_digest().as_ref().clone()
848 /// Verifies that the invoice was for a request or refund created using the given key. Returns
849 /// the associated [`PaymentId`] to use when sending the payment.
850 pub fn verify<T: secp256k1::Signing>(
851 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
852 ) -> Result<PaymentId, ()> {
853 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
856 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
857 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
858 self.contents.as_tlv_stream();
859 let signature_tlv_stream = SignatureTlvStreamRef {
860 signature: Some(&self.signature),
862 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
863 signature_tlv_stream)
867 impl InvoiceContents {
868 /// Whether the original offer or refund has expired.
869 #[cfg(feature = "std")]
870 fn is_offer_or_refund_expired(&self) -> bool {
872 InvoiceContents::ForOffer { invoice_request, .. } =>
873 invoice_request.inner.offer.is_expired(),
874 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
878 #[cfg(not(feature = "std"))]
879 fn is_offer_or_refund_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
881 InvoiceContents::ForOffer { invoice_request, .. } =>
882 invoice_request.inner.offer.is_expired_no_std(duration_since_epoch),
883 InvoiceContents::ForRefund { refund, .. } =>
884 refund.is_expired_no_std(duration_since_epoch),
888 fn offer_chains(&self) -> Option<Vec<ChainHash>> {
890 InvoiceContents::ForOffer { invoice_request, .. } =>
891 Some(invoice_request.inner.offer.chains()),
892 InvoiceContents::ForRefund { .. } => None,
896 fn chain(&self) -> ChainHash {
898 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
899 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
903 fn metadata(&self) -> Option<&Vec<u8>> {
905 InvoiceContents::ForOffer { invoice_request, .. } =>
906 invoice_request.inner.offer.metadata(),
907 InvoiceContents::ForRefund { .. } => None,
911 fn amount(&self) -> Option<&Amount> {
913 InvoiceContents::ForOffer { invoice_request, .. } =>
914 invoice_request.inner.offer.amount(),
915 InvoiceContents::ForRefund { .. } => None,
919 fn description(&self) -> PrintableString {
921 InvoiceContents::ForOffer { invoice_request, .. } => {
922 invoice_request.inner.offer.description()
924 InvoiceContents::ForRefund { refund, .. } => refund.description(),
928 fn offer_features(&self) -> Option<&OfferFeatures> {
930 InvoiceContents::ForOffer { invoice_request, .. } => {
931 Some(invoice_request.inner.offer.features())
933 InvoiceContents::ForRefund { .. } => None,
937 fn absolute_expiry(&self) -> Option<Duration> {
939 InvoiceContents::ForOffer { invoice_request, .. } => {
940 invoice_request.inner.offer.absolute_expiry()
942 InvoiceContents::ForRefund { refund, .. } => refund.absolute_expiry(),
946 fn issuer(&self) -> Option<PrintableString> {
948 InvoiceContents::ForOffer { invoice_request, .. } => {
949 invoice_request.inner.offer.issuer()
951 InvoiceContents::ForRefund { refund, .. } => refund.issuer(),
955 fn message_paths(&self) -> &[BlindedPath] {
957 InvoiceContents::ForOffer { invoice_request, .. } => {
958 invoice_request.inner.offer.paths()
960 InvoiceContents::ForRefund { refund, .. } => refund.paths(),
964 fn supported_quantity(&self) -> Option<Quantity> {
966 InvoiceContents::ForOffer { invoice_request, .. } => {
967 Some(invoice_request.inner.offer.supported_quantity())
969 InvoiceContents::ForRefund { .. } => None,
973 fn payer_metadata(&self) -> &[u8] {
975 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.metadata(),
976 InvoiceContents::ForRefund { refund, .. } => refund.metadata(),
980 fn invoice_request_features(&self) -> &InvoiceRequestFeatures {
982 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.features(),
983 InvoiceContents::ForRefund { refund, .. } => refund.features(),
987 fn quantity(&self) -> Option<u64> {
989 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.quantity(),
990 InvoiceContents::ForRefund { refund, .. } => refund.quantity(),
994 fn payer_id(&self) -> PublicKey {
996 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_id(),
997 InvoiceContents::ForRefund { refund, .. } => refund.payer_id(),
1001 fn payer_note(&self) -> Option<PrintableString> {
1003 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_note(),
1004 InvoiceContents::ForRefund { refund, .. } => refund.payer_note(),
1008 fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1009 &self.fields().payment_paths[..]
1012 fn created_at(&self) -> Duration {
1013 self.fields().created_at
1016 fn relative_expiry(&self) -> Duration {
1017 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
1020 #[cfg(feature = "std")]
1021 fn is_expired(&self) -> bool {
1022 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
1023 match absolute_expiry {
1024 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
1025 Ok(elapsed) => elapsed > seconds_from_epoch,
1032 fn payment_hash(&self) -> PaymentHash {
1033 self.fields().payment_hash
1036 fn amount_msats(&self) -> u64 {
1037 self.fields().amount_msats
1040 fn fallbacks(&self) -> Vec<Address> {
1041 let chain = self.chain();
1042 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
1044 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
1046 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
1048 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
1054 let to_valid_address = |address: &FallbackAddress| {
1055 let version = match WitnessVersion::try_from(address.version) {
1056 Ok(version) => version,
1057 Err(_) => return None,
1060 let program = &address.program;
1061 let witness_program = match WitnessProgram::new(version, program.clone()) {
1062 Ok(witness_program) => witness_program,
1063 Err(_) => return None,
1065 Some(Address::new(network, Payload::WitnessProgram(witness_program)))
1068 self.fields().fallbacks
1070 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
1071 .unwrap_or_else(Vec::new)
1074 fn features(&self) -> &Bolt12InvoiceFeatures {
1075 &self.fields().features
1078 fn signing_pubkey(&self) -> PublicKey {
1079 self.fields().signing_pubkey
1082 fn fields(&self) -> &InvoiceFields {
1084 InvoiceContents::ForOffer { fields, .. } => fields,
1085 InvoiceContents::ForRefund { fields, .. } => fields,
1089 fn fields_mut(&mut self) -> &mut InvoiceFields {
1091 InvoiceContents::ForOffer { fields, .. } => fields,
1092 InvoiceContents::ForRefund { fields, .. } => fields,
1096 fn verify<T: secp256k1::Signing>(
1097 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
1098 ) -> Result<PaymentId, ()> {
1099 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
1100 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
1101 match record.r#type {
1102 PAYER_METADATA_TYPE => false, // Should be outside range
1103 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
1107 let tlv_stream = offer_records.chain(invreq_records);
1109 let (metadata, payer_id, iv_bytes) = match self {
1110 InvoiceContents::ForOffer { invoice_request, .. } => {
1111 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
1113 InvoiceContents::ForRefund { refund, .. } => {
1114 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
1118 signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
1121 fn derives_keys(&self) -> bool {
1123 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
1124 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
1128 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
1129 let (payer, offer, invoice_request) = match self {
1130 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
1131 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
1133 let invoice = self.fields().as_tlv_stream();
1135 (payer, offer, invoice_request, invoice)
1139 impl InvoiceFields {
1140 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
1142 if self.features == Bolt12InvoiceFeatures::empty() { None }
1143 else { Some(&self.features) }
1146 InvoiceTlvStreamRef {
1147 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
1148 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
1149 created_at: Some(self.created_at.as_secs()),
1150 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
1151 payment_hash: Some(&self.payment_hash),
1152 amount: Some(self.amount_msats),
1153 fallbacks: self.fallbacks.as_ref(),
1155 node_id: Some(&self.signing_pubkey),
1160 impl Writeable for UnsignedBolt12Invoice {
1161 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1162 WithoutLength(&self.bytes).write(writer)
1166 impl Writeable for Bolt12Invoice {
1167 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1168 WithoutLength(&self.bytes).write(writer)
1172 impl Writeable for InvoiceContents {
1173 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1174 self.as_tlv_stream().write(writer)
1178 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
1179 type Error = Bolt12ParseError;
1181 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1182 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
1183 let ParsedMessage { bytes, tlv_stream } = invoice;
1185 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1187 let contents = InvoiceContents::try_from(
1188 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1191 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1193 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
1197 impl TryFrom<Vec<u8>> for Bolt12Invoice {
1198 type Error = Bolt12ParseError;
1200 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1201 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
1202 Bolt12Invoice::try_from(parsed_invoice)
1206 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
1207 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
1208 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
1209 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
1210 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
1211 (168, payment_hash: PaymentHash),
1212 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
1213 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
1214 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
1215 (176, node_id: PublicKey),
1218 type BlindedPathIter<'a> = core::iter::Map<
1219 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1220 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
1223 type BlindedPayInfoIter<'a> = core::iter::Map<
1224 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1225 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
1228 /// Information needed to route a payment across a [`BlindedPath`].
1229 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
1230 pub struct BlindedPayInfo {
1231 /// Base fee charged (in millisatoshi) for the entire blinded path.
1232 pub fee_base_msat: u32,
1234 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
1235 /// (i.e., 10,000 is 1%).
1236 pub fee_proportional_millionths: u32,
1238 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
1240 pub cltv_expiry_delta: u16,
1242 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1243 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1244 /// seen by the recipient.
1245 pub htlc_minimum_msat: u64,
1247 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1248 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1249 /// seen by the recipient.
1250 pub htlc_maximum_msat: u64,
1252 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
1254 pub features: BlindedHopFeatures,
1257 impl_writeable!(BlindedPayInfo, {
1259 fee_proportional_millionths,
1266 /// Wire representation for an on-chain fallback address.
1267 #[derive(Clone, Debug, PartialEq)]
1268 pub(super) struct FallbackAddress {
1273 impl_writeable!(FallbackAddress, { version, program });
1275 type FullInvoiceTlvStream =
1276 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
1278 type FullInvoiceTlvStreamRef<'a> = (
1279 PayerTlvStreamRef<'a>,
1280 OfferTlvStreamRef<'a>,
1281 InvoiceRequestTlvStreamRef<'a>,
1282 InvoiceTlvStreamRef<'a>,
1283 SignatureTlvStreamRef<'a>,
1286 impl SeekReadable for FullInvoiceTlvStream {
1287 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1288 let payer = SeekReadable::read(r)?;
1289 let offer = SeekReadable::read(r)?;
1290 let invoice_request = SeekReadable::read(r)?;
1291 let invoice = SeekReadable::read(r)?;
1292 let signature = SeekReadable::read(r)?;
1294 Ok((payer, offer, invoice_request, invoice, signature))
1298 type PartialInvoiceTlvStream =
1299 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
1301 type PartialInvoiceTlvStreamRef<'a> = (
1302 PayerTlvStreamRef<'a>,
1303 OfferTlvStreamRef<'a>,
1304 InvoiceRequestTlvStreamRef<'a>,
1305 InvoiceTlvStreamRef<'a>,
1308 impl SeekReadable for PartialInvoiceTlvStream {
1309 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1310 let payer = SeekReadable::read(r)?;
1311 let offer = SeekReadable::read(r)?;
1312 let invoice_request = SeekReadable::read(r)?;
1313 let invoice = SeekReadable::read(r)?;
1315 Ok((payer, offer, invoice_request, invoice))
1319 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
1320 type Error = Bolt12ParseError;
1322 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
1323 let ParsedMessage { bytes, tlv_stream } = invoice;
1325 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1326 SignatureTlvStream { signature },
1328 let contents = InvoiceContents::try_from(
1329 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1332 let signature = match signature {
1333 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1334 Some(signature) => signature,
1336 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1337 let pubkey = contents.fields().signing_pubkey;
1338 merkle::verify_signature(&signature, &tagged_hash, pubkey)?;
1340 Ok(Bolt12Invoice { bytes, contents, signature, tagged_hash })
1344 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
1345 type Error = Bolt12SemanticError;
1347 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
1351 invoice_request_tlv_stream,
1353 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
1358 let payment_paths = match (blindedpay, paths) {
1359 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
1360 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
1361 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1362 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
1363 return Err(Bolt12SemanticError::InvalidPayInfo);
1365 (Some(blindedpay), Some(paths)) => {
1366 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
1370 let created_at = match created_at {
1371 None => return Err(Bolt12SemanticError::MissingCreationTime),
1372 Some(timestamp) => Duration::from_secs(timestamp),
1375 let relative_expiry = relative_expiry
1376 .map(Into::<u64>::into)
1377 .map(Duration::from_secs);
1379 let payment_hash = match payment_hash {
1380 None => return Err(Bolt12SemanticError::MissingPaymentHash),
1381 Some(payment_hash) => payment_hash,
1384 let amount_msats = match amount {
1385 None => return Err(Bolt12SemanticError::MissingAmount),
1386 Some(amount) => amount,
1389 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1391 let signing_pubkey = match node_id {
1392 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1393 Some(node_id) => node_id,
1396 let fields = InvoiceFields {
1397 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1398 features, signing_pubkey,
1401 match offer_tlv_stream.node_id {
1402 Some(expected_signing_pubkey) => {
1403 if fields.signing_pubkey != expected_signing_pubkey {
1404 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1407 let invoice_request = InvoiceRequestContents::try_from(
1408 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1410 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1413 let refund = RefundContents::try_from(
1414 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1416 Ok(InvoiceContents::ForRefund { refund, fields })
1424 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1426 use bitcoin::blockdata::constants::ChainHash;
1427 use bitcoin::blockdata::script::ScriptBuf;
1428 use bitcoin::hashes::Hash;
1429 use bitcoin::network::constants::Network;
1430 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
1431 use bitcoin::address::{Address, Payload, WitnessProgram, WitnessVersion};
1432 use bitcoin::key::TweakedPublicKey;
1433 use core::convert::TryFrom;
1434 use core::time::Duration;
1435 use crate::blinded_path::{BlindedHop, BlindedPath};
1436 use crate::sign::KeyMaterial;
1437 use crate::ln::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
1438 use crate::ln::inbound_payment::ExpandedKey;
1439 use crate::ln::msgs::DecodeError;
1440 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1441 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1442 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1443 #[cfg(not(c_bindings))]
1445 crate::offers::offer::OfferBuilder,
1446 crate::offers::refund::RefundBuilder,
1450 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1451 crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
1453 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1454 use crate::offers::payer::PayerTlvStreamRef;
1455 use crate::offers::test_utils::*;
1456 use crate::util::ser::{BigSize, Iterable, Writeable};
1457 use crate::util::string::PrintableString;
1460 fn to_bytes(&self) -> Vec<u8>;
1463 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1464 fn to_bytes(&self) -> Vec<u8> {
1465 let mut buffer = Vec::new();
1466 self.0.write(&mut buffer).unwrap();
1467 self.1.write(&mut buffer).unwrap();
1468 self.2.write(&mut buffer).unwrap();
1469 self.3.write(&mut buffer).unwrap();
1470 self.4.write(&mut buffer).unwrap();
1476 fn builds_invoice_for_offer_with_defaults() {
1477 let payment_paths = payment_paths();
1478 let payment_hash = payment_hash();
1480 let unsigned_invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1483 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1485 .sign(payer_sign).unwrap()
1486 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1489 let mut buffer = Vec::new();
1490 unsigned_invoice.write(&mut buffer).unwrap();
1492 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1493 assert_eq!(unsigned_invoice.payer_metadata(), &[1; 32]);
1494 assert_eq!(unsigned_invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1495 assert_eq!(unsigned_invoice.metadata(), None);
1496 assert_eq!(unsigned_invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1497 assert_eq!(unsigned_invoice.description(), PrintableString("foo"));
1498 assert_eq!(unsigned_invoice.offer_features(), Some(&OfferFeatures::empty()));
1499 assert_eq!(unsigned_invoice.absolute_expiry(), None);
1500 assert_eq!(unsigned_invoice.message_paths(), &[]);
1501 assert_eq!(unsigned_invoice.issuer(), None);
1502 assert_eq!(unsigned_invoice.supported_quantity(), Some(Quantity::One));
1503 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1504 assert_eq!(unsigned_invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1505 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1506 assert_eq!(unsigned_invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1507 assert_eq!(unsigned_invoice.quantity(), None);
1508 assert_eq!(unsigned_invoice.payer_id(), payer_pubkey());
1509 assert_eq!(unsigned_invoice.payer_note(), None);
1510 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1511 assert_eq!(unsigned_invoice.created_at(), now);
1512 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1513 #[cfg(feature = "std")]
1514 assert!(!unsigned_invoice.is_expired());
1515 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1516 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1517 assert_eq!(unsigned_invoice.fallbacks(), vec![]);
1518 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1519 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1521 match UnsignedBolt12Invoice::try_from(buffer) {
1522 Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1524 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1525 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1530 let mut unsigned_invoice = unsigned_invoice;
1531 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1533 let mut buffer = Vec::new();
1534 invoice.write(&mut buffer).unwrap();
1536 assert_eq!(invoice.bytes, buffer.as_slice());
1537 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1538 assert_eq!(invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1539 assert_eq!(invoice.metadata(), None);
1540 assert_eq!(invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1541 assert_eq!(invoice.description(), PrintableString("foo"));
1542 assert_eq!(invoice.offer_features(), Some(&OfferFeatures::empty()));
1543 assert_eq!(invoice.absolute_expiry(), None);
1544 assert_eq!(invoice.message_paths(), &[]);
1545 assert_eq!(invoice.issuer(), None);
1546 assert_eq!(invoice.supported_quantity(), Some(Quantity::One));
1547 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1548 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1549 assert_eq!(invoice.amount_msats(), 1000);
1550 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1551 assert_eq!(invoice.quantity(), None);
1552 assert_eq!(invoice.payer_id(), payer_pubkey());
1553 assert_eq!(invoice.payer_note(), None);
1554 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1555 assert_eq!(invoice.created_at(), now);
1556 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1557 #[cfg(feature = "std")]
1558 assert!(!invoice.is_expired());
1559 assert_eq!(invoice.payment_hash(), payment_hash);
1560 assert_eq!(invoice.amount_msats(), 1000);
1561 assert_eq!(invoice.fallbacks(), vec![]);
1562 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1563 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1565 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1566 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1568 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1569 let pubkey = recipient_pubkey().into();
1570 let secp_ctx = Secp256k1::verification_only();
1571 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1574 invoice.as_tlv_stream(),
1576 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1582 description: Some(&String::from("foo")),
1584 absolute_expiry: None,
1588 node_id: Some(&recipient_pubkey()),
1590 InvoiceRequestTlvStreamRef {
1595 payer_id: Some(&payer_pubkey()),
1598 InvoiceTlvStreamRef {
1599 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1600 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1601 created_at: Some(now.as_secs()),
1602 relative_expiry: None,
1603 payment_hash: Some(&payment_hash),
1607 node_id: Some(&recipient_pubkey()),
1609 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1613 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1614 panic!("error parsing invoice: {:?}", e);
1619 fn builds_invoice_for_refund_with_defaults() {
1620 let payment_paths = payment_paths();
1621 let payment_hash = payment_hash();
1623 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1625 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1628 .sign(recipient_sign).unwrap();
1630 let mut buffer = Vec::new();
1631 invoice.write(&mut buffer).unwrap();
1633 assert_eq!(invoice.bytes, buffer.as_slice());
1634 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1635 assert_eq!(invoice.offer_chains(), None);
1636 assert_eq!(invoice.metadata(), None);
1637 assert_eq!(invoice.amount(), None);
1638 assert_eq!(invoice.description(), PrintableString("foo"));
1639 assert_eq!(invoice.offer_features(), None);
1640 assert_eq!(invoice.absolute_expiry(), None);
1641 assert_eq!(invoice.message_paths(), &[]);
1642 assert_eq!(invoice.issuer(), None);
1643 assert_eq!(invoice.supported_quantity(), None);
1644 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1645 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1646 assert_eq!(invoice.amount_msats(), 1000);
1647 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1648 assert_eq!(invoice.quantity(), None);
1649 assert_eq!(invoice.payer_id(), payer_pubkey());
1650 assert_eq!(invoice.payer_note(), None);
1651 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1652 assert_eq!(invoice.created_at(), now);
1653 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1654 #[cfg(feature = "std")]
1655 assert!(!invoice.is_expired());
1656 assert_eq!(invoice.payment_hash(), payment_hash);
1657 assert_eq!(invoice.amount_msats(), 1000);
1658 assert_eq!(invoice.fallbacks(), vec![]);
1659 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1660 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1662 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1663 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1666 invoice.as_tlv_stream(),
1668 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1674 description: Some(&String::from("foo")),
1676 absolute_expiry: None,
1682 InvoiceRequestTlvStreamRef {
1687 payer_id: Some(&payer_pubkey()),
1690 InvoiceTlvStreamRef {
1691 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1692 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1693 created_at: Some(now.as_secs()),
1694 relative_expiry: None,
1695 payment_hash: Some(&payment_hash),
1699 node_id: Some(&recipient_pubkey()),
1701 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1705 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1706 panic!("error parsing invoice: {:?}", e);
1710 #[cfg(feature = "std")]
1712 fn builds_invoice_from_offer_with_expiration() {
1713 let future_expiry = Duration::from_secs(u64::max_value());
1714 let past_expiry = Duration::from_secs(0);
1716 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1718 .absolute_expiry(future_expiry)
1720 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1722 .sign(payer_sign).unwrap()
1723 .respond_with(payment_paths(), payment_hash())
1727 panic!("error building invoice: {:?}", e);
1730 match OfferBuilder::new("foo".into(), recipient_pubkey())
1732 .absolute_expiry(past_expiry)
1734 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1736 .sign(payer_sign).unwrap()
1737 .respond_with(payment_paths(), payment_hash())
1741 Ok(_) => panic!("expected error"),
1742 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1746 #[cfg(feature = "std")]
1748 fn builds_invoice_from_refund_with_expiration() {
1749 let future_expiry = Duration::from_secs(u64::max_value());
1750 let past_expiry = Duration::from_secs(0);
1752 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1753 .absolute_expiry(future_expiry)
1755 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1759 panic!("error building invoice: {:?}", e);
1762 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1763 .absolute_expiry(past_expiry)
1765 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1769 Ok(_) => panic!("expected error"),
1770 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1775 fn builds_invoice_from_offer_using_derived_keys() {
1776 let desc = "foo".to_string();
1777 let node_id = recipient_pubkey();
1778 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1779 let entropy = FixedEntropy {};
1780 let secp_ctx = Secp256k1::new();
1782 let blinded_path = BlindedPath {
1783 introduction_node_id: pubkey(40),
1784 blinding_point: pubkey(41),
1786 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1787 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1792 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
1793 let offer = OfferBuilder
1794 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1798 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1800 .sign(payer_sign).unwrap();
1802 if let Err(e) = invoice_request.clone()
1803 .verify(&expanded_key, &secp_ctx).unwrap()
1804 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
1805 .build_and_sign(&secp_ctx)
1807 panic!("error building invoice: {:?}", e);
1810 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1811 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1813 let desc = "foo".to_string();
1814 let offer = OfferBuilder
1815 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1817 // Omit the path so that node_id is used for the signing pubkey instead of deriving
1819 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1821 .sign(payer_sign).unwrap();
1823 match invoice_request
1824 .verify(&expanded_key, &secp_ctx).unwrap()
1825 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
1827 Ok(_) => panic!("expected error"),
1828 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1833 fn builds_invoice_from_refund_using_derived_keys() {
1834 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1835 let entropy = FixedEntropy {};
1836 let secp_ctx = Secp256k1::new();
1838 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1841 if let Err(e) = refund
1842 .respond_using_derived_keys_no_std(
1843 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1846 .build_and_sign(&secp_ctx)
1848 panic!("error building invoice: {:?}", e);
1853 fn builds_invoice_with_relative_expiry() {
1855 let one_hour = Duration::from_secs(3600);
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()
1864 .relative_expiry(one_hour.as_secs() as u32)
1866 .sign(recipient_sign).unwrap();
1867 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1868 #[cfg(feature = "std")]
1869 assert!(!invoice.is_expired());
1870 assert_eq!(invoice.relative_expiry(), one_hour);
1871 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1873 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1876 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1878 .sign(payer_sign).unwrap()
1879 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1880 .relative_expiry(one_hour.as_secs() as u32 - 1)
1882 .sign(recipient_sign).unwrap();
1883 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1884 #[cfg(feature = "std")]
1885 assert!(invoice.is_expired());
1886 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1887 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1891 fn builds_invoice_with_amount_from_request() {
1892 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1895 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1896 .amount_msats(1001).unwrap()
1898 .sign(payer_sign).unwrap()
1899 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1901 .sign(recipient_sign).unwrap();
1902 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1903 assert_eq!(invoice.amount_msats(), 1001);
1904 assert_eq!(tlv_stream.amount, Some(1001));
1908 fn builds_invoice_with_quantity_from_request() {
1909 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1911 .supported_quantity(Quantity::Unbounded)
1913 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1914 .quantity(2).unwrap()
1916 .sign(payer_sign).unwrap()
1917 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1919 .sign(recipient_sign).unwrap();
1920 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1921 assert_eq!(invoice.amount_msats(), 2000);
1922 assert_eq!(tlv_stream.amount, Some(2000));
1924 match OfferBuilder::new("foo".into(), recipient_pubkey())
1926 .supported_quantity(Quantity::Unbounded)
1928 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1929 .quantity(u64::max_value()).unwrap()
1931 .sign(payer_sign).unwrap()
1932 .respond_with_no_std(payment_paths(), payment_hash(), now())
1934 Ok(_) => panic!("expected error"),
1935 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1940 fn builds_invoice_with_fallback_address() {
1941 let script = ScriptBuf::new();
1942 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
1943 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1944 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1946 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1949 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1951 .sign(payer_sign).unwrap()
1952 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1953 .fallback_v0_p2wsh(&script.wscript_hash())
1954 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1955 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1957 .sign(recipient_sign).unwrap();
1958 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1960 invoice.fallbacks(),
1962 Address::p2wsh(&script, Network::Bitcoin),
1963 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1964 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1968 tlv_stream.fallbacks,
1971 version: WitnessVersion::V0.to_num(),
1972 program: Vec::from(script.wscript_hash().to_byte_array()),
1975 version: WitnessVersion::V0.to_num(),
1976 program: Vec::from(pubkey.wpubkey_hash().unwrap().to_byte_array()),
1979 version: WitnessVersion::V1.to_num(),
1980 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1987 fn builds_invoice_with_allow_mpp() {
1988 let mut features = Bolt12InvoiceFeatures::empty();
1989 features.set_basic_mpp_optional();
1991 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1994 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1996 .sign(payer_sign).unwrap()
1997 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2000 .sign(recipient_sign).unwrap();
2001 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
2002 assert_eq!(invoice.invoice_features(), &features);
2003 assert_eq!(tlv_stream.features, Some(&features));
2007 fn fails_signing_invoice() {
2008 match OfferBuilder::new("foo".into(), recipient_pubkey())
2011 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2013 .sign(payer_sign).unwrap()
2014 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2018 Ok(_) => panic!("expected error"),
2019 Err(e) => assert_eq!(e, SignError::Signing(())),
2022 match OfferBuilder::new("foo".into(), recipient_pubkey())
2025 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2027 .sign(payer_sign).unwrap()
2028 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2032 Ok(_) => panic!("expected error"),
2033 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
2038 fn parses_invoice_with_payment_paths() {
2039 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2042 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2044 .sign(payer_sign).unwrap()
2045 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2047 .sign(recipient_sign).unwrap();
2049 let mut buffer = Vec::new();
2050 invoice.write(&mut buffer).unwrap();
2052 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2053 panic!("error parsing invoice: {:?}", e);
2056 let mut tlv_stream = invoice.as_tlv_stream();
2057 tlv_stream.3.paths = None;
2059 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2060 Ok(_) => panic!("expected error"),
2061 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2064 let mut tlv_stream = invoice.as_tlv_stream();
2065 tlv_stream.3.blindedpay = None;
2067 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2068 Ok(_) => panic!("expected error"),
2069 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2072 let empty_payment_paths = vec![];
2073 let mut tlv_stream = invoice.as_tlv_stream();
2074 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
2076 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2077 Ok(_) => panic!("expected error"),
2078 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2081 let mut payment_paths = payment_paths();
2082 payment_paths.pop();
2083 let mut tlv_stream = invoice.as_tlv_stream();
2084 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
2086 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2087 Ok(_) => panic!("expected error"),
2088 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2093 fn parses_invoice_with_created_at() {
2094 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2097 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2099 .sign(payer_sign).unwrap()
2100 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2102 .sign(recipient_sign).unwrap();
2104 let mut buffer = Vec::new();
2105 invoice.write(&mut buffer).unwrap();
2107 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2108 panic!("error parsing invoice: {:?}", e);
2111 let mut tlv_stream = invoice.as_tlv_stream();
2112 tlv_stream.3.created_at = None;
2114 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2115 Ok(_) => panic!("expected error"),
2117 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
2123 fn parses_invoice_with_relative_expiry() {
2124 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2127 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2129 .sign(payer_sign).unwrap()
2130 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2131 .relative_expiry(3600)
2133 .sign(recipient_sign).unwrap();
2135 let mut buffer = Vec::new();
2136 invoice.write(&mut buffer).unwrap();
2138 match Bolt12Invoice::try_from(buffer) {
2139 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
2140 Err(e) => panic!("error parsing invoice: {:?}", e),
2145 fn parses_invoice_with_payment_hash() {
2146 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2149 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2151 .sign(payer_sign).unwrap()
2152 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2154 .sign(recipient_sign).unwrap();
2156 let mut buffer = Vec::new();
2157 invoice.write(&mut buffer).unwrap();
2159 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2160 panic!("error parsing invoice: {:?}", e);
2163 let mut tlv_stream = invoice.as_tlv_stream();
2164 tlv_stream.3.payment_hash = None;
2166 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2167 Ok(_) => panic!("expected error"),
2169 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
2175 fn parses_invoice_with_amount() {
2176 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2179 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2181 .sign(payer_sign).unwrap()
2182 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2184 .sign(recipient_sign).unwrap();
2186 let mut buffer = Vec::new();
2187 invoice.write(&mut buffer).unwrap();
2189 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2190 panic!("error parsing invoice: {:?}", e);
2193 let mut tlv_stream = invoice.as_tlv_stream();
2194 tlv_stream.3.amount = None;
2196 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2197 Ok(_) => panic!("expected error"),
2198 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2203 fn parses_invoice_with_allow_mpp() {
2204 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2207 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2209 .sign(payer_sign).unwrap()
2210 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2213 .sign(recipient_sign).unwrap();
2215 let mut buffer = Vec::new();
2216 invoice.write(&mut buffer).unwrap();
2218 match Bolt12Invoice::try_from(buffer) {
2220 let mut features = Bolt12InvoiceFeatures::empty();
2221 features.set_basic_mpp_optional();
2222 assert_eq!(invoice.invoice_features(), &features);
2224 Err(e) => panic!("error parsing invoice: {:?}", e),
2229 fn parses_invoice_with_fallback_address() {
2230 let script = ScriptBuf::new();
2231 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
2232 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
2233 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
2235 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2238 let invoice_request = offer
2239 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2241 .sign(payer_sign).unwrap();
2242 #[cfg(not(c_bindings))]
2243 let invoice_builder = invoice_request
2244 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2246 let mut invoice_builder = invoice_request
2247 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2248 let invoice_builder = invoice_builder
2249 .fallback_v0_p2wsh(&script.wscript_hash())
2250 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
2251 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
2252 #[cfg(not(c_bindings))]
2253 let mut invoice_builder = invoice_builder;
2255 // Only standard addresses will be included.
2256 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
2257 // Non-standard addresses
2258 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
2259 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
2260 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
2262 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
2263 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
2265 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
2266 let mut buffer = Vec::new();
2267 invoice.write(&mut buffer).unwrap();
2269 match Bolt12Invoice::try_from(buffer) {
2271 let v1_witness_program = WitnessProgram::new(WitnessVersion::V1, vec![0u8; 33]).unwrap();
2272 let v2_witness_program = WitnessProgram::new(WitnessVersion::V2, vec![0u8; 40]).unwrap();
2274 invoice.fallbacks(),
2276 Address::p2wsh(&script, Network::Bitcoin),
2277 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
2278 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
2279 Address::new(Network::Bitcoin, Payload::WitnessProgram(v1_witness_program)),
2280 Address::new(Network::Bitcoin, Payload::WitnessProgram(v2_witness_program)),
2284 Err(e) => panic!("error parsing invoice: {:?}", e),
2289 fn parses_invoice_with_node_id() {
2290 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2293 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2295 .sign(payer_sign).unwrap()
2296 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2298 .sign(recipient_sign).unwrap();
2300 let mut buffer = Vec::new();
2301 invoice.write(&mut buffer).unwrap();
2303 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2304 panic!("error parsing invoice: {:?}", e);
2307 let mut tlv_stream = invoice.as_tlv_stream();
2308 tlv_stream.3.node_id = None;
2310 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2311 Ok(_) => panic!("expected error"),
2313 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2317 let invalid_pubkey = payer_pubkey();
2318 let mut tlv_stream = invoice.as_tlv_stream();
2319 tlv_stream.3.node_id = Some(&invalid_pubkey);
2321 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2322 Ok(_) => panic!("expected error"),
2324 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
2330 fn fails_parsing_invoice_without_signature() {
2331 let mut buffer = Vec::new();
2332 OfferBuilder::new("foo".into(), recipient_pubkey())
2335 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2337 .sign(payer_sign).unwrap()
2338 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2341 .write(&mut buffer).unwrap();
2343 match Bolt12Invoice::try_from(buffer) {
2344 Ok(_) => panic!("expected error"),
2345 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2350 fn fails_parsing_invoice_with_invalid_signature() {
2351 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2354 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2356 .sign(payer_sign).unwrap()
2357 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2359 .sign(recipient_sign).unwrap();
2360 let last_signature_byte = invoice.bytes.last_mut().unwrap();
2361 *last_signature_byte = last_signature_byte.wrapping_add(1);
2363 let mut buffer = Vec::new();
2364 invoice.write(&mut buffer).unwrap();
2366 match Bolt12Invoice::try_from(buffer) {
2367 Ok(_) => panic!("expected error"),
2369 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2375 fn fails_parsing_invoice_with_extra_tlv_records() {
2376 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2379 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2381 .sign(payer_sign).unwrap()
2382 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2384 .sign(recipient_sign).unwrap();
2386 let mut encoded_invoice = Vec::new();
2387 invoice.write(&mut encoded_invoice).unwrap();
2388 BigSize(1002).write(&mut encoded_invoice).unwrap();
2389 BigSize(32).write(&mut encoded_invoice).unwrap();
2390 [42u8; 32].write(&mut encoded_invoice).unwrap();
2392 match Bolt12Invoice::try_from(encoded_invoice) {
2393 Ok(_) => panic!("expected error"),
2394 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),