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::onion_message::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::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::inbound_payment::ExpandedKey;
110 use crate::ln::msgs::DecodeError;
111 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
112 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, WithoutSignatures, self};
113 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
114 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
115 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
116 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
117 use crate::offers::signer;
118 use crate::onion_message::BlindedPath;
119 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
121 use crate::prelude::*;
123 #[cfg(feature = "std")]
124 use std::time::SystemTime;
126 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
128 pub(super) const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
130 /// Builds an [`Invoice`] from either:
131 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
132 /// - a [`Refund`] for the "offer for money" flow.
134 /// See [module-level documentation] for usage.
136 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
137 /// [`Refund`]: crate::offers::refund::Refund
138 /// [module-level documentation]: self
139 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
140 invreq_bytes: &'a Vec<u8>,
141 invoice: InvoiceContents,
142 keys: Option<KeyPair>,
143 signing_pubkey_strategy: core::marker::PhantomData<S>,
146 /// Indicates how [`Invoice::signing_pubkey`] was set.
147 pub trait SigningPubkeyStrategy {}
149 /// [`Invoice::signing_pubkey`] was explicitly set.
150 pub struct ExplicitSigningPubkey {}
152 /// [`Invoice::signing_pubkey`] was derived.
153 pub struct DerivedSigningPubkey {}
155 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
156 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
158 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
159 pub(super) fn for_offer(
160 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
161 created_at: Duration, payment_hash: PaymentHash
162 ) -> Result<Self, SemanticError> {
163 let amount_msats = Self::check_amount_msats(invoice_request)?;
164 let contents = InvoiceContents::ForOffer {
165 invoice_request: invoice_request.contents.clone(),
166 fields: InvoiceFields {
167 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
168 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
169 signing_pubkey: invoice_request.contents.inner.offer.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 contents = InvoiceContents::ForRefund {
181 refund: refund.contents.clone(),
182 fields: InvoiceFields {
183 payment_paths, created_at, relative_expiry: None, payment_hash,
184 amount_msats: refund.amount_msats(), fallbacks: None,
185 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
189 Self::new(&refund.bytes, contents, None)
193 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
194 pub(super) fn for_offer_using_keys(
195 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
196 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
197 ) -> Result<Self, SemanticError> {
198 let amount_msats = Self::check_amount_msats(invoice_request)?;
199 let contents = InvoiceContents::ForOffer {
200 invoice_request: invoice_request.contents.clone(),
201 fields: InvoiceFields {
202 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
203 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
204 signing_pubkey: invoice_request.contents.inner.offer.signing_pubkey(),
208 Self::new(&invoice_request.bytes, contents, Some(keys))
211 pub(super) fn for_refund_using_keys(
212 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
213 payment_hash: PaymentHash, keys: KeyPair,
214 ) -> Result<Self, SemanticError> {
215 let contents = InvoiceContents::ForRefund {
216 refund: refund.contents.clone(),
217 fields: InvoiceFields {
218 payment_paths, created_at, relative_expiry: None, payment_hash,
219 amount_msats: refund.amount_msats(), fallbacks: None,
220 features: Bolt12InvoiceFeatures::empty(), signing_pubkey: keys.public_key(),
224 Self::new(&refund.bytes, contents, Some(keys))
228 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
229 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, SemanticError> {
230 match invoice_request.amount_msats() {
231 Some(amount_msats) => Ok(amount_msats),
232 None => match invoice_request.contents.inner.offer.amount() {
233 Some(Amount::Bitcoin { amount_msats }) => {
234 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
235 .ok_or(SemanticError::InvalidAmount)
237 Some(Amount::Currency { .. }) => Err(SemanticError::UnsupportedCurrency),
238 None => Err(SemanticError::MissingAmount),
244 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
245 ) -> Result<Self, SemanticError> {
246 if contents.fields().payment_paths.is_empty() {
247 return Err(SemanticError::MissingPaths);
254 signing_pubkey_strategy: core::marker::PhantomData,
258 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
259 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
261 /// Successive calls to this method will override the previous setting.
262 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
263 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
264 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
268 /// Adds a P2WSH address to [`Invoice::fallbacks`].
270 /// Successive calls to this method will add another address. Caller is responsible for not
271 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
272 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
273 let address = FallbackAddress {
274 version: WitnessVersion::V0.to_num(),
275 program: Vec::from(&script_hash.into_inner()[..]),
277 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
281 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
283 /// Successive calls to this method will add another address. Caller is responsible for not
284 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
285 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
286 let address = FallbackAddress {
287 version: WitnessVersion::V0.to_num(),
288 program: Vec::from(&pubkey_hash.into_inner()[..]),
290 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
294 /// Adds a P2TR address to [`Invoice::fallbacks`].
296 /// Successive calls to this method will add another address. Caller is responsible for not
297 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
298 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
299 let address = FallbackAddress {
300 version: WitnessVersion::V1.to_num(),
301 program: Vec::from(&output_key.serialize()[..]),
303 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
307 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
308 pub fn allow_mpp(mut self) -> Self {
309 self.invoice.fields_mut().features.set_basic_mpp_optional();
314 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
315 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
316 /// [`UnsignedInvoice::sign`].
317 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
318 #[cfg(feature = "std")] {
319 if self.invoice.is_offer_or_refund_expired() {
320 return Err(SemanticError::AlreadyExpired);
324 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
325 Ok(UnsignedInvoice { invreq_bytes, invoice })
329 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
330 /// Builds a signed [`Invoice`] after checking for valid semantics.
331 pub fn build_and_sign<T: secp256k1::Signing>(
332 self, secp_ctx: &Secp256k1<T>
333 ) -> Result<Invoice, 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, keys, .. } = self;
341 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
343 let keys = keys.unwrap();
344 let invoice = unsigned_invoice
345 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
351 /// A semantically valid [`Invoice`] that hasn't been signed.
352 pub struct UnsignedInvoice<'a> {
353 invreq_bytes: &'a Vec<u8>,
354 invoice: InvoiceContents,
357 impl<'a> UnsignedInvoice<'a> {
358 /// The public key corresponding to the key needed to sign the invoice.
359 pub fn signing_pubkey(&self) -> PublicKey {
360 self.invoice.fields().signing_pubkey
363 /// Signs the invoice using the given function.
364 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
366 F: FnOnce(&Message) -> Result<Signature, E>
368 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
369 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
371 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
372 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
373 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
375 let mut bytes = Vec::new();
376 unsigned_tlv_stream.write(&mut bytes).unwrap();
378 let pubkey = self.invoice.fields().signing_pubkey;
379 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
381 // Append the signature TLV record to the bytes.
382 let signature_tlv_stream = SignatureTlvStreamRef {
383 signature: Some(&signature),
385 signature_tlv_stream.write(&mut bytes).unwrap();
389 contents: self.invoice,
395 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
397 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
398 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
400 /// [`Offer`]: crate::offers::offer::Offer
401 /// [`Refund`]: crate::offers::refund::Refund
402 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
403 #[derive(Clone, Debug)]
404 #[cfg_attr(test, derive(PartialEq))]
407 contents: InvoiceContents,
408 signature: Signature,
411 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
413 /// [`Offer`]: crate::offers::offer::Offer
414 /// [`Refund`]: crate::offers::refund::Refund
415 #[derive(Clone, Debug)]
416 #[cfg_attr(test, derive(PartialEq))]
417 enum InvoiceContents {
418 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
420 /// [`Offer`]: crate::offers::offer::Offer
422 invoice_request: InvoiceRequestContents,
423 fields: InvoiceFields,
425 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
427 /// [`Refund`]: crate::offers::refund::Refund
429 refund: RefundContents,
430 fields: InvoiceFields,
434 /// Invoice-specific fields for an `invoice` message.
435 #[derive(Clone, Debug, PartialEq)]
436 struct InvoiceFields {
437 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
438 created_at: Duration,
439 relative_expiry: Option<Duration>,
440 payment_hash: PaymentHash,
442 fallbacks: Option<Vec<FallbackAddress>>,
443 features: Bolt12InvoiceFeatures,
444 signing_pubkey: PublicKey,
448 /// Paths to the recipient originating from publicly reachable nodes, including information
449 /// needed for routing payments across them.
451 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
452 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
453 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
454 &self.contents.fields().payment_paths[..]
457 /// Duration since the Unix epoch when the invoice was created.
458 pub fn created_at(&self) -> Duration {
459 self.contents.fields().created_at
462 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
464 pub fn relative_expiry(&self) -> Duration {
465 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
468 /// Whether the invoice has expired.
469 #[cfg(feature = "std")]
470 pub fn is_expired(&self) -> bool {
471 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
472 match absolute_expiry {
473 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
474 Ok(elapsed) => elapsed > seconds_from_epoch,
481 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
482 pub fn payment_hash(&self) -> PaymentHash {
483 self.contents.fields().payment_hash
486 /// The minimum amount required for a successful payment of the invoice.
487 pub fn amount_msats(&self) -> u64 {
488 self.contents.fields().amount_msats
491 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
493 pub fn fallbacks(&self) -> Vec<Address> {
494 let network = match self.network() {
495 None => return Vec::new(),
496 Some(network) => network,
499 let to_valid_address = |address: &FallbackAddress| {
500 let version = match WitnessVersion::try_from(address.version) {
501 Ok(version) => version,
502 Err(_) => return None,
505 let program = &address.program;
506 if program.len() < 2 || program.len() > 40 {
510 let address = Address {
511 payload: Payload::WitnessProgram {
513 program: address.program.clone(),
518 if !address.is_standard() && version == WitnessVersion::V0 {
525 self.contents.fields().fallbacks
527 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
528 .unwrap_or_else(Vec::new)
531 fn network(&self) -> Option<Network> {
532 let chain = self.contents.chain();
533 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
534 Some(Network::Bitcoin)
535 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
536 Some(Network::Testnet)
537 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
538 Some(Network::Signet)
539 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
540 Some(Network::Regtest)
546 /// Features pertaining to paying an invoice.
547 pub fn features(&self) -> &Bolt12InvoiceFeatures {
548 &self.contents.fields().features
551 /// The public key corresponding to the key used to sign the invoice.
552 pub fn signing_pubkey(&self) -> PublicKey {
553 self.contents.fields().signing_pubkey
556 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
557 pub fn signature(&self) -> Signature {
561 /// Hash that was used for signing the invoice.
562 pub fn signable_hash(&self) -> [u8; 32] {
563 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
566 /// Verifies that the invoice was for a request or refund created using the given key.
567 pub fn verify<T: secp256k1::Signing>(
568 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
570 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
574 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
575 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
576 self.contents.as_tlv_stream();
577 let signature_tlv_stream = SignatureTlvStreamRef {
578 signature: Some(&self.signature),
580 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
581 signature_tlv_stream)
585 impl InvoiceContents {
586 /// Whether the original offer or refund has expired.
587 #[cfg(feature = "std")]
588 fn is_offer_or_refund_expired(&self) -> bool {
590 InvoiceContents::ForOffer { invoice_request, .. } =>
591 invoice_request.inner.offer.is_expired(),
592 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
596 fn chain(&self) -> ChainHash {
598 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
599 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
603 fn fields(&self) -> &InvoiceFields {
605 InvoiceContents::ForOffer { fields, .. } => fields,
606 InvoiceContents::ForRefund { fields, .. } => fields,
610 fn fields_mut(&mut self) -> &mut InvoiceFields {
612 InvoiceContents::ForOffer { fields, .. } => fields,
613 InvoiceContents::ForRefund { fields, .. } => fields,
617 fn verify<T: secp256k1::Signing>(
618 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
620 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
621 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
622 match record.r#type {
623 PAYER_METADATA_TYPE => false, // Should be outside range
624 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
628 let tlv_stream = offer_records.chain(invreq_records);
630 let (metadata, payer_id, iv_bytes) = match self {
631 InvoiceContents::ForOffer { invoice_request, .. } => {
632 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
634 InvoiceContents::ForRefund { refund, .. } => {
635 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
639 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
645 fn derives_keys(&self) -> bool {
647 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
648 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
652 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
653 let (payer, offer, invoice_request) = match self {
654 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
655 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
657 let invoice = self.fields().as_tlv_stream();
659 (payer, offer, invoice_request, invoice)
664 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
666 if self.features == Bolt12InvoiceFeatures::empty() { None }
667 else { Some(&self.features) }
670 InvoiceTlvStreamRef {
671 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
672 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
673 created_at: Some(self.created_at.as_secs()),
674 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
675 payment_hash: Some(&self.payment_hash),
676 amount: Some(self.amount_msats),
677 fallbacks: self.fallbacks.as_ref(),
679 node_id: Some(&self.signing_pubkey),
684 impl Writeable for Invoice {
685 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
686 WithoutLength(&self.bytes).write(writer)
690 impl Writeable for InvoiceContents {
691 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692 self.as_tlv_stream().write(writer)
696 impl TryFrom<Vec<u8>> for Invoice {
697 type Error = ParseError;
699 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
700 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
701 Invoice::try_from(parsed_invoice)
705 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
706 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
707 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
708 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
709 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
710 (168, payment_hash: PaymentHash),
711 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
712 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
713 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
714 (176, node_id: PublicKey),
717 type BlindedPathIter<'a> = core::iter::Map<
718 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
719 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
722 type BlindedPayInfoIter<'a> = core::iter::Map<
723 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
724 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
727 /// Information needed to route a payment across a [`BlindedPath`].
728 #[derive(Clone, Debug, PartialEq)]
729 pub struct BlindedPayInfo {
730 /// Base fee charged (in millisatoshi) for the entire blinded path.
731 pub fee_base_msat: u32,
733 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
734 /// (i.e., 10,000 is 1%).
735 pub fee_proportional_millionths: u32,
737 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
739 pub cltv_expiry_delta: u16,
741 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
742 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
743 /// seen by the recipient.
744 pub htlc_minimum_msat: u64,
746 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
747 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
748 /// seen by the recipient.
749 pub htlc_maximum_msat: u64,
751 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
753 pub features: BlindedHopFeatures,
756 impl_writeable!(BlindedPayInfo, {
758 fee_proportional_millionths,
765 /// Wire representation for an on-chain fallback address.
766 #[derive(Clone, Debug, PartialEq)]
767 pub(super) struct FallbackAddress {
772 impl_writeable!(FallbackAddress, { version, program });
774 type FullInvoiceTlvStream =
775 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
778 type FullInvoiceTlvStreamRef<'a> = (
779 PayerTlvStreamRef<'a>,
780 OfferTlvStreamRef<'a>,
781 InvoiceRequestTlvStreamRef<'a>,
782 InvoiceTlvStreamRef<'a>,
783 SignatureTlvStreamRef<'a>,
786 impl SeekReadable for FullInvoiceTlvStream {
787 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
788 let payer = SeekReadable::read(r)?;
789 let offer = SeekReadable::read(r)?;
790 let invoice_request = SeekReadable::read(r)?;
791 let invoice = SeekReadable::read(r)?;
792 let signature = SeekReadable::read(r)?;
794 Ok((payer, offer, invoice_request, invoice, signature))
798 type PartialInvoiceTlvStream =
799 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
801 type PartialInvoiceTlvStreamRef<'a> = (
802 PayerTlvStreamRef<'a>,
803 OfferTlvStreamRef<'a>,
804 InvoiceRequestTlvStreamRef<'a>,
805 InvoiceTlvStreamRef<'a>,
808 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
809 type Error = ParseError;
811 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
812 let ParsedMessage { bytes, tlv_stream } = invoice;
814 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
815 SignatureTlvStream { signature },
817 let contents = InvoiceContents::try_from(
818 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
821 let signature = match signature {
822 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
823 Some(signature) => signature,
825 let pubkey = contents.fields().signing_pubkey;
826 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
828 Ok(Invoice { bytes, contents, signature })
832 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
833 type Error = SemanticError;
835 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
839 invoice_request_tlv_stream,
841 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
846 let payment_paths = match (paths, blindedpay) {
847 (None, _) => return Err(SemanticError::MissingPaths),
848 (_, None) => return Err(SemanticError::InvalidPayInfo),
849 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
850 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
851 return Err(SemanticError::InvalidPayInfo);
853 (Some(paths), Some(blindedpay)) => {
854 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
858 let created_at = match created_at {
859 None => return Err(SemanticError::MissingCreationTime),
860 Some(timestamp) => Duration::from_secs(timestamp),
863 let relative_expiry = relative_expiry
864 .map(Into::<u64>::into)
865 .map(Duration::from_secs);
867 let payment_hash = match payment_hash {
868 None => return Err(SemanticError::MissingPaymentHash),
869 Some(payment_hash) => payment_hash,
872 let amount_msats = match amount {
873 None => return Err(SemanticError::MissingAmount),
874 Some(amount) => amount,
877 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
879 let signing_pubkey = match node_id {
880 None => return Err(SemanticError::MissingSigningPubkey),
881 Some(node_id) => node_id,
884 let fields = InvoiceFields {
885 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
886 features, signing_pubkey,
889 match offer_tlv_stream.node_id {
890 Some(expected_signing_pubkey) => {
891 if fields.signing_pubkey != expected_signing_pubkey {
892 return Err(SemanticError::InvalidSigningPubkey);
895 let invoice_request = InvoiceRequestContents::try_from(
896 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
898 Ok(InvoiceContents::ForOffer { invoice_request, fields })
901 let refund = RefundContents::try_from(
902 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
904 Ok(InvoiceContents::ForRefund { refund, fields })
912 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
914 use bitcoin::blockdata::script::Script;
915 use bitcoin::hashes::Hash;
916 use bitcoin::network::constants::Network;
917 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
918 use bitcoin::util::address::{Address, Payload, WitnessVersion};
919 use bitcoin::util::schnorr::TweakedPublicKey;
920 use core::convert::TryFrom;
921 use core::time::Duration;
922 use crate::chain::keysinterface::KeyMaterial;
923 use crate::ln::features::Bolt12InvoiceFeatures;
924 use crate::ln::inbound_payment::ExpandedKey;
925 use crate::ln::msgs::DecodeError;
926 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
927 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
928 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
929 use crate::offers::parse::{ParseError, SemanticError};
930 use crate::offers::payer::PayerTlvStreamRef;
931 use crate::offers::refund::RefundBuilder;
932 use crate::offers::test_utils::*;
933 use crate::onion_message::{BlindedHop, BlindedPath};
934 use crate::util::ser::{BigSize, Iterable, Writeable};
937 fn to_bytes(&self) -> Vec<u8>;
940 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
941 fn to_bytes(&self) -> Vec<u8> {
942 let mut buffer = Vec::new();
943 self.0.write(&mut buffer).unwrap();
944 self.1.write(&mut buffer).unwrap();
945 self.2.write(&mut buffer).unwrap();
946 self.3.write(&mut buffer).unwrap();
947 self.4.write(&mut buffer).unwrap();
953 fn builds_invoice_for_offer_with_defaults() {
954 let payment_paths = payment_paths();
955 let payment_hash = payment_hash();
957 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
960 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
962 .sign(payer_sign).unwrap()
963 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
965 .sign(recipient_sign).unwrap();
967 let mut buffer = Vec::new();
968 invoice.write(&mut buffer).unwrap();
970 assert_eq!(invoice.bytes, buffer.as_slice());
971 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
972 assert_eq!(invoice.created_at(), now);
973 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
974 #[cfg(feature = "std")]
975 assert!(!invoice.is_expired());
976 assert_eq!(invoice.payment_hash(), payment_hash);
977 assert_eq!(invoice.amount_msats(), 1000);
978 assert_eq!(invoice.fallbacks(), vec![]);
979 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
980 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
982 merkle::verify_signature(
983 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
987 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
988 let pubkey = recipient_pubkey().into();
989 let secp_ctx = Secp256k1::verification_only();
990 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
993 invoice.as_tlv_stream(),
995 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1001 description: Some(&String::from("foo")),
1003 absolute_expiry: None,
1007 node_id: Some(&recipient_pubkey()),
1009 InvoiceRequestTlvStreamRef {
1014 payer_id: Some(&payer_pubkey()),
1017 InvoiceTlvStreamRef {
1018 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1019 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1020 created_at: Some(now.as_secs()),
1021 relative_expiry: None,
1022 payment_hash: Some(&payment_hash),
1026 node_id: Some(&recipient_pubkey()),
1028 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1032 if let Err(e) = Invoice::try_from(buffer) {
1033 panic!("error parsing invoice: {:?}", e);
1038 fn builds_invoice_for_refund_with_defaults() {
1039 let payment_paths = payment_paths();
1040 let payment_hash = payment_hash();
1042 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1044 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1047 .sign(recipient_sign).unwrap();
1049 let mut buffer = Vec::new();
1050 invoice.write(&mut buffer).unwrap();
1052 assert_eq!(invoice.bytes, buffer.as_slice());
1053 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1054 assert_eq!(invoice.created_at(), now);
1055 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1056 #[cfg(feature = "std")]
1057 assert!(!invoice.is_expired());
1058 assert_eq!(invoice.payment_hash(), payment_hash);
1059 assert_eq!(invoice.amount_msats(), 1000);
1060 assert_eq!(invoice.fallbacks(), vec![]);
1061 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1062 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1064 merkle::verify_signature(
1065 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1070 invoice.as_tlv_stream(),
1072 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1078 description: Some(&String::from("foo")),
1080 absolute_expiry: None,
1086 InvoiceRequestTlvStreamRef {
1091 payer_id: Some(&payer_pubkey()),
1094 InvoiceTlvStreamRef {
1095 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1096 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1097 created_at: Some(now.as_secs()),
1098 relative_expiry: None,
1099 payment_hash: Some(&payment_hash),
1103 node_id: Some(&recipient_pubkey()),
1105 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1109 if let Err(e) = Invoice::try_from(buffer) {
1110 panic!("error parsing invoice: {:?}", e);
1114 #[cfg(feature = "std")]
1116 fn builds_invoice_from_offer_with_expiration() {
1117 let future_expiry = Duration::from_secs(u64::max_value());
1118 let past_expiry = Duration::from_secs(0);
1120 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1122 .absolute_expiry(future_expiry)
1124 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1126 .sign(payer_sign).unwrap()
1127 .respond_with(payment_paths(), payment_hash())
1131 panic!("error building invoice: {:?}", e);
1134 match OfferBuilder::new("foo".into(), recipient_pubkey())
1136 .absolute_expiry(past_expiry)
1138 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1140 .sign(payer_sign).unwrap()
1141 .respond_with(payment_paths(), payment_hash())
1145 Ok(_) => panic!("expected error"),
1146 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1150 #[cfg(feature = "std")]
1152 fn builds_invoice_from_refund_with_expiration() {
1153 let future_expiry = Duration::from_secs(u64::max_value());
1154 let past_expiry = Duration::from_secs(0);
1156 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1157 .absolute_expiry(future_expiry)
1159 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1163 panic!("error building invoice: {:?}", e);
1166 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1167 .absolute_expiry(past_expiry)
1169 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1173 Ok(_) => panic!("expected error"),
1174 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1179 fn builds_invoice_from_offer_using_derived_keys() {
1180 let desc = "foo".to_string();
1181 let node_id = recipient_pubkey();
1182 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1183 let entropy = FixedEntropy {};
1184 let secp_ctx = Secp256k1::new();
1186 let blinded_path = BlindedPath {
1187 introduction_node_id: pubkey(40),
1188 blinding_point: pubkey(41),
1190 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1191 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1195 let offer = OfferBuilder
1196 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1200 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1202 .sign(payer_sign).unwrap();
1204 if let Err(e) = invoice_request
1205 .verify_and_respond_using_derived_keys_no_std(
1206 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1209 .build_and_sign(&secp_ctx)
1211 panic!("error building invoice: {:?}", e);
1214 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1215 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1216 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1218 Ok(_) => panic!("expected error"),
1219 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1222 let desc = "foo".to_string();
1223 let offer = OfferBuilder
1224 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1227 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229 .sign(payer_sign).unwrap();
1231 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1232 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1234 Ok(_) => panic!("expected error"),
1235 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1240 fn builds_invoice_from_refund_using_derived_keys() {
1241 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1242 let entropy = FixedEntropy {};
1243 let secp_ctx = Secp256k1::new();
1245 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1248 if let Err(e) = refund
1249 .respond_using_derived_keys_no_std(
1250 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1253 .build_and_sign(&secp_ctx)
1255 panic!("error building invoice: {:?}", e);
1260 fn builds_invoice_with_relative_expiry() {
1262 let one_hour = Duration::from_secs(3600);
1264 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1267 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1269 .sign(payer_sign).unwrap()
1270 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1271 .relative_expiry(one_hour.as_secs() as u32)
1273 .sign(recipient_sign).unwrap();
1274 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1275 #[cfg(feature = "std")]
1276 assert!(!invoice.is_expired());
1277 assert_eq!(invoice.relative_expiry(), one_hour);
1278 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1280 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1285 .sign(payer_sign).unwrap()
1286 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1287 .relative_expiry(one_hour.as_secs() as u32 - 1)
1289 .sign(recipient_sign).unwrap();
1290 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1291 #[cfg(feature = "std")]
1292 assert!(invoice.is_expired());
1293 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1294 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1298 fn builds_invoice_with_amount_from_request() {
1299 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1303 .amount_msats(1001).unwrap()
1305 .sign(payer_sign).unwrap()
1306 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1308 .sign(recipient_sign).unwrap();
1309 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1310 assert_eq!(invoice.amount_msats(), 1001);
1311 assert_eq!(tlv_stream.amount, Some(1001));
1315 fn builds_invoice_with_quantity_from_request() {
1316 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1318 .supported_quantity(Quantity::Unbounded)
1320 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1321 .quantity(2).unwrap()
1323 .sign(payer_sign).unwrap()
1324 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1326 .sign(recipient_sign).unwrap();
1327 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1328 assert_eq!(invoice.amount_msats(), 2000);
1329 assert_eq!(tlv_stream.amount, Some(2000));
1331 match OfferBuilder::new("foo".into(), recipient_pubkey())
1333 .supported_quantity(Quantity::Unbounded)
1335 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1336 .quantity(u64::max_value()).unwrap()
1338 .sign(payer_sign).unwrap()
1339 .respond_with_no_std(payment_paths(), payment_hash(), now())
1341 Ok(_) => panic!("expected error"),
1342 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1347 fn builds_invoice_with_fallback_address() {
1348 let script = Script::new();
1349 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1350 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1351 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1353 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1356 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1358 .sign(payer_sign).unwrap()
1359 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1360 .fallback_v0_p2wsh(&script.wscript_hash())
1361 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1362 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1364 .sign(recipient_sign).unwrap();
1365 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1367 invoice.fallbacks(),
1369 Address::p2wsh(&script, Network::Bitcoin),
1370 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1371 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1375 tlv_stream.fallbacks,
1378 version: WitnessVersion::V0.to_num(),
1379 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1382 version: WitnessVersion::V0.to_num(),
1383 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1386 version: WitnessVersion::V1.to_num(),
1387 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1394 fn builds_invoice_with_allow_mpp() {
1395 let mut features = Bolt12InvoiceFeatures::empty();
1396 features.set_basic_mpp_optional();
1398 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1401 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1403 .sign(payer_sign).unwrap()
1404 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1407 .sign(recipient_sign).unwrap();
1408 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1409 assert_eq!(invoice.features(), &features);
1410 assert_eq!(tlv_stream.features, Some(&features));
1414 fn fails_signing_invoice() {
1415 match OfferBuilder::new("foo".into(), recipient_pubkey())
1418 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1420 .sign(payer_sign).unwrap()
1421 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1425 Ok(_) => panic!("expected error"),
1426 Err(e) => assert_eq!(e, SignError::Signing(())),
1429 match OfferBuilder::new("foo".into(), recipient_pubkey())
1432 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1434 .sign(payer_sign).unwrap()
1435 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1439 Ok(_) => panic!("expected error"),
1440 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1445 fn parses_invoice_with_payment_paths() {
1446 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1449 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1451 .sign(payer_sign).unwrap()
1452 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1454 .sign(recipient_sign).unwrap();
1456 let mut buffer = Vec::new();
1457 invoice.write(&mut buffer).unwrap();
1459 if let Err(e) = Invoice::try_from(buffer) {
1460 panic!("error parsing invoice: {:?}", e);
1463 let mut tlv_stream = invoice.as_tlv_stream();
1464 tlv_stream.3.paths = None;
1466 match Invoice::try_from(tlv_stream.to_bytes()) {
1467 Ok(_) => panic!("expected error"),
1468 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1471 let mut tlv_stream = invoice.as_tlv_stream();
1472 tlv_stream.3.blindedpay = None;
1474 match Invoice::try_from(tlv_stream.to_bytes()) {
1475 Ok(_) => panic!("expected error"),
1476 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1479 let empty_payment_paths = vec![];
1480 let mut tlv_stream = invoice.as_tlv_stream();
1481 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1483 match Invoice::try_from(tlv_stream.to_bytes()) {
1484 Ok(_) => panic!("expected error"),
1485 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1488 let mut payment_paths = payment_paths();
1489 payment_paths.pop();
1490 let mut tlv_stream = invoice.as_tlv_stream();
1491 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1493 match Invoice::try_from(tlv_stream.to_bytes()) {
1494 Ok(_) => panic!("expected error"),
1495 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1500 fn parses_invoice_with_created_at() {
1501 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1504 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 .sign(payer_sign).unwrap()
1507 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1509 .sign(recipient_sign).unwrap();
1511 let mut buffer = Vec::new();
1512 invoice.write(&mut buffer).unwrap();
1514 if let Err(e) = Invoice::try_from(buffer) {
1515 panic!("error parsing invoice: {:?}", e);
1518 let mut tlv_stream = invoice.as_tlv_stream();
1519 tlv_stream.3.created_at = None;
1521 match Invoice::try_from(tlv_stream.to_bytes()) {
1522 Ok(_) => panic!("expected error"),
1524 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1530 fn parses_invoice_with_relative_expiry() {
1531 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1534 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1536 .sign(payer_sign).unwrap()
1537 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1538 .relative_expiry(3600)
1540 .sign(recipient_sign).unwrap();
1542 let mut buffer = Vec::new();
1543 invoice.write(&mut buffer).unwrap();
1545 match Invoice::try_from(buffer) {
1546 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1547 Err(e) => panic!("error parsing invoice: {:?}", e),
1552 fn parses_invoice_with_payment_hash() {
1553 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1556 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1558 .sign(payer_sign).unwrap()
1559 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1561 .sign(recipient_sign).unwrap();
1563 let mut buffer = Vec::new();
1564 invoice.write(&mut buffer).unwrap();
1566 if let Err(e) = Invoice::try_from(buffer) {
1567 panic!("error parsing invoice: {:?}", e);
1570 let mut tlv_stream = invoice.as_tlv_stream();
1571 tlv_stream.3.payment_hash = None;
1573 match Invoice::try_from(tlv_stream.to_bytes()) {
1574 Ok(_) => panic!("expected error"),
1576 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1582 fn parses_invoice_with_amount() {
1583 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1586 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1588 .sign(payer_sign).unwrap()
1589 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1591 .sign(recipient_sign).unwrap();
1593 let mut buffer = Vec::new();
1594 invoice.write(&mut buffer).unwrap();
1596 if let Err(e) = Invoice::try_from(buffer) {
1597 panic!("error parsing invoice: {:?}", e);
1600 let mut tlv_stream = invoice.as_tlv_stream();
1601 tlv_stream.3.amount = None;
1603 match Invoice::try_from(tlv_stream.to_bytes()) {
1604 Ok(_) => panic!("expected error"),
1605 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1610 fn parses_invoice_with_allow_mpp() {
1611 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1614 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1616 .sign(payer_sign).unwrap()
1617 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1620 .sign(recipient_sign).unwrap();
1622 let mut buffer = Vec::new();
1623 invoice.write(&mut buffer).unwrap();
1625 match Invoice::try_from(buffer) {
1627 let mut features = Bolt12InvoiceFeatures::empty();
1628 features.set_basic_mpp_optional();
1629 assert_eq!(invoice.features(), &features);
1631 Err(e) => panic!("error parsing invoice: {:?}", e),
1636 fn parses_invoice_with_fallback_address() {
1637 let script = Script::new();
1638 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1639 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1640 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1642 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1645 let invoice_request = offer
1646 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1648 .sign(payer_sign).unwrap();
1649 let mut unsigned_invoice = invoice_request
1650 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1651 .fallback_v0_p2wsh(&script.wscript_hash())
1652 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1653 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1656 // Only standard addresses will be included.
1657 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1658 // Non-standard addresses
1659 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1660 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1661 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1663 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1664 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1666 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1667 let mut buffer = Vec::new();
1668 invoice.write(&mut buffer).unwrap();
1670 match Invoice::try_from(buffer) {
1673 invoice.fallbacks(),
1675 Address::p2wsh(&script, Network::Bitcoin),
1676 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1677 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1679 payload: Payload::WitnessProgram {
1680 version: WitnessVersion::V1,
1681 program: vec![0u8; 33],
1683 network: Network::Bitcoin,
1686 payload: Payload::WitnessProgram {
1687 version: WitnessVersion::V2,
1688 program: vec![0u8; 40],
1690 network: Network::Bitcoin,
1695 Err(e) => panic!("error parsing invoice: {:?}", e),
1700 fn parses_invoice_with_node_id() {
1701 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1704 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1706 .sign(payer_sign).unwrap()
1707 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1709 .sign(recipient_sign).unwrap();
1711 let mut buffer = Vec::new();
1712 invoice.write(&mut buffer).unwrap();
1714 if let Err(e) = Invoice::try_from(buffer) {
1715 panic!("error parsing invoice: {:?}", e);
1718 let mut tlv_stream = invoice.as_tlv_stream();
1719 tlv_stream.3.node_id = None;
1721 match Invoice::try_from(tlv_stream.to_bytes()) {
1722 Ok(_) => panic!("expected error"),
1724 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1728 let invalid_pubkey = payer_pubkey();
1729 let mut tlv_stream = invoice.as_tlv_stream();
1730 tlv_stream.3.node_id = Some(&invalid_pubkey);
1732 match Invoice::try_from(tlv_stream.to_bytes()) {
1733 Ok(_) => panic!("expected error"),
1735 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1741 fn fails_parsing_invoice_without_signature() {
1742 let mut buffer = Vec::new();
1743 OfferBuilder::new("foo".into(), recipient_pubkey())
1746 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1748 .sign(payer_sign).unwrap()
1749 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1752 .write(&mut buffer).unwrap();
1754 match Invoice::try_from(buffer) {
1755 Ok(_) => panic!("expected error"),
1756 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1761 fn fails_parsing_invoice_with_invalid_signature() {
1762 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1765 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1767 .sign(payer_sign).unwrap()
1768 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1770 .sign(recipient_sign).unwrap();
1771 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1772 *last_signature_byte = last_signature_byte.wrapping_add(1);
1774 let mut buffer = Vec::new();
1775 invoice.write(&mut buffer).unwrap();
1777 match Invoice::try_from(buffer) {
1778 Ok(_) => panic!("expected error"),
1780 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1786 fn fails_parsing_invoice_with_extra_tlv_records() {
1787 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1790 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1792 .sign(payer_sign).unwrap()
1793 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1795 .sign(recipient_sign).unwrap();
1797 let mut encoded_invoice = Vec::new();
1798 invoice.write(&mut encoded_invoice).unwrap();
1799 BigSize(1002).write(&mut encoded_invoice).unwrap();
1800 BigSize(32).write(&mut encoded_invoice).unwrap();
1801 [42u8; 32].write(&mut encoded_invoice).unwrap();
1803 match Invoice::try_from(encoded_invoice) {
1804 Ok(_) => panic!("expected error"),
1805 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),