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::{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::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::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
112 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, WithoutSignatures, self};
113 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
114 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
115 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
116 use crate::offers::refund::{Refund, RefundContents};
117 use crate::onion_message::BlindedPath;
118 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
120 use crate::prelude::*;
122 #[cfg(feature = "std")]
123 use std::time::SystemTime;
125 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
127 pub(super) const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
129 /// Builds an [`Invoice`] from either:
130 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
131 /// - a [`Refund`] for the "offer for money" flow.
133 /// See [module-level documentation] for usage.
135 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
136 /// [`Refund`]: crate::offers::refund::Refund
137 /// [module-level documentation]: self
138 pub struct InvoiceBuilder<'a> {
139 invreq_bytes: &'a Vec<u8>,
140 invoice: InvoiceContents,
143 impl<'a> InvoiceBuilder<'a> {
144 pub(super) fn for_offer(
145 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
146 created_at: Duration, payment_hash: PaymentHash
147 ) -> Result<Self, SemanticError> {
148 let amount_msats = match invoice_request.amount_msats() {
149 Some(amount_msats) => amount_msats,
150 None => match invoice_request.contents.inner.offer.amount() {
151 Some(Amount::Bitcoin { amount_msats }) => {
152 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
153 .ok_or(SemanticError::InvalidAmount)?
155 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
156 None => return Err(SemanticError::MissingAmount),
160 let contents = InvoiceContents::ForOffer {
161 invoice_request: invoice_request.contents.clone(),
162 fields: InvoiceFields {
163 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
164 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
165 signing_pubkey: invoice_request.contents.inner.offer.signing_pubkey(),
169 Self::new(&invoice_request.bytes, contents)
172 pub(super) fn for_refund(
173 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
174 payment_hash: PaymentHash, signing_pubkey: PublicKey
175 ) -> Result<Self, SemanticError> {
176 let contents = InvoiceContents::ForRefund {
177 refund: refund.contents.clone(),
178 fields: InvoiceFields {
179 payment_paths, created_at, relative_expiry: None, payment_hash,
180 amount_msats: refund.amount_msats(), fallbacks: None,
181 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
185 Self::new(&refund.bytes, contents)
188 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
189 if contents.fields().payment_paths.is_empty() {
190 return Err(SemanticError::MissingPaths);
193 Ok(Self { invreq_bytes, invoice: contents })
196 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
197 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
199 /// Successive calls to this method will override the previous setting.
200 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
201 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
202 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
206 /// Adds a P2WSH address to [`Invoice::fallbacks`].
208 /// Successive calls to this method will add another address. Caller is responsible for not
209 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
210 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
211 let address = FallbackAddress {
212 version: WitnessVersion::V0.to_num(),
213 program: Vec::from(&script_hash.into_inner()[..]),
215 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
219 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
221 /// Successive calls to this method will add another address. Caller is responsible for not
222 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
223 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
224 let address = FallbackAddress {
225 version: WitnessVersion::V0.to_num(),
226 program: Vec::from(&pubkey_hash.into_inner()[..]),
228 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
232 /// Adds a P2TR address to [`Invoice::fallbacks`].
234 /// Successive calls to this method will add another address. Caller is responsible for not
235 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
236 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
237 let address = FallbackAddress {
238 version: WitnessVersion::V1.to_num(),
239 program: Vec::from(&output_key.serialize()[..]),
241 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
245 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
246 pub fn allow_mpp(mut self) -> Self {
247 self.invoice.fields_mut().features.set_basic_mpp_optional();
251 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
252 /// [`UnsignedInvoice::sign`].
253 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
254 #[cfg(feature = "std")] {
255 if self.invoice.is_offer_or_refund_expired() {
256 return Err(SemanticError::AlreadyExpired);
260 let InvoiceBuilder { invreq_bytes, invoice } = self;
261 Ok(UnsignedInvoice { invreq_bytes, invoice })
265 /// A semantically valid [`Invoice`] that hasn't been signed.
266 pub struct UnsignedInvoice<'a> {
267 invreq_bytes: &'a Vec<u8>,
268 invoice: InvoiceContents,
271 impl<'a> UnsignedInvoice<'a> {
272 /// The public key corresponding to the key needed to sign the invoice.
273 pub fn signing_pubkey(&self) -> PublicKey {
274 self.invoice.fields().signing_pubkey
277 /// Signs the invoice using the given function.
278 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
280 F: FnOnce(&Message) -> Result<Signature, E>
282 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
283 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
285 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
286 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
287 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
289 let mut bytes = Vec::new();
290 unsigned_tlv_stream.write(&mut bytes).unwrap();
292 let pubkey = self.invoice.fields().signing_pubkey;
293 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
295 // Append the signature TLV record to the bytes.
296 let signature_tlv_stream = SignatureTlvStreamRef {
297 signature: Some(&signature),
299 signature_tlv_stream.write(&mut bytes).unwrap();
303 contents: self.invoice,
309 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
311 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
312 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
314 /// [`Offer`]: crate::offers::offer::Offer
315 /// [`Refund`]: crate::offers::refund::Refund
316 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
317 #[derive(Clone, Debug)]
318 #[cfg_attr(test, derive(PartialEq))]
321 contents: InvoiceContents,
322 signature: Signature,
325 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
327 /// [`Offer`]: crate::offers::offer::Offer
328 /// [`Refund`]: crate::offers::refund::Refund
329 #[derive(Clone, Debug)]
330 #[cfg_attr(test, derive(PartialEq))]
331 enum InvoiceContents {
332 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
334 /// [`Offer`]: crate::offers::offer::Offer
336 invoice_request: InvoiceRequestContents,
337 fields: InvoiceFields,
339 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
341 /// [`Refund`]: crate::offers::refund::Refund
343 refund: RefundContents,
344 fields: InvoiceFields,
348 /// Invoice-specific fields for an `invoice` message.
349 #[derive(Clone, Debug, PartialEq)]
350 struct InvoiceFields {
351 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
352 created_at: Duration,
353 relative_expiry: Option<Duration>,
354 payment_hash: PaymentHash,
356 fallbacks: Option<Vec<FallbackAddress>>,
357 features: Bolt12InvoiceFeatures,
358 signing_pubkey: PublicKey,
362 /// Paths to the recipient originating from publicly reachable nodes, including information
363 /// needed for routing payments across them.
365 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
366 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
367 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
368 &self.contents.fields().payment_paths[..]
371 /// Duration since the Unix epoch when the invoice was created.
372 pub fn created_at(&self) -> Duration {
373 self.contents.fields().created_at
376 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
378 pub fn relative_expiry(&self) -> Duration {
379 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
382 /// Whether the invoice has expired.
383 #[cfg(feature = "std")]
384 pub fn is_expired(&self) -> bool {
385 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
386 match absolute_expiry {
387 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
388 Ok(elapsed) => elapsed > seconds_from_epoch,
395 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
396 pub fn payment_hash(&self) -> PaymentHash {
397 self.contents.fields().payment_hash
400 /// The minimum amount required for a successful payment of the invoice.
401 pub fn amount_msats(&self) -> u64 {
402 self.contents.fields().amount_msats
405 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
407 pub fn fallbacks(&self) -> Vec<Address> {
408 let network = match self.network() {
409 None => return Vec::new(),
410 Some(network) => network,
413 let to_valid_address = |address: &FallbackAddress| {
414 let version = match WitnessVersion::try_from(address.version) {
415 Ok(version) => version,
416 Err(_) => return None,
419 let program = &address.program;
420 if program.len() < 2 || program.len() > 40 {
424 let address = Address {
425 payload: Payload::WitnessProgram {
427 program: address.program.clone(),
432 if !address.is_standard() && version == WitnessVersion::V0 {
439 self.contents.fields().fallbacks
441 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
442 .unwrap_or_else(Vec::new)
445 fn network(&self) -> Option<Network> {
446 let chain = self.contents.chain();
447 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
448 Some(Network::Bitcoin)
449 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
450 Some(Network::Testnet)
451 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
452 Some(Network::Signet)
453 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
454 Some(Network::Regtest)
460 /// Features pertaining to paying an invoice.
461 pub fn features(&self) -> &Bolt12InvoiceFeatures {
462 &self.contents.fields().features
465 /// The public key corresponding to the key used to sign the invoice.
466 pub fn signing_pubkey(&self) -> PublicKey {
467 self.contents.fields().signing_pubkey
470 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
471 pub fn signature(&self) -> Signature {
475 /// Hash that was used for signing the invoice.
476 pub fn signable_hash(&self) -> [u8; 32] {
477 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
480 /// Verifies that the invoice was for a request or refund created using the given key.
481 pub fn verify<T: secp256k1::Signing>(
482 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
484 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
488 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
489 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
490 self.contents.as_tlv_stream();
491 let signature_tlv_stream = SignatureTlvStreamRef {
492 signature: Some(&self.signature),
494 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
495 signature_tlv_stream)
499 impl InvoiceContents {
500 /// Whether the original offer or refund has expired.
501 #[cfg(feature = "std")]
502 fn is_offer_or_refund_expired(&self) -> bool {
504 InvoiceContents::ForOffer { invoice_request, .. } =>
505 invoice_request.inner.offer.is_expired(),
506 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
510 fn chain(&self) -> ChainHash {
512 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
513 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
517 fn fields(&self) -> &InvoiceFields {
519 InvoiceContents::ForOffer { fields, .. } => fields,
520 InvoiceContents::ForRefund { fields, .. } => fields,
524 fn fields_mut(&mut self) -> &mut InvoiceFields {
526 InvoiceContents::ForOffer { fields, .. } => fields,
527 InvoiceContents::ForRefund { fields, .. } => fields,
531 fn verify<T: secp256k1::Signing>(
532 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
535 InvoiceContents::ForOffer { invoice_request, .. } => {
536 invoice_request.verify(tlv_stream, key, secp_ctx)
542 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
543 let (payer, offer, invoice_request) = match self {
544 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
545 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
547 let invoice = self.fields().as_tlv_stream();
549 (payer, offer, invoice_request, invoice)
554 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
556 if self.features == Bolt12InvoiceFeatures::empty() { None }
557 else { Some(&self.features) }
560 InvoiceTlvStreamRef {
561 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
562 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
563 created_at: Some(self.created_at.as_secs()),
564 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
565 payment_hash: Some(&self.payment_hash),
566 amount: Some(self.amount_msats),
567 fallbacks: self.fallbacks.as_ref(),
569 node_id: Some(&self.signing_pubkey),
574 impl Writeable for Invoice {
575 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
576 WithoutLength(&self.bytes).write(writer)
580 impl Writeable for InvoiceContents {
581 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
582 self.as_tlv_stream().write(writer)
586 impl TryFrom<Vec<u8>> for Invoice {
587 type Error = ParseError;
589 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
590 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
591 Invoice::try_from(parsed_invoice)
595 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
596 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
597 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
598 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
599 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
600 (168, payment_hash: PaymentHash),
601 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
602 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
603 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
604 (176, node_id: PublicKey),
607 type BlindedPathIter<'a> = core::iter::Map<
608 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
609 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
612 type BlindedPayInfoIter<'a> = core::iter::Map<
613 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
614 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
617 /// Information needed to route a payment across a [`BlindedPath`].
618 #[derive(Clone, Debug, PartialEq)]
619 pub struct BlindedPayInfo {
620 /// Base fee charged (in millisatoshi) for the entire blinded path.
621 pub fee_base_msat: u32,
623 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
624 /// (i.e., 10,000 is 1%).
625 pub fee_proportional_millionths: u32,
627 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
629 pub cltv_expiry_delta: u16,
631 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
632 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
633 /// seen by the recipient.
634 pub htlc_minimum_msat: u64,
636 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
637 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
638 /// seen by the recipient.
639 pub htlc_maximum_msat: u64,
641 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
643 pub features: BlindedHopFeatures,
646 impl_writeable!(BlindedPayInfo, {
648 fee_proportional_millionths,
655 /// Wire representation for an on-chain fallback address.
656 #[derive(Clone, Debug, PartialEq)]
657 pub(super) struct FallbackAddress {
662 impl_writeable!(FallbackAddress, { version, program });
664 type FullInvoiceTlvStream =
665 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
668 type FullInvoiceTlvStreamRef<'a> = (
669 PayerTlvStreamRef<'a>,
670 OfferTlvStreamRef<'a>,
671 InvoiceRequestTlvStreamRef<'a>,
672 InvoiceTlvStreamRef<'a>,
673 SignatureTlvStreamRef<'a>,
676 impl SeekReadable for FullInvoiceTlvStream {
677 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
678 let payer = SeekReadable::read(r)?;
679 let offer = SeekReadable::read(r)?;
680 let invoice_request = SeekReadable::read(r)?;
681 let invoice = SeekReadable::read(r)?;
682 let signature = SeekReadable::read(r)?;
684 Ok((payer, offer, invoice_request, invoice, signature))
688 type PartialInvoiceTlvStream =
689 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
691 type PartialInvoiceTlvStreamRef<'a> = (
692 PayerTlvStreamRef<'a>,
693 OfferTlvStreamRef<'a>,
694 InvoiceRequestTlvStreamRef<'a>,
695 InvoiceTlvStreamRef<'a>,
698 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
699 type Error = ParseError;
701 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
702 let ParsedMessage { bytes, tlv_stream } = invoice;
704 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
705 SignatureTlvStream { signature },
707 let contents = InvoiceContents::try_from(
708 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
711 let signature = match signature {
712 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
713 Some(signature) => signature,
715 let pubkey = contents.fields().signing_pubkey;
716 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
718 Ok(Invoice { bytes, contents, signature })
722 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
723 type Error = SemanticError;
725 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
729 invoice_request_tlv_stream,
731 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
736 let payment_paths = match (paths, blindedpay) {
737 (None, _) => return Err(SemanticError::MissingPaths),
738 (_, None) => return Err(SemanticError::InvalidPayInfo),
739 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
740 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
741 return Err(SemanticError::InvalidPayInfo);
743 (Some(paths), Some(blindedpay)) => {
744 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
748 let created_at = match created_at {
749 None => return Err(SemanticError::MissingCreationTime),
750 Some(timestamp) => Duration::from_secs(timestamp),
753 let relative_expiry = relative_expiry
754 .map(Into::<u64>::into)
755 .map(Duration::from_secs);
757 let payment_hash = match payment_hash {
758 None => return Err(SemanticError::MissingPaymentHash),
759 Some(payment_hash) => payment_hash,
762 let amount_msats = match amount {
763 None => return Err(SemanticError::MissingAmount),
764 Some(amount) => amount,
767 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
769 let signing_pubkey = match node_id {
770 None => return Err(SemanticError::MissingSigningPubkey),
771 Some(node_id) => node_id,
774 let fields = InvoiceFields {
775 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
776 features, signing_pubkey,
779 match offer_tlv_stream.node_id {
780 Some(expected_signing_pubkey) => {
781 if fields.signing_pubkey != expected_signing_pubkey {
782 return Err(SemanticError::InvalidSigningPubkey);
785 let invoice_request = InvoiceRequestContents::try_from(
786 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
788 Ok(InvoiceContents::ForOffer { invoice_request, fields })
791 let refund = RefundContents::try_from(
792 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
794 Ok(InvoiceContents::ForRefund { refund, fields })
802 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
804 use bitcoin::blockdata::script::Script;
805 use bitcoin::hashes::Hash;
806 use bitcoin::network::constants::Network;
807 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
808 use bitcoin::util::address::{Address, Payload, WitnessVersion};
809 use bitcoin::util::schnorr::TweakedPublicKey;
810 use core::convert::TryFrom;
811 use core::time::Duration;
812 use crate::ln::msgs::DecodeError;
813 use crate::ln::features::Bolt12InvoiceFeatures;
814 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
815 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
816 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
817 use crate::offers::parse::{ParseError, SemanticError};
818 use crate::offers::payer::PayerTlvStreamRef;
819 use crate::offers::refund::RefundBuilder;
820 use crate::offers::test_utils::*;
821 use crate::util::ser::{BigSize, Iterable, Writeable};
824 fn to_bytes(&self) -> Vec<u8>;
827 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
828 fn to_bytes(&self) -> Vec<u8> {
829 let mut buffer = Vec::new();
830 self.0.write(&mut buffer).unwrap();
831 self.1.write(&mut buffer).unwrap();
832 self.2.write(&mut buffer).unwrap();
833 self.3.write(&mut buffer).unwrap();
834 self.4.write(&mut buffer).unwrap();
840 fn builds_invoice_for_offer_with_defaults() {
841 let payment_paths = payment_paths();
842 let payment_hash = payment_hash();
844 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
847 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
849 .sign(payer_sign).unwrap()
850 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
852 .sign(recipient_sign).unwrap();
854 let mut buffer = Vec::new();
855 invoice.write(&mut buffer).unwrap();
857 assert_eq!(invoice.bytes, buffer.as_slice());
858 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
859 assert_eq!(invoice.created_at(), now);
860 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
861 #[cfg(feature = "std")]
862 assert!(!invoice.is_expired());
863 assert_eq!(invoice.payment_hash(), payment_hash);
864 assert_eq!(invoice.amount_msats(), 1000);
865 assert_eq!(invoice.fallbacks(), vec![]);
866 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
867 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
869 merkle::verify_signature(
870 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
874 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
875 let pubkey = recipient_pubkey().into();
876 let secp_ctx = Secp256k1::verification_only();
877 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
880 invoice.as_tlv_stream(),
882 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
888 description: Some(&String::from("foo")),
890 absolute_expiry: None,
894 node_id: Some(&recipient_pubkey()),
896 InvoiceRequestTlvStreamRef {
901 payer_id: Some(&payer_pubkey()),
904 InvoiceTlvStreamRef {
905 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
906 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
907 created_at: Some(now.as_secs()),
908 relative_expiry: None,
909 payment_hash: Some(&payment_hash),
913 node_id: Some(&recipient_pubkey()),
915 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
919 if let Err(e) = Invoice::try_from(buffer) {
920 panic!("error parsing invoice: {:?}", e);
925 fn builds_invoice_for_refund_with_defaults() {
926 let payment_paths = payment_paths();
927 let payment_hash = payment_hash();
929 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
931 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
934 .sign(recipient_sign).unwrap();
936 let mut buffer = Vec::new();
937 invoice.write(&mut buffer).unwrap();
939 assert_eq!(invoice.bytes, buffer.as_slice());
940 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
941 assert_eq!(invoice.created_at(), now);
942 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
943 #[cfg(feature = "std")]
944 assert!(!invoice.is_expired());
945 assert_eq!(invoice.payment_hash(), payment_hash);
946 assert_eq!(invoice.amount_msats(), 1000);
947 assert_eq!(invoice.fallbacks(), vec![]);
948 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
949 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
951 merkle::verify_signature(
952 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
957 invoice.as_tlv_stream(),
959 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
965 description: Some(&String::from("foo")),
967 absolute_expiry: None,
973 InvoiceRequestTlvStreamRef {
978 payer_id: Some(&payer_pubkey()),
981 InvoiceTlvStreamRef {
982 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
983 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
984 created_at: Some(now.as_secs()),
985 relative_expiry: None,
986 payment_hash: Some(&payment_hash),
990 node_id: Some(&recipient_pubkey()),
992 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
996 if let Err(e) = Invoice::try_from(buffer) {
997 panic!("error parsing invoice: {:?}", e);
1001 #[cfg(feature = "std")]
1003 fn builds_invoice_from_offer_with_expiration() {
1004 let future_expiry = Duration::from_secs(u64::max_value());
1005 let past_expiry = Duration::from_secs(0);
1007 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1009 .absolute_expiry(future_expiry)
1011 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1013 .sign(payer_sign).unwrap()
1014 .respond_with(payment_paths(), payment_hash())
1018 panic!("error building invoice: {:?}", e);
1021 match OfferBuilder::new("foo".into(), recipient_pubkey())
1023 .absolute_expiry(past_expiry)
1025 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1027 .sign(payer_sign).unwrap()
1028 .respond_with(payment_paths(), payment_hash())
1032 Ok(_) => panic!("expected error"),
1033 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1037 #[cfg(feature = "std")]
1039 fn builds_invoice_from_refund_with_expiration() {
1040 let future_expiry = Duration::from_secs(u64::max_value());
1041 let past_expiry = Duration::from_secs(0);
1043 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1044 .absolute_expiry(future_expiry)
1046 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1050 panic!("error building invoice: {:?}", e);
1053 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1054 .absolute_expiry(past_expiry)
1056 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1060 Ok(_) => panic!("expected error"),
1061 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1066 fn builds_invoice_with_relative_expiry() {
1068 let one_hour = Duration::from_secs(3600);
1070 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1073 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1075 .sign(payer_sign).unwrap()
1076 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1077 .relative_expiry(one_hour.as_secs() as u32)
1079 .sign(recipient_sign).unwrap();
1080 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1081 #[cfg(feature = "std")]
1082 assert!(!invoice.is_expired());
1083 assert_eq!(invoice.relative_expiry(), one_hour);
1084 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1086 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1089 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1091 .sign(payer_sign).unwrap()
1092 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1093 .relative_expiry(one_hour.as_secs() as u32 - 1)
1095 .sign(recipient_sign).unwrap();
1096 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1097 #[cfg(feature = "std")]
1098 assert!(invoice.is_expired());
1099 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1100 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1104 fn builds_invoice_with_amount_from_request() {
1105 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1108 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1109 .amount_msats(1001).unwrap()
1111 .sign(payer_sign).unwrap()
1112 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1114 .sign(recipient_sign).unwrap();
1115 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1116 assert_eq!(invoice.amount_msats(), 1001);
1117 assert_eq!(tlv_stream.amount, Some(1001));
1121 fn builds_invoice_with_quantity_from_request() {
1122 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1124 .supported_quantity(Quantity::Unbounded)
1126 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1127 .quantity(2).unwrap()
1129 .sign(payer_sign).unwrap()
1130 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1132 .sign(recipient_sign).unwrap();
1133 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1134 assert_eq!(invoice.amount_msats(), 2000);
1135 assert_eq!(tlv_stream.amount, Some(2000));
1137 match OfferBuilder::new("foo".into(), recipient_pubkey())
1139 .supported_quantity(Quantity::Unbounded)
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142 .quantity(u64::max_value()).unwrap()
1144 .sign(payer_sign).unwrap()
1145 .respond_with_no_std(payment_paths(), payment_hash(), now())
1147 Ok(_) => panic!("expected error"),
1148 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1153 fn builds_invoice_with_fallback_address() {
1154 let script = Script::new();
1155 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1156 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1157 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1159 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1162 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .sign(payer_sign).unwrap()
1165 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1166 .fallback_v0_p2wsh(&script.wscript_hash())
1167 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1168 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1170 .sign(recipient_sign).unwrap();
1171 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1173 invoice.fallbacks(),
1175 Address::p2wsh(&script, Network::Bitcoin),
1176 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1177 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1181 tlv_stream.fallbacks,
1184 version: WitnessVersion::V0.to_num(),
1185 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1188 version: WitnessVersion::V0.to_num(),
1189 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1192 version: WitnessVersion::V1.to_num(),
1193 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1200 fn builds_invoice_with_allow_mpp() {
1201 let mut features = Bolt12InvoiceFeatures::empty();
1202 features.set_basic_mpp_optional();
1204 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1207 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1209 .sign(payer_sign).unwrap()
1210 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1213 .sign(recipient_sign).unwrap();
1214 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1215 assert_eq!(invoice.features(), &features);
1216 assert_eq!(tlv_stream.features, Some(&features));
1220 fn fails_signing_invoice() {
1221 match OfferBuilder::new("foo".into(), recipient_pubkey())
1224 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1226 .sign(payer_sign).unwrap()
1227 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1231 Ok(_) => panic!("expected error"),
1232 Err(e) => assert_eq!(e, SignError::Signing(())),
1235 match OfferBuilder::new("foo".into(), recipient_pubkey())
1238 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1240 .sign(payer_sign).unwrap()
1241 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1245 Ok(_) => panic!("expected error"),
1246 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1251 fn parses_invoice_with_payment_paths() {
1252 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1255 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1257 .sign(payer_sign).unwrap()
1258 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1260 .sign(recipient_sign).unwrap();
1262 let mut buffer = Vec::new();
1263 invoice.write(&mut buffer).unwrap();
1265 if let Err(e) = Invoice::try_from(buffer) {
1266 panic!("error parsing invoice: {:?}", e);
1269 let mut tlv_stream = invoice.as_tlv_stream();
1270 tlv_stream.3.paths = None;
1272 match Invoice::try_from(tlv_stream.to_bytes()) {
1273 Ok(_) => panic!("expected error"),
1274 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1277 let mut tlv_stream = invoice.as_tlv_stream();
1278 tlv_stream.3.blindedpay = None;
1280 match Invoice::try_from(tlv_stream.to_bytes()) {
1281 Ok(_) => panic!("expected error"),
1282 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1285 let empty_payment_paths = vec![];
1286 let mut tlv_stream = invoice.as_tlv_stream();
1287 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1289 match Invoice::try_from(tlv_stream.to_bytes()) {
1290 Ok(_) => panic!("expected error"),
1291 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1294 let mut payment_paths = payment_paths();
1295 payment_paths.pop();
1296 let mut tlv_stream = invoice.as_tlv_stream();
1297 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1299 match Invoice::try_from(tlv_stream.to_bytes()) {
1300 Ok(_) => panic!("expected error"),
1301 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1306 fn parses_invoice_with_created_at() {
1307 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1310 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1312 .sign(payer_sign).unwrap()
1313 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1315 .sign(recipient_sign).unwrap();
1317 let mut buffer = Vec::new();
1318 invoice.write(&mut buffer).unwrap();
1320 if let Err(e) = Invoice::try_from(buffer) {
1321 panic!("error parsing invoice: {:?}", e);
1324 let mut tlv_stream = invoice.as_tlv_stream();
1325 tlv_stream.3.created_at = None;
1327 match Invoice::try_from(tlv_stream.to_bytes()) {
1328 Ok(_) => panic!("expected error"),
1330 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1336 fn parses_invoice_with_relative_expiry() {
1337 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1342 .sign(payer_sign).unwrap()
1343 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1344 .relative_expiry(3600)
1346 .sign(recipient_sign).unwrap();
1348 let mut buffer = Vec::new();
1349 invoice.write(&mut buffer).unwrap();
1351 match Invoice::try_from(buffer) {
1352 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1353 Err(e) => panic!("error parsing invoice: {:?}", e),
1358 fn parses_invoice_with_payment_hash() {
1359 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1362 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1364 .sign(payer_sign).unwrap()
1365 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1367 .sign(recipient_sign).unwrap();
1369 let mut buffer = Vec::new();
1370 invoice.write(&mut buffer).unwrap();
1372 if let Err(e) = Invoice::try_from(buffer) {
1373 panic!("error parsing invoice: {:?}", e);
1376 let mut tlv_stream = invoice.as_tlv_stream();
1377 tlv_stream.3.payment_hash = None;
1379 match Invoice::try_from(tlv_stream.to_bytes()) {
1380 Ok(_) => panic!("expected error"),
1382 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1388 fn parses_invoice_with_amount() {
1389 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1392 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1394 .sign(payer_sign).unwrap()
1395 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1397 .sign(recipient_sign).unwrap();
1399 let mut buffer = Vec::new();
1400 invoice.write(&mut buffer).unwrap();
1402 if let Err(e) = Invoice::try_from(buffer) {
1403 panic!("error parsing invoice: {:?}", e);
1406 let mut tlv_stream = invoice.as_tlv_stream();
1407 tlv_stream.3.amount = None;
1409 match Invoice::try_from(tlv_stream.to_bytes()) {
1410 Ok(_) => panic!("expected error"),
1411 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1416 fn parses_invoice_with_allow_mpp() {
1417 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1420 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1422 .sign(payer_sign).unwrap()
1423 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1426 .sign(recipient_sign).unwrap();
1428 let mut buffer = Vec::new();
1429 invoice.write(&mut buffer).unwrap();
1431 match Invoice::try_from(buffer) {
1433 let mut features = Bolt12InvoiceFeatures::empty();
1434 features.set_basic_mpp_optional();
1435 assert_eq!(invoice.features(), &features);
1437 Err(e) => panic!("error parsing invoice: {:?}", e),
1442 fn parses_invoice_with_fallback_address() {
1443 let script = Script::new();
1444 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1445 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1446 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1448 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1451 let invoice_request = offer
1452 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1454 .sign(payer_sign).unwrap();
1455 let mut unsigned_invoice = invoice_request
1456 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1457 .fallback_v0_p2wsh(&script.wscript_hash())
1458 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1459 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1462 // Only standard addresses will be included.
1463 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1464 // Non-standard addresses
1465 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1466 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1467 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1469 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1470 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1472 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1473 let mut buffer = Vec::new();
1474 invoice.write(&mut buffer).unwrap();
1476 match Invoice::try_from(buffer) {
1479 invoice.fallbacks(),
1481 Address::p2wsh(&script, Network::Bitcoin),
1482 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1483 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1485 payload: Payload::WitnessProgram {
1486 version: WitnessVersion::V1,
1487 program: vec![0u8; 33],
1489 network: Network::Bitcoin,
1492 payload: Payload::WitnessProgram {
1493 version: WitnessVersion::V2,
1494 program: vec![0u8; 40],
1496 network: Network::Bitcoin,
1501 Err(e) => panic!("error parsing invoice: {:?}", e),
1506 fn parses_invoice_with_node_id() {
1507 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1510 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1512 .sign(payer_sign).unwrap()
1513 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1515 .sign(recipient_sign).unwrap();
1517 let mut buffer = Vec::new();
1518 invoice.write(&mut buffer).unwrap();
1520 if let Err(e) = Invoice::try_from(buffer) {
1521 panic!("error parsing invoice: {:?}", e);
1524 let mut tlv_stream = invoice.as_tlv_stream();
1525 tlv_stream.3.node_id = None;
1527 match Invoice::try_from(tlv_stream.to_bytes()) {
1528 Ok(_) => panic!("expected error"),
1530 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1534 let invalid_pubkey = payer_pubkey();
1535 let mut tlv_stream = invoice.as_tlv_stream();
1536 tlv_stream.3.node_id = Some(&invalid_pubkey);
1538 match Invoice::try_from(tlv_stream.to_bytes()) {
1539 Ok(_) => panic!("expected error"),
1541 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1547 fn fails_parsing_invoice_without_signature() {
1548 let mut buffer = Vec::new();
1549 OfferBuilder::new("foo".into(), recipient_pubkey())
1552 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1554 .sign(payer_sign).unwrap()
1555 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1558 .write(&mut buffer).unwrap();
1560 match Invoice::try_from(buffer) {
1561 Ok(_) => panic!("expected error"),
1562 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1567 fn fails_parsing_invoice_with_invalid_signature() {
1568 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1571 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1573 .sign(payer_sign).unwrap()
1574 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1576 .sign(recipient_sign).unwrap();
1577 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1578 *last_signature_byte = last_signature_byte.wrapping_add(1);
1580 let mut buffer = Vec::new();
1581 invoice.write(&mut buffer).unwrap();
1583 match Invoice::try_from(buffer) {
1584 Ok(_) => panic!("expected error"),
1586 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1592 fn fails_parsing_invoice_with_extra_tlv_records() {
1593 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1596 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598 .sign(payer_sign).unwrap()
1599 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1601 .sign(recipient_sign).unwrap();
1603 let mut encoded_invoice = Vec::new();
1604 invoice.write(&mut encoded_invoice).unwrap();
1605 BigSize(1002).write(&mut encoded_invoice).unwrap();
1606 BigSize(32).write(&mut encoded_invoice).unwrap();
1607 [42u8; 32].write(&mut encoded_invoice).unwrap();
1609 match Invoice::try_from(encoded_invoice) {
1610 Ok(_) => panic!("expected error"),
1611 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),