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 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
138 /// [`Refund`]: crate::offers::refund::Refund
139 /// [module-level documentation]: self
140 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
141 invreq_bytes: &'a Vec<u8>,
142 invoice: InvoiceContents,
143 keys: Option<KeyPair>,
144 signing_pubkey_strategy: core::marker::PhantomData<S>,
147 /// Indicates how [`Invoice::signing_pubkey`] was set.
148 pub trait SigningPubkeyStrategy {}
150 /// [`Invoice::signing_pubkey`] was explicitly set.
151 pub struct ExplicitSigningPubkey {}
153 /// [`Invoice::signing_pubkey`] was derived.
154 pub struct DerivedSigningPubkey {}
156 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
157 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
159 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
160 pub(super) fn for_offer(
161 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
162 created_at: Duration, payment_hash: PaymentHash
163 ) -> Result<Self, SemanticError> {
164 let amount_msats = Self::check_amount_msats(invoice_request)?;
165 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
166 let contents = InvoiceContents::ForOffer {
167 invoice_request: invoice_request.contents.clone(),
168 fields: Self::fields(
169 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
173 Self::new(&invoice_request.bytes, contents, None)
176 pub(super) fn for_refund(
177 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
178 payment_hash: PaymentHash, signing_pubkey: PublicKey
179 ) -> Result<Self, SemanticError> {
180 let amount_msats = refund.amount_msats();
181 let contents = InvoiceContents::ForRefund {
182 refund: refund.contents.clone(),
183 fields: Self::fields(
184 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
188 Self::new(&refund.bytes, contents, None)
192 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
193 pub(super) fn for_offer_using_keys(
194 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
195 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
196 ) -> Result<Self, SemanticError> {
197 let amount_msats = Self::check_amount_msats(invoice_request)?;
198 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
199 let contents = InvoiceContents::ForOffer {
200 invoice_request: invoice_request.contents.clone(),
201 fields: Self::fields(
202 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
206 Self::new(&invoice_request.bytes, contents, Some(keys))
209 pub(super) fn for_refund_using_keys(
210 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
211 payment_hash: PaymentHash, keys: KeyPair,
212 ) -> Result<Self, SemanticError> {
213 let amount_msats = refund.amount_msats();
214 let signing_pubkey = keys.public_key();
215 let contents = InvoiceContents::ForRefund {
216 refund: refund.contents.clone(),
217 fields: Self::fields(
218 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
222 Self::new(&refund.bytes, contents, Some(keys))
226 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
227 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, SemanticError> {
228 match invoice_request.amount_msats() {
229 Some(amount_msats) => Ok(amount_msats),
230 None => match invoice_request.contents.inner.offer.amount() {
231 Some(Amount::Bitcoin { amount_msats }) => {
232 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
233 .ok_or(SemanticError::InvalidAmount)
235 Some(Amount::Currency { .. }) => Err(SemanticError::UnsupportedCurrency),
236 None => Err(SemanticError::MissingAmount),
242 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
243 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
246 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
247 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
252 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
253 ) -> Result<Self, SemanticError> {
254 if contents.fields().payment_paths.is_empty() {
255 return Err(SemanticError::MissingPaths);
262 signing_pubkey_strategy: core::marker::PhantomData,
266 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
267 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
269 /// Successive calls to this method will override the previous setting.
270 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
271 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
272 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
276 /// Adds a P2WSH address to [`Invoice::fallbacks`].
278 /// Successive calls to this method will add another address. Caller is responsible for not
279 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
280 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
281 let address = FallbackAddress {
282 version: WitnessVersion::V0.to_num(),
283 program: Vec::from(&script_hash.into_inner()[..]),
285 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
289 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
291 /// Successive calls to this method will add another address. Caller is responsible for not
292 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
293 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
294 let address = FallbackAddress {
295 version: WitnessVersion::V0.to_num(),
296 program: Vec::from(&pubkey_hash.into_inner()[..]),
298 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
302 /// Adds a P2TR address to [`Invoice::fallbacks`].
304 /// Successive calls to this method will add another address. Caller is responsible for not
305 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
306 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
307 let address = FallbackAddress {
308 version: WitnessVersion::V1.to_num(),
309 program: Vec::from(&output_key.serialize()[..]),
311 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
315 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
316 pub fn allow_mpp(mut self) -> Self {
317 self.invoice.fields_mut().features.set_basic_mpp_optional();
322 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
323 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
324 /// [`UnsignedInvoice::sign`].
325 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
326 #[cfg(feature = "std")] {
327 if self.invoice.is_offer_or_refund_expired() {
328 return Err(SemanticError::AlreadyExpired);
332 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
333 Ok(UnsignedInvoice { invreq_bytes, invoice })
337 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
338 /// Builds a signed [`Invoice`] after checking for valid semantics.
339 pub fn build_and_sign<T: secp256k1::Signing>(
340 self, secp_ctx: &Secp256k1<T>
341 ) -> Result<Invoice, SemanticError> {
342 #[cfg(feature = "std")] {
343 if self.invoice.is_offer_or_refund_expired() {
344 return Err(SemanticError::AlreadyExpired);
348 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
349 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
351 let keys = keys.unwrap();
352 let invoice = unsigned_invoice
353 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
359 /// A semantically valid [`Invoice`] that hasn't been signed.
360 pub struct UnsignedInvoice<'a> {
361 invreq_bytes: &'a Vec<u8>,
362 invoice: InvoiceContents,
365 impl<'a> UnsignedInvoice<'a> {
366 /// The public key corresponding to the key needed to sign the invoice.
367 pub fn signing_pubkey(&self) -> PublicKey {
368 self.invoice.fields().signing_pubkey
371 /// Signs the invoice using the given function.
372 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
374 F: FnOnce(&Message) -> Result<Signature, E>
376 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
377 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
379 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
380 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
381 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
383 let mut bytes = Vec::new();
384 unsigned_tlv_stream.write(&mut bytes).unwrap();
386 let pubkey = self.invoice.fields().signing_pubkey;
387 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
389 // Append the signature TLV record to the bytes.
390 let signature_tlv_stream = SignatureTlvStreamRef {
391 signature: Some(&signature),
393 signature_tlv_stream.write(&mut bytes).unwrap();
397 contents: self.invoice,
403 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
405 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
406 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
408 /// [`Offer`]: crate::offers::offer::Offer
409 /// [`Refund`]: crate::offers::refund::Refund
410 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
411 #[derive(Clone, Debug)]
412 #[cfg_attr(test, derive(PartialEq))]
415 contents: InvoiceContents,
416 signature: Signature,
419 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
421 /// [`Offer`]: crate::offers::offer::Offer
422 /// [`Refund`]: crate::offers::refund::Refund
423 #[derive(Clone, Debug)]
424 #[cfg_attr(test, derive(PartialEq))]
425 enum InvoiceContents {
426 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
428 /// [`Offer`]: crate::offers::offer::Offer
430 invoice_request: InvoiceRequestContents,
431 fields: InvoiceFields,
433 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
435 /// [`Refund`]: crate::offers::refund::Refund
437 refund: RefundContents,
438 fields: InvoiceFields,
442 /// Invoice-specific fields for an `invoice` message.
443 #[derive(Clone, Debug, PartialEq)]
444 struct InvoiceFields {
445 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
446 created_at: Duration,
447 relative_expiry: Option<Duration>,
448 payment_hash: PaymentHash,
450 fallbacks: Option<Vec<FallbackAddress>>,
451 features: Bolt12InvoiceFeatures,
452 signing_pubkey: PublicKey,
456 /// A complete description of the purpose of the originating offer or refund. Intended to be
457 /// displayed to the user but with the caveat that it has not been verified in any way.
458 pub fn description(&self) -> PrintableString {
459 self.contents.description()
462 /// Paths to the recipient originating from publicly reachable nodes, including information
463 /// needed for routing payments across them.
465 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
466 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
467 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
468 &self.contents.fields().payment_paths[..]
471 /// Duration since the Unix epoch when the invoice was created.
472 pub fn created_at(&self) -> Duration {
473 self.contents.fields().created_at
476 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
478 pub fn relative_expiry(&self) -> Duration {
479 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
482 /// Whether the invoice has expired.
483 #[cfg(feature = "std")]
484 pub fn is_expired(&self) -> bool {
485 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
486 match absolute_expiry {
487 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
488 Ok(elapsed) => elapsed > seconds_from_epoch,
495 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
496 pub fn payment_hash(&self) -> PaymentHash {
497 self.contents.fields().payment_hash
500 /// The minimum amount required for a successful payment of the invoice.
501 pub fn amount_msats(&self) -> u64 {
502 self.contents.fields().amount_msats
505 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
507 pub fn fallbacks(&self) -> Vec<Address> {
508 let network = match self.network() {
509 None => return Vec::new(),
510 Some(network) => network,
513 let to_valid_address = |address: &FallbackAddress| {
514 let version = match WitnessVersion::try_from(address.version) {
515 Ok(version) => version,
516 Err(_) => return None,
519 let program = &address.program;
520 if program.len() < 2 || program.len() > 40 {
524 let address = Address {
525 payload: Payload::WitnessProgram {
527 program: address.program.clone(),
532 if !address.is_standard() && version == WitnessVersion::V0 {
539 self.contents.fields().fallbacks
541 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
542 .unwrap_or_else(Vec::new)
545 fn network(&self) -> Option<Network> {
546 let chain = self.contents.chain();
547 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
548 Some(Network::Bitcoin)
549 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
550 Some(Network::Testnet)
551 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
552 Some(Network::Signet)
553 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
554 Some(Network::Regtest)
560 /// Features pertaining to paying an invoice.
561 pub fn features(&self) -> &Bolt12InvoiceFeatures {
562 &self.contents.fields().features
565 /// The public key corresponding to the key used to sign the invoice.
566 pub fn signing_pubkey(&self) -> PublicKey {
567 self.contents.fields().signing_pubkey
570 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
571 pub fn signature(&self) -> Signature {
575 /// Hash that was used for signing the invoice.
576 pub fn signable_hash(&self) -> [u8; 32] {
577 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
580 /// Verifies that the invoice was for a request or refund created using the given key.
581 pub fn verify<T: secp256k1::Signing>(
582 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
584 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
588 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
589 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
590 self.contents.as_tlv_stream();
591 let signature_tlv_stream = SignatureTlvStreamRef {
592 signature: Some(&self.signature),
594 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
595 signature_tlv_stream)
599 impl InvoiceContents {
600 /// Whether the original offer or refund has expired.
601 #[cfg(feature = "std")]
602 fn is_offer_or_refund_expired(&self) -> bool {
604 InvoiceContents::ForOffer { invoice_request, .. } =>
605 invoice_request.inner.offer.is_expired(),
606 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
610 fn chain(&self) -> ChainHash {
612 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
613 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
617 fn description(&self) -> PrintableString {
619 InvoiceContents::ForOffer { invoice_request, .. } => {
620 invoice_request.inner.offer.description()
622 InvoiceContents::ForRefund { refund, .. } => refund.description(),
626 fn fields(&self) -> &InvoiceFields {
628 InvoiceContents::ForOffer { fields, .. } => fields,
629 InvoiceContents::ForRefund { fields, .. } => fields,
633 fn fields_mut(&mut self) -> &mut InvoiceFields {
635 InvoiceContents::ForOffer { fields, .. } => fields,
636 InvoiceContents::ForRefund { fields, .. } => fields,
640 fn verify<T: secp256k1::Signing>(
641 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
643 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
644 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
645 match record.r#type {
646 PAYER_METADATA_TYPE => false, // Should be outside range
647 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
651 let tlv_stream = offer_records.chain(invreq_records);
653 let (metadata, payer_id, iv_bytes) = match self {
654 InvoiceContents::ForOffer { invoice_request, .. } => {
655 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
657 InvoiceContents::ForRefund { refund, .. } => {
658 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
662 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
668 fn derives_keys(&self) -> bool {
670 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
671 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
675 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
676 let (payer, offer, invoice_request) = match self {
677 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
678 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
680 let invoice = self.fields().as_tlv_stream();
682 (payer, offer, invoice_request, invoice)
687 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
689 if self.features == Bolt12InvoiceFeatures::empty() { None }
690 else { Some(&self.features) }
693 InvoiceTlvStreamRef {
694 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
695 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
696 created_at: Some(self.created_at.as_secs()),
697 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
698 payment_hash: Some(&self.payment_hash),
699 amount: Some(self.amount_msats),
700 fallbacks: self.fallbacks.as_ref(),
702 node_id: Some(&self.signing_pubkey),
707 impl Writeable for Invoice {
708 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
709 WithoutLength(&self.bytes).write(writer)
713 impl Writeable for InvoiceContents {
714 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
715 self.as_tlv_stream().write(writer)
719 impl TryFrom<Vec<u8>> for Invoice {
720 type Error = ParseError;
722 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
723 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
724 Invoice::try_from(parsed_invoice)
728 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
729 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
730 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
731 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
732 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
733 (168, payment_hash: PaymentHash),
734 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
735 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
736 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
737 (176, node_id: PublicKey),
740 type BlindedPathIter<'a> = core::iter::Map<
741 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
742 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
745 type BlindedPayInfoIter<'a> = core::iter::Map<
746 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
747 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
750 /// Information needed to route a payment across a [`BlindedPath`].
751 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
752 pub struct BlindedPayInfo {
753 /// Base fee charged (in millisatoshi) for the entire blinded path.
754 pub fee_base_msat: u32,
756 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
757 /// (i.e., 10,000 is 1%).
758 pub fee_proportional_millionths: u32,
760 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
762 pub cltv_expiry_delta: u16,
764 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
765 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
766 /// seen by the recipient.
767 pub htlc_minimum_msat: u64,
769 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
770 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
771 /// seen by the recipient.
772 pub htlc_maximum_msat: u64,
774 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
776 pub features: BlindedHopFeatures,
779 impl_writeable!(BlindedPayInfo, {
781 fee_proportional_millionths,
788 /// Wire representation for an on-chain fallback address.
789 #[derive(Clone, Debug, PartialEq)]
790 pub(super) struct FallbackAddress {
795 impl_writeable!(FallbackAddress, { version, program });
797 type FullInvoiceTlvStream =
798 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
801 type FullInvoiceTlvStreamRef<'a> = (
802 PayerTlvStreamRef<'a>,
803 OfferTlvStreamRef<'a>,
804 InvoiceRequestTlvStreamRef<'a>,
805 InvoiceTlvStreamRef<'a>,
806 SignatureTlvStreamRef<'a>,
809 impl SeekReadable for FullInvoiceTlvStream {
810 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
811 let payer = SeekReadable::read(r)?;
812 let offer = SeekReadable::read(r)?;
813 let invoice_request = SeekReadable::read(r)?;
814 let invoice = SeekReadable::read(r)?;
815 let signature = SeekReadable::read(r)?;
817 Ok((payer, offer, invoice_request, invoice, signature))
821 type PartialInvoiceTlvStream =
822 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
824 type PartialInvoiceTlvStreamRef<'a> = (
825 PayerTlvStreamRef<'a>,
826 OfferTlvStreamRef<'a>,
827 InvoiceRequestTlvStreamRef<'a>,
828 InvoiceTlvStreamRef<'a>,
831 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
832 type Error = ParseError;
834 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
835 let ParsedMessage { bytes, tlv_stream } = invoice;
837 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
838 SignatureTlvStream { signature },
840 let contents = InvoiceContents::try_from(
841 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
844 let signature = match signature {
845 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
846 Some(signature) => signature,
848 let pubkey = contents.fields().signing_pubkey;
849 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
851 Ok(Invoice { bytes, contents, signature })
855 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
856 type Error = SemanticError;
858 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
862 invoice_request_tlv_stream,
864 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
869 let payment_paths = match (paths, blindedpay) {
870 (None, _) => return Err(SemanticError::MissingPaths),
871 (_, None) => return Err(SemanticError::InvalidPayInfo),
872 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
873 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
874 return Err(SemanticError::InvalidPayInfo);
876 (Some(paths), Some(blindedpay)) => {
877 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
881 let created_at = match created_at {
882 None => return Err(SemanticError::MissingCreationTime),
883 Some(timestamp) => Duration::from_secs(timestamp),
886 let relative_expiry = relative_expiry
887 .map(Into::<u64>::into)
888 .map(Duration::from_secs);
890 let payment_hash = match payment_hash {
891 None => return Err(SemanticError::MissingPaymentHash),
892 Some(payment_hash) => payment_hash,
895 let amount_msats = match amount {
896 None => return Err(SemanticError::MissingAmount),
897 Some(amount) => amount,
900 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
902 let signing_pubkey = match node_id {
903 None => return Err(SemanticError::MissingSigningPubkey),
904 Some(node_id) => node_id,
907 let fields = InvoiceFields {
908 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
909 features, signing_pubkey,
912 match offer_tlv_stream.node_id {
913 Some(expected_signing_pubkey) => {
914 if fields.signing_pubkey != expected_signing_pubkey {
915 return Err(SemanticError::InvalidSigningPubkey);
918 let invoice_request = InvoiceRequestContents::try_from(
919 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
921 Ok(InvoiceContents::ForOffer { invoice_request, fields })
924 let refund = RefundContents::try_from(
925 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
927 Ok(InvoiceContents::ForRefund { refund, fields })
935 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
937 use bitcoin::blockdata::script::Script;
938 use bitcoin::hashes::Hash;
939 use bitcoin::network::constants::Network;
940 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
941 use bitcoin::util::address::{Address, Payload, WitnessVersion};
942 use bitcoin::util::schnorr::TweakedPublicKey;
943 use core::convert::TryFrom;
944 use core::time::Duration;
945 use crate::blinded_path::{BlindedHop, BlindedPath};
946 use crate::chain::keysinterface::KeyMaterial;
947 use crate::ln::features::Bolt12InvoiceFeatures;
948 use crate::ln::inbound_payment::ExpandedKey;
949 use crate::ln::msgs::DecodeError;
950 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
951 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
952 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
953 use crate::offers::parse::{ParseError, SemanticError};
954 use crate::offers::payer::PayerTlvStreamRef;
955 use crate::offers::refund::RefundBuilder;
956 use crate::offers::test_utils::*;
957 use crate::util::ser::{BigSize, Iterable, Writeable};
958 use crate::util::string::PrintableString;
961 fn to_bytes(&self) -> Vec<u8>;
964 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
965 fn to_bytes(&self) -> Vec<u8> {
966 let mut buffer = Vec::new();
967 self.0.write(&mut buffer).unwrap();
968 self.1.write(&mut buffer).unwrap();
969 self.2.write(&mut buffer).unwrap();
970 self.3.write(&mut buffer).unwrap();
971 self.4.write(&mut buffer).unwrap();
977 fn builds_invoice_for_offer_with_defaults() {
978 let payment_paths = payment_paths();
979 let payment_hash = payment_hash();
981 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
984 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
986 .sign(payer_sign).unwrap()
987 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
989 .sign(recipient_sign).unwrap();
991 let mut buffer = Vec::new();
992 invoice.write(&mut buffer).unwrap();
994 assert_eq!(invoice.bytes, buffer.as_slice());
995 assert_eq!(invoice.description(), PrintableString("foo"));
996 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
997 assert_eq!(invoice.created_at(), now);
998 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
999 #[cfg(feature = "std")]
1000 assert!(!invoice.is_expired());
1001 assert_eq!(invoice.payment_hash(), payment_hash);
1002 assert_eq!(invoice.amount_msats(), 1000);
1003 assert_eq!(invoice.fallbacks(), vec![]);
1004 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1005 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1007 merkle::verify_signature(
1008 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1012 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1013 let pubkey = recipient_pubkey().into();
1014 let secp_ctx = Secp256k1::verification_only();
1015 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1018 invoice.as_tlv_stream(),
1020 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1026 description: Some(&String::from("foo")),
1028 absolute_expiry: None,
1032 node_id: Some(&recipient_pubkey()),
1034 InvoiceRequestTlvStreamRef {
1039 payer_id: Some(&payer_pubkey()),
1042 InvoiceTlvStreamRef {
1043 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1044 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1045 created_at: Some(now.as_secs()),
1046 relative_expiry: None,
1047 payment_hash: Some(&payment_hash),
1051 node_id: Some(&recipient_pubkey()),
1053 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1057 if let Err(e) = Invoice::try_from(buffer) {
1058 panic!("error parsing invoice: {:?}", e);
1063 fn builds_invoice_for_refund_with_defaults() {
1064 let payment_paths = payment_paths();
1065 let payment_hash = payment_hash();
1067 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1069 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1072 .sign(recipient_sign).unwrap();
1074 let mut buffer = Vec::new();
1075 invoice.write(&mut buffer).unwrap();
1077 assert_eq!(invoice.bytes, buffer.as_slice());
1078 assert_eq!(invoice.description(), PrintableString("foo"));
1079 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1080 assert_eq!(invoice.created_at(), now);
1081 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1082 #[cfg(feature = "std")]
1083 assert!(!invoice.is_expired());
1084 assert_eq!(invoice.payment_hash(), payment_hash);
1085 assert_eq!(invoice.amount_msats(), 1000);
1086 assert_eq!(invoice.fallbacks(), vec![]);
1087 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1088 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1090 merkle::verify_signature(
1091 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1096 invoice.as_tlv_stream(),
1098 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1104 description: Some(&String::from("foo")),
1106 absolute_expiry: None,
1112 InvoiceRequestTlvStreamRef {
1117 payer_id: Some(&payer_pubkey()),
1120 InvoiceTlvStreamRef {
1121 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1122 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1123 created_at: Some(now.as_secs()),
1124 relative_expiry: None,
1125 payment_hash: Some(&payment_hash),
1129 node_id: Some(&recipient_pubkey()),
1131 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1135 if let Err(e) = Invoice::try_from(buffer) {
1136 panic!("error parsing invoice: {:?}", e);
1140 #[cfg(feature = "std")]
1142 fn builds_invoice_from_offer_with_expiration() {
1143 let future_expiry = Duration::from_secs(u64::max_value());
1144 let past_expiry = Duration::from_secs(0);
1146 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1148 .absolute_expiry(future_expiry)
1150 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1152 .sign(payer_sign).unwrap()
1153 .respond_with(payment_paths(), payment_hash())
1157 panic!("error building invoice: {:?}", e);
1160 match OfferBuilder::new("foo".into(), recipient_pubkey())
1162 .absolute_expiry(past_expiry)
1164 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1166 .sign(payer_sign).unwrap()
1167 .respond_with(payment_paths(), payment_hash())
1171 Ok(_) => panic!("expected error"),
1172 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1176 #[cfg(feature = "std")]
1178 fn builds_invoice_from_refund_with_expiration() {
1179 let future_expiry = Duration::from_secs(u64::max_value());
1180 let past_expiry = Duration::from_secs(0);
1182 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1183 .absolute_expiry(future_expiry)
1185 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1189 panic!("error building invoice: {:?}", e);
1192 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1193 .absolute_expiry(past_expiry)
1195 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1199 Ok(_) => panic!("expected error"),
1200 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1205 fn builds_invoice_from_offer_using_derived_keys() {
1206 let desc = "foo".to_string();
1207 let node_id = recipient_pubkey();
1208 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1209 let entropy = FixedEntropy {};
1210 let secp_ctx = Secp256k1::new();
1212 let blinded_path = BlindedPath {
1213 introduction_node_id: pubkey(40),
1214 blinding_point: pubkey(41),
1216 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1217 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1221 let offer = OfferBuilder
1222 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1226 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1228 .sign(payer_sign).unwrap();
1230 if let Err(e) = invoice_request
1231 .verify_and_respond_using_derived_keys_no_std(
1232 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1235 .build_and_sign(&secp_ctx)
1237 panic!("error building invoice: {:?}", e);
1240 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1241 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1242 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1244 Ok(_) => panic!("expected error"),
1245 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1248 let desc = "foo".to_string();
1249 let offer = OfferBuilder
1250 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1253 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1255 .sign(payer_sign).unwrap();
1257 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1258 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1260 Ok(_) => panic!("expected error"),
1261 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1266 fn builds_invoice_from_refund_using_derived_keys() {
1267 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1268 let entropy = FixedEntropy {};
1269 let secp_ctx = Secp256k1::new();
1271 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1274 if let Err(e) = refund
1275 .respond_using_derived_keys_no_std(
1276 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1279 .build_and_sign(&secp_ctx)
1281 panic!("error building invoice: {:?}", e);
1286 fn builds_invoice_with_relative_expiry() {
1288 let one_hour = Duration::from_secs(3600);
1290 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1293 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1295 .sign(payer_sign).unwrap()
1296 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1297 .relative_expiry(one_hour.as_secs() as u32)
1299 .sign(recipient_sign).unwrap();
1300 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1301 #[cfg(feature = "std")]
1302 assert!(!invoice.is_expired());
1303 assert_eq!(invoice.relative_expiry(), one_hour);
1304 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1306 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1309 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1311 .sign(payer_sign).unwrap()
1312 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1313 .relative_expiry(one_hour.as_secs() as u32 - 1)
1315 .sign(recipient_sign).unwrap();
1316 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1317 #[cfg(feature = "std")]
1318 assert!(invoice.is_expired());
1319 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1320 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1324 fn builds_invoice_with_amount_from_request() {
1325 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1328 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1329 .amount_msats(1001).unwrap()
1331 .sign(payer_sign).unwrap()
1332 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1334 .sign(recipient_sign).unwrap();
1335 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1336 assert_eq!(invoice.amount_msats(), 1001);
1337 assert_eq!(tlv_stream.amount, Some(1001));
1341 fn builds_invoice_with_quantity_from_request() {
1342 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1344 .supported_quantity(Quantity::Unbounded)
1346 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .quantity(2).unwrap()
1349 .sign(payer_sign).unwrap()
1350 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1352 .sign(recipient_sign).unwrap();
1353 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1354 assert_eq!(invoice.amount_msats(), 2000);
1355 assert_eq!(tlv_stream.amount, Some(2000));
1357 match OfferBuilder::new("foo".into(), recipient_pubkey())
1359 .supported_quantity(Quantity::Unbounded)
1361 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1362 .quantity(u64::max_value()).unwrap()
1364 .sign(payer_sign).unwrap()
1365 .respond_with_no_std(payment_paths(), payment_hash(), now())
1367 Ok(_) => panic!("expected error"),
1368 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1373 fn builds_invoice_with_fallback_address() {
1374 let script = Script::new();
1375 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1376 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1377 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1379 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1382 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1384 .sign(payer_sign).unwrap()
1385 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1386 .fallback_v0_p2wsh(&script.wscript_hash())
1387 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1388 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1390 .sign(recipient_sign).unwrap();
1391 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1393 invoice.fallbacks(),
1395 Address::p2wsh(&script, Network::Bitcoin),
1396 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1397 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1401 tlv_stream.fallbacks,
1404 version: WitnessVersion::V0.to_num(),
1405 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1408 version: WitnessVersion::V0.to_num(),
1409 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1412 version: WitnessVersion::V1.to_num(),
1413 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1420 fn builds_invoice_with_allow_mpp() {
1421 let mut features = Bolt12InvoiceFeatures::empty();
1422 features.set_basic_mpp_optional();
1424 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1427 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1429 .sign(payer_sign).unwrap()
1430 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1433 .sign(recipient_sign).unwrap();
1434 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1435 assert_eq!(invoice.features(), &features);
1436 assert_eq!(tlv_stream.features, Some(&features));
1440 fn fails_signing_invoice() {
1441 match OfferBuilder::new("foo".into(), recipient_pubkey())
1444 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446 .sign(payer_sign).unwrap()
1447 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1451 Ok(_) => panic!("expected error"),
1452 Err(e) => assert_eq!(e, SignError::Signing(())),
1455 match OfferBuilder::new("foo".into(), recipient_pubkey())
1458 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1460 .sign(payer_sign).unwrap()
1461 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1465 Ok(_) => panic!("expected error"),
1466 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1471 fn parses_invoice_with_payment_paths() {
1472 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1475 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 .sign(payer_sign).unwrap()
1478 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1480 .sign(recipient_sign).unwrap();
1482 let mut buffer = Vec::new();
1483 invoice.write(&mut buffer).unwrap();
1485 if let Err(e) = Invoice::try_from(buffer) {
1486 panic!("error parsing invoice: {:?}", e);
1489 let mut tlv_stream = invoice.as_tlv_stream();
1490 tlv_stream.3.paths = None;
1492 match Invoice::try_from(tlv_stream.to_bytes()) {
1493 Ok(_) => panic!("expected error"),
1494 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1497 let mut tlv_stream = invoice.as_tlv_stream();
1498 tlv_stream.3.blindedpay = None;
1500 match Invoice::try_from(tlv_stream.to_bytes()) {
1501 Ok(_) => panic!("expected error"),
1502 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1505 let empty_payment_paths = vec![];
1506 let mut tlv_stream = invoice.as_tlv_stream();
1507 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1509 match Invoice::try_from(tlv_stream.to_bytes()) {
1510 Ok(_) => panic!("expected error"),
1511 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1514 let mut payment_paths = payment_paths();
1515 payment_paths.pop();
1516 let mut tlv_stream = invoice.as_tlv_stream();
1517 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1519 match Invoice::try_from(tlv_stream.to_bytes()) {
1520 Ok(_) => panic!("expected error"),
1521 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1526 fn parses_invoice_with_created_at() {
1527 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1532 .sign(payer_sign).unwrap()
1533 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1535 .sign(recipient_sign).unwrap();
1537 let mut buffer = Vec::new();
1538 invoice.write(&mut buffer).unwrap();
1540 if let Err(e) = Invoice::try_from(buffer) {
1541 panic!("error parsing invoice: {:?}", e);
1544 let mut tlv_stream = invoice.as_tlv_stream();
1545 tlv_stream.3.created_at = None;
1547 match Invoice::try_from(tlv_stream.to_bytes()) {
1548 Ok(_) => panic!("expected error"),
1550 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1556 fn parses_invoice_with_relative_expiry() {
1557 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1560 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1562 .sign(payer_sign).unwrap()
1563 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1564 .relative_expiry(3600)
1566 .sign(recipient_sign).unwrap();
1568 let mut buffer = Vec::new();
1569 invoice.write(&mut buffer).unwrap();
1571 match Invoice::try_from(buffer) {
1572 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1573 Err(e) => panic!("error parsing invoice: {:?}", e),
1578 fn parses_invoice_with_payment_hash() {
1579 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1582 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1584 .sign(payer_sign).unwrap()
1585 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1587 .sign(recipient_sign).unwrap();
1589 let mut buffer = Vec::new();
1590 invoice.write(&mut buffer).unwrap();
1592 if let Err(e) = Invoice::try_from(buffer) {
1593 panic!("error parsing invoice: {:?}", e);
1596 let mut tlv_stream = invoice.as_tlv_stream();
1597 tlv_stream.3.payment_hash = None;
1599 match Invoice::try_from(tlv_stream.to_bytes()) {
1600 Ok(_) => panic!("expected error"),
1602 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1608 fn parses_invoice_with_amount() {
1609 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1612 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1614 .sign(payer_sign).unwrap()
1615 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1617 .sign(recipient_sign).unwrap();
1619 let mut buffer = Vec::new();
1620 invoice.write(&mut buffer).unwrap();
1622 if let Err(e) = Invoice::try_from(buffer) {
1623 panic!("error parsing invoice: {:?}", e);
1626 let mut tlv_stream = invoice.as_tlv_stream();
1627 tlv_stream.3.amount = None;
1629 match Invoice::try_from(tlv_stream.to_bytes()) {
1630 Ok(_) => panic!("expected error"),
1631 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1636 fn parses_invoice_with_allow_mpp() {
1637 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1640 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1642 .sign(payer_sign).unwrap()
1643 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1646 .sign(recipient_sign).unwrap();
1648 let mut buffer = Vec::new();
1649 invoice.write(&mut buffer).unwrap();
1651 match Invoice::try_from(buffer) {
1653 let mut features = Bolt12InvoiceFeatures::empty();
1654 features.set_basic_mpp_optional();
1655 assert_eq!(invoice.features(), &features);
1657 Err(e) => panic!("error parsing invoice: {:?}", e),
1662 fn parses_invoice_with_fallback_address() {
1663 let script = Script::new();
1664 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1665 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1666 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1668 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1671 let invoice_request = offer
1672 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1674 .sign(payer_sign).unwrap();
1675 let mut unsigned_invoice = invoice_request
1676 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1677 .fallback_v0_p2wsh(&script.wscript_hash())
1678 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1679 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1682 // Only standard addresses will be included.
1683 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1684 // Non-standard addresses
1685 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1686 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1687 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1689 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1690 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1692 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1693 let mut buffer = Vec::new();
1694 invoice.write(&mut buffer).unwrap();
1696 match Invoice::try_from(buffer) {
1699 invoice.fallbacks(),
1701 Address::p2wsh(&script, Network::Bitcoin),
1702 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1703 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1705 payload: Payload::WitnessProgram {
1706 version: WitnessVersion::V1,
1707 program: vec![0u8; 33],
1709 network: Network::Bitcoin,
1712 payload: Payload::WitnessProgram {
1713 version: WitnessVersion::V2,
1714 program: vec![0u8; 40],
1716 network: Network::Bitcoin,
1721 Err(e) => panic!("error parsing invoice: {:?}", e),
1726 fn parses_invoice_with_node_id() {
1727 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1730 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1732 .sign(payer_sign).unwrap()
1733 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1735 .sign(recipient_sign).unwrap();
1737 let mut buffer = Vec::new();
1738 invoice.write(&mut buffer).unwrap();
1740 if let Err(e) = Invoice::try_from(buffer) {
1741 panic!("error parsing invoice: {:?}", e);
1744 let mut tlv_stream = invoice.as_tlv_stream();
1745 tlv_stream.3.node_id = None;
1747 match Invoice::try_from(tlv_stream.to_bytes()) {
1748 Ok(_) => panic!("expected error"),
1750 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1754 let invalid_pubkey = payer_pubkey();
1755 let mut tlv_stream = invoice.as_tlv_stream();
1756 tlv_stream.3.node_id = Some(&invalid_pubkey);
1758 match Invoice::try_from(tlv_stream.to_bytes()) {
1759 Ok(_) => panic!("expected error"),
1761 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1767 fn fails_parsing_invoice_without_signature() {
1768 let mut buffer = Vec::new();
1769 OfferBuilder::new("foo".into(), recipient_pubkey())
1772 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1774 .sign(payer_sign).unwrap()
1775 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1778 .write(&mut buffer).unwrap();
1780 match Invoice::try_from(buffer) {
1781 Ok(_) => panic!("expected error"),
1782 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1787 fn fails_parsing_invoice_with_invalid_signature() {
1788 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1791 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1793 .sign(payer_sign).unwrap()
1794 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1796 .sign(recipient_sign).unwrap();
1797 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1798 *last_signature_byte = last_signature_byte.wrapping_add(1);
1800 let mut buffer = Vec::new();
1801 invoice.write(&mut buffer).unwrap();
1803 match Invoice::try_from(buffer) {
1804 Ok(_) => panic!("expected error"),
1806 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1812 fn fails_parsing_invoice_with_extra_tlv_records() {
1813 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1816 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1818 .sign(payer_sign).unwrap()
1819 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1821 .sign(recipient_sign).unwrap();
1823 let mut encoded_invoice = Vec::new();
1824 invoice.write(&mut encoded_invoice).unwrap();
1825 BigSize(1002).write(&mut encoded_invoice).unwrap();
1826 BigSize(32).write(&mut encoded_invoice).unwrap();
1827 [42u8; 32].write(&mut encoded_invoice).unwrap();
1829 match Invoice::try_from(encoded_invoice) {
1830 Ok(_) => panic!("expected error"),
1831 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),