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::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
112 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, WithoutSignatures, self};
113 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
114 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
115 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
116 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
117 use crate::offers::signer;
118 use crate::onion_message::BlindedPath;
119 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
121 use crate::prelude::*;
123 #[cfg(feature = "std")]
124 use std::time::SystemTime;
126 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
128 pub(super) const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
130 /// Builds an [`Invoice`] from either:
131 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
132 /// - a [`Refund`] for the "offer for money" flow.
134 /// See [module-level documentation] for usage.
136 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
137 /// [`Refund`]: crate::offers::refund::Refund
138 /// [module-level documentation]: self
139 pub struct InvoiceBuilder<'a> {
140 invreq_bytes: &'a Vec<u8>,
141 invoice: InvoiceContents,
144 impl<'a> InvoiceBuilder<'a> {
145 pub(super) fn for_offer(
146 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
147 created_at: Duration, payment_hash: PaymentHash
148 ) -> Result<Self, SemanticError> {
149 let amount_msats = match invoice_request.amount_msats() {
150 Some(amount_msats) => amount_msats,
151 None => match invoice_request.contents.inner.offer.amount() {
152 Some(Amount::Bitcoin { amount_msats }) => {
153 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
154 .ok_or(SemanticError::InvalidAmount)?
156 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
157 None => return Err(SemanticError::MissingAmount),
161 let contents = InvoiceContents::ForOffer {
162 invoice_request: invoice_request.contents.clone(),
163 fields: InvoiceFields {
164 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
165 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
166 signing_pubkey: invoice_request.contents.inner.offer.signing_pubkey(),
170 Self::new(&invoice_request.bytes, contents)
173 pub(super) fn for_refund(
174 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
175 payment_hash: PaymentHash, signing_pubkey: PublicKey
176 ) -> Result<Self, SemanticError> {
177 let contents = InvoiceContents::ForRefund {
178 refund: refund.contents.clone(),
179 fields: InvoiceFields {
180 payment_paths, created_at, relative_expiry: None, payment_hash,
181 amount_msats: refund.amount_msats(), fallbacks: None,
182 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
186 Self::new(&refund.bytes, contents)
189 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
190 if contents.fields().payment_paths.is_empty() {
191 return Err(SemanticError::MissingPaths);
194 Ok(Self { invreq_bytes, invoice: contents })
197 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
198 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
200 /// Successive calls to this method will override the previous setting.
201 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
202 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
203 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
207 /// Adds a P2WSH address to [`Invoice::fallbacks`].
209 /// Successive calls to this method will add another address. Caller is responsible for not
210 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
211 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
212 let address = FallbackAddress {
213 version: WitnessVersion::V0.to_num(),
214 program: Vec::from(&script_hash.into_inner()[..]),
216 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
220 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
222 /// Successive calls to this method will add another address. Caller is responsible for not
223 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
224 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
225 let address = FallbackAddress {
226 version: WitnessVersion::V0.to_num(),
227 program: Vec::from(&pubkey_hash.into_inner()[..]),
229 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
233 /// Adds a P2TR address to [`Invoice::fallbacks`].
235 /// Successive calls to this method will add another address. Caller is responsible for not
236 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
237 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
238 let address = FallbackAddress {
239 version: WitnessVersion::V1.to_num(),
240 program: Vec::from(&output_key.serialize()[..]),
242 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
246 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
247 pub fn allow_mpp(mut self) -> Self {
248 self.invoice.fields_mut().features.set_basic_mpp_optional();
252 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
253 /// [`UnsignedInvoice::sign`].
254 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
255 #[cfg(feature = "std")] {
256 if self.invoice.is_offer_or_refund_expired() {
257 return Err(SemanticError::AlreadyExpired);
261 let InvoiceBuilder { invreq_bytes, invoice } = self;
262 Ok(UnsignedInvoice { invreq_bytes, invoice })
266 /// A semantically valid [`Invoice`] that hasn't been signed.
267 pub struct UnsignedInvoice<'a> {
268 invreq_bytes: &'a Vec<u8>,
269 invoice: InvoiceContents,
272 impl<'a> UnsignedInvoice<'a> {
273 /// The public key corresponding to the key needed to sign the invoice.
274 pub fn signing_pubkey(&self) -> PublicKey {
275 self.invoice.fields().signing_pubkey
278 /// Signs the invoice using the given function.
279 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
281 F: FnOnce(&Message) -> Result<Signature, E>
283 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
284 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
286 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
287 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
288 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
290 let mut bytes = Vec::new();
291 unsigned_tlv_stream.write(&mut bytes).unwrap();
293 let pubkey = self.invoice.fields().signing_pubkey;
294 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
296 // Append the signature TLV record to the bytes.
297 let signature_tlv_stream = SignatureTlvStreamRef {
298 signature: Some(&signature),
300 signature_tlv_stream.write(&mut bytes).unwrap();
304 contents: self.invoice,
310 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
312 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
313 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
315 /// [`Offer`]: crate::offers::offer::Offer
316 /// [`Refund`]: crate::offers::refund::Refund
317 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
318 #[derive(Clone, Debug)]
319 #[cfg_attr(test, derive(PartialEq))]
322 contents: InvoiceContents,
323 signature: Signature,
326 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
328 /// [`Offer`]: crate::offers::offer::Offer
329 /// [`Refund`]: crate::offers::refund::Refund
330 #[derive(Clone, Debug)]
331 #[cfg_attr(test, derive(PartialEq))]
332 enum InvoiceContents {
333 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
335 /// [`Offer`]: crate::offers::offer::Offer
337 invoice_request: InvoiceRequestContents,
338 fields: InvoiceFields,
340 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
342 /// [`Refund`]: crate::offers::refund::Refund
344 refund: RefundContents,
345 fields: InvoiceFields,
349 /// Invoice-specific fields for an `invoice` message.
350 #[derive(Clone, Debug, PartialEq)]
351 struct InvoiceFields {
352 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
353 created_at: Duration,
354 relative_expiry: Option<Duration>,
355 payment_hash: PaymentHash,
357 fallbacks: Option<Vec<FallbackAddress>>,
358 features: Bolt12InvoiceFeatures,
359 signing_pubkey: PublicKey,
363 /// Paths to the recipient originating from publicly reachable nodes, including information
364 /// needed for routing payments across them.
366 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
367 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
368 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
369 &self.contents.fields().payment_paths[..]
372 /// Duration since the Unix epoch when the invoice was created.
373 pub fn created_at(&self) -> Duration {
374 self.contents.fields().created_at
377 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
379 pub fn relative_expiry(&self) -> Duration {
380 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
383 /// Whether the invoice has expired.
384 #[cfg(feature = "std")]
385 pub fn is_expired(&self) -> bool {
386 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
387 match absolute_expiry {
388 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
389 Ok(elapsed) => elapsed > seconds_from_epoch,
396 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
397 pub fn payment_hash(&self) -> PaymentHash {
398 self.contents.fields().payment_hash
401 /// The minimum amount required for a successful payment of the invoice.
402 pub fn amount_msats(&self) -> u64 {
403 self.contents.fields().amount_msats
406 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
408 pub fn fallbacks(&self) -> Vec<Address> {
409 let network = match self.network() {
410 None => return Vec::new(),
411 Some(network) => network,
414 let to_valid_address = |address: &FallbackAddress| {
415 let version = match WitnessVersion::try_from(address.version) {
416 Ok(version) => version,
417 Err(_) => return None,
420 let program = &address.program;
421 if program.len() < 2 || program.len() > 40 {
425 let address = Address {
426 payload: Payload::WitnessProgram {
428 program: address.program.clone(),
433 if !address.is_standard() && version == WitnessVersion::V0 {
440 self.contents.fields().fallbacks
442 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
443 .unwrap_or_else(Vec::new)
446 fn network(&self) -> Option<Network> {
447 let chain = self.contents.chain();
448 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
449 Some(Network::Bitcoin)
450 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
451 Some(Network::Testnet)
452 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
453 Some(Network::Signet)
454 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
455 Some(Network::Regtest)
461 /// Features pertaining to paying an invoice.
462 pub fn features(&self) -> &Bolt12InvoiceFeatures {
463 &self.contents.fields().features
466 /// The public key corresponding to the key used to sign the invoice.
467 pub fn signing_pubkey(&self) -> PublicKey {
468 self.contents.fields().signing_pubkey
471 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
472 pub fn signature(&self) -> Signature {
476 /// Hash that was used for signing the invoice.
477 pub fn signable_hash(&self) -> [u8; 32] {
478 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
481 /// Verifies that the invoice was for a request or refund created using the given key.
482 pub fn verify<T: secp256k1::Signing>(
483 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
485 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
489 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
490 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
491 self.contents.as_tlv_stream();
492 let signature_tlv_stream = SignatureTlvStreamRef {
493 signature: Some(&self.signature),
495 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
496 signature_tlv_stream)
500 impl InvoiceContents {
501 /// Whether the original offer or refund has expired.
502 #[cfg(feature = "std")]
503 fn is_offer_or_refund_expired(&self) -> bool {
505 InvoiceContents::ForOffer { invoice_request, .. } =>
506 invoice_request.inner.offer.is_expired(),
507 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
511 fn chain(&self) -> ChainHash {
513 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
514 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
518 fn fields(&self) -> &InvoiceFields {
520 InvoiceContents::ForOffer { fields, .. } => fields,
521 InvoiceContents::ForRefund { fields, .. } => fields,
525 fn fields_mut(&mut self) -> &mut InvoiceFields {
527 InvoiceContents::ForOffer { fields, .. } => fields,
528 InvoiceContents::ForRefund { fields, .. } => fields,
532 fn verify<T: secp256k1::Signing>(
533 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
535 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
536 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
537 match record.r#type {
538 PAYER_METADATA_TYPE => false, // Should be outside range
539 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
543 let tlv_stream = offer_records.chain(invreq_records);
545 let (metadata, payer_id, iv_bytes) = match self {
546 InvoiceContents::ForOffer { invoice_request, .. } => {
547 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
549 InvoiceContents::ForRefund { refund, .. } => {
550 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
554 signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
557 fn derives_keys(&self) -> bool {
559 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
560 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
564 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
565 let (payer, offer, invoice_request) = match self {
566 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
567 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
569 let invoice = self.fields().as_tlv_stream();
571 (payer, offer, invoice_request, invoice)
576 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
578 if self.features == Bolt12InvoiceFeatures::empty() { None }
579 else { Some(&self.features) }
582 InvoiceTlvStreamRef {
583 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
584 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
585 created_at: Some(self.created_at.as_secs()),
586 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
587 payment_hash: Some(&self.payment_hash),
588 amount: Some(self.amount_msats),
589 fallbacks: self.fallbacks.as_ref(),
591 node_id: Some(&self.signing_pubkey),
596 impl Writeable for Invoice {
597 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
598 WithoutLength(&self.bytes).write(writer)
602 impl Writeable for InvoiceContents {
603 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
604 self.as_tlv_stream().write(writer)
608 impl TryFrom<Vec<u8>> for Invoice {
609 type Error = ParseError;
611 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
612 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
613 Invoice::try_from(parsed_invoice)
617 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
618 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
619 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
620 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
621 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
622 (168, payment_hash: PaymentHash),
623 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
624 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
625 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
626 (176, node_id: PublicKey),
629 type BlindedPathIter<'a> = core::iter::Map<
630 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
631 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
634 type BlindedPayInfoIter<'a> = core::iter::Map<
635 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
636 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
639 /// Information needed to route a payment across a [`BlindedPath`].
640 #[derive(Clone, Debug, PartialEq)]
641 pub struct BlindedPayInfo {
642 /// Base fee charged (in millisatoshi) for the entire blinded path.
643 pub fee_base_msat: u32,
645 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
646 /// (i.e., 10,000 is 1%).
647 pub fee_proportional_millionths: u32,
649 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
651 pub cltv_expiry_delta: u16,
653 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
654 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
655 /// seen by the recipient.
656 pub htlc_minimum_msat: u64,
658 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
659 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
660 /// seen by the recipient.
661 pub htlc_maximum_msat: u64,
663 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
665 pub features: BlindedHopFeatures,
668 impl_writeable!(BlindedPayInfo, {
670 fee_proportional_millionths,
677 /// Wire representation for an on-chain fallback address.
678 #[derive(Clone, Debug, PartialEq)]
679 pub(super) struct FallbackAddress {
684 impl_writeable!(FallbackAddress, { version, program });
686 type FullInvoiceTlvStream =
687 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
690 type FullInvoiceTlvStreamRef<'a> = (
691 PayerTlvStreamRef<'a>,
692 OfferTlvStreamRef<'a>,
693 InvoiceRequestTlvStreamRef<'a>,
694 InvoiceTlvStreamRef<'a>,
695 SignatureTlvStreamRef<'a>,
698 impl SeekReadable for FullInvoiceTlvStream {
699 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
700 let payer = SeekReadable::read(r)?;
701 let offer = SeekReadable::read(r)?;
702 let invoice_request = SeekReadable::read(r)?;
703 let invoice = SeekReadable::read(r)?;
704 let signature = SeekReadable::read(r)?;
706 Ok((payer, offer, invoice_request, invoice, signature))
710 type PartialInvoiceTlvStream =
711 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
713 type PartialInvoiceTlvStreamRef<'a> = (
714 PayerTlvStreamRef<'a>,
715 OfferTlvStreamRef<'a>,
716 InvoiceRequestTlvStreamRef<'a>,
717 InvoiceTlvStreamRef<'a>,
720 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
721 type Error = ParseError;
723 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
724 let ParsedMessage { bytes, tlv_stream } = invoice;
726 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
727 SignatureTlvStream { signature },
729 let contents = InvoiceContents::try_from(
730 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
733 let signature = match signature {
734 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
735 Some(signature) => signature,
737 let pubkey = contents.fields().signing_pubkey;
738 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
740 Ok(Invoice { bytes, contents, signature })
744 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
745 type Error = SemanticError;
747 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
751 invoice_request_tlv_stream,
753 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
758 let payment_paths = match (paths, blindedpay) {
759 (None, _) => return Err(SemanticError::MissingPaths),
760 (_, None) => return Err(SemanticError::InvalidPayInfo),
761 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
762 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
763 return Err(SemanticError::InvalidPayInfo);
765 (Some(paths), Some(blindedpay)) => {
766 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
770 let created_at = match created_at {
771 None => return Err(SemanticError::MissingCreationTime),
772 Some(timestamp) => Duration::from_secs(timestamp),
775 let relative_expiry = relative_expiry
776 .map(Into::<u64>::into)
777 .map(Duration::from_secs);
779 let payment_hash = match payment_hash {
780 None => return Err(SemanticError::MissingPaymentHash),
781 Some(payment_hash) => payment_hash,
784 let amount_msats = match amount {
785 None => return Err(SemanticError::MissingAmount),
786 Some(amount) => amount,
789 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
791 let signing_pubkey = match node_id {
792 None => return Err(SemanticError::MissingSigningPubkey),
793 Some(node_id) => node_id,
796 let fields = InvoiceFields {
797 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
798 features, signing_pubkey,
801 match offer_tlv_stream.node_id {
802 Some(expected_signing_pubkey) => {
803 if fields.signing_pubkey != expected_signing_pubkey {
804 return Err(SemanticError::InvalidSigningPubkey);
807 let invoice_request = InvoiceRequestContents::try_from(
808 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
810 Ok(InvoiceContents::ForOffer { invoice_request, fields })
813 let refund = RefundContents::try_from(
814 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
816 Ok(InvoiceContents::ForRefund { refund, fields })
824 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
826 use bitcoin::blockdata::script::Script;
827 use bitcoin::hashes::Hash;
828 use bitcoin::network::constants::Network;
829 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
830 use bitcoin::util::address::{Address, Payload, WitnessVersion};
831 use bitcoin::util::schnorr::TweakedPublicKey;
832 use core::convert::TryFrom;
833 use core::time::Duration;
834 use crate::ln::msgs::DecodeError;
835 use crate::ln::features::Bolt12InvoiceFeatures;
836 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
837 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
838 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
839 use crate::offers::parse::{ParseError, SemanticError};
840 use crate::offers::payer::PayerTlvStreamRef;
841 use crate::offers::refund::RefundBuilder;
842 use crate::offers::test_utils::*;
843 use crate::util::ser::{BigSize, Iterable, Writeable};
846 fn to_bytes(&self) -> Vec<u8>;
849 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
850 fn to_bytes(&self) -> Vec<u8> {
851 let mut buffer = Vec::new();
852 self.0.write(&mut buffer).unwrap();
853 self.1.write(&mut buffer).unwrap();
854 self.2.write(&mut buffer).unwrap();
855 self.3.write(&mut buffer).unwrap();
856 self.4.write(&mut buffer).unwrap();
862 fn builds_invoice_for_offer_with_defaults() {
863 let payment_paths = payment_paths();
864 let payment_hash = payment_hash();
866 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
869 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
871 .sign(payer_sign).unwrap()
872 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
874 .sign(recipient_sign).unwrap();
876 let mut buffer = Vec::new();
877 invoice.write(&mut buffer).unwrap();
879 assert_eq!(invoice.bytes, buffer.as_slice());
880 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
881 assert_eq!(invoice.created_at(), now);
882 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
883 #[cfg(feature = "std")]
884 assert!(!invoice.is_expired());
885 assert_eq!(invoice.payment_hash(), payment_hash);
886 assert_eq!(invoice.amount_msats(), 1000);
887 assert_eq!(invoice.fallbacks(), vec![]);
888 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
889 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
891 merkle::verify_signature(
892 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
896 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
897 let pubkey = recipient_pubkey().into();
898 let secp_ctx = Secp256k1::verification_only();
899 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
902 invoice.as_tlv_stream(),
904 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
910 description: Some(&String::from("foo")),
912 absolute_expiry: None,
916 node_id: Some(&recipient_pubkey()),
918 InvoiceRequestTlvStreamRef {
923 payer_id: Some(&payer_pubkey()),
926 InvoiceTlvStreamRef {
927 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
928 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
929 created_at: Some(now.as_secs()),
930 relative_expiry: None,
931 payment_hash: Some(&payment_hash),
935 node_id: Some(&recipient_pubkey()),
937 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
941 if let Err(e) = Invoice::try_from(buffer) {
942 panic!("error parsing invoice: {:?}", e);
947 fn builds_invoice_for_refund_with_defaults() {
948 let payment_paths = payment_paths();
949 let payment_hash = payment_hash();
951 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
953 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
956 .sign(recipient_sign).unwrap();
958 let mut buffer = Vec::new();
959 invoice.write(&mut buffer).unwrap();
961 assert_eq!(invoice.bytes, buffer.as_slice());
962 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
963 assert_eq!(invoice.created_at(), now);
964 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
965 #[cfg(feature = "std")]
966 assert!(!invoice.is_expired());
967 assert_eq!(invoice.payment_hash(), payment_hash);
968 assert_eq!(invoice.amount_msats(), 1000);
969 assert_eq!(invoice.fallbacks(), vec![]);
970 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
971 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
973 merkle::verify_signature(
974 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
979 invoice.as_tlv_stream(),
981 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
987 description: Some(&String::from("foo")),
989 absolute_expiry: None,
995 InvoiceRequestTlvStreamRef {
1000 payer_id: Some(&payer_pubkey()),
1003 InvoiceTlvStreamRef {
1004 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1005 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1006 created_at: Some(now.as_secs()),
1007 relative_expiry: None,
1008 payment_hash: Some(&payment_hash),
1012 node_id: Some(&recipient_pubkey()),
1014 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1018 if let Err(e) = Invoice::try_from(buffer) {
1019 panic!("error parsing invoice: {:?}", e);
1023 #[cfg(feature = "std")]
1025 fn builds_invoice_from_offer_with_expiration() {
1026 let future_expiry = Duration::from_secs(u64::max_value());
1027 let past_expiry = Duration::from_secs(0);
1029 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1031 .absolute_expiry(future_expiry)
1033 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1035 .sign(payer_sign).unwrap()
1036 .respond_with(payment_paths(), payment_hash())
1040 panic!("error building invoice: {:?}", e);
1043 match OfferBuilder::new("foo".into(), recipient_pubkey())
1045 .absolute_expiry(past_expiry)
1047 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1049 .sign(payer_sign).unwrap()
1050 .respond_with(payment_paths(), payment_hash())
1054 Ok(_) => panic!("expected error"),
1055 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1059 #[cfg(feature = "std")]
1061 fn builds_invoice_from_refund_with_expiration() {
1062 let future_expiry = Duration::from_secs(u64::max_value());
1063 let past_expiry = Duration::from_secs(0);
1065 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1066 .absolute_expiry(future_expiry)
1068 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1072 panic!("error building invoice: {:?}", e);
1075 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1076 .absolute_expiry(past_expiry)
1078 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1082 Ok(_) => panic!("expected error"),
1083 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1088 fn builds_invoice_with_relative_expiry() {
1090 let one_hour = Duration::from_secs(3600);
1092 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1095 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1097 .sign(payer_sign).unwrap()
1098 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1099 .relative_expiry(one_hour.as_secs() as u32)
1101 .sign(recipient_sign).unwrap();
1102 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1103 #[cfg(feature = "std")]
1104 assert!(!invoice.is_expired());
1105 assert_eq!(invoice.relative_expiry(), one_hour);
1106 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1108 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1111 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1113 .sign(payer_sign).unwrap()
1114 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1115 .relative_expiry(one_hour.as_secs() as u32 - 1)
1117 .sign(recipient_sign).unwrap();
1118 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1119 #[cfg(feature = "std")]
1120 assert!(invoice.is_expired());
1121 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1122 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1126 fn builds_invoice_with_amount_from_request() {
1127 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1130 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1131 .amount_msats(1001).unwrap()
1133 .sign(payer_sign).unwrap()
1134 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1136 .sign(recipient_sign).unwrap();
1137 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1138 assert_eq!(invoice.amount_msats(), 1001);
1139 assert_eq!(tlv_stream.amount, Some(1001));
1143 fn builds_invoice_with_quantity_from_request() {
1144 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1146 .supported_quantity(Quantity::Unbounded)
1148 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1149 .quantity(2).unwrap()
1151 .sign(payer_sign).unwrap()
1152 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1154 .sign(recipient_sign).unwrap();
1155 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1156 assert_eq!(invoice.amount_msats(), 2000);
1157 assert_eq!(tlv_stream.amount, Some(2000));
1159 match OfferBuilder::new("foo".into(), recipient_pubkey())
1161 .supported_quantity(Quantity::Unbounded)
1163 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .quantity(u64::max_value()).unwrap()
1166 .sign(payer_sign).unwrap()
1167 .respond_with_no_std(payment_paths(), payment_hash(), now())
1169 Ok(_) => panic!("expected error"),
1170 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1175 fn builds_invoice_with_fallback_address() {
1176 let script = Script::new();
1177 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1178 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1179 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1181 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1184 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186 .sign(payer_sign).unwrap()
1187 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1188 .fallback_v0_p2wsh(&script.wscript_hash())
1189 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1190 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1192 .sign(recipient_sign).unwrap();
1193 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1195 invoice.fallbacks(),
1197 Address::p2wsh(&script, Network::Bitcoin),
1198 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1199 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1203 tlv_stream.fallbacks,
1206 version: WitnessVersion::V0.to_num(),
1207 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1210 version: WitnessVersion::V0.to_num(),
1211 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1214 version: WitnessVersion::V1.to_num(),
1215 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1222 fn builds_invoice_with_allow_mpp() {
1223 let mut features = Bolt12InvoiceFeatures::empty();
1224 features.set_basic_mpp_optional();
1226 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1229 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231 .sign(payer_sign).unwrap()
1232 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1235 .sign(recipient_sign).unwrap();
1236 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1237 assert_eq!(invoice.features(), &features);
1238 assert_eq!(tlv_stream.features, Some(&features));
1242 fn fails_signing_invoice() {
1243 match OfferBuilder::new("foo".into(), recipient_pubkey())
1246 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248 .sign(payer_sign).unwrap()
1249 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1253 Ok(_) => panic!("expected error"),
1254 Err(e) => assert_eq!(e, SignError::Signing(())),
1257 match OfferBuilder::new("foo".into(), recipient_pubkey())
1260 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1262 .sign(payer_sign).unwrap()
1263 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1267 Ok(_) => panic!("expected error"),
1268 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1273 fn parses_invoice_with_payment_paths() {
1274 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1277 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1279 .sign(payer_sign).unwrap()
1280 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1282 .sign(recipient_sign).unwrap();
1284 let mut buffer = Vec::new();
1285 invoice.write(&mut buffer).unwrap();
1287 if let Err(e) = Invoice::try_from(buffer) {
1288 panic!("error parsing invoice: {:?}", e);
1291 let mut tlv_stream = invoice.as_tlv_stream();
1292 tlv_stream.3.paths = None;
1294 match Invoice::try_from(tlv_stream.to_bytes()) {
1295 Ok(_) => panic!("expected error"),
1296 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1299 let mut tlv_stream = invoice.as_tlv_stream();
1300 tlv_stream.3.blindedpay = None;
1302 match Invoice::try_from(tlv_stream.to_bytes()) {
1303 Ok(_) => panic!("expected error"),
1304 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1307 let empty_payment_paths = vec![];
1308 let mut tlv_stream = invoice.as_tlv_stream();
1309 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1311 match Invoice::try_from(tlv_stream.to_bytes()) {
1312 Ok(_) => panic!("expected error"),
1313 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1316 let mut payment_paths = payment_paths();
1317 payment_paths.pop();
1318 let mut tlv_stream = invoice.as_tlv_stream();
1319 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1321 match Invoice::try_from(tlv_stream.to_bytes()) {
1322 Ok(_) => panic!("expected error"),
1323 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1328 fn parses_invoice_with_created_at() {
1329 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1334 .sign(payer_sign).unwrap()
1335 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1337 .sign(recipient_sign).unwrap();
1339 let mut buffer = Vec::new();
1340 invoice.write(&mut buffer).unwrap();
1342 if let Err(e) = Invoice::try_from(buffer) {
1343 panic!("error parsing invoice: {:?}", e);
1346 let mut tlv_stream = invoice.as_tlv_stream();
1347 tlv_stream.3.created_at = None;
1349 match Invoice::try_from(tlv_stream.to_bytes()) {
1350 Ok(_) => panic!("expected error"),
1352 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1358 fn parses_invoice_with_relative_expiry() {
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()
1366 .relative_expiry(3600)
1368 .sign(recipient_sign).unwrap();
1370 let mut buffer = Vec::new();
1371 invoice.write(&mut buffer).unwrap();
1373 match Invoice::try_from(buffer) {
1374 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1375 Err(e) => panic!("error parsing invoice: {:?}", e),
1380 fn parses_invoice_with_payment_hash() {
1381 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1384 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1386 .sign(payer_sign).unwrap()
1387 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1389 .sign(recipient_sign).unwrap();
1391 let mut buffer = Vec::new();
1392 invoice.write(&mut buffer).unwrap();
1394 if let Err(e) = Invoice::try_from(buffer) {
1395 panic!("error parsing invoice: {:?}", e);
1398 let mut tlv_stream = invoice.as_tlv_stream();
1399 tlv_stream.3.payment_hash = None;
1401 match Invoice::try_from(tlv_stream.to_bytes()) {
1402 Ok(_) => panic!("expected error"),
1404 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1410 fn parses_invoice_with_amount() {
1411 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1414 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1416 .sign(payer_sign).unwrap()
1417 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1419 .sign(recipient_sign).unwrap();
1421 let mut buffer = Vec::new();
1422 invoice.write(&mut buffer).unwrap();
1424 if let Err(e) = Invoice::try_from(buffer) {
1425 panic!("error parsing invoice: {:?}", e);
1428 let mut tlv_stream = invoice.as_tlv_stream();
1429 tlv_stream.3.amount = None;
1431 match Invoice::try_from(tlv_stream.to_bytes()) {
1432 Ok(_) => panic!("expected error"),
1433 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1438 fn parses_invoice_with_allow_mpp() {
1439 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1442 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1444 .sign(payer_sign).unwrap()
1445 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1448 .sign(recipient_sign).unwrap();
1450 let mut buffer = Vec::new();
1451 invoice.write(&mut buffer).unwrap();
1453 match Invoice::try_from(buffer) {
1455 let mut features = Bolt12InvoiceFeatures::empty();
1456 features.set_basic_mpp_optional();
1457 assert_eq!(invoice.features(), &features);
1459 Err(e) => panic!("error parsing invoice: {:?}", e),
1464 fn parses_invoice_with_fallback_address() {
1465 let script = Script::new();
1466 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1467 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1468 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1470 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1473 let invoice_request = offer
1474 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1476 .sign(payer_sign).unwrap();
1477 let mut unsigned_invoice = invoice_request
1478 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1479 .fallback_v0_p2wsh(&script.wscript_hash())
1480 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1481 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1484 // Only standard addresses will be included.
1485 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1486 // Non-standard addresses
1487 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1488 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1489 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1491 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1492 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1494 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1495 let mut buffer = Vec::new();
1496 invoice.write(&mut buffer).unwrap();
1498 match Invoice::try_from(buffer) {
1501 invoice.fallbacks(),
1503 Address::p2wsh(&script, Network::Bitcoin),
1504 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1505 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1507 payload: Payload::WitnessProgram {
1508 version: WitnessVersion::V1,
1509 program: vec![0u8; 33],
1511 network: Network::Bitcoin,
1514 payload: Payload::WitnessProgram {
1515 version: WitnessVersion::V2,
1516 program: vec![0u8; 40],
1518 network: Network::Bitcoin,
1523 Err(e) => panic!("error parsing invoice: {:?}", e),
1528 fn parses_invoice_with_node_id() {
1529 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1532 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534 .sign(payer_sign).unwrap()
1535 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1537 .sign(recipient_sign).unwrap();
1539 let mut buffer = Vec::new();
1540 invoice.write(&mut buffer).unwrap();
1542 if let Err(e) = Invoice::try_from(buffer) {
1543 panic!("error parsing invoice: {:?}", e);
1546 let mut tlv_stream = invoice.as_tlv_stream();
1547 tlv_stream.3.node_id = None;
1549 match Invoice::try_from(tlv_stream.to_bytes()) {
1550 Ok(_) => panic!("expected error"),
1552 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1556 let invalid_pubkey = payer_pubkey();
1557 let mut tlv_stream = invoice.as_tlv_stream();
1558 tlv_stream.3.node_id = Some(&invalid_pubkey);
1560 match Invoice::try_from(tlv_stream.to_bytes()) {
1561 Ok(_) => panic!("expected error"),
1563 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1569 fn fails_parsing_invoice_without_signature() {
1570 let mut buffer = Vec::new();
1571 OfferBuilder::new("foo".into(), recipient_pubkey())
1574 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1576 .sign(payer_sign).unwrap()
1577 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1580 .write(&mut buffer).unwrap();
1582 match Invoice::try_from(buffer) {
1583 Ok(_) => panic!("expected error"),
1584 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1589 fn fails_parsing_invoice_with_invalid_signature() {
1590 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1593 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1595 .sign(payer_sign).unwrap()
1596 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1598 .sign(recipient_sign).unwrap();
1599 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1600 *last_signature_byte = last_signature_byte.wrapping_add(1);
1602 let mut buffer = Vec::new();
1603 invoice.write(&mut buffer).unwrap();
1605 match Invoice::try_from(buffer) {
1606 Ok(_) => panic!("expected error"),
1608 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1614 fn fails_parsing_invoice_with_extra_tlv_records() {
1615 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1618 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620 .sign(payer_sign).unwrap()
1621 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1623 .sign(recipient_sign).unwrap();
1625 let mut encoded_invoice = Vec::new();
1626 invoice.write(&mut encoded_invoice).unwrap();
1627 BigSize(1002).write(&mut encoded_invoice).unwrap();
1628 BigSize(32).write(&mut encoded_invoice).unwrap();
1629 [42u8; 32].write(&mut encoded_invoice).unwrap();
1631 match Invoice::try_from(encoded_invoice) {
1632 Ok(_) => panic!("expected error"),
1633 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),