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 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! the invoice to the intended payer, who will then pay it.
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
20 //! extern crate bitcoin;
21 //! extern crate lightning;
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::blinded_path::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49 .respond_with(payment_paths, payment_hash)?
51 #![cfg_attr(not(feature = "std"), doc = "
52 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
54 //! .relative_expiry(3600)
56 //! .fallback_v0_p2wpkh(&wpubkey_hash)
58 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //! .expect("failed verifying signature")
60 //! .write(&mut buffer)
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
74 //! // Invoice for the "offer for money" flow.
76 //! .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78 .respond_with(payment_paths, payment_hash, pubkey)?
80 #![cfg_attr(not(feature = "std"), doc = "
81 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
83 //! .relative_expiry(3600)
85 //! .fallback_v0_p2wpkh(&wpubkey_hash)
87 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //! .expect("failed verifying signature")
89 //! .write(&mut buffer)
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, self};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::{Infallible, TryFrom};
105 use core::time::Duration;
107 use crate::blinded_path::BlindedPath;
108 use crate::ln::PaymentHash;
109 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
110 use crate::ln::inbound_payment::ExpandedKey;
111 use crate::ln::msgs::DecodeError;
112 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
113 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, WithoutSignatures, self};
114 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
115 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
116 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
117 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
118 use crate::offers::signer;
119 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
120 use crate::util::string::PrintableString;
122 use crate::prelude::*;
124 #[cfg(feature = "std")]
125 use std::time::SystemTime;
127 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
129 pub(super) const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
131 /// Builds an [`Invoice`] from either:
132 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
133 /// - a [`Refund`] for the "offer for money" flow.
135 /// See [module-level documentation] for usage.
137 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
139 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
140 /// [`Refund`]: crate::offers::refund::Refund
141 /// [module-level documentation]: self
142 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
143 invreq_bytes: &'a Vec<u8>,
144 invoice: InvoiceContents,
145 keys: Option<KeyPair>,
146 signing_pubkey_strategy: core::marker::PhantomData<S>,
149 /// Indicates how [`Invoice::signing_pubkey`] was set.
151 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
152 pub trait SigningPubkeyStrategy {}
154 /// [`Invoice::signing_pubkey`] was explicitly set.
156 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
157 pub struct ExplicitSigningPubkey {}
159 /// [`Invoice::signing_pubkey`] was derived.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub struct DerivedSigningPubkey {}
164 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
165 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
167 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
168 pub(super) fn for_offer(
169 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
170 created_at: Duration, payment_hash: PaymentHash
171 ) -> Result<Self, SemanticError> {
172 let amount_msats = Self::check_amount_msats(invoice_request)?;
173 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
174 let contents = InvoiceContents::ForOffer {
175 invoice_request: invoice_request.contents.clone(),
176 fields: Self::fields(
177 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
181 Self::new(&invoice_request.bytes, contents, None)
184 pub(super) fn for_refund(
185 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
186 payment_hash: PaymentHash, signing_pubkey: PublicKey
187 ) -> Result<Self, SemanticError> {
188 let amount_msats = refund.amount_msats();
189 let contents = InvoiceContents::ForRefund {
190 refund: refund.contents.clone(),
191 fields: Self::fields(
192 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
196 Self::new(&refund.bytes, contents, None)
200 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
201 pub(super) fn for_offer_using_keys(
202 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
203 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
204 ) -> Result<Self, SemanticError> {
205 let amount_msats = Self::check_amount_msats(invoice_request)?;
206 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
207 let contents = InvoiceContents::ForOffer {
208 invoice_request: invoice_request.contents.clone(),
209 fields: Self::fields(
210 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
214 Self::new(&invoice_request.bytes, contents, Some(keys))
217 pub(super) fn for_refund_using_keys(
218 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
219 payment_hash: PaymentHash, keys: KeyPair,
220 ) -> Result<Self, SemanticError> {
221 let amount_msats = refund.amount_msats();
222 let signing_pubkey = keys.public_key();
223 let contents = InvoiceContents::ForRefund {
224 refund: refund.contents.clone(),
225 fields: Self::fields(
226 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
230 Self::new(&refund.bytes, contents, Some(keys))
234 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
235 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, SemanticError> {
236 match invoice_request.amount_msats() {
237 Some(amount_msats) => Ok(amount_msats),
238 None => match invoice_request.contents.inner.offer.amount() {
239 Some(Amount::Bitcoin { amount_msats }) => {
240 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
241 .ok_or(SemanticError::InvalidAmount)
243 Some(Amount::Currency { .. }) => Err(SemanticError::UnsupportedCurrency),
244 None => Err(SemanticError::MissingAmount),
250 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
251 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
254 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
255 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
260 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
261 ) -> Result<Self, SemanticError> {
262 if contents.fields().payment_paths.is_empty() {
263 return Err(SemanticError::MissingPaths);
270 signing_pubkey_strategy: core::marker::PhantomData,
274 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
275 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
277 /// Successive calls to this method will override the previous setting.
278 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
279 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
280 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
284 /// Adds a P2WSH address to [`Invoice::fallbacks`].
286 /// Successive calls to this method will add another address. Caller is responsible for not
287 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
288 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
289 let address = FallbackAddress {
290 version: WitnessVersion::V0.to_num(),
291 program: Vec::from(&script_hash.into_inner()[..]),
293 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
297 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
299 /// Successive calls to this method will add another address. Caller is responsible for not
300 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
301 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
302 let address = FallbackAddress {
303 version: WitnessVersion::V0.to_num(),
304 program: Vec::from(&pubkey_hash.into_inner()[..]),
306 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
310 /// Adds a P2TR address to [`Invoice::fallbacks`].
312 /// Successive calls to this method will add another address. Caller is responsible for not
313 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
315 /// This is not exported to bindings users as TweakedPublicKey isn't yet mapped.
316 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
317 let address = FallbackAddress {
318 version: WitnessVersion::V1.to_num(),
319 program: Vec::from(&output_key.serialize()[..]),
321 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
325 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
326 pub fn allow_mpp(mut self) -> Self {
327 self.invoice.fields_mut().features.set_basic_mpp_optional();
332 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
333 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
334 /// [`UnsignedInvoice::sign`].
335 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
336 #[cfg(feature = "std")] {
337 if self.invoice.is_offer_or_refund_expired() {
338 return Err(SemanticError::AlreadyExpired);
342 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
343 Ok(UnsignedInvoice { invreq_bytes, invoice })
347 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
348 /// Builds a signed [`Invoice`] after checking for valid semantics.
349 pub fn build_and_sign<T: secp256k1::Signing>(
350 self, secp_ctx: &Secp256k1<T>
351 ) -> Result<Invoice, SemanticError> {
352 #[cfg(feature = "std")] {
353 if self.invoice.is_offer_or_refund_expired() {
354 return Err(SemanticError::AlreadyExpired);
358 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
359 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
361 let keys = keys.unwrap();
362 let invoice = unsigned_invoice
363 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
369 /// A semantically valid [`Invoice`] that hasn't been signed.
370 pub struct UnsignedInvoice<'a> {
371 invreq_bytes: &'a Vec<u8>,
372 invoice: InvoiceContents,
375 impl<'a> UnsignedInvoice<'a> {
376 /// The public key corresponding to the key needed to sign the invoice.
377 pub fn signing_pubkey(&self) -> PublicKey {
378 self.invoice.fields().signing_pubkey
381 /// Signs the invoice using the given function.
383 /// This is not exported to bindings users as functions aren't currently mapped.
384 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
386 F: FnOnce(&Message) -> Result<Signature, E>
388 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
389 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
391 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
392 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
393 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
395 let mut bytes = Vec::new();
396 unsigned_tlv_stream.write(&mut bytes).unwrap();
398 let pubkey = self.invoice.fields().signing_pubkey;
399 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
401 // Append the signature TLV record to the bytes.
402 let signature_tlv_stream = SignatureTlvStreamRef {
403 signature: Some(&signature),
405 signature_tlv_stream.write(&mut bytes).unwrap();
409 contents: self.invoice,
415 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
417 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
418 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
420 /// This is not exported to bindings users as its name conflicts with the BOLT 11 Invoice type.
422 /// [`Offer`]: crate::offers::offer::Offer
423 /// [`Refund`]: crate::offers::refund::Refund
424 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
425 #[derive(Clone, Debug)]
426 #[cfg_attr(test, derive(PartialEq))]
429 contents: InvoiceContents,
430 signature: Signature,
433 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
435 /// [`Offer`]: crate::offers::offer::Offer
436 /// [`Refund`]: crate::offers::refund::Refund
437 #[derive(Clone, Debug)]
438 #[cfg_attr(test, derive(PartialEq))]
439 enum InvoiceContents {
440 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
442 /// [`Offer`]: crate::offers::offer::Offer
444 invoice_request: InvoiceRequestContents,
445 fields: InvoiceFields,
447 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
449 /// [`Refund`]: crate::offers::refund::Refund
451 refund: RefundContents,
452 fields: InvoiceFields,
456 /// Invoice-specific fields for an `invoice` message.
457 #[derive(Clone, Debug, PartialEq)]
458 struct InvoiceFields {
459 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
460 created_at: Duration,
461 relative_expiry: Option<Duration>,
462 payment_hash: PaymentHash,
464 fallbacks: Option<Vec<FallbackAddress>>,
465 features: Bolt12InvoiceFeatures,
466 signing_pubkey: PublicKey,
470 /// A complete description of the purpose of the originating offer or refund. Intended to be
471 /// displayed to the user but with the caveat that it has not been verified in any way.
472 pub fn description(&self) -> PrintableString {
473 self.contents.description()
476 /// Paths to the recipient originating from publicly reachable nodes, including information
477 /// needed for routing payments across them.
479 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
480 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
482 /// This is not exported to bindings users as a slice of tuples isn't exportable.
483 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
484 &self.contents.fields().payment_paths[..]
487 /// Duration since the Unix epoch when the invoice was created.
488 pub fn created_at(&self) -> Duration {
489 self.contents.fields().created_at
492 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
494 pub fn relative_expiry(&self) -> Duration {
495 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
498 /// Whether the invoice has expired.
499 #[cfg(feature = "std")]
500 pub fn is_expired(&self) -> bool {
501 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
502 match absolute_expiry {
503 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
504 Ok(elapsed) => elapsed > seconds_from_epoch,
511 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
512 pub fn payment_hash(&self) -> PaymentHash {
513 self.contents.fields().payment_hash
516 /// The minimum amount required for a successful payment of the invoice.
517 pub fn amount_msats(&self) -> u64 {
518 self.contents.fields().amount_msats
521 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
524 /// This is not exported to bindings users as Address is not yet mapped
525 pub fn fallbacks(&self) -> Vec<Address> {
526 let network = match self.network() {
527 None => return Vec::new(),
528 Some(network) => network,
531 let to_valid_address = |address: &FallbackAddress| {
532 let version = match WitnessVersion::try_from(address.version) {
533 Ok(version) => version,
534 Err(_) => return None,
537 let program = &address.program;
538 if program.len() < 2 || program.len() > 40 {
542 let address = Address {
543 payload: Payload::WitnessProgram {
545 program: address.program.clone(),
550 if !address.is_standard() && version == WitnessVersion::V0 {
557 self.contents.fields().fallbacks
559 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
560 .unwrap_or_else(Vec::new)
563 fn network(&self) -> Option<Network> {
564 let chain = self.contents.chain();
565 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
566 Some(Network::Bitcoin)
567 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
568 Some(Network::Testnet)
569 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
570 Some(Network::Signet)
571 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
572 Some(Network::Regtest)
578 /// Features pertaining to paying an invoice.
579 pub fn features(&self) -> &Bolt12InvoiceFeatures {
580 &self.contents.fields().features
583 /// The public key corresponding to the key used to sign the invoice.
584 pub fn signing_pubkey(&self) -> PublicKey {
585 self.contents.fields().signing_pubkey
588 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
590 /// This is not exported to bindings users as SIgnature is not yet mapped.
591 pub fn signature(&self) -> Signature {
595 /// Hash that was used for signing the invoice.
596 pub fn signable_hash(&self) -> [u8; 32] {
597 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
600 /// Verifies that the invoice was for a request or refund created using the given key.
601 pub fn verify<T: secp256k1::Signing>(
602 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
604 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
608 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
609 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
610 self.contents.as_tlv_stream();
611 let signature_tlv_stream = SignatureTlvStreamRef {
612 signature: Some(&self.signature),
614 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
615 signature_tlv_stream)
619 impl InvoiceContents {
620 /// Whether the original offer or refund has expired.
621 #[cfg(feature = "std")]
622 fn is_offer_or_refund_expired(&self) -> bool {
624 InvoiceContents::ForOffer { invoice_request, .. } =>
625 invoice_request.inner.offer.is_expired(),
626 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
630 fn chain(&self) -> ChainHash {
632 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
633 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
637 fn description(&self) -> PrintableString {
639 InvoiceContents::ForOffer { invoice_request, .. } => {
640 invoice_request.inner.offer.description()
642 InvoiceContents::ForRefund { refund, .. } => refund.description(),
646 fn fields(&self) -> &InvoiceFields {
648 InvoiceContents::ForOffer { fields, .. } => fields,
649 InvoiceContents::ForRefund { fields, .. } => fields,
653 fn fields_mut(&mut self) -> &mut InvoiceFields {
655 InvoiceContents::ForOffer { fields, .. } => fields,
656 InvoiceContents::ForRefund { fields, .. } => fields,
660 fn verify<T: secp256k1::Signing>(
661 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
663 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
664 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
665 match record.r#type {
666 PAYER_METADATA_TYPE => false, // Should be outside range
667 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
671 let tlv_stream = offer_records.chain(invreq_records);
673 let (metadata, payer_id, iv_bytes) = match self {
674 InvoiceContents::ForOffer { invoice_request, .. } => {
675 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
677 InvoiceContents::ForRefund { refund, .. } => {
678 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
682 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
688 fn derives_keys(&self) -> bool {
690 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
691 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
695 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
696 let (payer, offer, invoice_request) = match self {
697 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
698 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
700 let invoice = self.fields().as_tlv_stream();
702 (payer, offer, invoice_request, invoice)
707 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
709 if self.features == Bolt12InvoiceFeatures::empty() { None }
710 else { Some(&self.features) }
713 InvoiceTlvStreamRef {
714 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
715 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
716 created_at: Some(self.created_at.as_secs()),
717 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
718 payment_hash: Some(&self.payment_hash),
719 amount: Some(self.amount_msats),
720 fallbacks: self.fallbacks.as_ref(),
722 node_id: Some(&self.signing_pubkey),
727 impl Writeable for Invoice {
728 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
729 WithoutLength(&self.bytes).write(writer)
733 impl Writeable for InvoiceContents {
734 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
735 self.as_tlv_stream().write(writer)
739 impl TryFrom<Vec<u8>> for Invoice {
740 type Error = ParseError;
742 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
743 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
744 Invoice::try_from(parsed_invoice)
748 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
749 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
750 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
751 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
752 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
753 (168, payment_hash: PaymentHash),
754 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
755 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
756 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
757 (176, node_id: PublicKey),
760 type BlindedPathIter<'a> = core::iter::Map<
761 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
762 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
765 type BlindedPayInfoIter<'a> = core::iter::Map<
766 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
767 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
770 /// Information needed to route a payment across a [`BlindedPath`].
771 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
772 pub struct BlindedPayInfo {
773 /// Base fee charged (in millisatoshi) for the entire blinded path.
774 pub fee_base_msat: u32,
776 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
777 /// (i.e., 10,000 is 1%).
778 pub fee_proportional_millionths: u32,
780 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
782 pub cltv_expiry_delta: u16,
784 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
785 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
786 /// seen by the recipient.
787 pub htlc_minimum_msat: u64,
789 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
790 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
791 /// seen by the recipient.
792 pub htlc_maximum_msat: u64,
794 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
796 pub features: BlindedHopFeatures,
799 impl_writeable!(BlindedPayInfo, {
801 fee_proportional_millionths,
808 /// Wire representation for an on-chain fallback address.
809 #[derive(Clone, Debug, PartialEq)]
810 pub(super) struct FallbackAddress {
815 impl_writeable!(FallbackAddress, { version, program });
817 type FullInvoiceTlvStream =
818 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
821 type FullInvoiceTlvStreamRef<'a> = (
822 PayerTlvStreamRef<'a>,
823 OfferTlvStreamRef<'a>,
824 InvoiceRequestTlvStreamRef<'a>,
825 InvoiceTlvStreamRef<'a>,
826 SignatureTlvStreamRef<'a>,
829 impl SeekReadable for FullInvoiceTlvStream {
830 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
831 let payer = SeekReadable::read(r)?;
832 let offer = SeekReadable::read(r)?;
833 let invoice_request = SeekReadable::read(r)?;
834 let invoice = SeekReadable::read(r)?;
835 let signature = SeekReadable::read(r)?;
837 Ok((payer, offer, invoice_request, invoice, signature))
841 type PartialInvoiceTlvStream =
842 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
844 type PartialInvoiceTlvStreamRef<'a> = (
845 PayerTlvStreamRef<'a>,
846 OfferTlvStreamRef<'a>,
847 InvoiceRequestTlvStreamRef<'a>,
848 InvoiceTlvStreamRef<'a>,
851 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
852 type Error = ParseError;
854 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
855 let ParsedMessage { bytes, tlv_stream } = invoice;
857 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
858 SignatureTlvStream { signature },
860 let contents = InvoiceContents::try_from(
861 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
864 let signature = match signature {
865 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
866 Some(signature) => signature,
868 let pubkey = contents.fields().signing_pubkey;
869 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
871 Ok(Invoice { bytes, contents, signature })
875 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
876 type Error = SemanticError;
878 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
882 invoice_request_tlv_stream,
884 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
889 let payment_paths = match (paths, blindedpay) {
890 (None, _) => return Err(SemanticError::MissingPaths),
891 (_, None) => return Err(SemanticError::InvalidPayInfo),
892 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
893 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
894 return Err(SemanticError::InvalidPayInfo);
896 (Some(paths), Some(blindedpay)) => {
897 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
901 let created_at = match created_at {
902 None => return Err(SemanticError::MissingCreationTime),
903 Some(timestamp) => Duration::from_secs(timestamp),
906 let relative_expiry = relative_expiry
907 .map(Into::<u64>::into)
908 .map(Duration::from_secs);
910 let payment_hash = match payment_hash {
911 None => return Err(SemanticError::MissingPaymentHash),
912 Some(payment_hash) => payment_hash,
915 let amount_msats = match amount {
916 None => return Err(SemanticError::MissingAmount),
917 Some(amount) => amount,
920 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
922 let signing_pubkey = match node_id {
923 None => return Err(SemanticError::MissingSigningPubkey),
924 Some(node_id) => node_id,
927 let fields = InvoiceFields {
928 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
929 features, signing_pubkey,
932 match offer_tlv_stream.node_id {
933 Some(expected_signing_pubkey) => {
934 if fields.signing_pubkey != expected_signing_pubkey {
935 return Err(SemanticError::InvalidSigningPubkey);
938 let invoice_request = InvoiceRequestContents::try_from(
939 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
941 Ok(InvoiceContents::ForOffer { invoice_request, fields })
944 let refund = RefundContents::try_from(
945 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
947 Ok(InvoiceContents::ForRefund { refund, fields })
955 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
957 use bitcoin::blockdata::script::Script;
958 use bitcoin::hashes::Hash;
959 use bitcoin::network::constants::Network;
960 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
961 use bitcoin::util::address::{Address, Payload, WitnessVersion};
962 use bitcoin::util::schnorr::TweakedPublicKey;
963 use core::convert::TryFrom;
964 use core::time::Duration;
965 use crate::blinded_path::{BlindedHop, BlindedPath};
966 use crate::chain::keysinterface::KeyMaterial;
967 use crate::ln::features::Bolt12InvoiceFeatures;
968 use crate::ln::inbound_payment::ExpandedKey;
969 use crate::ln::msgs::DecodeError;
970 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
971 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
972 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
973 use crate::offers::parse::{ParseError, SemanticError};
974 use crate::offers::payer::PayerTlvStreamRef;
975 use crate::offers::refund::RefundBuilder;
976 use crate::offers::test_utils::*;
977 use crate::util::ser::{BigSize, Iterable, Writeable};
978 use crate::util::string::PrintableString;
981 fn to_bytes(&self) -> Vec<u8>;
984 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
985 fn to_bytes(&self) -> Vec<u8> {
986 let mut buffer = Vec::new();
987 self.0.write(&mut buffer).unwrap();
988 self.1.write(&mut buffer).unwrap();
989 self.2.write(&mut buffer).unwrap();
990 self.3.write(&mut buffer).unwrap();
991 self.4.write(&mut buffer).unwrap();
997 fn builds_invoice_for_offer_with_defaults() {
998 let payment_paths = payment_paths();
999 let payment_hash = payment_hash();
1001 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1004 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1006 .sign(payer_sign).unwrap()
1007 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1009 .sign(recipient_sign).unwrap();
1011 let mut buffer = Vec::new();
1012 invoice.write(&mut buffer).unwrap();
1014 assert_eq!(invoice.bytes, buffer.as_slice());
1015 assert_eq!(invoice.description(), PrintableString("foo"));
1016 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1017 assert_eq!(invoice.created_at(), now);
1018 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1019 #[cfg(feature = "std")]
1020 assert!(!invoice.is_expired());
1021 assert_eq!(invoice.payment_hash(), payment_hash);
1022 assert_eq!(invoice.amount_msats(), 1000);
1023 assert_eq!(invoice.fallbacks(), vec![]);
1024 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1025 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1027 merkle::verify_signature(
1028 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1032 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1033 let pubkey = recipient_pubkey().into();
1034 let secp_ctx = Secp256k1::verification_only();
1035 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1038 invoice.as_tlv_stream(),
1040 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1046 description: Some(&String::from("foo")),
1048 absolute_expiry: None,
1052 node_id: Some(&recipient_pubkey()),
1054 InvoiceRequestTlvStreamRef {
1059 payer_id: Some(&payer_pubkey()),
1062 InvoiceTlvStreamRef {
1063 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1064 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1065 created_at: Some(now.as_secs()),
1066 relative_expiry: None,
1067 payment_hash: Some(&payment_hash),
1071 node_id: Some(&recipient_pubkey()),
1073 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1077 if let Err(e) = Invoice::try_from(buffer) {
1078 panic!("error parsing invoice: {:?}", e);
1083 fn builds_invoice_for_refund_with_defaults() {
1084 let payment_paths = payment_paths();
1085 let payment_hash = payment_hash();
1087 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1089 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1092 .sign(recipient_sign).unwrap();
1094 let mut buffer = Vec::new();
1095 invoice.write(&mut buffer).unwrap();
1097 assert_eq!(invoice.bytes, buffer.as_slice());
1098 assert_eq!(invoice.description(), PrintableString("foo"));
1099 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1100 assert_eq!(invoice.created_at(), now);
1101 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1102 #[cfg(feature = "std")]
1103 assert!(!invoice.is_expired());
1104 assert_eq!(invoice.payment_hash(), payment_hash);
1105 assert_eq!(invoice.amount_msats(), 1000);
1106 assert_eq!(invoice.fallbacks(), vec![]);
1107 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1108 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1110 merkle::verify_signature(
1111 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1116 invoice.as_tlv_stream(),
1118 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1124 description: Some(&String::from("foo")),
1126 absolute_expiry: None,
1132 InvoiceRequestTlvStreamRef {
1137 payer_id: Some(&payer_pubkey()),
1140 InvoiceTlvStreamRef {
1141 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1142 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1143 created_at: Some(now.as_secs()),
1144 relative_expiry: None,
1145 payment_hash: Some(&payment_hash),
1149 node_id: Some(&recipient_pubkey()),
1151 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1155 if let Err(e) = Invoice::try_from(buffer) {
1156 panic!("error parsing invoice: {:?}", e);
1160 #[cfg(feature = "std")]
1162 fn builds_invoice_from_offer_with_expiration() {
1163 let future_expiry = Duration::from_secs(u64::max_value());
1164 let past_expiry = Duration::from_secs(0);
1166 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1168 .absolute_expiry(future_expiry)
1170 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1172 .sign(payer_sign).unwrap()
1173 .respond_with(payment_paths(), payment_hash())
1177 panic!("error building invoice: {:?}", e);
1180 match OfferBuilder::new("foo".into(), recipient_pubkey())
1182 .absolute_expiry(past_expiry)
1184 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186 .sign(payer_sign).unwrap()
1187 .respond_with(payment_paths(), payment_hash())
1191 Ok(_) => panic!("expected error"),
1192 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1196 #[cfg(feature = "std")]
1198 fn builds_invoice_from_refund_with_expiration() {
1199 let future_expiry = Duration::from_secs(u64::max_value());
1200 let past_expiry = Duration::from_secs(0);
1202 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1203 .absolute_expiry(future_expiry)
1205 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1209 panic!("error building invoice: {:?}", e);
1212 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1213 .absolute_expiry(past_expiry)
1215 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1219 Ok(_) => panic!("expected error"),
1220 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1225 fn builds_invoice_from_offer_using_derived_keys() {
1226 let desc = "foo".to_string();
1227 let node_id = recipient_pubkey();
1228 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1229 let entropy = FixedEntropy {};
1230 let secp_ctx = Secp256k1::new();
1232 let blinded_path = BlindedPath {
1233 introduction_node_id: pubkey(40),
1234 blinding_point: pubkey(41),
1236 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1237 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1241 let offer = OfferBuilder
1242 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1246 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248 .sign(payer_sign).unwrap();
1250 if let Err(e) = invoice_request
1251 .verify_and_respond_using_derived_keys_no_std(
1252 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1255 .build_and_sign(&secp_ctx)
1257 panic!("error building invoice: {:?}", e);
1260 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1261 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1262 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1264 Ok(_) => panic!("expected error"),
1265 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1268 let desc = "foo".to_string();
1269 let offer = OfferBuilder
1270 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1273 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275 .sign(payer_sign).unwrap();
1277 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1278 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1280 Ok(_) => panic!("expected error"),
1281 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1286 fn builds_invoice_from_refund_using_derived_keys() {
1287 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1288 let entropy = FixedEntropy {};
1289 let secp_ctx = Secp256k1::new();
1291 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1294 if let Err(e) = refund
1295 .respond_using_derived_keys_no_std(
1296 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1299 .build_and_sign(&secp_ctx)
1301 panic!("error building invoice: {:?}", e);
1306 fn builds_invoice_with_relative_expiry() {
1308 let one_hour = Duration::from_secs(3600);
1310 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1313 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 .sign(payer_sign).unwrap()
1316 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1317 .relative_expiry(one_hour.as_secs() as u32)
1319 .sign(recipient_sign).unwrap();
1320 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1321 #[cfg(feature = "std")]
1322 assert!(!invoice.is_expired());
1323 assert_eq!(invoice.relative_expiry(), one_hour);
1324 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1326 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1329 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1331 .sign(payer_sign).unwrap()
1332 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1333 .relative_expiry(one_hour.as_secs() as u32 - 1)
1335 .sign(recipient_sign).unwrap();
1336 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1337 #[cfg(feature = "std")]
1338 assert!(invoice.is_expired());
1339 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1340 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1344 fn builds_invoice_with_amount_from_request() {
1345 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1348 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1349 .amount_msats(1001).unwrap()
1351 .sign(payer_sign).unwrap()
1352 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1354 .sign(recipient_sign).unwrap();
1355 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1356 assert_eq!(invoice.amount_msats(), 1001);
1357 assert_eq!(tlv_stream.amount, Some(1001));
1361 fn builds_invoice_with_quantity_from_request() {
1362 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1364 .supported_quantity(Quantity::Unbounded)
1366 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1367 .quantity(2).unwrap()
1369 .sign(payer_sign).unwrap()
1370 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1372 .sign(recipient_sign).unwrap();
1373 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1374 assert_eq!(invoice.amount_msats(), 2000);
1375 assert_eq!(tlv_stream.amount, Some(2000));
1377 match OfferBuilder::new("foo".into(), recipient_pubkey())
1379 .supported_quantity(Quantity::Unbounded)
1381 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1382 .quantity(u64::max_value()).unwrap()
1384 .sign(payer_sign).unwrap()
1385 .respond_with_no_std(payment_paths(), payment_hash(), now())
1387 Ok(_) => panic!("expected error"),
1388 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1393 fn builds_invoice_with_fallback_address() {
1394 let script = Script::new();
1395 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1396 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1397 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1399 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1402 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1404 .sign(payer_sign).unwrap()
1405 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1406 .fallback_v0_p2wsh(&script.wscript_hash())
1407 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1408 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1410 .sign(recipient_sign).unwrap();
1411 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1413 invoice.fallbacks(),
1415 Address::p2wsh(&script, Network::Bitcoin),
1416 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1417 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1421 tlv_stream.fallbacks,
1424 version: WitnessVersion::V0.to_num(),
1425 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1428 version: WitnessVersion::V0.to_num(),
1429 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1432 version: WitnessVersion::V1.to_num(),
1433 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1440 fn builds_invoice_with_allow_mpp() {
1441 let mut features = Bolt12InvoiceFeatures::empty();
1442 features.set_basic_mpp_optional();
1444 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1447 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1449 .sign(payer_sign).unwrap()
1450 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1453 .sign(recipient_sign).unwrap();
1454 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1455 assert_eq!(invoice.features(), &features);
1456 assert_eq!(tlv_stream.features, Some(&features));
1460 fn fails_signing_invoice() {
1461 match OfferBuilder::new("foo".into(), recipient_pubkey())
1464 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1466 .sign(payer_sign).unwrap()
1467 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1471 Ok(_) => panic!("expected error"),
1472 Err(e) => assert_eq!(e, SignError::Signing(())),
1475 match OfferBuilder::new("foo".into(), recipient_pubkey())
1478 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1480 .sign(payer_sign).unwrap()
1481 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1485 Ok(_) => panic!("expected error"),
1486 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1491 fn parses_invoice_with_payment_paths() {
1492 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1495 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1497 .sign(payer_sign).unwrap()
1498 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1500 .sign(recipient_sign).unwrap();
1502 let mut buffer = Vec::new();
1503 invoice.write(&mut buffer).unwrap();
1505 if let Err(e) = Invoice::try_from(buffer) {
1506 panic!("error parsing invoice: {:?}", e);
1509 let mut tlv_stream = invoice.as_tlv_stream();
1510 tlv_stream.3.paths = None;
1512 match Invoice::try_from(tlv_stream.to_bytes()) {
1513 Ok(_) => panic!("expected error"),
1514 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1517 let mut tlv_stream = invoice.as_tlv_stream();
1518 tlv_stream.3.blindedpay = None;
1520 match Invoice::try_from(tlv_stream.to_bytes()) {
1521 Ok(_) => panic!("expected error"),
1522 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1525 let empty_payment_paths = vec![];
1526 let mut tlv_stream = invoice.as_tlv_stream();
1527 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1529 match Invoice::try_from(tlv_stream.to_bytes()) {
1530 Ok(_) => panic!("expected error"),
1531 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1534 let mut payment_paths = payment_paths();
1535 payment_paths.pop();
1536 let mut tlv_stream = invoice.as_tlv_stream();
1537 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1539 match Invoice::try_from(tlv_stream.to_bytes()) {
1540 Ok(_) => panic!("expected error"),
1541 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1546 fn parses_invoice_with_created_at() {
1547 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1550 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1552 .sign(payer_sign).unwrap()
1553 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1555 .sign(recipient_sign).unwrap();
1557 let mut buffer = Vec::new();
1558 invoice.write(&mut buffer).unwrap();
1560 if let Err(e) = Invoice::try_from(buffer) {
1561 panic!("error parsing invoice: {:?}", e);
1564 let mut tlv_stream = invoice.as_tlv_stream();
1565 tlv_stream.3.created_at = None;
1567 match Invoice::try_from(tlv_stream.to_bytes()) {
1568 Ok(_) => panic!("expected error"),
1570 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1576 fn parses_invoice_with_relative_expiry() {
1577 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1582 .sign(payer_sign).unwrap()
1583 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1584 .relative_expiry(3600)
1586 .sign(recipient_sign).unwrap();
1588 let mut buffer = Vec::new();
1589 invoice.write(&mut buffer).unwrap();
1591 match Invoice::try_from(buffer) {
1592 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1593 Err(e) => panic!("error parsing invoice: {:?}", e),
1598 fn parses_invoice_with_payment_hash() {
1599 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1602 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1604 .sign(payer_sign).unwrap()
1605 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1607 .sign(recipient_sign).unwrap();
1609 let mut buffer = Vec::new();
1610 invoice.write(&mut buffer).unwrap();
1612 if let Err(e) = Invoice::try_from(buffer) {
1613 panic!("error parsing invoice: {:?}", e);
1616 let mut tlv_stream = invoice.as_tlv_stream();
1617 tlv_stream.3.payment_hash = None;
1619 match Invoice::try_from(tlv_stream.to_bytes()) {
1620 Ok(_) => panic!("expected error"),
1622 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1628 fn parses_invoice_with_amount() {
1629 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1632 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1634 .sign(payer_sign).unwrap()
1635 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1637 .sign(recipient_sign).unwrap();
1639 let mut buffer = Vec::new();
1640 invoice.write(&mut buffer).unwrap();
1642 if let Err(e) = Invoice::try_from(buffer) {
1643 panic!("error parsing invoice: {:?}", e);
1646 let mut tlv_stream = invoice.as_tlv_stream();
1647 tlv_stream.3.amount = None;
1649 match Invoice::try_from(tlv_stream.to_bytes()) {
1650 Ok(_) => panic!("expected error"),
1651 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1656 fn parses_invoice_with_allow_mpp() {
1657 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1662 .sign(payer_sign).unwrap()
1663 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1666 .sign(recipient_sign).unwrap();
1668 let mut buffer = Vec::new();
1669 invoice.write(&mut buffer).unwrap();
1671 match Invoice::try_from(buffer) {
1673 let mut features = Bolt12InvoiceFeatures::empty();
1674 features.set_basic_mpp_optional();
1675 assert_eq!(invoice.features(), &features);
1677 Err(e) => panic!("error parsing invoice: {:?}", e),
1682 fn parses_invoice_with_fallback_address() {
1683 let script = Script::new();
1684 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1685 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1686 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1688 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1691 let invoice_request = offer
1692 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1694 .sign(payer_sign).unwrap();
1695 let mut unsigned_invoice = invoice_request
1696 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1697 .fallback_v0_p2wsh(&script.wscript_hash())
1698 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1699 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1702 // Only standard addresses will be included.
1703 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1704 // Non-standard addresses
1705 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1706 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1707 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1709 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1710 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1712 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1713 let mut buffer = Vec::new();
1714 invoice.write(&mut buffer).unwrap();
1716 match Invoice::try_from(buffer) {
1719 invoice.fallbacks(),
1721 Address::p2wsh(&script, Network::Bitcoin),
1722 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1723 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1725 payload: Payload::WitnessProgram {
1726 version: WitnessVersion::V1,
1727 program: vec![0u8; 33],
1729 network: Network::Bitcoin,
1732 payload: Payload::WitnessProgram {
1733 version: WitnessVersion::V2,
1734 program: vec![0u8; 40],
1736 network: Network::Bitcoin,
1741 Err(e) => panic!("error parsing invoice: {:?}", e),
1746 fn parses_invoice_with_node_id() {
1747 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1750 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1752 .sign(payer_sign).unwrap()
1753 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1755 .sign(recipient_sign).unwrap();
1757 let mut buffer = Vec::new();
1758 invoice.write(&mut buffer).unwrap();
1760 if let Err(e) = Invoice::try_from(buffer) {
1761 panic!("error parsing invoice: {:?}", e);
1764 let mut tlv_stream = invoice.as_tlv_stream();
1765 tlv_stream.3.node_id = None;
1767 match Invoice::try_from(tlv_stream.to_bytes()) {
1768 Ok(_) => panic!("expected error"),
1770 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1774 let invalid_pubkey = payer_pubkey();
1775 let mut tlv_stream = invoice.as_tlv_stream();
1776 tlv_stream.3.node_id = Some(&invalid_pubkey);
1778 match Invoice::try_from(tlv_stream.to_bytes()) {
1779 Ok(_) => panic!("expected error"),
1781 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1787 fn fails_parsing_invoice_without_signature() {
1788 let mut buffer = Vec::new();
1789 OfferBuilder::new("foo".into(), recipient_pubkey())
1792 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1794 .sign(payer_sign).unwrap()
1795 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1798 .write(&mut buffer).unwrap();
1800 match Invoice::try_from(buffer) {
1801 Ok(_) => panic!("expected error"),
1802 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1807 fn fails_parsing_invoice_with_invalid_signature() {
1808 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1811 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1813 .sign(payer_sign).unwrap()
1814 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1816 .sign(recipient_sign).unwrap();
1817 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1818 *last_signature_byte = last_signature_byte.wrapping_add(1);
1820 let mut buffer = Vec::new();
1821 invoice.write(&mut buffer).unwrap();
1823 match Invoice::try_from(buffer) {
1824 Ok(_) => panic!("expected error"),
1826 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1832 fn fails_parsing_invoice_with_extra_tlv_records() {
1833 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1836 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1838 .sign(payer_sign).unwrap()
1839 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1841 .sign(recipient_sign).unwrap();
1843 let mut encoded_invoice = Vec::new();
1844 invoice.write(&mut encoded_invoice).unwrap();
1845 BigSize(1002).write(&mut encoded_invoice).unwrap();
1846 BigSize(32).write(&mut encoded_invoice).unwrap();
1847 [42u8; 32].write(&mut encoded_invoice).unwrap();
1849 match Invoice::try_from(encoded_invoice) {
1850 Ok(_) => panic!("expected error"),
1851 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),