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};
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::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
119 use crate::prelude::*;
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
132 /// See [module-level documentation] for usage.
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138 invreq_bytes: &'a Vec<u8>,
139 invoice: InvoiceContents,
142 impl<'a> InvoiceBuilder<'a> {
143 pub(super) fn for_offer(
144 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145 created_at: Duration, payment_hash: PaymentHash
146 ) -> Result<Self, SemanticError> {
147 let amount_msats = match invoice_request.amount_msats() {
148 Some(amount_msats) => amount_msats,
149 None => match invoice_request.contents.offer.amount() {
150 Some(Amount::Bitcoin { amount_msats }) => {
151 amount_msats * invoice_request.quantity().unwrap_or(1)
153 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
154 None => return Err(SemanticError::MissingAmount),
158 let contents = InvoiceContents::ForOffer {
159 invoice_request: invoice_request.contents.clone(),
160 fields: InvoiceFields {
161 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
162 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
163 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
167 Self::new(&invoice_request.bytes, contents)
170 pub(super) fn for_refund(
171 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
172 payment_hash: PaymentHash, signing_pubkey: PublicKey
173 ) -> Result<Self, SemanticError> {
174 let contents = InvoiceContents::ForRefund {
175 refund: refund.contents.clone(),
176 fields: InvoiceFields {
177 payment_paths, created_at, relative_expiry: None, payment_hash,
178 amount_msats: refund.amount_msats(), fallbacks: None,
179 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
183 Self::new(&refund.bytes, contents)
186 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
187 if contents.fields().payment_paths.is_empty() {
188 return Err(SemanticError::MissingPaths);
191 Ok(Self { invreq_bytes, invoice: contents })
194 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
195 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
197 /// Successive calls to this method will override the previous setting.
198 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
199 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
200 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
204 /// Adds a P2WSH address to [`Invoice::fallbacks`].
206 /// Successive calls to this method will add another address. Caller is responsible for not
207 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
208 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
209 let address = FallbackAddress {
210 version: WitnessVersion::V0.to_num(),
211 program: Vec::from(&script_hash.into_inner()[..]),
213 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
217 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
219 /// Successive calls to this method will add another address. Caller is responsible for not
220 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
221 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
222 let address = FallbackAddress {
223 version: WitnessVersion::V0.to_num(),
224 program: Vec::from(&pubkey_hash.into_inner()[..]),
226 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
230 /// Adds a P2TR address to [`Invoice::fallbacks`].
232 /// Successive calls to this method will add another address. Caller is responsible for not
233 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
234 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
235 let address = FallbackAddress {
236 version: WitnessVersion::V1.to_num(),
237 program: Vec::from(&output_key.serialize()[..]),
239 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
243 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
244 pub fn allow_mpp(mut self) -> Self {
245 self.invoice.fields_mut().features.set_basic_mpp_optional();
249 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
250 /// [`UnsignedInvoice::sign`].
251 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
252 #[cfg(feature = "std")] {
253 if self.invoice.is_offer_or_refund_expired() {
254 return Err(SemanticError::AlreadyExpired);
258 let InvoiceBuilder { invreq_bytes, invoice } = self;
259 Ok(UnsignedInvoice { invreq_bytes, invoice })
263 /// A semantically valid [`Invoice`] that hasn't been signed.
264 pub struct UnsignedInvoice<'a> {
265 invreq_bytes: &'a Vec<u8>,
266 invoice: InvoiceContents,
269 impl<'a> UnsignedInvoice<'a> {
270 /// Signs the invoice using the given function.
271 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
273 F: FnOnce(&Message) -> Result<Signature, E>
275 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
276 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
278 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
279 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
280 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
282 let mut bytes = Vec::new();
283 unsigned_tlv_stream.write(&mut bytes).unwrap();
285 let pubkey = self.invoice.fields().signing_pubkey;
286 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
288 // Append the signature TLV record to the bytes.
289 let signature_tlv_stream = SignatureTlvStreamRef {
290 signature: Some(&signature),
292 signature_tlv_stream.write(&mut bytes).unwrap();
296 contents: self.invoice,
302 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
304 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
305 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
307 /// [`Offer`]: crate::offers::offer::Offer
308 /// [`Refund`]: crate::offers::refund::Refund
309 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
312 contents: InvoiceContents,
313 signature: Signature,
316 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
318 /// [`Offer`]: crate::offers::offer::Offer
319 /// [`Refund`]: crate::offers::refund::Refund
320 enum InvoiceContents {
321 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
323 /// [`Offer`]: crate::offers::offer::Offer
325 invoice_request: InvoiceRequestContents,
326 fields: InvoiceFields,
328 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
330 /// [`Refund`]: crate::offers::refund::Refund
332 refund: RefundContents,
333 fields: InvoiceFields,
337 /// Invoice-specific fields for an `invoice` message.
338 struct InvoiceFields {
339 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
340 created_at: Duration,
341 relative_expiry: Option<Duration>,
342 payment_hash: PaymentHash,
344 fallbacks: Option<Vec<FallbackAddress>>,
345 features: Bolt12InvoiceFeatures,
346 signing_pubkey: PublicKey,
350 /// Paths to the recipient originating from publicly reachable nodes, including information
351 /// needed for routing payments across them.
353 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
354 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
355 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
356 &self.contents.fields().payment_paths[..]
359 /// Duration since the Unix epoch when the invoice was created.
360 pub fn created_at(&self) -> Duration {
361 self.contents.fields().created_at
364 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
366 pub fn relative_expiry(&self) -> Duration {
367 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
370 /// Whether the invoice has expired.
371 #[cfg(feature = "std")]
372 pub fn is_expired(&self) -> bool {
373 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
374 match absolute_expiry {
375 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
376 Ok(elapsed) => elapsed > seconds_from_epoch,
383 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
384 pub fn payment_hash(&self) -> PaymentHash {
385 self.contents.fields().payment_hash
388 /// The minimum amount required for a successful payment of the invoice.
389 pub fn amount_msats(&self) -> u64 {
390 self.contents.fields().amount_msats
393 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
395 pub fn fallbacks(&self) -> Vec<Address> {
396 let network = match self.network() {
397 None => return Vec::new(),
398 Some(network) => network,
401 let to_valid_address = |address: &FallbackAddress| {
402 let version = match WitnessVersion::try_from(address.version) {
403 Ok(version) => version,
404 Err(_) => return None,
407 let program = &address.program;
408 if program.len() < 2 || program.len() > 40 {
412 let address = Address {
413 payload: Payload::WitnessProgram {
415 program: address.program.clone(),
420 if !address.is_standard() && version == WitnessVersion::V0 {
427 self.contents.fields().fallbacks
429 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
430 .unwrap_or_else(Vec::new)
433 fn network(&self) -> Option<Network> {
434 let chain = self.contents.chain();
435 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
436 Some(Network::Bitcoin)
437 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
438 Some(Network::Testnet)
439 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
440 Some(Network::Signet)
441 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
442 Some(Network::Regtest)
448 /// Features pertaining to paying an invoice.
449 pub fn features(&self) -> &Bolt12InvoiceFeatures {
450 &self.contents.fields().features
453 /// The public key used to sign invoices.
454 pub fn signing_pubkey(&self) -> PublicKey {
455 self.contents.fields().signing_pubkey
458 /// Signature of the invoice using [`Invoice::signing_pubkey`].
459 pub fn signature(&self) -> Signature {
464 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
465 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
466 self.contents.as_tlv_stream();
467 let signature_tlv_stream = SignatureTlvStreamRef {
468 signature: Some(&self.signature),
470 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
471 signature_tlv_stream)
475 impl InvoiceContents {
476 /// Whether the original offer or refund has expired.
477 #[cfg(feature = "std")]
478 fn is_offer_or_refund_expired(&self) -> bool {
480 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
481 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
485 fn chain(&self) -> ChainHash {
487 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
488 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
492 fn fields(&self) -> &InvoiceFields {
494 InvoiceContents::ForOffer { fields, .. } => fields,
495 InvoiceContents::ForRefund { fields, .. } => fields,
499 fn fields_mut(&mut self) -> &mut InvoiceFields {
501 InvoiceContents::ForOffer { fields, .. } => fields,
502 InvoiceContents::ForRefund { fields, .. } => fields,
506 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
507 let (payer, offer, invoice_request) = match self {
508 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
509 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
511 let invoice = self.fields().as_tlv_stream();
513 (payer, offer, invoice_request, invoice)
518 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
520 if self.features == Bolt12InvoiceFeatures::empty() { None }
521 else { Some(&self.features) }
524 InvoiceTlvStreamRef {
525 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
526 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
527 created_at: Some(self.created_at.as_secs()),
528 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
529 payment_hash: Some(&self.payment_hash),
530 amount: Some(self.amount_msats),
531 fallbacks: self.fallbacks.as_ref(),
533 node_id: Some(&self.signing_pubkey),
538 impl Writeable for Invoice {
539 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
540 WithoutLength(&self.bytes).write(writer)
544 impl Writeable for InvoiceContents {
545 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
546 self.as_tlv_stream().write(writer)
550 impl TryFrom<Vec<u8>> for Invoice {
551 type Error = ParseError;
553 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
554 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
555 Invoice::try_from(parsed_invoice)
559 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
560 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
561 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
562 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
563 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
564 (168, payment_hash: PaymentHash),
565 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
566 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
567 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
568 (176, node_id: PublicKey),
571 type BlindedPathIter<'a> = core::iter::Map<
572 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
573 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
576 type BlindedPayInfoIter<'a> = core::iter::Map<
577 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
578 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
581 /// Information needed to route a payment across a [`BlindedPath`].
582 #[derive(Clone, Debug, PartialEq)]
583 pub struct BlindedPayInfo {
584 /// Base fee charged (in millisatoshi) for the entire blinded path.
585 pub fee_base_msat: u32,
587 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
588 /// (i.e., 10,000 is 1%).
589 pub fee_proportional_millionths: u32,
591 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
593 pub cltv_expiry_delta: u16,
595 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
596 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
597 /// seen by the recipient.
598 pub htlc_minimum_msat: u64,
600 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
601 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
602 /// seen by the recipient.
603 pub htlc_maximum_msat: u64,
605 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
607 pub features: BlindedHopFeatures,
610 impl_writeable!(BlindedPayInfo, {
612 fee_proportional_millionths,
619 /// Wire representation for an on-chain fallback address.
620 #[derive(Clone, Debug, PartialEq)]
621 pub(super) struct FallbackAddress {
626 impl_writeable!(FallbackAddress, { version, program });
628 type FullInvoiceTlvStream =
629 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
632 type FullInvoiceTlvStreamRef<'a> = (
633 PayerTlvStreamRef<'a>,
634 OfferTlvStreamRef<'a>,
635 InvoiceRequestTlvStreamRef<'a>,
636 InvoiceTlvStreamRef<'a>,
637 SignatureTlvStreamRef<'a>,
640 impl SeekReadable for FullInvoiceTlvStream {
641 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
642 let payer = SeekReadable::read(r)?;
643 let offer = SeekReadable::read(r)?;
644 let invoice_request = SeekReadable::read(r)?;
645 let invoice = SeekReadable::read(r)?;
646 let signature = SeekReadable::read(r)?;
648 Ok((payer, offer, invoice_request, invoice, signature))
652 type PartialInvoiceTlvStream =
653 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
655 type PartialInvoiceTlvStreamRef<'a> = (
656 PayerTlvStreamRef<'a>,
657 OfferTlvStreamRef<'a>,
658 InvoiceRequestTlvStreamRef<'a>,
659 InvoiceTlvStreamRef<'a>,
662 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
663 type Error = ParseError;
665 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
666 let ParsedMessage { bytes, tlv_stream } = invoice;
668 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
669 SignatureTlvStream { signature },
671 let contents = InvoiceContents::try_from(
672 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
675 let signature = match signature {
676 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
677 Some(signature) => signature,
679 let pubkey = contents.fields().signing_pubkey;
680 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
682 Ok(Invoice { bytes, contents, signature })
686 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
687 type Error = SemanticError;
689 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
693 invoice_request_tlv_stream,
695 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
700 let payment_paths = match (paths, blindedpay) {
701 (None, _) => return Err(SemanticError::MissingPaths),
702 (_, None) => return Err(SemanticError::InvalidPayInfo),
703 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
704 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
705 return Err(SemanticError::InvalidPayInfo);
707 (Some(paths), Some(blindedpay)) => {
708 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
712 let created_at = match created_at {
713 None => return Err(SemanticError::MissingCreationTime),
714 Some(timestamp) => Duration::from_secs(timestamp),
717 let relative_expiry = relative_expiry
718 .map(Into::<u64>::into)
719 .map(Duration::from_secs);
721 let payment_hash = match payment_hash {
722 None => return Err(SemanticError::MissingPaymentHash),
723 Some(payment_hash) => payment_hash,
726 let amount_msats = match amount {
727 None => return Err(SemanticError::MissingAmount),
728 Some(amount) => amount,
731 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
733 let signing_pubkey = match node_id {
734 None => return Err(SemanticError::MissingSigningPubkey),
735 Some(node_id) => node_id,
738 let fields = InvoiceFields {
739 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
740 features, signing_pubkey,
743 match offer_tlv_stream.node_id {
744 Some(expected_signing_pubkey) => {
745 if fields.signing_pubkey != expected_signing_pubkey {
746 return Err(SemanticError::InvalidSigningPubkey);
749 let invoice_request = InvoiceRequestContents::try_from(
750 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
752 Ok(InvoiceContents::ForOffer { invoice_request, fields })
755 let refund = RefundContents::try_from(
756 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
758 Ok(InvoiceContents::ForRefund { refund, fields })
766 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
768 use bitcoin::blockdata::script::Script;
769 use bitcoin::hashes::Hash;
770 use bitcoin::network::constants::Network;
771 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
772 use bitcoin::secp256k1::schnorr::Signature;
773 use bitcoin::util::address::{Address, Payload, WitnessVersion};
774 use bitcoin::util::schnorr::TweakedPublicKey;
775 use core::convert::{Infallible, TryFrom};
776 use core::time::Duration;
777 use crate::ln::PaymentHash;
778 use crate::ln::msgs::DecodeError;
779 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
780 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
781 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
782 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
783 use crate::offers::parse::{ParseError, SemanticError};
784 use crate::offers::payer::PayerTlvStreamRef;
785 use crate::offers::refund::RefundBuilder;
786 use crate::onion_message::{BlindedHop, BlindedPath};
787 use crate::util::ser::{BigSize, Iterable, Writeable};
789 fn payer_keys() -> KeyPair {
790 let secp_ctx = Secp256k1::new();
791 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
794 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
795 let secp_ctx = Secp256k1::new();
796 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
797 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
800 fn payer_pubkey() -> PublicKey {
801 payer_keys().public_key()
804 fn recipient_keys() -> KeyPair {
805 let secp_ctx = Secp256k1::new();
806 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
809 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
810 let secp_ctx = Secp256k1::new();
811 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
812 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
815 fn recipient_pubkey() -> PublicKey {
816 recipient_keys().public_key()
819 fn pubkey(byte: u8) -> PublicKey {
820 let secp_ctx = Secp256k1::new();
821 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
824 fn privkey(byte: u8) -> SecretKey {
825 SecretKey::from_slice(&[byte; 32]).unwrap()
829 fn to_bytes(&self) -> Vec<u8>;
832 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
833 fn to_bytes(&self) -> Vec<u8> {
834 let mut buffer = Vec::new();
835 self.0.write(&mut buffer).unwrap();
836 self.1.write(&mut buffer).unwrap();
837 self.2.write(&mut buffer).unwrap();
838 self.3.write(&mut buffer).unwrap();
839 self.4.write(&mut buffer).unwrap();
844 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
847 introduction_node_id: pubkey(40),
848 blinding_point: pubkey(41),
850 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
851 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
855 introduction_node_id: pubkey(40),
856 blinding_point: pubkey(41),
858 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
859 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
867 fee_proportional_millionths: 1_000,
868 cltv_expiry_delta: 42,
869 htlc_minimum_msat: 100,
870 htlc_maximum_msat: 1_000_000_000_000,
871 features: BlindedHopFeatures::empty(),
875 fee_proportional_millionths: 1_000,
876 cltv_expiry_delta: 42,
877 htlc_minimum_msat: 100,
878 htlc_maximum_msat: 1_000_000_000_000,
879 features: BlindedHopFeatures::empty(),
883 paths.into_iter().zip(payinfo.into_iter()).collect()
886 fn payment_hash() -> PaymentHash {
887 PaymentHash([42; 32])
890 fn now() -> Duration {
891 std::time::SystemTime::now()
892 .duration_since(std::time::SystemTime::UNIX_EPOCH)
893 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
897 fn builds_invoice_for_offer_with_defaults() {
898 let payment_paths = payment_paths();
899 let payment_hash = payment_hash();
901 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
904 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
906 .sign(payer_sign).unwrap()
907 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
909 .sign(recipient_sign).unwrap();
911 let mut buffer = Vec::new();
912 invoice.write(&mut buffer).unwrap();
914 assert_eq!(invoice.bytes, buffer.as_slice());
915 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
916 assert_eq!(invoice.created_at(), now);
917 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
918 #[cfg(feature = "std")]
919 assert!(!invoice.is_expired());
920 assert_eq!(invoice.payment_hash(), payment_hash);
921 assert_eq!(invoice.amount_msats(), 1000);
922 assert_eq!(invoice.fallbacks(), vec![]);
923 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
924 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
926 merkle::verify_signature(
927 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
932 invoice.as_tlv_stream(),
934 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
940 description: Some(&String::from("foo")),
942 absolute_expiry: None,
946 node_id: Some(&recipient_pubkey()),
948 InvoiceRequestTlvStreamRef {
953 payer_id: Some(&payer_pubkey()),
956 InvoiceTlvStreamRef {
957 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
958 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
959 created_at: Some(now.as_secs()),
960 relative_expiry: None,
961 payment_hash: Some(&payment_hash),
965 node_id: Some(&recipient_pubkey()),
967 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
971 if let Err(e) = Invoice::try_from(buffer) {
972 panic!("error parsing invoice: {:?}", e);
977 fn builds_invoice_for_refund_with_defaults() {
978 let payment_paths = payment_paths();
979 let payment_hash = payment_hash();
981 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
983 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
986 .sign(recipient_sign).unwrap();
988 let mut buffer = Vec::new();
989 invoice.write(&mut buffer).unwrap();
991 assert_eq!(invoice.bytes, buffer.as_slice());
992 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
993 assert_eq!(invoice.created_at(), now);
994 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
995 #[cfg(feature = "std")]
996 assert!(!invoice.is_expired());
997 assert_eq!(invoice.payment_hash(), payment_hash);
998 assert_eq!(invoice.amount_msats(), 1000);
999 assert_eq!(invoice.fallbacks(), vec![]);
1000 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1001 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1003 merkle::verify_signature(
1004 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1009 invoice.as_tlv_stream(),
1011 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1017 description: Some(&String::from("foo")),
1019 absolute_expiry: None,
1025 InvoiceRequestTlvStreamRef {
1030 payer_id: Some(&payer_pubkey()),
1033 InvoiceTlvStreamRef {
1034 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1035 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1036 created_at: Some(now.as_secs()),
1037 relative_expiry: None,
1038 payment_hash: Some(&payment_hash),
1042 node_id: Some(&recipient_pubkey()),
1044 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1048 if let Err(e) = Invoice::try_from(buffer) {
1049 panic!("error parsing invoice: {:?}", e);
1053 #[cfg(feature = "std")]
1055 fn builds_invoice_from_offer_with_expiration() {
1056 let future_expiry = Duration::from_secs(u64::max_value());
1057 let past_expiry = Duration::from_secs(0);
1059 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1061 .absolute_expiry(future_expiry)
1063 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1065 .sign(payer_sign).unwrap()
1066 .respond_with(payment_paths(), payment_hash())
1070 panic!("error building invoice: {:?}", e);
1073 match OfferBuilder::new("foo".into(), recipient_pubkey())
1075 .absolute_expiry(past_expiry)
1077 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1079 .sign(payer_sign).unwrap()
1080 .respond_with(payment_paths(), payment_hash())
1084 Ok(_) => panic!("expected error"),
1085 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1089 #[cfg(feature = "std")]
1091 fn builds_invoice_from_refund_with_expiration() {
1092 let future_expiry = Duration::from_secs(u64::max_value());
1093 let past_expiry = Duration::from_secs(0);
1095 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1096 .absolute_expiry(future_expiry)
1098 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1102 panic!("error building invoice: {:?}", e);
1105 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1106 .absolute_expiry(past_expiry)
1108 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1112 Ok(_) => panic!("expected error"),
1113 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1118 fn builds_invoice_with_relative_expiry() {
1120 let one_hour = Duration::from_secs(3600);
1122 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1125 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1127 .sign(payer_sign).unwrap()
1128 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1129 .relative_expiry(one_hour.as_secs() as u32)
1131 .sign(recipient_sign).unwrap();
1132 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1133 #[cfg(feature = "std")]
1134 assert!(!invoice.is_expired());
1135 assert_eq!(invoice.relative_expiry(), one_hour);
1136 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1138 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1143 .sign(payer_sign).unwrap()
1144 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1145 .relative_expiry(one_hour.as_secs() as u32 - 1)
1147 .sign(recipient_sign).unwrap();
1148 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1149 #[cfg(feature = "std")]
1150 assert!(invoice.is_expired());
1151 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1152 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1156 fn builds_invoice_with_amount_from_request() {
1157 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1160 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1161 .amount_msats(1001).unwrap()
1163 .sign(payer_sign).unwrap()
1164 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1166 .sign(recipient_sign).unwrap();
1167 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1168 assert_eq!(invoice.amount_msats(), 1001);
1169 assert_eq!(tlv_stream.amount, Some(1001));
1173 fn builds_invoice_with_fallback_address() {
1174 let script = Script::new();
1175 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1176 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1177 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1179 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1182 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1184 .sign(payer_sign).unwrap()
1185 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1186 .fallback_v0_p2wsh(&script.wscript_hash())
1187 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1188 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1190 .sign(recipient_sign).unwrap();
1191 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1193 invoice.fallbacks(),
1195 Address::p2wsh(&script, Network::Bitcoin),
1196 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1197 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1201 tlv_stream.fallbacks,
1204 version: WitnessVersion::V0.to_num(),
1205 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1208 version: WitnessVersion::V0.to_num(),
1209 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1212 version: WitnessVersion::V1.to_num(),
1213 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1220 fn builds_invoice_with_allow_mpp() {
1221 let mut features = Bolt12InvoiceFeatures::empty();
1222 features.set_basic_mpp_optional();
1224 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1227 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229 .sign(payer_sign).unwrap()
1230 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1233 .sign(recipient_sign).unwrap();
1234 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1235 assert_eq!(invoice.features(), &features);
1236 assert_eq!(tlv_stream.features, Some(&features));
1240 fn fails_signing_invoice() {
1241 match OfferBuilder::new("foo".into(), recipient_pubkey())
1244 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1246 .sign(payer_sign).unwrap()
1247 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1251 Ok(_) => panic!("expected error"),
1252 Err(e) => assert_eq!(e, SignError::Signing(())),
1255 match OfferBuilder::new("foo".into(), recipient_pubkey())
1258 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1260 .sign(payer_sign).unwrap()
1261 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1265 Ok(_) => panic!("expected error"),
1266 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1271 fn parses_invoice_with_payment_paths() {
1272 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1275 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1277 .sign(payer_sign).unwrap()
1278 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1280 .sign(recipient_sign).unwrap();
1282 let mut buffer = Vec::new();
1283 invoice.write(&mut buffer).unwrap();
1285 if let Err(e) = Invoice::try_from(buffer) {
1286 panic!("error parsing invoice: {:?}", e);
1289 let mut tlv_stream = invoice.as_tlv_stream();
1290 tlv_stream.3.paths = None;
1292 match Invoice::try_from(tlv_stream.to_bytes()) {
1293 Ok(_) => panic!("expected error"),
1294 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1297 let mut tlv_stream = invoice.as_tlv_stream();
1298 tlv_stream.3.blindedpay = None;
1300 match Invoice::try_from(tlv_stream.to_bytes()) {
1301 Ok(_) => panic!("expected error"),
1302 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1305 let empty_payment_paths = vec![];
1306 let mut tlv_stream = invoice.as_tlv_stream();
1307 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1309 match Invoice::try_from(tlv_stream.to_bytes()) {
1310 Ok(_) => panic!("expected error"),
1311 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1314 let mut payment_paths = payment_paths();
1315 payment_paths.pop();
1316 let mut tlv_stream = invoice.as_tlv_stream();
1317 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1319 match Invoice::try_from(tlv_stream.to_bytes()) {
1320 Ok(_) => panic!("expected error"),
1321 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1326 fn parses_invoice_with_created_at() {
1327 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1330 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1332 .sign(payer_sign).unwrap()
1333 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1335 .sign(recipient_sign).unwrap();
1337 let mut buffer = Vec::new();
1338 invoice.write(&mut buffer).unwrap();
1340 if let Err(e) = Invoice::try_from(buffer) {
1341 panic!("error parsing invoice: {:?}", e);
1344 let mut tlv_stream = invoice.as_tlv_stream();
1345 tlv_stream.3.created_at = None;
1347 match Invoice::try_from(tlv_stream.to_bytes()) {
1348 Ok(_) => panic!("expected error"),
1350 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1356 fn parses_invoice_with_relative_expiry() {
1357 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1360 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1362 .sign(payer_sign).unwrap()
1363 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1364 .relative_expiry(3600)
1366 .sign(recipient_sign).unwrap();
1368 let mut buffer = Vec::new();
1369 invoice.write(&mut buffer).unwrap();
1371 match Invoice::try_from(buffer) {
1372 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1373 Err(e) => panic!("error parsing invoice: {:?}", e),
1378 fn parses_invoice_with_payment_hash() {
1379 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1382 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1384 .sign(payer_sign).unwrap()
1385 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1387 .sign(recipient_sign).unwrap();
1389 let mut buffer = Vec::new();
1390 invoice.write(&mut buffer).unwrap();
1392 if let Err(e) = Invoice::try_from(buffer) {
1393 panic!("error parsing invoice: {:?}", e);
1396 let mut tlv_stream = invoice.as_tlv_stream();
1397 tlv_stream.3.payment_hash = None;
1399 match Invoice::try_from(tlv_stream.to_bytes()) {
1400 Ok(_) => panic!("expected error"),
1402 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1408 fn parses_invoice_with_amount() {
1409 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1412 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1414 .sign(payer_sign).unwrap()
1415 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1417 .sign(recipient_sign).unwrap();
1419 let mut buffer = Vec::new();
1420 invoice.write(&mut buffer).unwrap();
1422 if let Err(e) = Invoice::try_from(buffer) {
1423 panic!("error parsing invoice: {:?}", e);
1426 let mut tlv_stream = invoice.as_tlv_stream();
1427 tlv_stream.3.amount = None;
1429 match Invoice::try_from(tlv_stream.to_bytes()) {
1430 Ok(_) => panic!("expected error"),
1431 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1436 fn parses_invoice_with_allow_mpp() {
1437 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1440 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442 .sign(payer_sign).unwrap()
1443 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1446 .sign(recipient_sign).unwrap();
1448 let mut buffer = Vec::new();
1449 invoice.write(&mut buffer).unwrap();
1451 match Invoice::try_from(buffer) {
1453 let mut features = Bolt12InvoiceFeatures::empty();
1454 features.set_basic_mpp_optional();
1455 assert_eq!(invoice.features(), &features);
1457 Err(e) => panic!("error parsing invoice: {:?}", e),
1462 fn parses_invoice_with_fallback_address() {
1463 let script = Script::new();
1464 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1465 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1466 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1468 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1471 let invoice_request = offer
1472 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1474 .sign(payer_sign).unwrap();
1475 let mut unsigned_invoice = invoice_request
1476 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1477 .fallback_v0_p2wsh(&script.wscript_hash())
1478 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1479 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1482 // Only standard addresses will be included.
1483 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1484 // Non-standard addresses
1485 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1486 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1487 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1489 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1490 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1492 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1493 let mut buffer = Vec::new();
1494 invoice.write(&mut buffer).unwrap();
1496 match Invoice::try_from(buffer) {
1499 invoice.fallbacks(),
1501 Address::p2wsh(&script, Network::Bitcoin),
1502 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1503 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1505 payload: Payload::WitnessProgram {
1506 version: WitnessVersion::V1,
1507 program: vec![0u8; 33],
1509 network: Network::Bitcoin,
1512 payload: Payload::WitnessProgram {
1513 version: WitnessVersion::V2,
1514 program: vec![0u8; 40],
1516 network: Network::Bitcoin,
1521 Err(e) => panic!("error parsing invoice: {:?}", e),
1526 fn parses_invoice_with_node_id() {
1527 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1532 .sign(payer_sign).unwrap()
1533 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1535 .sign(recipient_sign).unwrap();
1537 let mut buffer = Vec::new();
1538 invoice.write(&mut buffer).unwrap();
1540 if let Err(e) = Invoice::try_from(buffer) {
1541 panic!("error parsing invoice: {:?}", e);
1544 let mut tlv_stream = invoice.as_tlv_stream();
1545 tlv_stream.3.node_id = None;
1547 match Invoice::try_from(tlv_stream.to_bytes()) {
1548 Ok(_) => panic!("expected error"),
1550 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1554 let invalid_pubkey = payer_pubkey();
1555 let mut tlv_stream = invoice.as_tlv_stream();
1556 tlv_stream.3.node_id = Some(&invalid_pubkey);
1558 match Invoice::try_from(tlv_stream.to_bytes()) {
1559 Ok(_) => panic!("expected error"),
1561 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1567 fn fails_parsing_invoice_without_signature() {
1568 let mut buffer = Vec::new();
1569 OfferBuilder::new("foo".into(), recipient_pubkey())
1572 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1574 .sign(payer_sign).unwrap()
1575 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1578 .write(&mut buffer).unwrap();
1580 match Invoice::try_from(buffer) {
1581 Ok(_) => panic!("expected error"),
1582 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1587 fn fails_parsing_invoice_with_invalid_signature() {
1588 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1591 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1593 .sign(payer_sign).unwrap()
1594 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1596 .sign(recipient_sign).unwrap();
1597 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1598 *last_signature_byte = last_signature_byte.wrapping_add(1);
1600 let mut buffer = Vec::new();
1601 invoice.write(&mut buffer).unwrap();
1603 match Invoice::try_from(buffer) {
1604 Ok(_) => panic!("expected error"),
1606 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1612 fn fails_parsing_invoice_with_extra_tlv_records() {
1613 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1616 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1618 .sign(payer_sign).unwrap()
1619 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1621 .sign(recipient_sign).unwrap();
1623 let mut encoded_invoice = Vec::new();
1624 invoice.write(&mut encoded_invoice).unwrap();
1625 BigSize(1002).write(&mut encoded_invoice).unwrap();
1626 BigSize(32).write(&mut encoded_invoice).unwrap();
1627 [42u8; 32].write(&mut encoded_invoice).unwrap();
1629 match Invoice::try_from(encoded_invoice) {
1630 Ok(_) => panic!("expected error"),
1631 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),