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 {
585 fee_proportional_millionths: u32,
586 cltv_expiry_delta: u16,
587 htlc_minimum_msat: u64,
588 htlc_maximum_msat: u64,
589 features: BlindedHopFeatures,
592 impl_writeable!(BlindedPayInfo, {
594 fee_proportional_millionths,
601 /// Wire representation for an on-chain fallback address.
602 #[derive(Clone, Debug, PartialEq)]
603 pub(super) struct FallbackAddress {
608 impl_writeable!(FallbackAddress, { version, program });
610 type FullInvoiceTlvStream =
611 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
614 type FullInvoiceTlvStreamRef<'a> = (
615 PayerTlvStreamRef<'a>,
616 OfferTlvStreamRef<'a>,
617 InvoiceRequestTlvStreamRef<'a>,
618 InvoiceTlvStreamRef<'a>,
619 SignatureTlvStreamRef<'a>,
622 impl SeekReadable for FullInvoiceTlvStream {
623 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
624 let payer = SeekReadable::read(r)?;
625 let offer = SeekReadable::read(r)?;
626 let invoice_request = SeekReadable::read(r)?;
627 let invoice = SeekReadable::read(r)?;
628 let signature = SeekReadable::read(r)?;
630 Ok((payer, offer, invoice_request, invoice, signature))
634 type PartialInvoiceTlvStream =
635 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
637 type PartialInvoiceTlvStreamRef<'a> = (
638 PayerTlvStreamRef<'a>,
639 OfferTlvStreamRef<'a>,
640 InvoiceRequestTlvStreamRef<'a>,
641 InvoiceTlvStreamRef<'a>,
644 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
645 type Error = ParseError;
647 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
648 let ParsedMessage { bytes, tlv_stream } = invoice;
650 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
651 SignatureTlvStream { signature },
653 let contents = InvoiceContents::try_from(
654 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
657 let signature = match signature {
658 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
659 Some(signature) => signature,
661 let pubkey = contents.fields().signing_pubkey;
662 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
664 Ok(Invoice { bytes, contents, signature })
668 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
669 type Error = SemanticError;
671 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
675 invoice_request_tlv_stream,
677 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
682 let payment_paths = match (paths, blindedpay) {
683 (None, _) => return Err(SemanticError::MissingPaths),
684 (_, None) => return Err(SemanticError::InvalidPayInfo),
685 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
686 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
687 return Err(SemanticError::InvalidPayInfo);
689 (Some(paths), Some(blindedpay)) => {
690 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
694 let created_at = match created_at {
695 None => return Err(SemanticError::MissingCreationTime),
696 Some(timestamp) => Duration::from_secs(timestamp),
699 let relative_expiry = relative_expiry
700 .map(Into::<u64>::into)
701 .map(Duration::from_secs);
703 let payment_hash = match payment_hash {
704 None => return Err(SemanticError::MissingPaymentHash),
705 Some(payment_hash) => payment_hash,
708 let amount_msats = match amount {
709 None => return Err(SemanticError::MissingAmount),
710 Some(amount) => amount,
713 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
715 let signing_pubkey = match node_id {
716 None => return Err(SemanticError::MissingSigningPubkey),
717 Some(node_id) => node_id,
720 let fields = InvoiceFields {
721 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
722 features, signing_pubkey,
725 match offer_tlv_stream.node_id {
726 Some(expected_signing_pubkey) => {
727 if fields.signing_pubkey != expected_signing_pubkey {
728 return Err(SemanticError::InvalidSigningPubkey);
731 let invoice_request = InvoiceRequestContents::try_from(
732 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
734 Ok(InvoiceContents::ForOffer { invoice_request, fields })
737 let refund = RefundContents::try_from(
738 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
740 Ok(InvoiceContents::ForRefund { refund, fields })
748 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
750 use bitcoin::blockdata::script::Script;
751 use bitcoin::hashes::Hash;
752 use bitcoin::network::constants::Network;
753 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
754 use bitcoin::secp256k1::schnorr::Signature;
755 use bitcoin::util::address::{Address, Payload, WitnessVersion};
756 use bitcoin::util::schnorr::TweakedPublicKey;
757 use core::convert::{Infallible, TryFrom};
758 use core::time::Duration;
759 use crate::ln::PaymentHash;
760 use crate::ln::msgs::DecodeError;
761 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
762 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
763 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
764 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
765 use crate::offers::parse::{ParseError, SemanticError};
766 use crate::offers::payer::PayerTlvStreamRef;
767 use crate::offers::refund::RefundBuilder;
768 use crate::onion_message::{BlindedHop, BlindedPath};
769 use crate::util::ser::{BigSize, Iterable, Writeable};
771 fn payer_keys() -> KeyPair {
772 let secp_ctx = Secp256k1::new();
773 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
776 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
777 let secp_ctx = Secp256k1::new();
778 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
779 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
782 fn payer_pubkey() -> PublicKey {
783 payer_keys().public_key()
786 fn recipient_keys() -> KeyPair {
787 let secp_ctx = Secp256k1::new();
788 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
791 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
792 let secp_ctx = Secp256k1::new();
793 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
794 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
797 fn recipient_pubkey() -> PublicKey {
798 recipient_keys().public_key()
801 fn pubkey(byte: u8) -> PublicKey {
802 let secp_ctx = Secp256k1::new();
803 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
806 fn privkey(byte: u8) -> SecretKey {
807 SecretKey::from_slice(&[byte; 32]).unwrap()
811 fn to_bytes(&self) -> Vec<u8>;
814 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
815 fn to_bytes(&self) -> Vec<u8> {
816 let mut buffer = Vec::new();
817 self.0.write(&mut buffer).unwrap();
818 self.1.write(&mut buffer).unwrap();
819 self.2.write(&mut buffer).unwrap();
820 self.3.write(&mut buffer).unwrap();
821 self.4.write(&mut buffer).unwrap();
826 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
829 introduction_node_id: pubkey(40),
830 blinding_point: pubkey(41),
832 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
833 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
837 introduction_node_id: pubkey(40),
838 blinding_point: pubkey(41),
840 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
841 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
849 fee_proportional_millionths: 1_000,
850 cltv_expiry_delta: 42,
851 htlc_minimum_msat: 100,
852 htlc_maximum_msat: 1_000_000_000_000,
853 features: BlindedHopFeatures::empty(),
857 fee_proportional_millionths: 1_000,
858 cltv_expiry_delta: 42,
859 htlc_minimum_msat: 100,
860 htlc_maximum_msat: 1_000_000_000_000,
861 features: BlindedHopFeatures::empty(),
865 paths.into_iter().zip(payinfo.into_iter()).collect()
868 fn payment_hash() -> PaymentHash {
869 PaymentHash([42; 32])
872 fn now() -> Duration {
873 std::time::SystemTime::now()
874 .duration_since(std::time::SystemTime::UNIX_EPOCH)
875 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
879 fn builds_invoice_for_offer_with_defaults() {
880 let payment_paths = payment_paths();
881 let payment_hash = payment_hash();
883 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
886 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
888 .sign(payer_sign).unwrap()
889 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
891 .sign(recipient_sign).unwrap();
893 let mut buffer = Vec::new();
894 invoice.write(&mut buffer).unwrap();
896 assert_eq!(invoice.bytes, buffer.as_slice());
897 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
898 assert_eq!(invoice.created_at(), now);
899 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
900 #[cfg(feature = "std")]
901 assert!(!invoice.is_expired());
902 assert_eq!(invoice.payment_hash(), payment_hash);
903 assert_eq!(invoice.amount_msats(), 1000);
904 assert_eq!(invoice.fallbacks(), vec![]);
905 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
906 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
908 merkle::verify_signature(
909 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
914 invoice.as_tlv_stream(),
916 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
922 description: Some(&String::from("foo")),
924 absolute_expiry: None,
928 node_id: Some(&recipient_pubkey()),
930 InvoiceRequestTlvStreamRef {
935 payer_id: Some(&payer_pubkey()),
938 InvoiceTlvStreamRef {
939 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
940 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
941 created_at: Some(now.as_secs()),
942 relative_expiry: None,
943 payment_hash: Some(&payment_hash),
947 node_id: Some(&recipient_pubkey()),
949 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
953 if let Err(e) = Invoice::try_from(buffer) {
954 panic!("error parsing invoice: {:?}", e);
959 fn builds_invoice_for_refund_with_defaults() {
960 let payment_paths = payment_paths();
961 let payment_hash = payment_hash();
963 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
965 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
968 .sign(recipient_sign).unwrap();
970 let mut buffer = Vec::new();
971 invoice.write(&mut buffer).unwrap();
973 assert_eq!(invoice.bytes, buffer.as_slice());
974 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
975 assert_eq!(invoice.created_at(), now);
976 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
977 #[cfg(feature = "std")]
978 assert!(!invoice.is_expired());
979 assert_eq!(invoice.payment_hash(), payment_hash);
980 assert_eq!(invoice.amount_msats(), 1000);
981 assert_eq!(invoice.fallbacks(), vec![]);
982 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
983 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
985 merkle::verify_signature(
986 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
991 invoice.as_tlv_stream(),
993 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
999 description: Some(&String::from("foo")),
1001 absolute_expiry: None,
1007 InvoiceRequestTlvStreamRef {
1012 payer_id: Some(&payer_pubkey()),
1015 InvoiceTlvStreamRef {
1016 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1017 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1018 created_at: Some(now.as_secs()),
1019 relative_expiry: None,
1020 payment_hash: Some(&payment_hash),
1024 node_id: Some(&recipient_pubkey()),
1026 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1030 if let Err(e) = Invoice::try_from(buffer) {
1031 panic!("error parsing invoice: {:?}", e);
1035 #[cfg(feature = "std")]
1037 fn builds_invoice_from_refund_with_expiration() {
1038 let future_expiry = Duration::from_secs(u64::max_value());
1039 let past_expiry = Duration::from_secs(0);
1041 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1042 .absolute_expiry(future_expiry)
1044 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1048 panic!("error building invoice: {:?}", e);
1051 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1052 .absolute_expiry(past_expiry)
1054 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1058 Ok(_) => panic!("expected error"),
1059 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1064 fn builds_invoice_with_relative_expiry() {
1066 let one_hour = Duration::from_secs(3600);
1068 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1071 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 .sign(payer_sign).unwrap()
1074 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1075 .relative_expiry(one_hour.as_secs() as u32)
1077 .sign(recipient_sign).unwrap();
1078 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1079 #[cfg(feature = "std")]
1080 assert!(!invoice.is_expired());
1081 assert_eq!(invoice.relative_expiry(), one_hour);
1082 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1084 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1087 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1089 .sign(payer_sign).unwrap()
1090 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1091 .relative_expiry(one_hour.as_secs() as u32 - 1)
1093 .sign(recipient_sign).unwrap();
1094 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1095 #[cfg(feature = "std")]
1096 assert!(invoice.is_expired());
1097 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1098 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1102 fn builds_invoice_with_amount_from_request() {
1103 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1106 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1107 .amount_msats(1001).unwrap()
1109 .sign(payer_sign).unwrap()
1110 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1112 .sign(recipient_sign).unwrap();
1113 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1114 assert_eq!(invoice.amount_msats(), 1001);
1115 assert_eq!(tlv_stream.amount, Some(1001));
1119 fn builds_invoice_with_fallback_address() {
1120 let script = Script::new();
1121 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1122 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1123 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1125 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1128 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1130 .sign(payer_sign).unwrap()
1131 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1132 .fallback_v0_p2wsh(&script.wscript_hash())
1133 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1134 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1136 .sign(recipient_sign).unwrap();
1137 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1139 invoice.fallbacks(),
1141 Address::p2wsh(&script, Network::Bitcoin),
1142 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1143 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1147 tlv_stream.fallbacks,
1150 version: WitnessVersion::V0.to_num(),
1151 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1154 version: WitnessVersion::V0.to_num(),
1155 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1158 version: WitnessVersion::V1.to_num(),
1159 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1166 fn builds_invoice_with_allow_mpp() {
1167 let mut features = Bolt12InvoiceFeatures::empty();
1168 features.set_basic_mpp_optional();
1170 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1173 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1175 .sign(payer_sign).unwrap()
1176 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1179 .sign(recipient_sign).unwrap();
1180 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1181 assert_eq!(invoice.features(), &features);
1182 assert_eq!(tlv_stream.features, Some(&features));
1186 fn fails_signing_invoice() {
1187 match OfferBuilder::new("foo".into(), recipient_pubkey())
1190 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1192 .sign(payer_sign).unwrap()
1193 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1197 Ok(_) => panic!("expected error"),
1198 Err(e) => assert_eq!(e, SignError::Signing(())),
1201 match OfferBuilder::new("foo".into(), recipient_pubkey())
1204 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1206 .sign(payer_sign).unwrap()
1207 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1211 Ok(_) => panic!("expected error"),
1212 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1217 fn parses_invoice_with_payment_paths() {
1218 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1221 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1223 .sign(payer_sign).unwrap()
1224 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1226 .sign(recipient_sign).unwrap();
1228 let mut buffer = Vec::new();
1229 invoice.write(&mut buffer).unwrap();
1231 if let Err(e) = Invoice::try_from(buffer) {
1232 panic!("error parsing invoice: {:?}", e);
1235 let mut tlv_stream = invoice.as_tlv_stream();
1236 tlv_stream.3.paths = None;
1238 match Invoice::try_from(tlv_stream.to_bytes()) {
1239 Ok(_) => panic!("expected error"),
1240 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1243 let mut tlv_stream = invoice.as_tlv_stream();
1244 tlv_stream.3.blindedpay = None;
1246 match Invoice::try_from(tlv_stream.to_bytes()) {
1247 Ok(_) => panic!("expected error"),
1248 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1251 let empty_payment_paths = vec![];
1252 let mut tlv_stream = invoice.as_tlv_stream();
1253 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1255 match Invoice::try_from(tlv_stream.to_bytes()) {
1256 Ok(_) => panic!("expected error"),
1257 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1260 let mut payment_paths = payment_paths();
1261 payment_paths.pop();
1262 let mut tlv_stream = invoice.as_tlv_stream();
1263 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1265 match Invoice::try_from(tlv_stream.to_bytes()) {
1266 Ok(_) => panic!("expected error"),
1267 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1272 fn parses_invoice_with_created_at() {
1273 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1276 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1278 .sign(payer_sign).unwrap()
1279 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1281 .sign(recipient_sign).unwrap();
1283 let mut buffer = Vec::new();
1284 invoice.write(&mut buffer).unwrap();
1286 if let Err(e) = Invoice::try_from(buffer) {
1287 panic!("error parsing invoice: {:?}", e);
1290 let mut tlv_stream = invoice.as_tlv_stream();
1291 tlv_stream.3.created_at = None;
1293 match Invoice::try_from(tlv_stream.to_bytes()) {
1294 Ok(_) => panic!("expected error"),
1296 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1302 fn parses_invoice_with_relative_expiry() {
1303 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1306 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1308 .sign(payer_sign).unwrap()
1309 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1310 .relative_expiry(3600)
1312 .sign(recipient_sign).unwrap();
1314 let mut buffer = Vec::new();
1315 invoice.write(&mut buffer).unwrap();
1317 match Invoice::try_from(buffer) {
1318 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1319 Err(e) => panic!("error parsing invoice: {:?}", e),
1324 fn parses_invoice_with_payment_hash() {
1325 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1328 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1330 .sign(payer_sign).unwrap()
1331 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1333 .sign(recipient_sign).unwrap();
1335 let mut buffer = Vec::new();
1336 invoice.write(&mut buffer).unwrap();
1338 if let Err(e) = Invoice::try_from(buffer) {
1339 panic!("error parsing invoice: {:?}", e);
1342 let mut tlv_stream = invoice.as_tlv_stream();
1343 tlv_stream.3.payment_hash = None;
1345 match Invoice::try_from(tlv_stream.to_bytes()) {
1346 Ok(_) => panic!("expected error"),
1348 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1354 fn parses_invoice_with_amount() {
1355 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1358 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1360 .sign(payer_sign).unwrap()
1361 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1363 .sign(recipient_sign).unwrap();
1365 let mut buffer = Vec::new();
1366 invoice.write(&mut buffer).unwrap();
1368 if let Err(e) = Invoice::try_from(buffer) {
1369 panic!("error parsing invoice: {:?}", e);
1372 let mut tlv_stream = invoice.as_tlv_stream();
1373 tlv_stream.3.amount = None;
1375 match Invoice::try_from(tlv_stream.to_bytes()) {
1376 Ok(_) => panic!("expected error"),
1377 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1382 fn parses_invoice_with_allow_mpp() {
1383 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1386 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1388 .sign(payer_sign).unwrap()
1389 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1392 .sign(recipient_sign).unwrap();
1394 let mut buffer = Vec::new();
1395 invoice.write(&mut buffer).unwrap();
1397 match Invoice::try_from(buffer) {
1399 let mut features = Bolt12InvoiceFeatures::empty();
1400 features.set_basic_mpp_optional();
1401 assert_eq!(invoice.features(), &features);
1403 Err(e) => panic!("error parsing invoice: {:?}", e),
1408 fn parses_invoice_with_fallback_address() {
1409 let script = Script::new();
1410 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1411 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1412 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1414 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1417 let invoice_request = offer
1418 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1420 .sign(payer_sign).unwrap();
1421 let mut unsigned_invoice = invoice_request
1422 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1423 .fallback_v0_p2wsh(&script.wscript_hash())
1424 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1425 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1428 // Only standard addresses will be included.
1429 let mut fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1430 // Non-standard addresses
1431 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1432 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1433 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1435 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1436 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1438 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1439 let mut buffer = Vec::new();
1440 invoice.write(&mut buffer).unwrap();
1442 match Invoice::try_from(buffer) {
1445 invoice.fallbacks(),
1447 Address::p2wsh(&script, Network::Bitcoin),
1448 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1449 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1451 payload: Payload::WitnessProgram {
1452 version: WitnessVersion::V1,
1453 program: vec![0u8; 33],
1455 network: Network::Bitcoin,
1458 payload: Payload::WitnessProgram {
1459 version: WitnessVersion::V2,
1460 program: vec![0u8; 40],
1462 network: Network::Bitcoin,
1467 Err(e) => panic!("error parsing invoice: {:?}", e),
1472 fn parses_invoice_with_node_id() {
1473 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1476 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1478 .sign(payer_sign).unwrap()
1479 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1481 .sign(recipient_sign).unwrap();
1483 let mut buffer = Vec::new();
1484 invoice.write(&mut buffer).unwrap();
1486 if let Err(e) = Invoice::try_from(buffer) {
1487 panic!("error parsing invoice: {:?}", e);
1490 let mut tlv_stream = invoice.as_tlv_stream();
1491 tlv_stream.3.node_id = None;
1493 match Invoice::try_from(tlv_stream.to_bytes()) {
1494 Ok(_) => panic!("expected error"),
1496 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1500 let invalid_pubkey = payer_pubkey();
1501 let mut tlv_stream = invoice.as_tlv_stream();
1502 tlv_stream.3.node_id = Some(&invalid_pubkey);
1504 match Invoice::try_from(tlv_stream.to_bytes()) {
1505 Ok(_) => panic!("expected error"),
1507 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1513 fn fails_parsing_invoice_without_signature() {
1514 let mut buffer = Vec::new();
1515 OfferBuilder::new("foo".into(), recipient_pubkey())
1518 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1520 .sign(payer_sign).unwrap()
1521 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1524 .write(&mut buffer).unwrap();
1526 match Invoice::try_from(buffer) {
1527 Ok(_) => panic!("expected error"),
1528 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1533 fn fails_parsing_invoice_with_invalid_signature() {
1534 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1537 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1539 .sign(payer_sign).unwrap()
1540 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1542 .sign(recipient_sign).unwrap();
1543 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1544 *last_signature_byte = last_signature_byte.wrapping_add(1);
1546 let mut buffer = Vec::new();
1547 invoice.write(&mut buffer).unwrap();
1549 match Invoice::try_from(buffer) {
1550 Ok(_) => panic!("expected error"),
1552 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1558 fn fails_parsing_invoice_with_extra_tlv_records() {
1559 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1562 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1564 .sign(payer_sign).unwrap()
1565 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1567 .sign(recipient_sign).unwrap();
1569 let mut encoded_invoice = Vec::new();
1570 invoice.write(&mut encoded_invoice).unwrap();
1571 BigSize(1002).write(&mut encoded_invoice).unwrap();
1572 BigSize(32).write(&mut encoded_invoice).unwrap();
1573 [42u8; 32].write(&mut encoded_invoice).unwrap();
1575 match Invoice::try_from(encoded_invoice) {
1576 Ok(_) => panic!("expected error"),
1577 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),