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.
314 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
315 let address = FallbackAddress {
316 version: WitnessVersion::V1.to_num(),
317 program: Vec::from(&output_key.serialize()[..]),
319 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
323 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
324 pub fn allow_mpp(mut self) -> Self {
325 self.invoice.fields_mut().features.set_basic_mpp_optional();
330 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
331 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
332 /// [`UnsignedInvoice::sign`].
333 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
334 #[cfg(feature = "std")] {
335 if self.invoice.is_offer_or_refund_expired() {
336 return Err(SemanticError::AlreadyExpired);
340 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
341 Ok(UnsignedInvoice { invreq_bytes, invoice })
345 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
346 /// Builds a signed [`Invoice`] after checking for valid semantics.
347 pub fn build_and_sign<T: secp256k1::Signing>(
348 self, secp_ctx: &Secp256k1<T>
349 ) -> Result<Invoice, SemanticError> {
350 #[cfg(feature = "std")] {
351 if self.invoice.is_offer_or_refund_expired() {
352 return Err(SemanticError::AlreadyExpired);
356 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
357 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
359 let keys = keys.unwrap();
360 let invoice = unsigned_invoice
361 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
367 /// A semantically valid [`Invoice`] that hasn't been signed.
368 pub struct UnsignedInvoice<'a> {
369 invreq_bytes: &'a Vec<u8>,
370 invoice: InvoiceContents,
373 impl<'a> UnsignedInvoice<'a> {
374 /// The public key corresponding to the key needed to sign the invoice.
375 pub fn signing_pubkey(&self) -> PublicKey {
376 self.invoice.fields().signing_pubkey
379 /// Signs the invoice using the given function.
381 /// This is not exported to bindings users as functions aren't currently mapped.
382 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
384 F: FnOnce(&Message) -> Result<Signature, E>
386 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
387 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
389 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
390 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
391 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
393 let mut bytes = Vec::new();
394 unsigned_tlv_stream.write(&mut bytes).unwrap();
396 let pubkey = self.invoice.fields().signing_pubkey;
397 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
399 // Append the signature TLV record to the bytes.
400 let signature_tlv_stream = SignatureTlvStreamRef {
401 signature: Some(&signature),
403 signature_tlv_stream.write(&mut bytes).unwrap();
407 contents: self.invoice,
413 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
415 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
416 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
418 /// This is not exported to bindings users as its name conflicts with the BOLT 11 Invoice type.
420 /// [`Offer`]: crate::offers::offer::Offer
421 /// [`Refund`]: crate::offers::refund::Refund
422 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
423 #[derive(Clone, Debug)]
424 #[cfg_attr(test, derive(PartialEq))]
427 contents: InvoiceContents,
428 signature: Signature,
431 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
433 /// [`Offer`]: crate::offers::offer::Offer
434 /// [`Refund`]: crate::offers::refund::Refund
435 #[derive(Clone, Debug)]
436 #[cfg_attr(test, derive(PartialEq))]
437 enum InvoiceContents {
438 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
440 /// [`Offer`]: crate::offers::offer::Offer
442 invoice_request: InvoiceRequestContents,
443 fields: InvoiceFields,
445 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
447 /// [`Refund`]: crate::offers::refund::Refund
449 refund: RefundContents,
450 fields: InvoiceFields,
454 /// Invoice-specific fields for an `invoice` message.
455 #[derive(Clone, Debug, PartialEq)]
456 struct InvoiceFields {
457 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
458 created_at: Duration,
459 relative_expiry: Option<Duration>,
460 payment_hash: PaymentHash,
462 fallbacks: Option<Vec<FallbackAddress>>,
463 features: Bolt12InvoiceFeatures,
464 signing_pubkey: PublicKey,
468 /// A complete description of the purpose of the originating offer or refund. Intended to be
469 /// displayed to the user but with the caveat that it has not been verified in any way.
470 pub fn description(&self) -> PrintableString {
471 self.contents.description()
474 /// Paths to the recipient originating from publicly reachable nodes, including information
475 /// needed for routing payments across them.
477 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
478 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
479 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
480 &self.contents.fields().payment_paths[..]
483 /// Duration since the Unix epoch when the invoice was created.
484 pub fn created_at(&self) -> Duration {
485 self.contents.fields().created_at
488 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
490 pub fn relative_expiry(&self) -> Duration {
491 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
494 /// Whether the invoice has expired.
495 #[cfg(feature = "std")]
496 pub fn is_expired(&self) -> bool {
497 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
498 match absolute_expiry {
499 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
500 Ok(elapsed) => elapsed > seconds_from_epoch,
507 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
508 pub fn payment_hash(&self) -> PaymentHash {
509 self.contents.fields().payment_hash
512 /// The minimum amount required for a successful payment of the invoice.
513 pub fn amount_msats(&self) -> u64 {
514 self.contents.fields().amount_msats
517 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
519 pub fn fallbacks(&self) -> Vec<Address> {
520 let network = match self.network() {
521 None => return Vec::new(),
522 Some(network) => network,
525 let to_valid_address = |address: &FallbackAddress| {
526 let version = match WitnessVersion::try_from(address.version) {
527 Ok(version) => version,
528 Err(_) => return None,
531 let program = &address.program;
532 if program.len() < 2 || program.len() > 40 {
536 let address = Address {
537 payload: Payload::WitnessProgram {
539 program: address.program.clone(),
544 if !address.is_standard() && version == WitnessVersion::V0 {
551 self.contents.fields().fallbacks
553 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
554 .unwrap_or_else(Vec::new)
557 fn network(&self) -> Option<Network> {
558 let chain = self.contents.chain();
559 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
560 Some(Network::Bitcoin)
561 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
562 Some(Network::Testnet)
563 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
564 Some(Network::Signet)
565 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
566 Some(Network::Regtest)
572 /// Features pertaining to paying an invoice.
573 pub fn features(&self) -> &Bolt12InvoiceFeatures {
574 &self.contents.fields().features
577 /// The public key corresponding to the key used to sign the invoice.
578 pub fn signing_pubkey(&self) -> PublicKey {
579 self.contents.fields().signing_pubkey
582 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
583 pub fn signature(&self) -> Signature {
587 /// Hash that was used for signing the invoice.
588 pub fn signable_hash(&self) -> [u8; 32] {
589 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
592 /// Verifies that the invoice was for a request or refund created using the given key.
593 pub fn verify<T: secp256k1::Signing>(
594 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
596 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
600 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
601 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
602 self.contents.as_tlv_stream();
603 let signature_tlv_stream = SignatureTlvStreamRef {
604 signature: Some(&self.signature),
606 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
607 signature_tlv_stream)
611 impl InvoiceContents {
612 /// Whether the original offer or refund has expired.
613 #[cfg(feature = "std")]
614 fn is_offer_or_refund_expired(&self) -> bool {
616 InvoiceContents::ForOffer { invoice_request, .. } =>
617 invoice_request.inner.offer.is_expired(),
618 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
622 fn chain(&self) -> ChainHash {
624 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
625 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
629 fn description(&self) -> PrintableString {
631 InvoiceContents::ForOffer { invoice_request, .. } => {
632 invoice_request.inner.offer.description()
634 InvoiceContents::ForRefund { refund, .. } => refund.description(),
638 fn fields(&self) -> &InvoiceFields {
640 InvoiceContents::ForOffer { fields, .. } => fields,
641 InvoiceContents::ForRefund { fields, .. } => fields,
645 fn fields_mut(&mut self) -> &mut InvoiceFields {
647 InvoiceContents::ForOffer { fields, .. } => fields,
648 InvoiceContents::ForRefund { fields, .. } => fields,
652 fn verify<T: secp256k1::Signing>(
653 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
655 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
656 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
657 match record.r#type {
658 PAYER_METADATA_TYPE => false, // Should be outside range
659 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
663 let tlv_stream = offer_records.chain(invreq_records);
665 let (metadata, payer_id, iv_bytes) = match self {
666 InvoiceContents::ForOffer { invoice_request, .. } => {
667 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
669 InvoiceContents::ForRefund { refund, .. } => {
670 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
674 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
680 fn derives_keys(&self) -> bool {
682 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
683 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
687 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
688 let (payer, offer, invoice_request) = match self {
689 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
690 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
692 let invoice = self.fields().as_tlv_stream();
694 (payer, offer, invoice_request, invoice)
699 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
701 if self.features == Bolt12InvoiceFeatures::empty() { None }
702 else { Some(&self.features) }
705 InvoiceTlvStreamRef {
706 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
707 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
708 created_at: Some(self.created_at.as_secs()),
709 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
710 payment_hash: Some(&self.payment_hash),
711 amount: Some(self.amount_msats),
712 fallbacks: self.fallbacks.as_ref(),
714 node_id: Some(&self.signing_pubkey),
719 impl Writeable for Invoice {
720 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
721 WithoutLength(&self.bytes).write(writer)
725 impl Writeable for InvoiceContents {
726 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
727 self.as_tlv_stream().write(writer)
731 impl TryFrom<Vec<u8>> for Invoice {
732 type Error = ParseError;
734 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
735 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
736 Invoice::try_from(parsed_invoice)
740 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
741 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
742 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
743 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
744 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
745 (168, payment_hash: PaymentHash),
746 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
747 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
748 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
749 (176, node_id: PublicKey),
752 type BlindedPathIter<'a> = core::iter::Map<
753 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
754 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
757 type BlindedPayInfoIter<'a> = core::iter::Map<
758 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
759 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
762 /// Information needed to route a payment across a [`BlindedPath`].
763 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
764 pub struct BlindedPayInfo {
765 /// Base fee charged (in millisatoshi) for the entire blinded path.
766 pub fee_base_msat: u32,
768 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
769 /// (i.e., 10,000 is 1%).
770 pub fee_proportional_millionths: u32,
772 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
774 pub cltv_expiry_delta: u16,
776 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
777 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
778 /// seen by the recipient.
779 pub htlc_minimum_msat: u64,
781 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
782 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
783 /// seen by the recipient.
784 pub htlc_maximum_msat: u64,
786 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
788 pub features: BlindedHopFeatures,
791 impl_writeable!(BlindedPayInfo, {
793 fee_proportional_millionths,
800 /// Wire representation for an on-chain fallback address.
801 #[derive(Clone, Debug, PartialEq)]
802 pub(super) struct FallbackAddress {
807 impl_writeable!(FallbackAddress, { version, program });
809 type FullInvoiceTlvStream =
810 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
813 type FullInvoiceTlvStreamRef<'a> = (
814 PayerTlvStreamRef<'a>,
815 OfferTlvStreamRef<'a>,
816 InvoiceRequestTlvStreamRef<'a>,
817 InvoiceTlvStreamRef<'a>,
818 SignatureTlvStreamRef<'a>,
821 impl SeekReadable for FullInvoiceTlvStream {
822 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
823 let payer = SeekReadable::read(r)?;
824 let offer = SeekReadable::read(r)?;
825 let invoice_request = SeekReadable::read(r)?;
826 let invoice = SeekReadable::read(r)?;
827 let signature = SeekReadable::read(r)?;
829 Ok((payer, offer, invoice_request, invoice, signature))
833 type PartialInvoiceTlvStream =
834 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
836 type PartialInvoiceTlvStreamRef<'a> = (
837 PayerTlvStreamRef<'a>,
838 OfferTlvStreamRef<'a>,
839 InvoiceRequestTlvStreamRef<'a>,
840 InvoiceTlvStreamRef<'a>,
843 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
844 type Error = ParseError;
846 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
847 let ParsedMessage { bytes, tlv_stream } = invoice;
849 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
850 SignatureTlvStream { signature },
852 let contents = InvoiceContents::try_from(
853 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
856 let signature = match signature {
857 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
858 Some(signature) => signature,
860 let pubkey = contents.fields().signing_pubkey;
861 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
863 Ok(Invoice { bytes, contents, signature })
867 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
868 type Error = SemanticError;
870 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
874 invoice_request_tlv_stream,
876 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
881 let payment_paths = match (paths, blindedpay) {
882 (None, _) => return Err(SemanticError::MissingPaths),
883 (_, None) => return Err(SemanticError::InvalidPayInfo),
884 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
885 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
886 return Err(SemanticError::InvalidPayInfo);
888 (Some(paths), Some(blindedpay)) => {
889 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
893 let created_at = match created_at {
894 None => return Err(SemanticError::MissingCreationTime),
895 Some(timestamp) => Duration::from_secs(timestamp),
898 let relative_expiry = relative_expiry
899 .map(Into::<u64>::into)
900 .map(Duration::from_secs);
902 let payment_hash = match payment_hash {
903 None => return Err(SemanticError::MissingPaymentHash),
904 Some(payment_hash) => payment_hash,
907 let amount_msats = match amount {
908 None => return Err(SemanticError::MissingAmount),
909 Some(amount) => amount,
912 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
914 let signing_pubkey = match node_id {
915 None => return Err(SemanticError::MissingSigningPubkey),
916 Some(node_id) => node_id,
919 let fields = InvoiceFields {
920 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
921 features, signing_pubkey,
924 match offer_tlv_stream.node_id {
925 Some(expected_signing_pubkey) => {
926 if fields.signing_pubkey != expected_signing_pubkey {
927 return Err(SemanticError::InvalidSigningPubkey);
930 let invoice_request = InvoiceRequestContents::try_from(
931 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
933 Ok(InvoiceContents::ForOffer { invoice_request, fields })
936 let refund = RefundContents::try_from(
937 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
939 Ok(InvoiceContents::ForRefund { refund, fields })
947 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
949 use bitcoin::blockdata::script::Script;
950 use bitcoin::hashes::Hash;
951 use bitcoin::network::constants::Network;
952 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
953 use bitcoin::util::address::{Address, Payload, WitnessVersion};
954 use bitcoin::util::schnorr::TweakedPublicKey;
955 use core::convert::TryFrom;
956 use core::time::Duration;
957 use crate::blinded_path::{BlindedHop, BlindedPath};
958 use crate::sign::KeyMaterial;
959 use crate::ln::features::Bolt12InvoiceFeatures;
960 use crate::ln::inbound_payment::ExpandedKey;
961 use crate::ln::msgs::DecodeError;
962 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
963 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
964 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
965 use crate::offers::parse::{ParseError, SemanticError};
966 use crate::offers::payer::PayerTlvStreamRef;
967 use crate::offers::refund::RefundBuilder;
968 use crate::offers::test_utils::*;
969 use crate::util::ser::{BigSize, Iterable, Writeable};
970 use crate::util::string::PrintableString;
973 fn to_bytes(&self) -> Vec<u8>;
976 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
977 fn to_bytes(&self) -> Vec<u8> {
978 let mut buffer = Vec::new();
979 self.0.write(&mut buffer).unwrap();
980 self.1.write(&mut buffer).unwrap();
981 self.2.write(&mut buffer).unwrap();
982 self.3.write(&mut buffer).unwrap();
983 self.4.write(&mut buffer).unwrap();
989 fn builds_invoice_for_offer_with_defaults() {
990 let payment_paths = payment_paths();
991 let payment_hash = payment_hash();
993 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
996 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
998 .sign(payer_sign).unwrap()
999 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1001 .sign(recipient_sign).unwrap();
1003 let mut buffer = Vec::new();
1004 invoice.write(&mut buffer).unwrap();
1006 assert_eq!(invoice.bytes, buffer.as_slice());
1007 assert_eq!(invoice.description(), PrintableString("foo"));
1008 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1009 assert_eq!(invoice.created_at(), now);
1010 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1011 #[cfg(feature = "std")]
1012 assert!(!invoice.is_expired());
1013 assert_eq!(invoice.payment_hash(), payment_hash);
1014 assert_eq!(invoice.amount_msats(), 1000);
1015 assert_eq!(invoice.fallbacks(), vec![]);
1016 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1017 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1019 merkle::verify_signature(
1020 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1024 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1025 let pubkey = recipient_pubkey().into();
1026 let secp_ctx = Secp256k1::verification_only();
1027 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1030 invoice.as_tlv_stream(),
1032 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1038 description: Some(&String::from("foo")),
1040 absolute_expiry: None,
1044 node_id: Some(&recipient_pubkey()),
1046 InvoiceRequestTlvStreamRef {
1051 payer_id: Some(&payer_pubkey()),
1054 InvoiceTlvStreamRef {
1055 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1056 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1057 created_at: Some(now.as_secs()),
1058 relative_expiry: None,
1059 payment_hash: Some(&payment_hash),
1063 node_id: Some(&recipient_pubkey()),
1065 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1069 if let Err(e) = Invoice::try_from(buffer) {
1070 panic!("error parsing invoice: {:?}", e);
1075 fn builds_invoice_for_refund_with_defaults() {
1076 let payment_paths = payment_paths();
1077 let payment_hash = payment_hash();
1079 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1081 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1084 .sign(recipient_sign).unwrap();
1086 let mut buffer = Vec::new();
1087 invoice.write(&mut buffer).unwrap();
1089 assert_eq!(invoice.bytes, buffer.as_slice());
1090 assert_eq!(invoice.description(), PrintableString("foo"));
1091 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1092 assert_eq!(invoice.created_at(), now);
1093 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1094 #[cfg(feature = "std")]
1095 assert!(!invoice.is_expired());
1096 assert_eq!(invoice.payment_hash(), payment_hash);
1097 assert_eq!(invoice.amount_msats(), 1000);
1098 assert_eq!(invoice.fallbacks(), vec![]);
1099 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1100 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1102 merkle::verify_signature(
1103 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1108 invoice.as_tlv_stream(),
1110 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1116 description: Some(&String::from("foo")),
1118 absolute_expiry: None,
1124 InvoiceRequestTlvStreamRef {
1129 payer_id: Some(&payer_pubkey()),
1132 InvoiceTlvStreamRef {
1133 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1134 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1135 created_at: Some(now.as_secs()),
1136 relative_expiry: None,
1137 payment_hash: Some(&payment_hash),
1141 node_id: Some(&recipient_pubkey()),
1143 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1147 if let Err(e) = Invoice::try_from(buffer) {
1148 panic!("error parsing invoice: {:?}", e);
1152 #[cfg(feature = "std")]
1154 fn builds_invoice_from_offer_with_expiration() {
1155 let future_expiry = Duration::from_secs(u64::max_value());
1156 let past_expiry = Duration::from_secs(0);
1158 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1160 .absolute_expiry(future_expiry)
1162 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .sign(payer_sign).unwrap()
1165 .respond_with(payment_paths(), payment_hash())
1169 panic!("error building invoice: {:?}", e);
1172 match OfferBuilder::new("foo".into(), recipient_pubkey())
1174 .absolute_expiry(past_expiry)
1176 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1178 .sign(payer_sign).unwrap()
1179 .respond_with(payment_paths(), payment_hash())
1183 Ok(_) => panic!("expected error"),
1184 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1188 #[cfg(feature = "std")]
1190 fn builds_invoice_from_refund_with_expiration() {
1191 let future_expiry = Duration::from_secs(u64::max_value());
1192 let past_expiry = Duration::from_secs(0);
1194 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1195 .absolute_expiry(future_expiry)
1197 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1201 panic!("error building invoice: {:?}", e);
1204 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1205 .absolute_expiry(past_expiry)
1207 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1211 Ok(_) => panic!("expected error"),
1212 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1217 fn builds_invoice_from_offer_using_derived_keys() {
1218 let desc = "foo".to_string();
1219 let node_id = recipient_pubkey();
1220 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1221 let entropy = FixedEntropy {};
1222 let secp_ctx = Secp256k1::new();
1224 let blinded_path = BlindedPath {
1225 introduction_node_id: pubkey(40),
1226 blinding_point: pubkey(41),
1228 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1229 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1233 let offer = OfferBuilder
1234 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1238 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1240 .sign(payer_sign).unwrap();
1242 if let Err(e) = invoice_request
1243 .verify_and_respond_using_derived_keys_no_std(
1244 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1247 .build_and_sign(&secp_ctx)
1249 panic!("error building invoice: {:?}", e);
1252 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1253 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1254 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1256 Ok(_) => panic!("expected error"),
1257 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1260 let desc = "foo".to_string();
1261 let offer = OfferBuilder
1262 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1265 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1267 .sign(payer_sign).unwrap();
1269 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1270 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1272 Ok(_) => panic!("expected error"),
1273 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1278 fn builds_invoice_from_refund_using_derived_keys() {
1279 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1280 let entropy = FixedEntropy {};
1281 let secp_ctx = Secp256k1::new();
1283 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1286 if let Err(e) = refund
1287 .respond_using_derived_keys_no_std(
1288 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1291 .build_and_sign(&secp_ctx)
1293 panic!("error building invoice: {:?}", e);
1298 fn builds_invoice_with_relative_expiry() {
1300 let one_hour = Duration::from_secs(3600);
1302 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1305 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1307 .sign(payer_sign).unwrap()
1308 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1309 .relative_expiry(one_hour.as_secs() as u32)
1311 .sign(recipient_sign).unwrap();
1312 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1313 #[cfg(feature = "std")]
1314 assert!(!invoice.is_expired());
1315 assert_eq!(invoice.relative_expiry(), one_hour);
1316 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1318 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1321 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1323 .sign(payer_sign).unwrap()
1324 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1325 .relative_expiry(one_hour.as_secs() as u32 - 1)
1327 .sign(recipient_sign).unwrap();
1328 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1329 #[cfg(feature = "std")]
1330 assert!(invoice.is_expired());
1331 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1332 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1336 fn builds_invoice_with_amount_from_request() {
1337 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1341 .amount_msats(1001).unwrap()
1343 .sign(payer_sign).unwrap()
1344 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1346 .sign(recipient_sign).unwrap();
1347 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1348 assert_eq!(invoice.amount_msats(), 1001);
1349 assert_eq!(tlv_stream.amount, Some(1001));
1353 fn builds_invoice_with_quantity_from_request() {
1354 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1356 .supported_quantity(Quantity::Unbounded)
1358 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1359 .quantity(2).unwrap()
1361 .sign(payer_sign).unwrap()
1362 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1364 .sign(recipient_sign).unwrap();
1365 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1366 assert_eq!(invoice.amount_msats(), 2000);
1367 assert_eq!(tlv_stream.amount, Some(2000));
1369 match OfferBuilder::new("foo".into(), recipient_pubkey())
1371 .supported_quantity(Quantity::Unbounded)
1373 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1374 .quantity(u64::max_value()).unwrap()
1376 .sign(payer_sign).unwrap()
1377 .respond_with_no_std(payment_paths(), payment_hash(), now())
1379 Ok(_) => panic!("expected error"),
1380 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1385 fn builds_invoice_with_fallback_address() {
1386 let script = Script::new();
1387 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1388 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1389 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1391 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1394 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1396 .sign(payer_sign).unwrap()
1397 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1398 .fallback_v0_p2wsh(&script.wscript_hash())
1399 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1400 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1402 .sign(recipient_sign).unwrap();
1403 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1405 invoice.fallbacks(),
1407 Address::p2wsh(&script, Network::Bitcoin),
1408 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1409 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1413 tlv_stream.fallbacks,
1416 version: WitnessVersion::V0.to_num(),
1417 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1420 version: WitnessVersion::V0.to_num(),
1421 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1424 version: WitnessVersion::V1.to_num(),
1425 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1432 fn builds_invoice_with_allow_mpp() {
1433 let mut features = Bolt12InvoiceFeatures::empty();
1434 features.set_basic_mpp_optional();
1436 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1439 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1441 .sign(payer_sign).unwrap()
1442 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1445 .sign(recipient_sign).unwrap();
1446 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1447 assert_eq!(invoice.features(), &features);
1448 assert_eq!(tlv_stream.features, Some(&features));
1452 fn fails_signing_invoice() {
1453 match OfferBuilder::new("foo".into(), recipient_pubkey())
1456 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1458 .sign(payer_sign).unwrap()
1459 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1463 Ok(_) => panic!("expected error"),
1464 Err(e) => assert_eq!(e, SignError::Signing(())),
1467 match OfferBuilder::new("foo".into(), recipient_pubkey())
1470 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1472 .sign(payer_sign).unwrap()
1473 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1477 Ok(_) => panic!("expected error"),
1478 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1483 fn parses_invoice_with_payment_paths() {
1484 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1487 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1489 .sign(payer_sign).unwrap()
1490 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1492 .sign(recipient_sign).unwrap();
1494 let mut buffer = Vec::new();
1495 invoice.write(&mut buffer).unwrap();
1497 if let Err(e) = Invoice::try_from(buffer) {
1498 panic!("error parsing invoice: {:?}", e);
1501 let mut tlv_stream = invoice.as_tlv_stream();
1502 tlv_stream.3.paths = None;
1504 match Invoice::try_from(tlv_stream.to_bytes()) {
1505 Ok(_) => panic!("expected error"),
1506 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1509 let mut tlv_stream = invoice.as_tlv_stream();
1510 tlv_stream.3.blindedpay = None;
1512 match Invoice::try_from(tlv_stream.to_bytes()) {
1513 Ok(_) => panic!("expected error"),
1514 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1517 let empty_payment_paths = vec![];
1518 let mut tlv_stream = invoice.as_tlv_stream();
1519 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1521 match Invoice::try_from(tlv_stream.to_bytes()) {
1522 Ok(_) => panic!("expected error"),
1523 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1526 let mut payment_paths = payment_paths();
1527 payment_paths.pop();
1528 let mut tlv_stream = invoice.as_tlv_stream();
1529 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1531 match Invoice::try_from(tlv_stream.to_bytes()) {
1532 Ok(_) => panic!("expected error"),
1533 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1538 fn parses_invoice_with_created_at() {
1539 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1542 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1544 .sign(payer_sign).unwrap()
1545 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1547 .sign(recipient_sign).unwrap();
1549 let mut buffer = Vec::new();
1550 invoice.write(&mut buffer).unwrap();
1552 if let Err(e) = Invoice::try_from(buffer) {
1553 panic!("error parsing invoice: {:?}", e);
1556 let mut tlv_stream = invoice.as_tlv_stream();
1557 tlv_stream.3.created_at = None;
1559 match Invoice::try_from(tlv_stream.to_bytes()) {
1560 Ok(_) => panic!("expected error"),
1562 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1568 fn parses_invoice_with_relative_expiry() {
1569 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1572 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1574 .sign(payer_sign).unwrap()
1575 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1576 .relative_expiry(3600)
1578 .sign(recipient_sign).unwrap();
1580 let mut buffer = Vec::new();
1581 invoice.write(&mut buffer).unwrap();
1583 match Invoice::try_from(buffer) {
1584 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1585 Err(e) => panic!("error parsing invoice: {:?}", e),
1590 fn parses_invoice_with_payment_hash() {
1591 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1594 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1596 .sign(payer_sign).unwrap()
1597 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1599 .sign(recipient_sign).unwrap();
1601 let mut buffer = Vec::new();
1602 invoice.write(&mut buffer).unwrap();
1604 if let Err(e) = Invoice::try_from(buffer) {
1605 panic!("error parsing invoice: {:?}", e);
1608 let mut tlv_stream = invoice.as_tlv_stream();
1609 tlv_stream.3.payment_hash = None;
1611 match Invoice::try_from(tlv_stream.to_bytes()) {
1612 Ok(_) => panic!("expected error"),
1614 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1620 fn parses_invoice_with_amount() {
1621 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1624 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 .sign(payer_sign).unwrap()
1627 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1629 .sign(recipient_sign).unwrap();
1631 let mut buffer = Vec::new();
1632 invoice.write(&mut buffer).unwrap();
1634 if let Err(e) = Invoice::try_from(buffer) {
1635 panic!("error parsing invoice: {:?}", e);
1638 let mut tlv_stream = invoice.as_tlv_stream();
1639 tlv_stream.3.amount = None;
1641 match Invoice::try_from(tlv_stream.to_bytes()) {
1642 Ok(_) => panic!("expected error"),
1643 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1648 fn parses_invoice_with_allow_mpp() {
1649 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1652 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1654 .sign(payer_sign).unwrap()
1655 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1658 .sign(recipient_sign).unwrap();
1660 let mut buffer = Vec::new();
1661 invoice.write(&mut buffer).unwrap();
1663 match Invoice::try_from(buffer) {
1665 let mut features = Bolt12InvoiceFeatures::empty();
1666 features.set_basic_mpp_optional();
1667 assert_eq!(invoice.features(), &features);
1669 Err(e) => panic!("error parsing invoice: {:?}", e),
1674 fn parses_invoice_with_fallback_address() {
1675 let script = Script::new();
1676 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1677 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1678 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1680 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1683 let invoice_request = offer
1684 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1686 .sign(payer_sign).unwrap();
1687 let mut unsigned_invoice = invoice_request
1688 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1689 .fallback_v0_p2wsh(&script.wscript_hash())
1690 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1691 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1694 // Only standard addresses will be included.
1695 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1696 // Non-standard addresses
1697 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1698 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1699 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1701 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1702 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1704 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1705 let mut buffer = Vec::new();
1706 invoice.write(&mut buffer).unwrap();
1708 match Invoice::try_from(buffer) {
1711 invoice.fallbacks(),
1713 Address::p2wsh(&script, Network::Bitcoin),
1714 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1715 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1717 payload: Payload::WitnessProgram {
1718 version: WitnessVersion::V1,
1719 program: vec![0u8; 33],
1721 network: Network::Bitcoin,
1724 payload: Payload::WitnessProgram {
1725 version: WitnessVersion::V2,
1726 program: vec![0u8; 40],
1728 network: Network::Bitcoin,
1733 Err(e) => panic!("error parsing invoice: {:?}", e),
1738 fn parses_invoice_with_node_id() {
1739 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1742 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1744 .sign(payer_sign).unwrap()
1745 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1747 .sign(recipient_sign).unwrap();
1749 let mut buffer = Vec::new();
1750 invoice.write(&mut buffer).unwrap();
1752 if let Err(e) = Invoice::try_from(buffer) {
1753 panic!("error parsing invoice: {:?}", e);
1756 let mut tlv_stream = invoice.as_tlv_stream();
1757 tlv_stream.3.node_id = None;
1759 match Invoice::try_from(tlv_stream.to_bytes()) {
1760 Ok(_) => panic!("expected error"),
1762 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1766 let invalid_pubkey = payer_pubkey();
1767 let mut tlv_stream = invoice.as_tlv_stream();
1768 tlv_stream.3.node_id = Some(&invalid_pubkey);
1770 match Invoice::try_from(tlv_stream.to_bytes()) {
1771 Ok(_) => panic!("expected error"),
1773 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1779 fn fails_parsing_invoice_without_signature() {
1780 let mut buffer = Vec::new();
1781 OfferBuilder::new("foo".into(), recipient_pubkey())
1784 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1786 .sign(payer_sign).unwrap()
1787 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1790 .write(&mut buffer).unwrap();
1792 match Invoice::try_from(buffer) {
1793 Ok(_) => panic!("expected error"),
1794 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1799 fn fails_parsing_invoice_with_invalid_signature() {
1800 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1803 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1805 .sign(payer_sign).unwrap()
1806 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1808 .sign(recipient_sign).unwrap();
1809 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1810 *last_signature_byte = last_signature_byte.wrapping_add(1);
1812 let mut buffer = Vec::new();
1813 invoice.write(&mut buffer).unwrap();
1815 match Invoice::try_from(buffer) {
1816 Ok(_) => panic!("expected error"),
1818 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1824 fn fails_parsing_invoice_with_extra_tlv_records() {
1825 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1828 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1830 .sign(payer_sign).unwrap()
1831 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1833 .sign(recipient_sign).unwrap();
1835 let mut encoded_invoice = Vec::new();
1836 invoice.write(&mut encoded_invoice).unwrap();
1837 BigSize(1002).write(&mut encoded_invoice).unwrap();
1838 BigSize(32).write(&mut encoded_invoice).unwrap();
1839 [42u8; 32].write(&mut encoded_invoice).unwrap();
1841 match Invoice::try_from(encoded_invoice) {
1842 Ok(_) => panic!("expected error"),
1843 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),