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))
212 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
213 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, SemanticError> {
214 match invoice_request.amount_msats() {
215 Some(amount_msats) => Ok(amount_msats),
216 None => match invoice_request.contents.inner.offer.amount() {
217 Some(Amount::Bitcoin { amount_msats }) => {
218 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
219 .ok_or(SemanticError::InvalidAmount)
221 Some(Amount::Currency { .. }) => Err(SemanticError::UnsupportedCurrency),
222 None => Err(SemanticError::MissingAmount),
228 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
229 ) -> Result<Self, SemanticError> {
230 if contents.fields().payment_paths.is_empty() {
231 return Err(SemanticError::MissingPaths);
238 signing_pubkey_strategy: core::marker::PhantomData,
242 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
243 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
245 /// Successive calls to this method will override the previous setting.
246 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
247 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
248 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
252 /// Adds a P2WSH address to [`Invoice::fallbacks`].
254 /// Successive calls to this method will add another address. Caller is responsible for not
255 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
256 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
257 let address = FallbackAddress {
258 version: WitnessVersion::V0.to_num(),
259 program: Vec::from(&script_hash.into_inner()[..]),
261 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
265 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
267 /// Successive calls to this method will add another address. Caller is responsible for not
268 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
269 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
270 let address = FallbackAddress {
271 version: WitnessVersion::V0.to_num(),
272 program: Vec::from(&pubkey_hash.into_inner()[..]),
274 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
278 /// Adds a P2TR address to [`Invoice::fallbacks`].
280 /// Successive calls to this method will add another address. Caller is responsible for not
281 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
282 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
283 let address = FallbackAddress {
284 version: WitnessVersion::V1.to_num(),
285 program: Vec::from(&output_key.serialize()[..]),
287 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
291 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
292 pub fn allow_mpp(mut self) -> Self {
293 self.invoice.fields_mut().features.set_basic_mpp_optional();
298 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
299 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
300 /// [`UnsignedInvoice::sign`].
301 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
302 #[cfg(feature = "std")] {
303 if self.invoice.is_offer_or_refund_expired() {
304 return Err(SemanticError::AlreadyExpired);
308 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
309 Ok(UnsignedInvoice { invreq_bytes, invoice })
313 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
314 /// Builds a signed [`Invoice`] after checking for valid semantics.
315 pub fn build_and_sign<T: secp256k1::Signing>(
316 self, secp_ctx: &Secp256k1<T>
317 ) -> Result<Invoice, 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, keys, .. } = self;
325 let keys = match &invoice {
326 InvoiceContents::ForOffer { .. } => keys.unwrap(),
327 InvoiceContents::ForRefund { .. } => unreachable!(),
330 let unsigned_invoice = UnsignedInvoice { invreq_bytes, invoice };
331 let invoice = unsigned_invoice
332 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
338 /// A semantically valid [`Invoice`] that hasn't been signed.
339 pub struct UnsignedInvoice<'a> {
340 invreq_bytes: &'a Vec<u8>,
341 invoice: InvoiceContents,
344 impl<'a> UnsignedInvoice<'a> {
345 /// The public key corresponding to the key needed to sign the invoice.
346 pub fn signing_pubkey(&self) -> PublicKey {
347 self.invoice.fields().signing_pubkey
350 /// Signs the invoice using the given function.
351 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
353 F: FnOnce(&Message) -> Result<Signature, E>
355 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
356 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
358 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
359 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
360 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
362 let mut bytes = Vec::new();
363 unsigned_tlv_stream.write(&mut bytes).unwrap();
365 let pubkey = self.invoice.fields().signing_pubkey;
366 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
368 // Append the signature TLV record to the bytes.
369 let signature_tlv_stream = SignatureTlvStreamRef {
370 signature: Some(&signature),
372 signature_tlv_stream.write(&mut bytes).unwrap();
376 contents: self.invoice,
382 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
384 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
385 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
387 /// [`Offer`]: crate::offers::offer::Offer
388 /// [`Refund`]: crate::offers::refund::Refund
389 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
390 #[derive(Clone, Debug)]
391 #[cfg_attr(test, derive(PartialEq))]
394 contents: InvoiceContents,
395 signature: Signature,
398 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
400 /// [`Offer`]: crate::offers::offer::Offer
401 /// [`Refund`]: crate::offers::refund::Refund
402 #[derive(Clone, Debug)]
403 #[cfg_attr(test, derive(PartialEq))]
404 enum InvoiceContents {
405 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
407 /// [`Offer`]: crate::offers::offer::Offer
409 invoice_request: InvoiceRequestContents,
410 fields: InvoiceFields,
412 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
414 /// [`Refund`]: crate::offers::refund::Refund
416 refund: RefundContents,
417 fields: InvoiceFields,
421 /// Invoice-specific fields for an `invoice` message.
422 #[derive(Clone, Debug, PartialEq)]
423 struct InvoiceFields {
424 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
425 created_at: Duration,
426 relative_expiry: Option<Duration>,
427 payment_hash: PaymentHash,
429 fallbacks: Option<Vec<FallbackAddress>>,
430 features: Bolt12InvoiceFeatures,
431 signing_pubkey: PublicKey,
435 /// Paths to the recipient originating from publicly reachable nodes, including information
436 /// needed for routing payments across them.
438 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
439 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
440 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
441 &self.contents.fields().payment_paths[..]
444 /// Duration since the Unix epoch when the invoice was created.
445 pub fn created_at(&self) -> Duration {
446 self.contents.fields().created_at
449 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
451 pub fn relative_expiry(&self) -> Duration {
452 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
455 /// Whether the invoice has expired.
456 #[cfg(feature = "std")]
457 pub fn is_expired(&self) -> bool {
458 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
459 match absolute_expiry {
460 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
461 Ok(elapsed) => elapsed > seconds_from_epoch,
468 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
469 pub fn payment_hash(&self) -> PaymentHash {
470 self.contents.fields().payment_hash
473 /// The minimum amount required for a successful payment of the invoice.
474 pub fn amount_msats(&self) -> u64 {
475 self.contents.fields().amount_msats
478 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
480 pub fn fallbacks(&self) -> Vec<Address> {
481 let network = match self.network() {
482 None => return Vec::new(),
483 Some(network) => network,
486 let to_valid_address = |address: &FallbackAddress| {
487 let version = match WitnessVersion::try_from(address.version) {
488 Ok(version) => version,
489 Err(_) => return None,
492 let program = &address.program;
493 if program.len() < 2 || program.len() > 40 {
497 let address = Address {
498 payload: Payload::WitnessProgram {
500 program: address.program.clone(),
505 if !address.is_standard() && version == WitnessVersion::V0 {
512 self.contents.fields().fallbacks
514 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
515 .unwrap_or_else(Vec::new)
518 fn network(&self) -> Option<Network> {
519 let chain = self.contents.chain();
520 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
521 Some(Network::Bitcoin)
522 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
523 Some(Network::Testnet)
524 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
525 Some(Network::Signet)
526 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
527 Some(Network::Regtest)
533 /// Features pertaining to paying an invoice.
534 pub fn features(&self) -> &Bolt12InvoiceFeatures {
535 &self.contents.fields().features
538 /// The public key corresponding to the key used to sign the invoice.
539 pub fn signing_pubkey(&self) -> PublicKey {
540 self.contents.fields().signing_pubkey
543 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
544 pub fn signature(&self) -> Signature {
548 /// Hash that was used for signing the invoice.
549 pub fn signable_hash(&self) -> [u8; 32] {
550 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
553 /// Verifies that the invoice was for a request or refund created using the given key.
554 pub fn verify<T: secp256k1::Signing>(
555 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
557 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
561 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
562 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
563 self.contents.as_tlv_stream();
564 let signature_tlv_stream = SignatureTlvStreamRef {
565 signature: Some(&self.signature),
567 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
568 signature_tlv_stream)
572 impl InvoiceContents {
573 /// Whether the original offer or refund has expired.
574 #[cfg(feature = "std")]
575 fn is_offer_or_refund_expired(&self) -> bool {
577 InvoiceContents::ForOffer { invoice_request, .. } =>
578 invoice_request.inner.offer.is_expired(),
579 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
583 fn chain(&self) -> ChainHash {
585 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
586 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
590 fn fields(&self) -> &InvoiceFields {
592 InvoiceContents::ForOffer { fields, .. } => fields,
593 InvoiceContents::ForRefund { fields, .. } => fields,
597 fn fields_mut(&mut self) -> &mut InvoiceFields {
599 InvoiceContents::ForOffer { fields, .. } => fields,
600 InvoiceContents::ForRefund { fields, .. } => fields,
604 fn verify<T: secp256k1::Signing>(
605 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
607 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
608 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
609 match record.r#type {
610 PAYER_METADATA_TYPE => false, // Should be outside range
611 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
615 let tlv_stream = offer_records.chain(invreq_records);
617 let (metadata, payer_id, iv_bytes) = match self {
618 InvoiceContents::ForOffer { invoice_request, .. } => {
619 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
621 InvoiceContents::ForRefund { refund, .. } => {
622 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
626 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
632 fn derives_keys(&self) -> bool {
634 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
635 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
639 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
640 let (payer, offer, invoice_request) = match self {
641 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
642 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
644 let invoice = self.fields().as_tlv_stream();
646 (payer, offer, invoice_request, invoice)
651 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
653 if self.features == Bolt12InvoiceFeatures::empty() { None }
654 else { Some(&self.features) }
657 InvoiceTlvStreamRef {
658 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
659 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
660 created_at: Some(self.created_at.as_secs()),
661 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
662 payment_hash: Some(&self.payment_hash),
663 amount: Some(self.amount_msats),
664 fallbacks: self.fallbacks.as_ref(),
666 node_id: Some(&self.signing_pubkey),
671 impl Writeable for Invoice {
672 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
673 WithoutLength(&self.bytes).write(writer)
677 impl Writeable for InvoiceContents {
678 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
679 self.as_tlv_stream().write(writer)
683 impl TryFrom<Vec<u8>> for Invoice {
684 type Error = ParseError;
686 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
687 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
688 Invoice::try_from(parsed_invoice)
692 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
693 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
694 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
695 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
696 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
697 (168, payment_hash: PaymentHash),
698 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
699 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
700 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
701 (176, node_id: PublicKey),
704 type BlindedPathIter<'a> = core::iter::Map<
705 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
706 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
709 type BlindedPayInfoIter<'a> = core::iter::Map<
710 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
711 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
714 /// Information needed to route a payment across a [`BlindedPath`].
715 #[derive(Clone, Debug, PartialEq)]
716 pub struct BlindedPayInfo {
717 /// Base fee charged (in millisatoshi) for the entire blinded path.
718 pub fee_base_msat: u32,
720 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
721 /// (i.e., 10,000 is 1%).
722 pub fee_proportional_millionths: u32,
724 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
726 pub cltv_expiry_delta: u16,
728 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
729 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
730 /// seen by the recipient.
731 pub htlc_minimum_msat: u64,
733 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
734 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
735 /// seen by the recipient.
736 pub htlc_maximum_msat: u64,
738 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
740 pub features: BlindedHopFeatures,
743 impl_writeable!(BlindedPayInfo, {
745 fee_proportional_millionths,
752 /// Wire representation for an on-chain fallback address.
753 #[derive(Clone, Debug, PartialEq)]
754 pub(super) struct FallbackAddress {
759 impl_writeable!(FallbackAddress, { version, program });
761 type FullInvoiceTlvStream =
762 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
765 type FullInvoiceTlvStreamRef<'a> = (
766 PayerTlvStreamRef<'a>,
767 OfferTlvStreamRef<'a>,
768 InvoiceRequestTlvStreamRef<'a>,
769 InvoiceTlvStreamRef<'a>,
770 SignatureTlvStreamRef<'a>,
773 impl SeekReadable for FullInvoiceTlvStream {
774 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
775 let payer = SeekReadable::read(r)?;
776 let offer = SeekReadable::read(r)?;
777 let invoice_request = SeekReadable::read(r)?;
778 let invoice = SeekReadable::read(r)?;
779 let signature = SeekReadable::read(r)?;
781 Ok((payer, offer, invoice_request, invoice, signature))
785 type PartialInvoiceTlvStream =
786 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
788 type PartialInvoiceTlvStreamRef<'a> = (
789 PayerTlvStreamRef<'a>,
790 OfferTlvStreamRef<'a>,
791 InvoiceRequestTlvStreamRef<'a>,
792 InvoiceTlvStreamRef<'a>,
795 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
796 type Error = ParseError;
798 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
799 let ParsedMessage { bytes, tlv_stream } = invoice;
801 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
802 SignatureTlvStream { signature },
804 let contents = InvoiceContents::try_from(
805 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
808 let signature = match signature {
809 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
810 Some(signature) => signature,
812 let pubkey = contents.fields().signing_pubkey;
813 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
815 Ok(Invoice { bytes, contents, signature })
819 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
820 type Error = SemanticError;
822 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
826 invoice_request_tlv_stream,
828 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
833 let payment_paths = match (paths, blindedpay) {
834 (None, _) => return Err(SemanticError::MissingPaths),
835 (_, None) => return Err(SemanticError::InvalidPayInfo),
836 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
837 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
838 return Err(SemanticError::InvalidPayInfo);
840 (Some(paths), Some(blindedpay)) => {
841 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
845 let created_at = match created_at {
846 None => return Err(SemanticError::MissingCreationTime),
847 Some(timestamp) => Duration::from_secs(timestamp),
850 let relative_expiry = relative_expiry
851 .map(Into::<u64>::into)
852 .map(Duration::from_secs);
854 let payment_hash = match payment_hash {
855 None => return Err(SemanticError::MissingPaymentHash),
856 Some(payment_hash) => payment_hash,
859 let amount_msats = match amount {
860 None => return Err(SemanticError::MissingAmount),
861 Some(amount) => amount,
864 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
866 let signing_pubkey = match node_id {
867 None => return Err(SemanticError::MissingSigningPubkey),
868 Some(node_id) => node_id,
871 let fields = InvoiceFields {
872 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
873 features, signing_pubkey,
876 match offer_tlv_stream.node_id {
877 Some(expected_signing_pubkey) => {
878 if fields.signing_pubkey != expected_signing_pubkey {
879 return Err(SemanticError::InvalidSigningPubkey);
882 let invoice_request = InvoiceRequestContents::try_from(
883 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
885 Ok(InvoiceContents::ForOffer { invoice_request, fields })
888 let refund = RefundContents::try_from(
889 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
891 Ok(InvoiceContents::ForRefund { refund, fields })
899 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
901 use bitcoin::blockdata::script::Script;
902 use bitcoin::hashes::Hash;
903 use bitcoin::network::constants::Network;
904 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
905 use bitcoin::util::address::{Address, Payload, WitnessVersion};
906 use bitcoin::util::schnorr::TweakedPublicKey;
907 use core::convert::TryFrom;
908 use core::time::Duration;
909 use crate::chain::keysinterface::KeyMaterial;
910 use crate::ln::features::Bolt12InvoiceFeatures;
911 use crate::ln::inbound_payment::ExpandedKey;
912 use crate::ln::msgs::DecodeError;
913 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
914 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
915 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
916 use crate::offers::parse::{ParseError, SemanticError};
917 use crate::offers::payer::PayerTlvStreamRef;
918 use crate::offers::refund::RefundBuilder;
919 use crate::offers::test_utils::*;
920 use crate::onion_message::{BlindedHop, BlindedPath};
921 use crate::util::ser::{BigSize, Iterable, Writeable};
924 fn to_bytes(&self) -> Vec<u8>;
927 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
928 fn to_bytes(&self) -> Vec<u8> {
929 let mut buffer = Vec::new();
930 self.0.write(&mut buffer).unwrap();
931 self.1.write(&mut buffer).unwrap();
932 self.2.write(&mut buffer).unwrap();
933 self.3.write(&mut buffer).unwrap();
934 self.4.write(&mut buffer).unwrap();
940 fn builds_invoice_for_offer_with_defaults() {
941 let payment_paths = payment_paths();
942 let payment_hash = payment_hash();
944 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
947 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
949 .sign(payer_sign).unwrap()
950 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
952 .sign(recipient_sign).unwrap();
954 let mut buffer = Vec::new();
955 invoice.write(&mut buffer).unwrap();
957 assert_eq!(invoice.bytes, buffer.as_slice());
958 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
959 assert_eq!(invoice.created_at(), now);
960 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
961 #[cfg(feature = "std")]
962 assert!(!invoice.is_expired());
963 assert_eq!(invoice.payment_hash(), payment_hash);
964 assert_eq!(invoice.amount_msats(), 1000);
965 assert_eq!(invoice.fallbacks(), vec![]);
966 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
967 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
969 merkle::verify_signature(
970 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
974 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
975 let pubkey = recipient_pubkey().into();
976 let secp_ctx = Secp256k1::verification_only();
977 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
980 invoice.as_tlv_stream(),
982 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
988 description: Some(&String::from("foo")),
990 absolute_expiry: None,
994 node_id: Some(&recipient_pubkey()),
996 InvoiceRequestTlvStreamRef {
1001 payer_id: Some(&payer_pubkey()),
1004 InvoiceTlvStreamRef {
1005 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1006 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1007 created_at: Some(now.as_secs()),
1008 relative_expiry: None,
1009 payment_hash: Some(&payment_hash),
1013 node_id: Some(&recipient_pubkey()),
1015 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1019 if let Err(e) = Invoice::try_from(buffer) {
1020 panic!("error parsing invoice: {:?}", e);
1025 fn builds_invoice_for_refund_with_defaults() {
1026 let payment_paths = payment_paths();
1027 let payment_hash = payment_hash();
1029 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1031 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1034 .sign(recipient_sign).unwrap();
1036 let mut buffer = Vec::new();
1037 invoice.write(&mut buffer).unwrap();
1039 assert_eq!(invoice.bytes, buffer.as_slice());
1040 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1041 assert_eq!(invoice.created_at(), now);
1042 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1043 #[cfg(feature = "std")]
1044 assert!(!invoice.is_expired());
1045 assert_eq!(invoice.payment_hash(), payment_hash);
1046 assert_eq!(invoice.amount_msats(), 1000);
1047 assert_eq!(invoice.fallbacks(), vec![]);
1048 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1049 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1051 merkle::verify_signature(
1052 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1057 invoice.as_tlv_stream(),
1059 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1065 description: Some(&String::from("foo")),
1067 absolute_expiry: None,
1073 InvoiceRequestTlvStreamRef {
1078 payer_id: Some(&payer_pubkey()),
1081 InvoiceTlvStreamRef {
1082 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1083 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1084 created_at: Some(now.as_secs()),
1085 relative_expiry: None,
1086 payment_hash: Some(&payment_hash),
1090 node_id: Some(&recipient_pubkey()),
1092 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1096 if let Err(e) = Invoice::try_from(buffer) {
1097 panic!("error parsing invoice: {:?}", e);
1101 #[cfg(feature = "std")]
1103 fn builds_invoice_from_offer_with_expiration() {
1104 let future_expiry = Duration::from_secs(u64::max_value());
1105 let past_expiry = Duration::from_secs(0);
1107 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1109 .absolute_expiry(future_expiry)
1111 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1113 .sign(payer_sign).unwrap()
1114 .respond_with(payment_paths(), payment_hash())
1118 panic!("error building invoice: {:?}", e);
1121 match OfferBuilder::new("foo".into(), recipient_pubkey())
1123 .absolute_expiry(past_expiry)
1125 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1127 .sign(payer_sign).unwrap()
1128 .respond_with(payment_paths(), payment_hash())
1132 Ok(_) => panic!("expected error"),
1133 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1137 #[cfg(feature = "std")]
1139 fn builds_invoice_from_refund_with_expiration() {
1140 let future_expiry = Duration::from_secs(u64::max_value());
1141 let past_expiry = Duration::from_secs(0);
1143 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1144 .absolute_expiry(future_expiry)
1146 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1150 panic!("error building invoice: {:?}", e);
1153 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1154 .absolute_expiry(past_expiry)
1156 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1160 Ok(_) => panic!("expected error"),
1161 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1166 fn builds_invoice_from_offer_using_derived_keys() {
1167 let desc = "foo".to_string();
1168 let node_id = recipient_pubkey();
1169 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1170 let entropy = FixedEntropy {};
1171 let secp_ctx = Secp256k1::new();
1173 let blinded_path = BlindedPath {
1174 introduction_node_id: pubkey(40),
1175 blinding_point: pubkey(41),
1177 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1178 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1182 let offer = OfferBuilder
1183 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1187 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1189 .sign(payer_sign).unwrap();
1191 if let Err(e) = invoice_request
1192 .verify_and_respond_using_derived_keys_no_std(
1193 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1196 .build_and_sign(&secp_ctx)
1198 panic!("error building invoice: {:?}", e);
1201 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1202 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1203 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1205 Ok(_) => panic!("expected error"),
1206 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1209 let desc = "foo".to_string();
1210 let offer = OfferBuilder
1211 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1214 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1216 .sign(payer_sign).unwrap();
1218 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1219 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1221 Ok(_) => panic!("expected error"),
1222 Err(e) => assert_eq!(e, SemanticError::InvalidMetadata),
1227 fn builds_invoice_with_relative_expiry() {
1229 let one_hour = Duration::from_secs(3600);
1231 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1234 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236 .sign(payer_sign).unwrap()
1237 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1238 .relative_expiry(one_hour.as_secs() as u32)
1240 .sign(recipient_sign).unwrap();
1241 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1242 #[cfg(feature = "std")]
1243 assert!(!invoice.is_expired());
1244 assert_eq!(invoice.relative_expiry(), one_hour);
1245 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1247 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1250 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1252 .sign(payer_sign).unwrap()
1253 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1254 .relative_expiry(one_hour.as_secs() as u32 - 1)
1256 .sign(recipient_sign).unwrap();
1257 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1258 #[cfg(feature = "std")]
1259 assert!(invoice.is_expired());
1260 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1261 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1265 fn builds_invoice_with_amount_from_request() {
1266 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1269 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1270 .amount_msats(1001).unwrap()
1272 .sign(payer_sign).unwrap()
1273 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1275 .sign(recipient_sign).unwrap();
1276 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1277 assert_eq!(invoice.amount_msats(), 1001);
1278 assert_eq!(tlv_stream.amount, Some(1001));
1282 fn builds_invoice_with_quantity_from_request() {
1283 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1285 .supported_quantity(Quantity::Unbounded)
1287 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288 .quantity(2).unwrap()
1290 .sign(payer_sign).unwrap()
1291 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1293 .sign(recipient_sign).unwrap();
1294 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1295 assert_eq!(invoice.amount_msats(), 2000);
1296 assert_eq!(tlv_stream.amount, Some(2000));
1298 match OfferBuilder::new("foo".into(), recipient_pubkey())
1300 .supported_quantity(Quantity::Unbounded)
1302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1303 .quantity(u64::max_value()).unwrap()
1305 .sign(payer_sign).unwrap()
1306 .respond_with_no_std(payment_paths(), payment_hash(), now())
1308 Ok(_) => panic!("expected error"),
1309 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1314 fn builds_invoice_with_fallback_address() {
1315 let script = Script::new();
1316 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1317 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1318 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1320 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1323 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1325 .sign(payer_sign).unwrap()
1326 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1327 .fallback_v0_p2wsh(&script.wscript_hash())
1328 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1329 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1331 .sign(recipient_sign).unwrap();
1332 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1334 invoice.fallbacks(),
1336 Address::p2wsh(&script, Network::Bitcoin),
1337 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1338 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1342 tlv_stream.fallbacks,
1345 version: WitnessVersion::V0.to_num(),
1346 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1349 version: WitnessVersion::V0.to_num(),
1350 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1353 version: WitnessVersion::V1.to_num(),
1354 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1361 fn builds_invoice_with_allow_mpp() {
1362 let mut features = Bolt12InvoiceFeatures::empty();
1363 features.set_basic_mpp_optional();
1365 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1368 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1370 .sign(payer_sign).unwrap()
1371 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1374 .sign(recipient_sign).unwrap();
1375 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1376 assert_eq!(invoice.features(), &features);
1377 assert_eq!(tlv_stream.features, Some(&features));
1381 fn fails_signing_invoice() {
1382 match OfferBuilder::new("foo".into(), recipient_pubkey())
1385 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1387 .sign(payer_sign).unwrap()
1388 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1392 Ok(_) => panic!("expected error"),
1393 Err(e) => assert_eq!(e, SignError::Signing(())),
1396 match OfferBuilder::new("foo".into(), recipient_pubkey())
1399 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1401 .sign(payer_sign).unwrap()
1402 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1406 Ok(_) => panic!("expected error"),
1407 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1412 fn parses_invoice_with_payment_paths() {
1413 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1416 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1418 .sign(payer_sign).unwrap()
1419 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1421 .sign(recipient_sign).unwrap();
1423 let mut buffer = Vec::new();
1424 invoice.write(&mut buffer).unwrap();
1426 if let Err(e) = Invoice::try_from(buffer) {
1427 panic!("error parsing invoice: {:?}", e);
1430 let mut tlv_stream = invoice.as_tlv_stream();
1431 tlv_stream.3.paths = None;
1433 match Invoice::try_from(tlv_stream.to_bytes()) {
1434 Ok(_) => panic!("expected error"),
1435 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1438 let mut tlv_stream = invoice.as_tlv_stream();
1439 tlv_stream.3.blindedpay = None;
1441 match Invoice::try_from(tlv_stream.to_bytes()) {
1442 Ok(_) => panic!("expected error"),
1443 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1446 let empty_payment_paths = vec![];
1447 let mut tlv_stream = invoice.as_tlv_stream();
1448 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1450 match Invoice::try_from(tlv_stream.to_bytes()) {
1451 Ok(_) => panic!("expected error"),
1452 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1455 let mut payment_paths = payment_paths();
1456 payment_paths.pop();
1457 let mut tlv_stream = invoice.as_tlv_stream();
1458 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1460 match Invoice::try_from(tlv_stream.to_bytes()) {
1461 Ok(_) => panic!("expected error"),
1462 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1467 fn parses_invoice_with_created_at() {
1468 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1471 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1473 .sign(payer_sign).unwrap()
1474 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1476 .sign(recipient_sign).unwrap();
1478 let mut buffer = Vec::new();
1479 invoice.write(&mut buffer).unwrap();
1481 if let Err(e) = Invoice::try_from(buffer) {
1482 panic!("error parsing invoice: {:?}", e);
1485 let mut tlv_stream = invoice.as_tlv_stream();
1486 tlv_stream.3.created_at = None;
1488 match Invoice::try_from(tlv_stream.to_bytes()) {
1489 Ok(_) => panic!("expected error"),
1491 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1497 fn parses_invoice_with_relative_expiry() {
1498 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1501 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1503 .sign(payer_sign).unwrap()
1504 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1505 .relative_expiry(3600)
1507 .sign(recipient_sign).unwrap();
1509 let mut buffer = Vec::new();
1510 invoice.write(&mut buffer).unwrap();
1512 match Invoice::try_from(buffer) {
1513 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1514 Err(e) => panic!("error parsing invoice: {:?}", e),
1519 fn parses_invoice_with_payment_hash() {
1520 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1523 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1525 .sign(payer_sign).unwrap()
1526 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1528 .sign(recipient_sign).unwrap();
1530 let mut buffer = Vec::new();
1531 invoice.write(&mut buffer).unwrap();
1533 if let Err(e) = Invoice::try_from(buffer) {
1534 panic!("error parsing invoice: {:?}", e);
1537 let mut tlv_stream = invoice.as_tlv_stream();
1538 tlv_stream.3.payment_hash = None;
1540 match Invoice::try_from(tlv_stream.to_bytes()) {
1541 Ok(_) => panic!("expected error"),
1543 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1549 fn parses_invoice_with_amount() {
1550 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1553 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555 .sign(payer_sign).unwrap()
1556 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1558 .sign(recipient_sign).unwrap();
1560 let mut buffer = Vec::new();
1561 invoice.write(&mut buffer).unwrap();
1563 if let Err(e) = Invoice::try_from(buffer) {
1564 panic!("error parsing invoice: {:?}", e);
1567 let mut tlv_stream = invoice.as_tlv_stream();
1568 tlv_stream.3.amount = None;
1570 match Invoice::try_from(tlv_stream.to_bytes()) {
1571 Ok(_) => panic!("expected error"),
1572 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1577 fn parses_invoice_with_allow_mpp() {
1578 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1581 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1583 .sign(payer_sign).unwrap()
1584 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1587 .sign(recipient_sign).unwrap();
1589 let mut buffer = Vec::new();
1590 invoice.write(&mut buffer).unwrap();
1592 match Invoice::try_from(buffer) {
1594 let mut features = Bolt12InvoiceFeatures::empty();
1595 features.set_basic_mpp_optional();
1596 assert_eq!(invoice.features(), &features);
1598 Err(e) => panic!("error parsing invoice: {:?}", e),
1603 fn parses_invoice_with_fallback_address() {
1604 let script = Script::new();
1605 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1606 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1607 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1609 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1612 let invoice_request = offer
1613 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1615 .sign(payer_sign).unwrap();
1616 let mut unsigned_invoice = invoice_request
1617 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1618 .fallback_v0_p2wsh(&script.wscript_hash())
1619 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1620 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1623 // Only standard addresses will be included.
1624 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1625 // Non-standard addresses
1626 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1627 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1628 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1630 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1631 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1633 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1634 let mut buffer = Vec::new();
1635 invoice.write(&mut buffer).unwrap();
1637 match Invoice::try_from(buffer) {
1640 invoice.fallbacks(),
1642 Address::p2wsh(&script, Network::Bitcoin),
1643 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1644 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1646 payload: Payload::WitnessProgram {
1647 version: WitnessVersion::V1,
1648 program: vec![0u8; 33],
1650 network: Network::Bitcoin,
1653 payload: Payload::WitnessProgram {
1654 version: WitnessVersion::V2,
1655 program: vec![0u8; 40],
1657 network: Network::Bitcoin,
1662 Err(e) => panic!("error parsing invoice: {:?}", e),
1667 fn parses_invoice_with_node_id() {
1668 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1671 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1673 .sign(payer_sign).unwrap()
1674 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1676 .sign(recipient_sign).unwrap();
1678 let mut buffer = Vec::new();
1679 invoice.write(&mut buffer).unwrap();
1681 if let Err(e) = Invoice::try_from(buffer) {
1682 panic!("error parsing invoice: {:?}", e);
1685 let mut tlv_stream = invoice.as_tlv_stream();
1686 tlv_stream.3.node_id = None;
1688 match Invoice::try_from(tlv_stream.to_bytes()) {
1689 Ok(_) => panic!("expected error"),
1691 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1695 let invalid_pubkey = payer_pubkey();
1696 let mut tlv_stream = invoice.as_tlv_stream();
1697 tlv_stream.3.node_id = Some(&invalid_pubkey);
1699 match Invoice::try_from(tlv_stream.to_bytes()) {
1700 Ok(_) => panic!("expected error"),
1702 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1708 fn fails_parsing_invoice_without_signature() {
1709 let mut buffer = Vec::new();
1710 OfferBuilder::new("foo".into(), recipient_pubkey())
1713 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715 .sign(payer_sign).unwrap()
1716 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1719 .write(&mut buffer).unwrap();
1721 match Invoice::try_from(buffer) {
1722 Ok(_) => panic!("expected error"),
1723 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1728 fn fails_parsing_invoice_with_invalid_signature() {
1729 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1732 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1734 .sign(payer_sign).unwrap()
1735 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1737 .sign(recipient_sign).unwrap();
1738 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1739 *last_signature_byte = last_signature_byte.wrapping_add(1);
1741 let mut buffer = Vec::new();
1742 invoice.write(&mut buffer).unwrap();
1744 match Invoice::try_from(buffer) {
1745 Ok(_) => panic!("expected error"),
1747 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1753 fn fails_parsing_invoice_with_extra_tlv_records() {
1754 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1757 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1759 .sign(payer_sign).unwrap()
1760 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1762 .sign(recipient_sign).unwrap();
1764 let mut encoded_invoice = Vec::new();
1765 invoice.write(&mut encoded_invoice).unwrap();
1766 BigSize(1002).write(&mut encoded_invoice).unwrap();
1767 BigSize(32).write(&mut encoded_invoice).unwrap();
1768 [42u8; 32].write(&mut encoded_invoice).unwrap();
1770 match Invoice::try_from(encoded_invoice) {
1771 Ok(_) => panic!("expected error"),
1772 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),