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 signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
165 let contents = InvoiceContents::ForOffer {
166 invoice_request: invoice_request.contents.clone(),
167 fields: Self::fields(
168 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
172 Self::new(&invoice_request.bytes, contents, None)
175 pub(super) fn for_refund(
176 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
177 payment_hash: PaymentHash, signing_pubkey: PublicKey
178 ) -> Result<Self, SemanticError> {
179 let amount_msats = refund.amount_msats();
180 let contents = InvoiceContents::ForRefund {
181 refund: refund.contents.clone(),
182 fields: Self::fields(
183 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
187 Self::new(&refund.bytes, contents, None)
191 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
192 pub(super) fn for_offer_using_keys(
193 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
194 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
195 ) -> Result<Self, SemanticError> {
196 let amount_msats = Self::check_amount_msats(invoice_request)?;
197 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
198 let contents = InvoiceContents::ForOffer {
199 invoice_request: invoice_request.contents.clone(),
200 fields: Self::fields(
201 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
205 Self::new(&invoice_request.bytes, contents, Some(keys))
208 pub(super) fn for_refund_using_keys(
209 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
210 payment_hash: PaymentHash, keys: KeyPair,
211 ) -> Result<Self, SemanticError> {
212 let amount_msats = refund.amount_msats();
213 let signing_pubkey = keys.public_key();
214 let contents = InvoiceContents::ForRefund {
215 refund: refund.contents.clone(),
216 fields: Self::fields(
217 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
221 Self::new(&refund.bytes, contents, Some(keys))
225 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
226 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, SemanticError> {
227 match invoice_request.amount_msats() {
228 Some(amount_msats) => Ok(amount_msats),
229 None => match invoice_request.contents.inner.offer.amount() {
230 Some(Amount::Bitcoin { amount_msats }) => {
231 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
232 .ok_or(SemanticError::InvalidAmount)
234 Some(Amount::Currency { .. }) => Err(SemanticError::UnsupportedCurrency),
235 None => Err(SemanticError::MissingAmount),
241 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
242 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
245 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
246 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
251 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
252 ) -> Result<Self, SemanticError> {
253 if contents.fields().payment_paths.is_empty() {
254 return Err(SemanticError::MissingPaths);
261 signing_pubkey_strategy: core::marker::PhantomData,
265 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
266 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
268 /// Successive calls to this method will override the previous setting.
269 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
270 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
271 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
275 /// Adds a P2WSH address to [`Invoice::fallbacks`].
277 /// Successive calls to this method will add another address. Caller is responsible for not
278 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
279 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
280 let address = FallbackAddress {
281 version: WitnessVersion::V0.to_num(),
282 program: Vec::from(&script_hash.into_inner()[..]),
284 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
288 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
290 /// Successive calls to this method will add another address. Caller is responsible for not
291 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
292 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
293 let address = FallbackAddress {
294 version: WitnessVersion::V0.to_num(),
295 program: Vec::from(&pubkey_hash.into_inner()[..]),
297 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
301 /// Adds a P2TR address to [`Invoice::fallbacks`].
303 /// Successive calls to this method will add another address. Caller is responsible for not
304 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
305 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
306 let address = FallbackAddress {
307 version: WitnessVersion::V1.to_num(),
308 program: Vec::from(&output_key.serialize()[..]),
310 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
314 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
315 pub fn allow_mpp(mut self) -> Self {
316 self.invoice.fields_mut().features.set_basic_mpp_optional();
321 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
322 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
323 /// [`UnsignedInvoice::sign`].
324 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
325 #[cfg(feature = "std")] {
326 if self.invoice.is_offer_or_refund_expired() {
327 return Err(SemanticError::AlreadyExpired);
331 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
332 Ok(UnsignedInvoice { invreq_bytes, invoice })
336 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
337 /// Builds a signed [`Invoice`] after checking for valid semantics.
338 pub fn build_and_sign<T: secp256k1::Signing>(
339 self, secp_ctx: &Secp256k1<T>
340 ) -> Result<Invoice, SemanticError> {
341 #[cfg(feature = "std")] {
342 if self.invoice.is_offer_or_refund_expired() {
343 return Err(SemanticError::AlreadyExpired);
347 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
348 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
350 let keys = keys.unwrap();
351 let invoice = unsigned_invoice
352 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
358 /// A semantically valid [`Invoice`] that hasn't been signed.
359 pub struct UnsignedInvoice<'a> {
360 invreq_bytes: &'a Vec<u8>,
361 invoice: InvoiceContents,
364 impl<'a> UnsignedInvoice<'a> {
365 /// The public key corresponding to the key needed to sign the invoice.
366 pub fn signing_pubkey(&self) -> PublicKey {
367 self.invoice.fields().signing_pubkey
370 /// Signs the invoice using the given function.
371 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
373 F: FnOnce(&Message) -> Result<Signature, E>
375 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
376 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
378 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
379 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
380 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
382 let mut bytes = Vec::new();
383 unsigned_tlv_stream.write(&mut bytes).unwrap();
385 let pubkey = self.invoice.fields().signing_pubkey;
386 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
388 // Append the signature TLV record to the bytes.
389 let signature_tlv_stream = SignatureTlvStreamRef {
390 signature: Some(&signature),
392 signature_tlv_stream.write(&mut bytes).unwrap();
396 contents: self.invoice,
402 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
404 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
405 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
407 /// [`Offer`]: crate::offers::offer::Offer
408 /// [`Refund`]: crate::offers::refund::Refund
409 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
410 #[derive(Clone, Debug)]
411 #[cfg_attr(test, derive(PartialEq))]
414 contents: InvoiceContents,
415 signature: Signature,
418 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
420 /// [`Offer`]: crate::offers::offer::Offer
421 /// [`Refund`]: crate::offers::refund::Refund
422 #[derive(Clone, Debug)]
423 #[cfg_attr(test, derive(PartialEq))]
424 enum InvoiceContents {
425 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
427 /// [`Offer`]: crate::offers::offer::Offer
429 invoice_request: InvoiceRequestContents,
430 fields: InvoiceFields,
432 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
434 /// [`Refund`]: crate::offers::refund::Refund
436 refund: RefundContents,
437 fields: InvoiceFields,
441 /// Invoice-specific fields for an `invoice` message.
442 #[derive(Clone, Debug, PartialEq)]
443 struct InvoiceFields {
444 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
445 created_at: Duration,
446 relative_expiry: Option<Duration>,
447 payment_hash: PaymentHash,
449 fallbacks: Option<Vec<FallbackAddress>>,
450 features: Bolt12InvoiceFeatures,
451 signing_pubkey: PublicKey,
455 /// Paths to the recipient originating from publicly reachable nodes, including information
456 /// needed for routing payments across them.
458 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
459 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
460 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
461 &self.contents.fields().payment_paths[..]
464 /// Duration since the Unix epoch when the invoice was created.
465 pub fn created_at(&self) -> Duration {
466 self.contents.fields().created_at
469 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
471 pub fn relative_expiry(&self) -> Duration {
472 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
475 /// Whether the invoice has expired.
476 #[cfg(feature = "std")]
477 pub fn is_expired(&self) -> bool {
478 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
479 match absolute_expiry {
480 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
481 Ok(elapsed) => elapsed > seconds_from_epoch,
488 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
489 pub fn payment_hash(&self) -> PaymentHash {
490 self.contents.fields().payment_hash
493 /// The minimum amount required for a successful payment of the invoice.
494 pub fn amount_msats(&self) -> u64 {
495 self.contents.fields().amount_msats
498 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
500 pub fn fallbacks(&self) -> Vec<Address> {
501 let network = match self.network() {
502 None => return Vec::new(),
503 Some(network) => network,
506 let to_valid_address = |address: &FallbackAddress| {
507 let version = match WitnessVersion::try_from(address.version) {
508 Ok(version) => version,
509 Err(_) => return None,
512 let program = &address.program;
513 if program.len() < 2 || program.len() > 40 {
517 let address = Address {
518 payload: Payload::WitnessProgram {
520 program: address.program.clone(),
525 if !address.is_standard() && version == WitnessVersion::V0 {
532 self.contents.fields().fallbacks
534 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
535 .unwrap_or_else(Vec::new)
538 fn network(&self) -> Option<Network> {
539 let chain = self.contents.chain();
540 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
541 Some(Network::Bitcoin)
542 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
543 Some(Network::Testnet)
544 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
545 Some(Network::Signet)
546 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
547 Some(Network::Regtest)
553 /// Features pertaining to paying an invoice.
554 pub fn features(&self) -> &Bolt12InvoiceFeatures {
555 &self.contents.fields().features
558 /// The public key corresponding to the key used to sign the invoice.
559 pub fn signing_pubkey(&self) -> PublicKey {
560 self.contents.fields().signing_pubkey
563 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
564 pub fn signature(&self) -> Signature {
568 /// Hash that was used for signing the invoice.
569 pub fn signable_hash(&self) -> [u8; 32] {
570 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
573 /// Verifies that the invoice was for a request or refund created using the given key.
574 pub fn verify<T: secp256k1::Signing>(
575 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
577 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
581 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
582 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
583 self.contents.as_tlv_stream();
584 let signature_tlv_stream = SignatureTlvStreamRef {
585 signature: Some(&self.signature),
587 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
588 signature_tlv_stream)
592 impl InvoiceContents {
593 /// Whether the original offer or refund has expired.
594 #[cfg(feature = "std")]
595 fn is_offer_or_refund_expired(&self) -> bool {
597 InvoiceContents::ForOffer { invoice_request, .. } =>
598 invoice_request.inner.offer.is_expired(),
599 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
603 fn chain(&self) -> ChainHash {
605 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
606 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
610 fn fields(&self) -> &InvoiceFields {
612 InvoiceContents::ForOffer { fields, .. } => fields,
613 InvoiceContents::ForRefund { fields, .. } => fields,
617 fn fields_mut(&mut self) -> &mut InvoiceFields {
619 InvoiceContents::ForOffer { fields, .. } => fields,
620 InvoiceContents::ForRefund { fields, .. } => fields,
624 fn verify<T: secp256k1::Signing>(
625 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
627 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
628 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
629 match record.r#type {
630 PAYER_METADATA_TYPE => false, // Should be outside range
631 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
635 let tlv_stream = offer_records.chain(invreq_records);
637 let (metadata, payer_id, iv_bytes) = match self {
638 InvoiceContents::ForOffer { invoice_request, .. } => {
639 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
641 InvoiceContents::ForRefund { refund, .. } => {
642 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
646 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
652 fn derives_keys(&self) -> bool {
654 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
655 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
659 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
660 let (payer, offer, invoice_request) = match self {
661 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
662 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
664 let invoice = self.fields().as_tlv_stream();
666 (payer, offer, invoice_request, invoice)
671 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
673 if self.features == Bolt12InvoiceFeatures::empty() { None }
674 else { Some(&self.features) }
677 InvoiceTlvStreamRef {
678 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
679 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
680 created_at: Some(self.created_at.as_secs()),
681 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
682 payment_hash: Some(&self.payment_hash),
683 amount: Some(self.amount_msats),
684 fallbacks: self.fallbacks.as_ref(),
686 node_id: Some(&self.signing_pubkey),
691 impl Writeable for Invoice {
692 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
693 WithoutLength(&self.bytes).write(writer)
697 impl Writeable for InvoiceContents {
698 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
699 self.as_tlv_stream().write(writer)
703 impl TryFrom<Vec<u8>> for Invoice {
704 type Error = ParseError;
706 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
707 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
708 Invoice::try_from(parsed_invoice)
712 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
713 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
714 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
715 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
716 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
717 (168, payment_hash: PaymentHash),
718 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
719 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
720 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
721 (176, node_id: PublicKey),
724 type BlindedPathIter<'a> = core::iter::Map<
725 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
726 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
729 type BlindedPayInfoIter<'a> = core::iter::Map<
730 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
731 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
734 /// Information needed to route a payment across a [`BlindedPath`].
735 #[derive(Clone, Debug, PartialEq)]
736 pub struct BlindedPayInfo {
737 /// Base fee charged (in millisatoshi) for the entire blinded path.
738 pub fee_base_msat: u32,
740 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
741 /// (i.e., 10,000 is 1%).
742 pub fee_proportional_millionths: u32,
744 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
746 pub cltv_expiry_delta: u16,
748 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
749 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
750 /// seen by the recipient.
751 pub htlc_minimum_msat: u64,
753 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
754 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
755 /// seen by the recipient.
756 pub htlc_maximum_msat: u64,
758 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
760 pub features: BlindedHopFeatures,
763 impl_writeable!(BlindedPayInfo, {
765 fee_proportional_millionths,
772 /// Wire representation for an on-chain fallback address.
773 #[derive(Clone, Debug, PartialEq)]
774 pub(super) struct FallbackAddress {
779 impl_writeable!(FallbackAddress, { version, program });
781 type FullInvoiceTlvStream =
782 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
785 type FullInvoiceTlvStreamRef<'a> = (
786 PayerTlvStreamRef<'a>,
787 OfferTlvStreamRef<'a>,
788 InvoiceRequestTlvStreamRef<'a>,
789 InvoiceTlvStreamRef<'a>,
790 SignatureTlvStreamRef<'a>,
793 impl SeekReadable for FullInvoiceTlvStream {
794 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
795 let payer = SeekReadable::read(r)?;
796 let offer = SeekReadable::read(r)?;
797 let invoice_request = SeekReadable::read(r)?;
798 let invoice = SeekReadable::read(r)?;
799 let signature = SeekReadable::read(r)?;
801 Ok((payer, offer, invoice_request, invoice, signature))
805 type PartialInvoiceTlvStream =
806 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
808 type PartialInvoiceTlvStreamRef<'a> = (
809 PayerTlvStreamRef<'a>,
810 OfferTlvStreamRef<'a>,
811 InvoiceRequestTlvStreamRef<'a>,
812 InvoiceTlvStreamRef<'a>,
815 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
816 type Error = ParseError;
818 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
819 let ParsedMessage { bytes, tlv_stream } = invoice;
821 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
822 SignatureTlvStream { signature },
824 let contents = InvoiceContents::try_from(
825 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
828 let signature = match signature {
829 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
830 Some(signature) => signature,
832 let pubkey = contents.fields().signing_pubkey;
833 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
835 Ok(Invoice { bytes, contents, signature })
839 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
840 type Error = SemanticError;
842 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
846 invoice_request_tlv_stream,
848 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
853 let payment_paths = match (paths, blindedpay) {
854 (None, _) => return Err(SemanticError::MissingPaths),
855 (_, None) => return Err(SemanticError::InvalidPayInfo),
856 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
857 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
858 return Err(SemanticError::InvalidPayInfo);
860 (Some(paths), Some(blindedpay)) => {
861 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
865 let created_at = match created_at {
866 None => return Err(SemanticError::MissingCreationTime),
867 Some(timestamp) => Duration::from_secs(timestamp),
870 let relative_expiry = relative_expiry
871 .map(Into::<u64>::into)
872 .map(Duration::from_secs);
874 let payment_hash = match payment_hash {
875 None => return Err(SemanticError::MissingPaymentHash),
876 Some(payment_hash) => payment_hash,
879 let amount_msats = match amount {
880 None => return Err(SemanticError::MissingAmount),
881 Some(amount) => amount,
884 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
886 let signing_pubkey = match node_id {
887 None => return Err(SemanticError::MissingSigningPubkey),
888 Some(node_id) => node_id,
891 let fields = InvoiceFields {
892 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
893 features, signing_pubkey,
896 match offer_tlv_stream.node_id {
897 Some(expected_signing_pubkey) => {
898 if fields.signing_pubkey != expected_signing_pubkey {
899 return Err(SemanticError::InvalidSigningPubkey);
902 let invoice_request = InvoiceRequestContents::try_from(
903 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
905 Ok(InvoiceContents::ForOffer { invoice_request, fields })
908 let refund = RefundContents::try_from(
909 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
911 Ok(InvoiceContents::ForRefund { refund, fields })
919 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
921 use bitcoin::blockdata::script::Script;
922 use bitcoin::hashes::Hash;
923 use bitcoin::network::constants::Network;
924 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
925 use bitcoin::util::address::{Address, Payload, WitnessVersion};
926 use bitcoin::util::schnorr::TweakedPublicKey;
927 use core::convert::TryFrom;
928 use core::time::Duration;
929 use crate::chain::keysinterface::KeyMaterial;
930 use crate::ln::features::Bolt12InvoiceFeatures;
931 use crate::ln::inbound_payment::ExpandedKey;
932 use crate::ln::msgs::DecodeError;
933 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
934 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
935 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
936 use crate::offers::parse::{ParseError, SemanticError};
937 use crate::offers::payer::PayerTlvStreamRef;
938 use crate::offers::refund::RefundBuilder;
939 use crate::offers::test_utils::*;
940 use crate::onion_message::{BlindedHop, BlindedPath};
941 use crate::util::ser::{BigSize, Iterable, Writeable};
944 fn to_bytes(&self) -> Vec<u8>;
947 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
948 fn to_bytes(&self) -> Vec<u8> {
949 let mut buffer = Vec::new();
950 self.0.write(&mut buffer).unwrap();
951 self.1.write(&mut buffer).unwrap();
952 self.2.write(&mut buffer).unwrap();
953 self.3.write(&mut buffer).unwrap();
954 self.4.write(&mut buffer).unwrap();
960 fn builds_invoice_for_offer_with_defaults() {
961 let payment_paths = payment_paths();
962 let payment_hash = payment_hash();
964 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
967 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
969 .sign(payer_sign).unwrap()
970 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
972 .sign(recipient_sign).unwrap();
974 let mut buffer = Vec::new();
975 invoice.write(&mut buffer).unwrap();
977 assert_eq!(invoice.bytes, buffer.as_slice());
978 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
979 assert_eq!(invoice.created_at(), now);
980 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
981 #[cfg(feature = "std")]
982 assert!(!invoice.is_expired());
983 assert_eq!(invoice.payment_hash(), payment_hash);
984 assert_eq!(invoice.amount_msats(), 1000);
985 assert_eq!(invoice.fallbacks(), vec![]);
986 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
987 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
989 merkle::verify_signature(
990 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
994 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
995 let pubkey = recipient_pubkey().into();
996 let secp_ctx = Secp256k1::verification_only();
997 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1000 invoice.as_tlv_stream(),
1002 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1008 description: Some(&String::from("foo")),
1010 absolute_expiry: None,
1014 node_id: Some(&recipient_pubkey()),
1016 InvoiceRequestTlvStreamRef {
1021 payer_id: Some(&payer_pubkey()),
1024 InvoiceTlvStreamRef {
1025 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1026 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1027 created_at: Some(now.as_secs()),
1028 relative_expiry: None,
1029 payment_hash: Some(&payment_hash),
1033 node_id: Some(&recipient_pubkey()),
1035 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1039 if let Err(e) = Invoice::try_from(buffer) {
1040 panic!("error parsing invoice: {:?}", e);
1045 fn builds_invoice_for_refund_with_defaults() {
1046 let payment_paths = payment_paths();
1047 let payment_hash = payment_hash();
1049 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1051 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1054 .sign(recipient_sign).unwrap();
1056 let mut buffer = Vec::new();
1057 invoice.write(&mut buffer).unwrap();
1059 assert_eq!(invoice.bytes, buffer.as_slice());
1060 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1061 assert_eq!(invoice.created_at(), now);
1062 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1063 #[cfg(feature = "std")]
1064 assert!(!invoice.is_expired());
1065 assert_eq!(invoice.payment_hash(), payment_hash);
1066 assert_eq!(invoice.amount_msats(), 1000);
1067 assert_eq!(invoice.fallbacks(), vec![]);
1068 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1069 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1071 merkle::verify_signature(
1072 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1077 invoice.as_tlv_stream(),
1079 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1085 description: Some(&String::from("foo")),
1087 absolute_expiry: None,
1093 InvoiceRequestTlvStreamRef {
1098 payer_id: Some(&payer_pubkey()),
1101 InvoiceTlvStreamRef {
1102 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1103 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1104 created_at: Some(now.as_secs()),
1105 relative_expiry: None,
1106 payment_hash: Some(&payment_hash),
1110 node_id: Some(&recipient_pubkey()),
1112 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1116 if let Err(e) = Invoice::try_from(buffer) {
1117 panic!("error parsing invoice: {:?}", e);
1121 #[cfg(feature = "std")]
1123 fn builds_invoice_from_offer_with_expiration() {
1124 let future_expiry = Duration::from_secs(u64::max_value());
1125 let past_expiry = Duration::from_secs(0);
1127 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1129 .absolute_expiry(future_expiry)
1131 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1133 .sign(payer_sign).unwrap()
1134 .respond_with(payment_paths(), payment_hash())
1138 panic!("error building invoice: {:?}", e);
1141 match OfferBuilder::new("foo".into(), recipient_pubkey())
1143 .absolute_expiry(past_expiry)
1145 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1147 .sign(payer_sign).unwrap()
1148 .respond_with(payment_paths(), payment_hash())
1152 Ok(_) => panic!("expected error"),
1153 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1157 #[cfg(feature = "std")]
1159 fn builds_invoice_from_refund_with_expiration() {
1160 let future_expiry = Duration::from_secs(u64::max_value());
1161 let past_expiry = Duration::from_secs(0);
1163 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1164 .absolute_expiry(future_expiry)
1166 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1170 panic!("error building invoice: {:?}", e);
1173 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1174 .absolute_expiry(past_expiry)
1176 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1180 Ok(_) => panic!("expected error"),
1181 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1186 fn builds_invoice_from_offer_using_derived_keys() {
1187 let desc = "foo".to_string();
1188 let node_id = recipient_pubkey();
1189 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1190 let entropy = FixedEntropy {};
1191 let secp_ctx = Secp256k1::new();
1193 let blinded_path = BlindedPath {
1194 introduction_node_id: pubkey(40),
1195 blinding_point: pubkey(41),
1197 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1198 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1202 let offer = OfferBuilder
1203 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1207 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1209 .sign(payer_sign).unwrap();
1211 if let Err(e) = invoice_request
1212 .verify_and_respond_using_derived_keys_no_std(
1213 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1216 .build_and_sign(&secp_ctx)
1218 panic!("error building invoice: {:?}", e);
1221 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1222 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1223 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1225 Ok(_) => panic!("expected error"),
1226 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1229 let desc = "foo".to_string();
1230 let offer = OfferBuilder
1231 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1234 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236 .sign(payer_sign).unwrap();
1238 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1239 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1241 Ok(_) => panic!("expected error"),
1242 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1247 fn builds_invoice_from_refund_using_derived_keys() {
1248 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1249 let entropy = FixedEntropy {};
1250 let secp_ctx = Secp256k1::new();
1252 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1255 if let Err(e) = refund
1256 .respond_using_derived_keys_no_std(
1257 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1260 .build_and_sign(&secp_ctx)
1262 panic!("error building invoice: {:?}", e);
1267 fn builds_invoice_with_relative_expiry() {
1269 let one_hour = Duration::from_secs(3600);
1271 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1274 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1276 .sign(payer_sign).unwrap()
1277 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1278 .relative_expiry(one_hour.as_secs() as u32)
1280 .sign(recipient_sign).unwrap();
1281 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1282 #[cfg(feature = "std")]
1283 assert!(!invoice.is_expired());
1284 assert_eq!(invoice.relative_expiry(), one_hour);
1285 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1287 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1290 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1292 .sign(payer_sign).unwrap()
1293 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1294 .relative_expiry(one_hour.as_secs() as u32 - 1)
1296 .sign(recipient_sign).unwrap();
1297 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1298 #[cfg(feature = "std")]
1299 assert!(invoice.is_expired());
1300 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1301 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1305 fn builds_invoice_with_amount_from_request() {
1306 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1309 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1310 .amount_msats(1001).unwrap()
1312 .sign(payer_sign).unwrap()
1313 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1315 .sign(recipient_sign).unwrap();
1316 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1317 assert_eq!(invoice.amount_msats(), 1001);
1318 assert_eq!(tlv_stream.amount, Some(1001));
1322 fn builds_invoice_with_quantity_from_request() {
1323 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1325 .supported_quantity(Quantity::Unbounded)
1327 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1328 .quantity(2).unwrap()
1330 .sign(payer_sign).unwrap()
1331 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1333 .sign(recipient_sign).unwrap();
1334 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1335 assert_eq!(invoice.amount_msats(), 2000);
1336 assert_eq!(tlv_stream.amount, Some(2000));
1338 match OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .supported_quantity(Quantity::Unbounded)
1342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1343 .quantity(u64::max_value()).unwrap()
1345 .sign(payer_sign).unwrap()
1346 .respond_with_no_std(payment_paths(), payment_hash(), now())
1348 Ok(_) => panic!("expected error"),
1349 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1354 fn builds_invoice_with_fallback_address() {
1355 let script = Script::new();
1356 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1357 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1358 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1360 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1363 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1365 .sign(payer_sign).unwrap()
1366 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1367 .fallback_v0_p2wsh(&script.wscript_hash())
1368 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1369 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1371 .sign(recipient_sign).unwrap();
1372 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1374 invoice.fallbacks(),
1376 Address::p2wsh(&script, Network::Bitcoin),
1377 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1378 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1382 tlv_stream.fallbacks,
1385 version: WitnessVersion::V0.to_num(),
1386 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1389 version: WitnessVersion::V0.to_num(),
1390 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1393 version: WitnessVersion::V1.to_num(),
1394 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1401 fn builds_invoice_with_allow_mpp() {
1402 let mut features = Bolt12InvoiceFeatures::empty();
1403 features.set_basic_mpp_optional();
1405 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1408 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1410 .sign(payer_sign).unwrap()
1411 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1414 .sign(recipient_sign).unwrap();
1415 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1416 assert_eq!(invoice.features(), &features);
1417 assert_eq!(tlv_stream.features, Some(&features));
1421 fn fails_signing_invoice() {
1422 match OfferBuilder::new("foo".into(), recipient_pubkey())
1425 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1427 .sign(payer_sign).unwrap()
1428 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1432 Ok(_) => panic!("expected error"),
1433 Err(e) => assert_eq!(e, SignError::Signing(())),
1436 match OfferBuilder::new("foo".into(), recipient_pubkey())
1439 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1441 .sign(payer_sign).unwrap()
1442 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1446 Ok(_) => panic!("expected error"),
1447 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1452 fn parses_invoice_with_payment_paths() {
1453 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1456 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1458 .sign(payer_sign).unwrap()
1459 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1461 .sign(recipient_sign).unwrap();
1463 let mut buffer = Vec::new();
1464 invoice.write(&mut buffer).unwrap();
1466 if let Err(e) = Invoice::try_from(buffer) {
1467 panic!("error parsing invoice: {:?}", e);
1470 let mut tlv_stream = invoice.as_tlv_stream();
1471 tlv_stream.3.paths = None;
1473 match Invoice::try_from(tlv_stream.to_bytes()) {
1474 Ok(_) => panic!("expected error"),
1475 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1478 let mut tlv_stream = invoice.as_tlv_stream();
1479 tlv_stream.3.blindedpay = None;
1481 match Invoice::try_from(tlv_stream.to_bytes()) {
1482 Ok(_) => panic!("expected error"),
1483 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1486 let empty_payment_paths = vec![];
1487 let mut tlv_stream = invoice.as_tlv_stream();
1488 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1490 match Invoice::try_from(tlv_stream.to_bytes()) {
1491 Ok(_) => panic!("expected error"),
1492 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1495 let mut payment_paths = payment_paths();
1496 payment_paths.pop();
1497 let mut tlv_stream = invoice.as_tlv_stream();
1498 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1500 match Invoice::try_from(tlv_stream.to_bytes()) {
1501 Ok(_) => panic!("expected error"),
1502 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1507 fn parses_invoice_with_created_at() {
1508 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1511 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1513 .sign(payer_sign).unwrap()
1514 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1516 .sign(recipient_sign).unwrap();
1518 let mut buffer = Vec::new();
1519 invoice.write(&mut buffer).unwrap();
1521 if let Err(e) = Invoice::try_from(buffer) {
1522 panic!("error parsing invoice: {:?}", e);
1525 let mut tlv_stream = invoice.as_tlv_stream();
1526 tlv_stream.3.created_at = None;
1528 match Invoice::try_from(tlv_stream.to_bytes()) {
1529 Ok(_) => panic!("expected error"),
1531 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1537 fn parses_invoice_with_relative_expiry() {
1538 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1541 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1543 .sign(payer_sign).unwrap()
1544 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1545 .relative_expiry(3600)
1547 .sign(recipient_sign).unwrap();
1549 let mut buffer = Vec::new();
1550 invoice.write(&mut buffer).unwrap();
1552 match Invoice::try_from(buffer) {
1553 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1554 Err(e) => panic!("error parsing invoice: {:?}", e),
1559 fn parses_invoice_with_payment_hash() {
1560 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1563 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1565 .sign(payer_sign).unwrap()
1566 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1568 .sign(recipient_sign).unwrap();
1570 let mut buffer = Vec::new();
1571 invoice.write(&mut buffer).unwrap();
1573 if let Err(e) = Invoice::try_from(buffer) {
1574 panic!("error parsing invoice: {:?}", e);
1577 let mut tlv_stream = invoice.as_tlv_stream();
1578 tlv_stream.3.payment_hash = None;
1580 match Invoice::try_from(tlv_stream.to_bytes()) {
1581 Ok(_) => panic!("expected error"),
1583 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1589 fn parses_invoice_with_amount() {
1590 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1593 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1595 .sign(payer_sign).unwrap()
1596 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1598 .sign(recipient_sign).unwrap();
1600 let mut buffer = Vec::new();
1601 invoice.write(&mut buffer).unwrap();
1603 if let Err(e) = Invoice::try_from(buffer) {
1604 panic!("error parsing invoice: {:?}", e);
1607 let mut tlv_stream = invoice.as_tlv_stream();
1608 tlv_stream.3.amount = None;
1610 match Invoice::try_from(tlv_stream.to_bytes()) {
1611 Ok(_) => panic!("expected error"),
1612 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1617 fn parses_invoice_with_allow_mpp() {
1618 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1621 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623 .sign(payer_sign).unwrap()
1624 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1627 .sign(recipient_sign).unwrap();
1629 let mut buffer = Vec::new();
1630 invoice.write(&mut buffer).unwrap();
1632 match Invoice::try_from(buffer) {
1634 let mut features = Bolt12InvoiceFeatures::empty();
1635 features.set_basic_mpp_optional();
1636 assert_eq!(invoice.features(), &features);
1638 Err(e) => panic!("error parsing invoice: {:?}", e),
1643 fn parses_invoice_with_fallback_address() {
1644 let script = Script::new();
1645 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1646 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1647 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1649 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1652 let invoice_request = offer
1653 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1655 .sign(payer_sign).unwrap();
1656 let mut unsigned_invoice = invoice_request
1657 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1658 .fallback_v0_p2wsh(&script.wscript_hash())
1659 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1660 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1663 // Only standard addresses will be included.
1664 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1665 // Non-standard addresses
1666 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1667 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1668 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1670 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1671 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1673 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1674 let mut buffer = Vec::new();
1675 invoice.write(&mut buffer).unwrap();
1677 match Invoice::try_from(buffer) {
1680 invoice.fallbacks(),
1682 Address::p2wsh(&script, Network::Bitcoin),
1683 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1684 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1686 payload: Payload::WitnessProgram {
1687 version: WitnessVersion::V1,
1688 program: vec![0u8; 33],
1690 network: Network::Bitcoin,
1693 payload: Payload::WitnessProgram {
1694 version: WitnessVersion::V2,
1695 program: vec![0u8; 40],
1697 network: Network::Bitcoin,
1702 Err(e) => panic!("error parsing invoice: {:?}", e),
1707 fn parses_invoice_with_node_id() {
1708 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1711 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1713 .sign(payer_sign).unwrap()
1714 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1716 .sign(recipient_sign).unwrap();
1718 let mut buffer = Vec::new();
1719 invoice.write(&mut buffer).unwrap();
1721 if let Err(e) = Invoice::try_from(buffer) {
1722 panic!("error parsing invoice: {:?}", e);
1725 let mut tlv_stream = invoice.as_tlv_stream();
1726 tlv_stream.3.node_id = None;
1728 match Invoice::try_from(tlv_stream.to_bytes()) {
1729 Ok(_) => panic!("expected error"),
1731 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1735 let invalid_pubkey = payer_pubkey();
1736 let mut tlv_stream = invoice.as_tlv_stream();
1737 tlv_stream.3.node_id = Some(&invalid_pubkey);
1739 match Invoice::try_from(tlv_stream.to_bytes()) {
1740 Ok(_) => panic!("expected error"),
1742 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1748 fn fails_parsing_invoice_without_signature() {
1749 let mut buffer = Vec::new();
1750 OfferBuilder::new("foo".into(), recipient_pubkey())
1753 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1755 .sign(payer_sign).unwrap()
1756 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1759 .write(&mut buffer).unwrap();
1761 match Invoice::try_from(buffer) {
1762 Ok(_) => panic!("expected error"),
1763 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1768 fn fails_parsing_invoice_with_invalid_signature() {
1769 let mut invoice = 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()
1777 .sign(recipient_sign).unwrap();
1778 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1779 *last_signature_byte = last_signature_byte.wrapping_add(1);
1781 let mut buffer = Vec::new();
1782 invoice.write(&mut buffer).unwrap();
1784 match Invoice::try_from(buffer) {
1785 Ok(_) => panic!("expected error"),
1787 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1793 fn fails_parsing_invoice_with_extra_tlv_records() {
1794 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1797 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1799 .sign(payer_sign).unwrap()
1800 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1802 .sign(recipient_sign).unwrap();
1804 let mut encoded_invoice = Vec::new();
1805 invoice.write(&mut encoded_invoice).unwrap();
1806 BigSize(1002).write(&mut encoded_invoice).unwrap();
1807 BigSize(32).write(&mut encoded_invoice).unwrap();
1808 [42u8; 32].write(&mut encoded_invoice).unwrap();
1810 match Invoice::try_from(encoded_invoice) {
1811 Ok(_) => panic!("expected error"),
1812 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),