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)
538 InvoiceContents::ForRefund { refund, .. } => {
539 refund.verify(tlv_stream, key, secp_ctx)
544 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
545 let (payer, offer, invoice_request) = match self {
546 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
547 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
549 let invoice = self.fields().as_tlv_stream();
551 (payer, offer, invoice_request, invoice)
556 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
558 if self.features == Bolt12InvoiceFeatures::empty() { None }
559 else { Some(&self.features) }
562 InvoiceTlvStreamRef {
563 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
564 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
565 created_at: Some(self.created_at.as_secs()),
566 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
567 payment_hash: Some(&self.payment_hash),
568 amount: Some(self.amount_msats),
569 fallbacks: self.fallbacks.as_ref(),
571 node_id: Some(&self.signing_pubkey),
576 impl Writeable for Invoice {
577 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
578 WithoutLength(&self.bytes).write(writer)
582 impl Writeable for InvoiceContents {
583 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
584 self.as_tlv_stream().write(writer)
588 impl TryFrom<Vec<u8>> for Invoice {
589 type Error = ParseError;
591 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
592 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
593 Invoice::try_from(parsed_invoice)
597 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
598 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
599 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
600 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
601 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
602 (168, payment_hash: PaymentHash),
603 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
604 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
605 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
606 (176, node_id: PublicKey),
609 type BlindedPathIter<'a> = core::iter::Map<
610 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
611 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
614 type BlindedPayInfoIter<'a> = core::iter::Map<
615 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
616 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
619 /// Information needed to route a payment across a [`BlindedPath`].
620 #[derive(Clone, Debug, PartialEq)]
621 pub struct BlindedPayInfo {
622 /// Base fee charged (in millisatoshi) for the entire blinded path.
623 pub fee_base_msat: u32,
625 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
626 /// (i.e., 10,000 is 1%).
627 pub fee_proportional_millionths: u32,
629 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
631 pub cltv_expiry_delta: u16,
633 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
634 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
635 /// seen by the recipient.
636 pub htlc_minimum_msat: u64,
638 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
639 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
640 /// seen by the recipient.
641 pub htlc_maximum_msat: u64,
643 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
645 pub features: BlindedHopFeatures,
648 impl_writeable!(BlindedPayInfo, {
650 fee_proportional_millionths,
657 /// Wire representation for an on-chain fallback address.
658 #[derive(Clone, Debug, PartialEq)]
659 pub(super) struct FallbackAddress {
664 impl_writeable!(FallbackAddress, { version, program });
666 type FullInvoiceTlvStream =
667 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
670 type FullInvoiceTlvStreamRef<'a> = (
671 PayerTlvStreamRef<'a>,
672 OfferTlvStreamRef<'a>,
673 InvoiceRequestTlvStreamRef<'a>,
674 InvoiceTlvStreamRef<'a>,
675 SignatureTlvStreamRef<'a>,
678 impl SeekReadable for FullInvoiceTlvStream {
679 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
680 let payer = SeekReadable::read(r)?;
681 let offer = SeekReadable::read(r)?;
682 let invoice_request = SeekReadable::read(r)?;
683 let invoice = SeekReadable::read(r)?;
684 let signature = SeekReadable::read(r)?;
686 Ok((payer, offer, invoice_request, invoice, signature))
690 type PartialInvoiceTlvStream =
691 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
693 type PartialInvoiceTlvStreamRef<'a> = (
694 PayerTlvStreamRef<'a>,
695 OfferTlvStreamRef<'a>,
696 InvoiceRequestTlvStreamRef<'a>,
697 InvoiceTlvStreamRef<'a>,
700 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
701 type Error = ParseError;
703 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
704 let ParsedMessage { bytes, tlv_stream } = invoice;
706 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
707 SignatureTlvStream { signature },
709 let contents = InvoiceContents::try_from(
710 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
713 let signature = match signature {
714 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
715 Some(signature) => signature,
717 let pubkey = contents.fields().signing_pubkey;
718 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
720 Ok(Invoice { bytes, contents, signature })
724 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
725 type Error = SemanticError;
727 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
731 invoice_request_tlv_stream,
733 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
738 let payment_paths = match (paths, blindedpay) {
739 (None, _) => return Err(SemanticError::MissingPaths),
740 (_, None) => return Err(SemanticError::InvalidPayInfo),
741 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
742 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
743 return Err(SemanticError::InvalidPayInfo);
745 (Some(paths), Some(blindedpay)) => {
746 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
750 let created_at = match created_at {
751 None => return Err(SemanticError::MissingCreationTime),
752 Some(timestamp) => Duration::from_secs(timestamp),
755 let relative_expiry = relative_expiry
756 .map(Into::<u64>::into)
757 .map(Duration::from_secs);
759 let payment_hash = match payment_hash {
760 None => return Err(SemanticError::MissingPaymentHash),
761 Some(payment_hash) => payment_hash,
764 let amount_msats = match amount {
765 None => return Err(SemanticError::MissingAmount),
766 Some(amount) => amount,
769 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
771 let signing_pubkey = match node_id {
772 None => return Err(SemanticError::MissingSigningPubkey),
773 Some(node_id) => node_id,
776 let fields = InvoiceFields {
777 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
778 features, signing_pubkey,
781 match offer_tlv_stream.node_id {
782 Some(expected_signing_pubkey) => {
783 if fields.signing_pubkey != expected_signing_pubkey {
784 return Err(SemanticError::InvalidSigningPubkey);
787 let invoice_request = InvoiceRequestContents::try_from(
788 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
790 Ok(InvoiceContents::ForOffer { invoice_request, fields })
793 let refund = RefundContents::try_from(
794 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
796 Ok(InvoiceContents::ForRefund { refund, fields })
804 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
806 use bitcoin::blockdata::script::Script;
807 use bitcoin::hashes::Hash;
808 use bitcoin::network::constants::Network;
809 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
810 use bitcoin::util::address::{Address, Payload, WitnessVersion};
811 use bitcoin::util::schnorr::TweakedPublicKey;
812 use core::convert::TryFrom;
813 use core::time::Duration;
814 use crate::ln::msgs::DecodeError;
815 use crate::ln::features::Bolt12InvoiceFeatures;
816 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
817 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
818 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
819 use crate::offers::parse::{ParseError, SemanticError};
820 use crate::offers::payer::PayerTlvStreamRef;
821 use crate::offers::refund::RefundBuilder;
822 use crate::offers::test_utils::*;
823 use crate::util::ser::{BigSize, Iterable, Writeable};
826 fn to_bytes(&self) -> Vec<u8>;
829 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
830 fn to_bytes(&self) -> Vec<u8> {
831 let mut buffer = Vec::new();
832 self.0.write(&mut buffer).unwrap();
833 self.1.write(&mut buffer).unwrap();
834 self.2.write(&mut buffer).unwrap();
835 self.3.write(&mut buffer).unwrap();
836 self.4.write(&mut buffer).unwrap();
842 fn builds_invoice_for_offer_with_defaults() {
843 let payment_paths = payment_paths();
844 let payment_hash = payment_hash();
846 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
849 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
851 .sign(payer_sign).unwrap()
852 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
854 .sign(recipient_sign).unwrap();
856 let mut buffer = Vec::new();
857 invoice.write(&mut buffer).unwrap();
859 assert_eq!(invoice.bytes, buffer.as_slice());
860 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
861 assert_eq!(invoice.created_at(), now);
862 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
863 #[cfg(feature = "std")]
864 assert!(!invoice.is_expired());
865 assert_eq!(invoice.payment_hash(), payment_hash);
866 assert_eq!(invoice.amount_msats(), 1000);
867 assert_eq!(invoice.fallbacks(), vec![]);
868 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
869 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
871 merkle::verify_signature(
872 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
876 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
877 let pubkey = recipient_pubkey().into();
878 let secp_ctx = Secp256k1::verification_only();
879 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
882 invoice.as_tlv_stream(),
884 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
890 description: Some(&String::from("foo")),
892 absolute_expiry: None,
896 node_id: Some(&recipient_pubkey()),
898 InvoiceRequestTlvStreamRef {
903 payer_id: Some(&payer_pubkey()),
906 InvoiceTlvStreamRef {
907 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
908 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
909 created_at: Some(now.as_secs()),
910 relative_expiry: None,
911 payment_hash: Some(&payment_hash),
915 node_id: Some(&recipient_pubkey()),
917 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
921 if let Err(e) = Invoice::try_from(buffer) {
922 panic!("error parsing invoice: {:?}", e);
927 fn builds_invoice_for_refund_with_defaults() {
928 let payment_paths = payment_paths();
929 let payment_hash = payment_hash();
931 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
933 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
936 .sign(recipient_sign).unwrap();
938 let mut buffer = Vec::new();
939 invoice.write(&mut buffer).unwrap();
941 assert_eq!(invoice.bytes, buffer.as_slice());
942 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
943 assert_eq!(invoice.created_at(), now);
944 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
945 #[cfg(feature = "std")]
946 assert!(!invoice.is_expired());
947 assert_eq!(invoice.payment_hash(), payment_hash);
948 assert_eq!(invoice.amount_msats(), 1000);
949 assert_eq!(invoice.fallbacks(), vec![]);
950 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
951 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
953 merkle::verify_signature(
954 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
959 invoice.as_tlv_stream(),
961 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
967 description: Some(&String::from("foo")),
969 absolute_expiry: None,
975 InvoiceRequestTlvStreamRef {
980 payer_id: Some(&payer_pubkey()),
983 InvoiceTlvStreamRef {
984 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
985 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
986 created_at: Some(now.as_secs()),
987 relative_expiry: None,
988 payment_hash: Some(&payment_hash),
992 node_id: Some(&recipient_pubkey()),
994 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
998 if let Err(e) = Invoice::try_from(buffer) {
999 panic!("error parsing invoice: {:?}", e);
1003 #[cfg(feature = "std")]
1005 fn builds_invoice_from_offer_with_expiration() {
1006 let future_expiry = Duration::from_secs(u64::max_value());
1007 let past_expiry = Duration::from_secs(0);
1009 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1011 .absolute_expiry(future_expiry)
1013 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1015 .sign(payer_sign).unwrap()
1016 .respond_with(payment_paths(), payment_hash())
1020 panic!("error building invoice: {:?}", e);
1023 match OfferBuilder::new("foo".into(), recipient_pubkey())
1025 .absolute_expiry(past_expiry)
1027 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1029 .sign(payer_sign).unwrap()
1030 .respond_with(payment_paths(), payment_hash())
1034 Ok(_) => panic!("expected error"),
1035 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1039 #[cfg(feature = "std")]
1041 fn builds_invoice_from_refund_with_expiration() {
1042 let future_expiry = Duration::from_secs(u64::max_value());
1043 let past_expiry = Duration::from_secs(0);
1045 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1046 .absolute_expiry(future_expiry)
1048 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1052 panic!("error building invoice: {:?}", e);
1055 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1056 .absolute_expiry(past_expiry)
1058 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1062 Ok(_) => panic!("expected error"),
1063 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1068 fn builds_invoice_with_relative_expiry() {
1070 let one_hour = Duration::from_secs(3600);
1072 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1075 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1077 .sign(payer_sign).unwrap()
1078 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1079 .relative_expiry(one_hour.as_secs() as u32)
1081 .sign(recipient_sign).unwrap();
1082 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1083 #[cfg(feature = "std")]
1084 assert!(!invoice.is_expired());
1085 assert_eq!(invoice.relative_expiry(), one_hour);
1086 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1088 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1091 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1093 .sign(payer_sign).unwrap()
1094 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1095 .relative_expiry(one_hour.as_secs() as u32 - 1)
1097 .sign(recipient_sign).unwrap();
1098 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1099 #[cfg(feature = "std")]
1100 assert!(invoice.is_expired());
1101 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1102 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1106 fn builds_invoice_with_amount_from_request() {
1107 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1110 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1111 .amount_msats(1001).unwrap()
1113 .sign(payer_sign).unwrap()
1114 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1116 .sign(recipient_sign).unwrap();
1117 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1118 assert_eq!(invoice.amount_msats(), 1001);
1119 assert_eq!(tlv_stream.amount, Some(1001));
1123 fn builds_invoice_with_quantity_from_request() {
1124 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1126 .supported_quantity(Quantity::Unbounded)
1128 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1129 .quantity(2).unwrap()
1131 .sign(payer_sign).unwrap()
1132 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1134 .sign(recipient_sign).unwrap();
1135 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1136 assert_eq!(invoice.amount_msats(), 2000);
1137 assert_eq!(tlv_stream.amount, Some(2000));
1139 match OfferBuilder::new("foo".into(), recipient_pubkey())
1141 .supported_quantity(Quantity::Unbounded)
1143 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1144 .quantity(u64::max_value()).unwrap()
1146 .sign(payer_sign).unwrap()
1147 .respond_with_no_std(payment_paths(), payment_hash(), now())
1149 Ok(_) => panic!("expected error"),
1150 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1155 fn builds_invoice_with_fallback_address() {
1156 let script = Script::new();
1157 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1158 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1159 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1161 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1164 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1166 .sign(payer_sign).unwrap()
1167 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1168 .fallback_v0_p2wsh(&script.wscript_hash())
1169 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1170 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1172 .sign(recipient_sign).unwrap();
1173 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1175 invoice.fallbacks(),
1177 Address::p2wsh(&script, Network::Bitcoin),
1178 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1179 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1183 tlv_stream.fallbacks,
1186 version: WitnessVersion::V0.to_num(),
1187 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1190 version: WitnessVersion::V0.to_num(),
1191 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1194 version: WitnessVersion::V1.to_num(),
1195 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1202 fn builds_invoice_with_allow_mpp() {
1203 let mut features = Bolt12InvoiceFeatures::empty();
1204 features.set_basic_mpp_optional();
1206 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1209 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1211 .sign(payer_sign).unwrap()
1212 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1215 .sign(recipient_sign).unwrap();
1216 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1217 assert_eq!(invoice.features(), &features);
1218 assert_eq!(tlv_stream.features, Some(&features));
1222 fn fails_signing_invoice() {
1223 match OfferBuilder::new("foo".into(), recipient_pubkey())
1226 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1228 .sign(payer_sign).unwrap()
1229 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1233 Ok(_) => panic!("expected error"),
1234 Err(e) => assert_eq!(e, SignError::Signing(())),
1237 match OfferBuilder::new("foo".into(), recipient_pubkey())
1240 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1242 .sign(payer_sign).unwrap()
1243 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1247 Ok(_) => panic!("expected error"),
1248 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1253 fn parses_invoice_with_payment_paths() {
1254 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1257 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1259 .sign(payer_sign).unwrap()
1260 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1262 .sign(recipient_sign).unwrap();
1264 let mut buffer = Vec::new();
1265 invoice.write(&mut buffer).unwrap();
1267 if let Err(e) = Invoice::try_from(buffer) {
1268 panic!("error parsing invoice: {:?}", e);
1271 let mut tlv_stream = invoice.as_tlv_stream();
1272 tlv_stream.3.paths = None;
1274 match Invoice::try_from(tlv_stream.to_bytes()) {
1275 Ok(_) => panic!("expected error"),
1276 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1279 let mut tlv_stream = invoice.as_tlv_stream();
1280 tlv_stream.3.blindedpay = None;
1282 match Invoice::try_from(tlv_stream.to_bytes()) {
1283 Ok(_) => panic!("expected error"),
1284 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1287 let empty_payment_paths = vec![];
1288 let mut tlv_stream = invoice.as_tlv_stream();
1289 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1291 match Invoice::try_from(tlv_stream.to_bytes()) {
1292 Ok(_) => panic!("expected error"),
1293 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1296 let mut payment_paths = payment_paths();
1297 payment_paths.pop();
1298 let mut tlv_stream = invoice.as_tlv_stream();
1299 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1301 match Invoice::try_from(tlv_stream.to_bytes()) {
1302 Ok(_) => panic!("expected error"),
1303 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1308 fn parses_invoice_with_created_at() {
1309 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1312 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1314 .sign(payer_sign).unwrap()
1315 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1317 .sign(recipient_sign).unwrap();
1319 let mut buffer = Vec::new();
1320 invoice.write(&mut buffer).unwrap();
1322 if let Err(e) = Invoice::try_from(buffer) {
1323 panic!("error parsing invoice: {:?}", e);
1326 let mut tlv_stream = invoice.as_tlv_stream();
1327 tlv_stream.3.created_at = None;
1329 match Invoice::try_from(tlv_stream.to_bytes()) {
1330 Ok(_) => panic!("expected error"),
1332 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1338 fn parses_invoice_with_relative_expiry() {
1339 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 .sign(payer_sign).unwrap()
1345 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1346 .relative_expiry(3600)
1348 .sign(recipient_sign).unwrap();
1350 let mut buffer = Vec::new();
1351 invoice.write(&mut buffer).unwrap();
1353 match Invoice::try_from(buffer) {
1354 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1355 Err(e) => panic!("error parsing invoice: {:?}", e),
1360 fn parses_invoice_with_payment_hash() {
1361 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1364 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1366 .sign(payer_sign).unwrap()
1367 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1369 .sign(recipient_sign).unwrap();
1371 let mut buffer = Vec::new();
1372 invoice.write(&mut buffer).unwrap();
1374 if let Err(e) = Invoice::try_from(buffer) {
1375 panic!("error parsing invoice: {:?}", e);
1378 let mut tlv_stream = invoice.as_tlv_stream();
1379 tlv_stream.3.payment_hash = None;
1381 match Invoice::try_from(tlv_stream.to_bytes()) {
1382 Ok(_) => panic!("expected error"),
1384 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1390 fn parses_invoice_with_amount() {
1391 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1394 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1396 .sign(payer_sign).unwrap()
1397 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1399 .sign(recipient_sign).unwrap();
1401 let mut buffer = Vec::new();
1402 invoice.write(&mut buffer).unwrap();
1404 if let Err(e) = Invoice::try_from(buffer) {
1405 panic!("error parsing invoice: {:?}", e);
1408 let mut tlv_stream = invoice.as_tlv_stream();
1409 tlv_stream.3.amount = None;
1411 match Invoice::try_from(tlv_stream.to_bytes()) {
1412 Ok(_) => panic!("expected error"),
1413 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1418 fn parses_invoice_with_allow_mpp() {
1419 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1422 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1424 .sign(payer_sign).unwrap()
1425 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1428 .sign(recipient_sign).unwrap();
1430 let mut buffer = Vec::new();
1431 invoice.write(&mut buffer).unwrap();
1433 match Invoice::try_from(buffer) {
1435 let mut features = Bolt12InvoiceFeatures::empty();
1436 features.set_basic_mpp_optional();
1437 assert_eq!(invoice.features(), &features);
1439 Err(e) => panic!("error parsing invoice: {:?}", e),
1444 fn parses_invoice_with_fallback_address() {
1445 let script = Script::new();
1446 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1447 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1448 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1450 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1453 let invoice_request = offer
1454 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1456 .sign(payer_sign).unwrap();
1457 let mut unsigned_invoice = invoice_request
1458 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1459 .fallback_v0_p2wsh(&script.wscript_hash())
1460 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1461 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1464 // Only standard addresses will be included.
1465 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1466 // Non-standard addresses
1467 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1468 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1469 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1471 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1472 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1474 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1475 let mut buffer = Vec::new();
1476 invoice.write(&mut buffer).unwrap();
1478 match Invoice::try_from(buffer) {
1481 invoice.fallbacks(),
1483 Address::p2wsh(&script, Network::Bitcoin),
1484 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1485 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1487 payload: Payload::WitnessProgram {
1488 version: WitnessVersion::V1,
1489 program: vec![0u8; 33],
1491 network: Network::Bitcoin,
1494 payload: Payload::WitnessProgram {
1495 version: WitnessVersion::V2,
1496 program: vec![0u8; 40],
1498 network: Network::Bitcoin,
1503 Err(e) => panic!("error parsing invoice: {:?}", e),
1508 fn parses_invoice_with_node_id() {
1509 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1512 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1514 .sign(payer_sign).unwrap()
1515 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1517 .sign(recipient_sign).unwrap();
1519 let mut buffer = Vec::new();
1520 invoice.write(&mut buffer).unwrap();
1522 if let Err(e) = Invoice::try_from(buffer) {
1523 panic!("error parsing invoice: {:?}", e);
1526 let mut tlv_stream = invoice.as_tlv_stream();
1527 tlv_stream.3.node_id = None;
1529 match Invoice::try_from(tlv_stream.to_bytes()) {
1530 Ok(_) => panic!("expected error"),
1532 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1536 let invalid_pubkey = payer_pubkey();
1537 let mut tlv_stream = invoice.as_tlv_stream();
1538 tlv_stream.3.node_id = Some(&invalid_pubkey);
1540 match Invoice::try_from(tlv_stream.to_bytes()) {
1541 Ok(_) => panic!("expected error"),
1543 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1549 fn fails_parsing_invoice_without_signature() {
1550 let mut buffer = Vec::new();
1551 OfferBuilder::new("foo".into(), recipient_pubkey())
1554 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1556 .sign(payer_sign).unwrap()
1557 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1560 .write(&mut buffer).unwrap();
1562 match Invoice::try_from(buffer) {
1563 Ok(_) => panic!("expected error"),
1564 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1569 fn fails_parsing_invoice_with_invalid_signature() {
1570 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1573 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1575 .sign(payer_sign).unwrap()
1576 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1578 .sign(recipient_sign).unwrap();
1579 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1580 *last_signature_byte = last_signature_byte.wrapping_add(1);
1582 let mut buffer = Vec::new();
1583 invoice.write(&mut buffer).unwrap();
1585 match Invoice::try_from(buffer) {
1586 Ok(_) => panic!("expected error"),
1588 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1594 fn fails_parsing_invoice_with_extra_tlv_records() {
1595 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1598 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1600 .sign(payer_sign).unwrap()
1601 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1603 .sign(recipient_sign).unwrap();
1605 let mut encoded_invoice = Vec::new();
1606 invoice.write(&mut encoded_invoice).unwrap();
1607 BigSize(1002).write(&mut encoded_invoice).unwrap();
1608 BigSize(32).write(&mut encoded_invoice).unwrap();
1609 [42u8; 32].write(&mut encoded_invoice).unwrap();
1611 match Invoice::try_from(encoded_invoice) {
1612 Ok(_) => panic!("expected error"),
1613 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),