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 //! .respond_with(payment_paths, payment_hash)?
49 //! .relative_expiry(3600)
51 //! .fallback_v0_p2wpkh(&wpubkey_hash)
53 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
54 //! .expect("failed verifying signature")
55 //! .write(&mut buffer)
60 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
61 //! # let payment_paths = create_payment_paths();
62 //! # let payment_hash = create_payment_hash();
63 //! # let secp_ctx = Secp256k1::new();
64 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
65 //! # let pubkey = PublicKey::from(keys);
66 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
67 //! # let mut buffer = Vec::new();
69 //! // Invoice for the "offer for money" flow.
71 //! .parse::<Refund>()?
72 //! .respond_with(payment_paths, payment_hash, pubkey)?
73 //! .relative_expiry(3600)
75 //! .fallback_v0_p2wpkh(&wpubkey_hash)
77 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
78 //! .expect("failed verifying signature")
79 //! .write(&mut buffer)
86 use bitcoin::blockdata::constants::ChainHash;
87 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
88 use bitcoin::hashes::Hash;
89 use bitcoin::network::constants::Network;
90 use bitcoin::secp256k1::{Message, PublicKey};
91 use bitcoin::secp256k1::schnorr::Signature;
92 use bitcoin::util::address::{Address, Payload, WitnessVersion};
93 use bitcoin::util::schnorr::TweakedPublicKey;
94 use core::convert::TryFrom;
95 use core::time::Duration;
97 use crate::ln::PaymentHash;
98 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
99 use crate::ln::msgs::DecodeError;
100 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
101 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
102 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
103 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
104 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
105 use crate::offers::refund::{Refund, RefundContents};
106 use crate::onion_message::BlindedPath;
107 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
109 use crate::prelude::*;
111 #[cfg(feature = "std")]
112 use std::time::SystemTime;
114 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
116 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
118 /// Builds an [`Invoice`] from either:
119 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
120 /// - a [`Refund`] for the "offer for money" flow.
122 /// See [module-level documentation] for usage.
124 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
125 /// [`Refund`]: crate::offers::refund::Refund
126 /// [module-level documentation]: self
127 pub struct InvoiceBuilder<'a> {
128 invreq_bytes: &'a Vec<u8>,
129 invoice: InvoiceContents,
132 impl<'a> InvoiceBuilder<'a> {
133 pub(super) fn for_offer(
134 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
135 created_at: Duration, payment_hash: PaymentHash
136 ) -> Result<Self, SemanticError> {
137 let amount_msats = match invoice_request.amount_msats() {
138 Some(amount_msats) => amount_msats,
139 None => match invoice_request.contents.offer.amount() {
140 Some(Amount::Bitcoin { amount_msats }) => {
141 amount_msats * invoice_request.quantity().unwrap_or(1)
143 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
144 None => return Err(SemanticError::MissingAmount),
148 let contents = InvoiceContents::ForOffer {
149 invoice_request: invoice_request.contents.clone(),
150 fields: InvoiceFields {
151 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
152 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
153 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
157 Self::new(&invoice_request.bytes, contents)
160 pub(super) fn for_refund(
161 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
162 payment_hash: PaymentHash, signing_pubkey: PublicKey
163 ) -> Result<Self, SemanticError> {
164 let contents = InvoiceContents::ForRefund {
165 refund: refund.contents.clone(),
166 fields: InvoiceFields {
167 payment_paths, created_at, relative_expiry: None, payment_hash,
168 amount_msats: refund.amount_msats(), fallbacks: None,
169 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
173 Self::new(&refund.bytes, contents)
176 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
177 if contents.fields().payment_paths.is_empty() {
178 return Err(SemanticError::MissingPaths);
181 Ok(Self { invreq_bytes, invoice: contents })
184 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
185 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
187 /// Successive calls to this method will override the previous setting.
188 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
189 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
190 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
194 /// Adds a P2WSH address to [`Invoice::fallbacks`].
196 /// Successive calls to this method will add another address. Caller is responsible for not
197 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
198 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
199 let address = FallbackAddress {
200 version: WitnessVersion::V0.to_num(),
201 program: Vec::from(&script_hash.into_inner()[..]),
203 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
207 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
209 /// Successive calls to this method will add another address. Caller is responsible for not
210 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
211 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
212 let address = FallbackAddress {
213 version: WitnessVersion::V0.to_num(),
214 program: Vec::from(&pubkey_hash.into_inner()[..]),
216 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
220 /// Adds a P2TR address to [`Invoice::fallbacks`].
222 /// Successive calls to this method will add another address. Caller is responsible for not
223 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
224 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
225 let address = FallbackAddress {
226 version: WitnessVersion::V1.to_num(),
227 program: Vec::from(&output_key.serialize()[..]),
229 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
233 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
234 pub fn allow_mpp(mut self) -> Self {
235 self.invoice.fields_mut().features.set_basic_mpp_optional();
239 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
240 /// [`UnsignedInvoice::sign`].
241 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
242 #[cfg(feature = "std")] {
243 if self.invoice.is_offer_or_refund_expired() {
244 return Err(SemanticError::AlreadyExpired);
248 let InvoiceBuilder { invreq_bytes, invoice } = self;
249 Ok(UnsignedInvoice { invreq_bytes, invoice })
253 /// A semantically valid [`Invoice`] that hasn't been signed.
254 pub struct UnsignedInvoice<'a> {
255 invreq_bytes: &'a Vec<u8>,
256 invoice: InvoiceContents,
259 impl<'a> UnsignedInvoice<'a> {
260 /// Signs the invoice using the given function.
261 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
263 F: FnOnce(&Message) -> Result<Signature, E>
265 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
266 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
268 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
269 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
270 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
272 let mut bytes = Vec::new();
273 unsigned_tlv_stream.write(&mut bytes).unwrap();
275 let pubkey = self.invoice.fields().signing_pubkey;
276 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
278 // Append the signature TLV record to the bytes.
279 let signature_tlv_stream = SignatureTlvStreamRef {
280 signature: Some(&signature),
282 signature_tlv_stream.write(&mut bytes).unwrap();
286 contents: self.invoice,
292 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
294 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
295 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
297 /// [`Offer`]: crate::offers::offer::Offer
298 /// [`Refund`]: crate::offers::refund::Refund
299 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
302 contents: InvoiceContents,
303 signature: Signature,
306 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
308 /// [`Offer`]: crate::offers::offer::Offer
309 /// [`Refund`]: crate::offers::refund::Refund
310 enum InvoiceContents {
311 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
313 /// [`Offer`]: crate::offers::offer::Offer
315 invoice_request: InvoiceRequestContents,
316 fields: InvoiceFields,
318 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
320 /// [`Refund`]: crate::offers::refund::Refund
322 refund: RefundContents,
323 fields: InvoiceFields,
327 /// Invoice-specific fields for an `invoice` message.
328 struct InvoiceFields {
329 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
330 created_at: Duration,
331 relative_expiry: Option<Duration>,
332 payment_hash: PaymentHash,
334 fallbacks: Option<Vec<FallbackAddress>>,
335 features: Bolt12InvoiceFeatures,
336 signing_pubkey: PublicKey,
340 /// Paths to the recipient originating from publicly reachable nodes, including information
341 /// needed for routing payments across them.
343 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
344 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
345 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
346 &self.contents.fields().payment_paths[..]
349 /// Duration since the Unix epoch when the invoice was created.
350 pub fn created_at(&self) -> Duration {
351 self.contents.fields().created_at
354 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
356 pub fn relative_expiry(&self) -> Duration {
357 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
360 /// Whether the invoice has expired.
361 #[cfg(feature = "std")]
362 pub fn is_expired(&self) -> bool {
363 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
364 match absolute_expiry {
365 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
366 Ok(elapsed) => elapsed > seconds_from_epoch,
373 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
374 pub fn payment_hash(&self) -> PaymentHash {
375 self.contents.fields().payment_hash
378 /// The minimum amount required for a successful payment of the invoice.
379 pub fn amount_msats(&self) -> u64 {
380 self.contents.fields().amount_msats
383 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
385 pub fn fallbacks(&self) -> Vec<Address> {
386 let network = match self.network() {
387 None => return Vec::new(),
388 Some(network) => network,
391 let to_valid_address = |address: &FallbackAddress| {
392 let version = match WitnessVersion::try_from(address.version) {
393 Ok(version) => version,
394 Err(_) => return None,
397 let program = &address.program;
398 if program.len() < 2 || program.len() > 40 {
402 let address = Address {
403 payload: Payload::WitnessProgram {
405 program: address.program.clone(),
410 if !address.is_standard() && version == WitnessVersion::V0 {
417 self.contents.fields().fallbacks
419 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
420 .unwrap_or_else(Vec::new)
423 fn network(&self) -> Option<Network> {
424 let chain = self.contents.chain();
425 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
426 Some(Network::Bitcoin)
427 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
428 Some(Network::Testnet)
429 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
430 Some(Network::Signet)
431 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
432 Some(Network::Regtest)
438 /// Features pertaining to paying an invoice.
439 pub fn features(&self) -> &Bolt12InvoiceFeatures {
440 &self.contents.fields().features
443 /// The public key used to sign invoices.
444 pub fn signing_pubkey(&self) -> PublicKey {
445 self.contents.fields().signing_pubkey
448 /// Signature of the invoice using [`Invoice::signing_pubkey`].
449 pub fn signature(&self) -> Signature {
454 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
455 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
456 self.contents.as_tlv_stream();
457 let signature_tlv_stream = SignatureTlvStreamRef {
458 signature: Some(&self.signature),
460 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
461 signature_tlv_stream)
465 impl InvoiceContents {
466 /// Whether the original offer or refund has expired.
467 #[cfg(feature = "std")]
468 fn is_offer_or_refund_expired(&self) -> bool {
470 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
471 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
475 fn chain(&self) -> ChainHash {
477 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
478 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
482 fn fields(&self) -> &InvoiceFields {
484 InvoiceContents::ForOffer { fields, .. } => fields,
485 InvoiceContents::ForRefund { fields, .. } => fields,
489 fn fields_mut(&mut self) -> &mut InvoiceFields {
491 InvoiceContents::ForOffer { fields, .. } => fields,
492 InvoiceContents::ForRefund { fields, .. } => fields,
496 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
497 let (payer, offer, invoice_request) = match self {
498 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
499 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
501 let invoice = self.fields().as_tlv_stream();
503 (payer, offer, invoice_request, invoice)
508 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
510 if self.features == Bolt12InvoiceFeatures::empty() { None }
511 else { Some(&self.features) }
514 InvoiceTlvStreamRef {
515 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
516 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
517 created_at: Some(self.created_at.as_secs()),
518 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
519 payment_hash: Some(&self.payment_hash),
520 amount: Some(self.amount_msats),
521 fallbacks: self.fallbacks.as_ref(),
523 node_id: Some(&self.signing_pubkey),
528 impl Writeable for Invoice {
529 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
530 WithoutLength(&self.bytes).write(writer)
534 impl Writeable for InvoiceContents {
535 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
536 self.as_tlv_stream().write(writer)
540 impl TryFrom<Vec<u8>> for Invoice {
541 type Error = ParseError;
543 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
544 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
545 Invoice::try_from(parsed_invoice)
549 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
550 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
551 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
552 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
553 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
554 (168, payment_hash: PaymentHash),
555 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
556 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
557 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
558 (176, node_id: PublicKey),
561 type BlindedPathIter<'a> = core::iter::Map<
562 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
563 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
566 type BlindedPayInfoIter<'a> = core::iter::Map<
567 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
568 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
571 /// Information needed to route a payment across a [`BlindedPath`].
572 #[derive(Clone, Debug, PartialEq)]
573 pub struct BlindedPayInfo {
575 fee_proportional_millionths: u32,
576 cltv_expiry_delta: u16,
577 htlc_minimum_msat: u64,
578 htlc_maximum_msat: u64,
579 features: BlindedHopFeatures,
582 impl_writeable!(BlindedPayInfo, {
584 fee_proportional_millionths,
591 /// Wire representation for an on-chain fallback address.
592 #[derive(Clone, Debug, PartialEq)]
593 pub(super) struct FallbackAddress {
598 impl_writeable!(FallbackAddress, { version, program });
600 type FullInvoiceTlvStream =
601 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
604 type FullInvoiceTlvStreamRef<'a> = (
605 PayerTlvStreamRef<'a>,
606 OfferTlvStreamRef<'a>,
607 InvoiceRequestTlvStreamRef<'a>,
608 InvoiceTlvStreamRef<'a>,
609 SignatureTlvStreamRef<'a>,
612 impl SeekReadable for FullInvoiceTlvStream {
613 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
614 let payer = SeekReadable::read(r)?;
615 let offer = SeekReadable::read(r)?;
616 let invoice_request = SeekReadable::read(r)?;
617 let invoice = SeekReadable::read(r)?;
618 let signature = SeekReadable::read(r)?;
620 Ok((payer, offer, invoice_request, invoice, signature))
624 type PartialInvoiceTlvStream =
625 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
627 type PartialInvoiceTlvStreamRef<'a> = (
628 PayerTlvStreamRef<'a>,
629 OfferTlvStreamRef<'a>,
630 InvoiceRequestTlvStreamRef<'a>,
631 InvoiceTlvStreamRef<'a>,
634 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
635 type Error = ParseError;
637 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
638 let ParsedMessage { bytes, tlv_stream } = invoice;
640 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
641 SignatureTlvStream { signature },
643 let contents = InvoiceContents::try_from(
644 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
647 let signature = match signature {
648 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
649 Some(signature) => signature,
651 let pubkey = contents.fields().signing_pubkey;
652 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
654 Ok(Invoice { bytes, contents, signature })
658 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
659 type Error = SemanticError;
661 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
665 invoice_request_tlv_stream,
667 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
672 let payment_paths = match (paths, blindedpay) {
673 (None, _) => return Err(SemanticError::MissingPaths),
674 (_, None) => return Err(SemanticError::InvalidPayInfo),
675 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
676 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
677 return Err(SemanticError::InvalidPayInfo);
679 (Some(paths), Some(blindedpay)) => {
680 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
684 let created_at = match created_at {
685 None => return Err(SemanticError::MissingCreationTime),
686 Some(timestamp) => Duration::from_secs(timestamp),
689 let relative_expiry = relative_expiry
690 .map(Into::<u64>::into)
691 .map(Duration::from_secs);
693 let payment_hash = match payment_hash {
694 None => return Err(SemanticError::MissingPaymentHash),
695 Some(payment_hash) => payment_hash,
698 let amount_msats = match amount {
699 None => return Err(SemanticError::MissingAmount),
700 Some(amount) => amount,
703 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
705 let signing_pubkey = match node_id {
706 None => return Err(SemanticError::MissingSigningPubkey),
707 Some(node_id) => node_id,
710 let fields = InvoiceFields {
711 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
712 features, signing_pubkey,
715 match offer_tlv_stream.node_id {
716 Some(expected_signing_pubkey) => {
717 if fields.signing_pubkey != expected_signing_pubkey {
718 return Err(SemanticError::InvalidSigningPubkey);
721 let invoice_request = InvoiceRequestContents::try_from(
722 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
724 Ok(InvoiceContents::ForOffer { invoice_request, fields })
727 let refund = RefundContents::try_from(
728 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
730 Ok(InvoiceContents::ForRefund { refund, fields })
738 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
740 use bitcoin::blockdata::script::Script;
741 use bitcoin::hashes::Hash;
742 use bitcoin::network::constants::Network;
743 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
744 use bitcoin::secp256k1::schnorr::Signature;
745 use bitcoin::util::address::{Address, Payload, WitnessVersion};
746 use bitcoin::util::schnorr::TweakedPublicKey;
747 use core::convert::{Infallible, TryFrom};
748 use core::time::Duration;
749 use crate::ln::PaymentHash;
750 use crate::ln::msgs::DecodeError;
751 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
752 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
753 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
754 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
755 use crate::offers::parse::{ParseError, SemanticError};
756 use crate::offers::payer::PayerTlvStreamRef;
757 use crate::offers::refund::RefundBuilder;
758 use crate::onion_message::{BlindedHop, BlindedPath};
759 use crate::util::ser::{BigSize, Iterable, Writeable};
761 fn payer_keys() -> KeyPair {
762 let secp_ctx = Secp256k1::new();
763 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
766 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
767 let secp_ctx = Secp256k1::new();
768 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
769 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
772 fn payer_pubkey() -> PublicKey {
773 payer_keys().public_key()
776 fn recipient_keys() -> KeyPair {
777 let secp_ctx = Secp256k1::new();
778 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
781 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
782 let secp_ctx = Secp256k1::new();
783 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
784 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
787 fn recipient_pubkey() -> PublicKey {
788 recipient_keys().public_key()
791 fn pubkey(byte: u8) -> PublicKey {
792 let secp_ctx = Secp256k1::new();
793 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
796 fn privkey(byte: u8) -> SecretKey {
797 SecretKey::from_slice(&[byte; 32]).unwrap()
801 fn to_bytes(&self) -> Vec<u8>;
804 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
805 fn to_bytes(&self) -> Vec<u8> {
806 let mut buffer = Vec::new();
807 self.0.write(&mut buffer).unwrap();
808 self.1.write(&mut buffer).unwrap();
809 self.2.write(&mut buffer).unwrap();
810 self.3.write(&mut buffer).unwrap();
811 self.4.write(&mut buffer).unwrap();
816 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
819 introduction_node_id: pubkey(40),
820 blinding_point: pubkey(41),
822 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
823 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
827 introduction_node_id: pubkey(40),
828 blinding_point: pubkey(41),
830 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
831 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
839 fee_proportional_millionths: 1_000,
840 cltv_expiry_delta: 42,
841 htlc_minimum_msat: 100,
842 htlc_maximum_msat: 1_000_000_000_000,
843 features: BlindedHopFeatures::empty(),
847 fee_proportional_millionths: 1_000,
848 cltv_expiry_delta: 42,
849 htlc_minimum_msat: 100,
850 htlc_maximum_msat: 1_000_000_000_000,
851 features: BlindedHopFeatures::empty(),
855 paths.into_iter().zip(payinfo.into_iter()).collect()
858 fn payment_hash() -> PaymentHash {
859 PaymentHash([42; 32])
862 fn now() -> Duration {
863 std::time::SystemTime::now()
864 .duration_since(std::time::SystemTime::UNIX_EPOCH)
865 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
869 fn builds_invoice_for_offer_with_defaults() {
870 let payment_paths = payment_paths();
871 let payment_hash = payment_hash();
873 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
876 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
878 .sign(payer_sign).unwrap()
879 .respond_with(payment_paths.clone(), payment_hash, now).unwrap()
881 .sign(recipient_sign).unwrap();
883 let mut buffer = Vec::new();
884 invoice.write(&mut buffer).unwrap();
886 assert_eq!(invoice.bytes, buffer.as_slice());
887 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
888 assert_eq!(invoice.created_at(), now);
889 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
890 #[cfg(feature = "std")]
891 assert!(!invoice.is_expired());
892 assert_eq!(invoice.payment_hash(), payment_hash);
893 assert_eq!(invoice.amount_msats(), 1000);
894 assert_eq!(invoice.fallbacks(), vec![]);
895 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
896 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
898 merkle::verify_signature(
899 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
904 invoice.as_tlv_stream(),
906 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
912 description: Some(&String::from("foo")),
914 absolute_expiry: None,
918 node_id: Some(&recipient_pubkey()),
920 InvoiceRequestTlvStreamRef {
925 payer_id: Some(&payer_pubkey()),
928 InvoiceTlvStreamRef {
929 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
930 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
931 created_at: Some(now.as_secs()),
932 relative_expiry: None,
933 payment_hash: Some(&payment_hash),
937 node_id: Some(&recipient_pubkey()),
939 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
943 if let Err(e) = Invoice::try_from(buffer) {
944 panic!("error parsing invoice: {:?}", e);
949 fn builds_invoice_for_refund_with_defaults() {
950 let payment_paths = payment_paths();
951 let payment_hash = payment_hash();
953 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
955 .respond_with(payment_paths.clone(), payment_hash, recipient_pubkey(), now).unwrap()
957 .sign(recipient_sign).unwrap();
959 let mut buffer = Vec::new();
960 invoice.write(&mut buffer).unwrap();
962 assert_eq!(invoice.bytes, buffer.as_slice());
963 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
964 assert_eq!(invoice.created_at(), now);
965 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
966 #[cfg(feature = "std")]
967 assert!(!invoice.is_expired());
968 assert_eq!(invoice.payment_hash(), payment_hash);
969 assert_eq!(invoice.amount_msats(), 1000);
970 assert_eq!(invoice.fallbacks(), vec![]);
971 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
972 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
974 merkle::verify_signature(
975 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
980 invoice.as_tlv_stream(),
982 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
988 description: Some(&String::from("foo")),
990 absolute_expiry: None,
996 InvoiceRequestTlvStreamRef {
1001 payer_id: Some(&payer_pubkey()),
1004 InvoiceTlvStreamRef {
1005 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1006 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1007 created_at: Some(now.as_secs()),
1008 relative_expiry: None,
1009 payment_hash: Some(&payment_hash),
1013 node_id: Some(&recipient_pubkey()),
1015 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1019 if let Err(e) = Invoice::try_from(buffer) {
1020 panic!("error parsing invoice: {:?}", e);
1024 #[cfg(feature = "std")]
1026 fn builds_invoice_from_refund_with_expiration() {
1027 let future_expiry = Duration::from_secs(u64::max_value());
1028 let past_expiry = Duration::from_secs(0);
1030 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1031 .absolute_expiry(future_expiry)
1033 .respond_with(payment_paths(), payment_hash(), recipient_pubkey(), now()).unwrap()
1036 panic!("error building invoice: {:?}", e);
1039 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1040 .absolute_expiry(past_expiry)
1042 .respond_with(payment_paths(), payment_hash(), recipient_pubkey(), now()).unwrap()
1045 Ok(_) => panic!("expected error"),
1046 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1051 fn builds_invoice_with_relative_expiry() {
1053 let one_hour = Duration::from_secs(3600);
1055 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1058 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1060 .sign(payer_sign).unwrap()
1061 .respond_with(payment_paths(), payment_hash(), now).unwrap()
1062 .relative_expiry(one_hour.as_secs() as u32)
1064 .sign(recipient_sign).unwrap();
1065 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1066 #[cfg(feature = "std")]
1067 assert!(!invoice.is_expired());
1068 assert_eq!(invoice.relative_expiry(), one_hour);
1069 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1071 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1074 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1076 .sign(payer_sign).unwrap()
1077 .respond_with(payment_paths(), payment_hash(), now - one_hour).unwrap()
1078 .relative_expiry(one_hour.as_secs() as u32 - 1)
1080 .sign(recipient_sign).unwrap();
1081 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1082 #[cfg(feature = "std")]
1083 assert!(invoice.is_expired());
1084 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1085 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1089 fn builds_invoice_with_amount_from_request() {
1090 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1093 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1094 .amount_msats(1001).unwrap()
1096 .sign(payer_sign).unwrap()
1097 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1099 .sign(recipient_sign).unwrap();
1100 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1101 assert_eq!(invoice.amount_msats(), 1001);
1102 assert_eq!(tlv_stream.amount, Some(1001));
1106 fn builds_invoice_with_fallback_address() {
1107 let script = Script::new();
1108 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1109 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1110 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1112 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1115 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1117 .sign(payer_sign).unwrap()
1118 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1119 .fallback_v0_p2wsh(&script.wscript_hash())
1120 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1121 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1123 .sign(recipient_sign).unwrap();
1124 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1126 invoice.fallbacks(),
1128 Address::p2wsh(&script, Network::Bitcoin),
1129 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1130 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1134 tlv_stream.fallbacks,
1137 version: WitnessVersion::V0.to_num(),
1138 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1141 version: WitnessVersion::V0.to_num(),
1142 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1145 version: WitnessVersion::V1.to_num(),
1146 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1153 fn builds_invoice_with_allow_mpp() {
1154 let mut features = Bolt12InvoiceFeatures::empty();
1155 features.set_basic_mpp_optional();
1157 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1160 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1162 .sign(payer_sign).unwrap()
1163 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1166 .sign(recipient_sign).unwrap();
1167 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1168 assert_eq!(invoice.features(), &features);
1169 assert_eq!(tlv_stream.features, Some(&features));
1173 fn fails_signing_invoice() {
1174 match OfferBuilder::new("foo".into(), recipient_pubkey())
1177 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1179 .sign(payer_sign).unwrap()
1180 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1184 Ok(_) => panic!("expected error"),
1185 Err(e) => assert_eq!(e, SignError::Signing(())),
1188 match OfferBuilder::new("foo".into(), recipient_pubkey())
1191 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1193 .sign(payer_sign).unwrap()
1194 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1198 Ok(_) => panic!("expected error"),
1199 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1204 fn parses_invoice_with_payment_paths() {
1205 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1208 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1210 .sign(payer_sign).unwrap()
1211 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1213 .sign(recipient_sign).unwrap();
1215 let mut buffer = Vec::new();
1216 invoice.write(&mut buffer).unwrap();
1218 if let Err(e) = Invoice::try_from(buffer) {
1219 panic!("error parsing invoice: {:?}", e);
1222 let mut tlv_stream = invoice.as_tlv_stream();
1223 tlv_stream.3.paths = None;
1225 match Invoice::try_from(tlv_stream.to_bytes()) {
1226 Ok(_) => panic!("expected error"),
1227 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1230 let mut tlv_stream = invoice.as_tlv_stream();
1231 tlv_stream.3.blindedpay = None;
1233 match Invoice::try_from(tlv_stream.to_bytes()) {
1234 Ok(_) => panic!("expected error"),
1235 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1238 let empty_payment_paths = vec![];
1239 let mut tlv_stream = invoice.as_tlv_stream();
1240 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1242 match Invoice::try_from(tlv_stream.to_bytes()) {
1243 Ok(_) => panic!("expected error"),
1244 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1247 let mut payment_paths = payment_paths();
1248 payment_paths.pop();
1249 let mut tlv_stream = invoice.as_tlv_stream();
1250 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1252 match Invoice::try_from(tlv_stream.to_bytes()) {
1253 Ok(_) => panic!("expected error"),
1254 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1259 fn parses_invoice_with_created_at() {
1260 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1263 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1265 .sign(payer_sign).unwrap()
1266 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1268 .sign(recipient_sign).unwrap();
1270 let mut buffer = Vec::new();
1271 invoice.write(&mut buffer).unwrap();
1273 if let Err(e) = Invoice::try_from(buffer) {
1274 panic!("error parsing invoice: {:?}", e);
1277 let mut tlv_stream = invoice.as_tlv_stream();
1278 tlv_stream.3.created_at = None;
1280 match Invoice::try_from(tlv_stream.to_bytes()) {
1281 Ok(_) => panic!("expected error"),
1283 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1289 fn parses_invoice_with_relative_expiry() {
1290 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1293 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1295 .sign(payer_sign).unwrap()
1296 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1297 .relative_expiry(3600)
1299 .sign(recipient_sign).unwrap();
1301 let mut buffer = Vec::new();
1302 invoice.write(&mut buffer).unwrap();
1304 match Invoice::try_from(buffer) {
1305 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1306 Err(e) => panic!("error parsing invoice: {:?}", e),
1311 fn parses_invoice_with_payment_hash() {
1312 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1315 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1317 .sign(payer_sign).unwrap()
1318 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1320 .sign(recipient_sign).unwrap();
1322 let mut buffer = Vec::new();
1323 invoice.write(&mut buffer).unwrap();
1325 if let Err(e) = Invoice::try_from(buffer) {
1326 panic!("error parsing invoice: {:?}", e);
1329 let mut tlv_stream = invoice.as_tlv_stream();
1330 tlv_stream.3.payment_hash = None;
1332 match Invoice::try_from(tlv_stream.to_bytes()) {
1333 Ok(_) => panic!("expected error"),
1335 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1341 fn parses_invoice_with_amount() {
1342 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1345 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .sign(payer_sign).unwrap()
1348 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1350 .sign(recipient_sign).unwrap();
1352 let mut buffer = Vec::new();
1353 invoice.write(&mut buffer).unwrap();
1355 if let Err(e) = Invoice::try_from(buffer) {
1356 panic!("error parsing invoice: {:?}", e);
1359 let mut tlv_stream = invoice.as_tlv_stream();
1360 tlv_stream.3.amount = None;
1362 match Invoice::try_from(tlv_stream.to_bytes()) {
1363 Ok(_) => panic!("expected error"),
1364 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1369 fn parses_invoice_with_allow_mpp() {
1370 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1373 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1375 .sign(payer_sign).unwrap()
1376 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1379 .sign(recipient_sign).unwrap();
1381 let mut buffer = Vec::new();
1382 invoice.write(&mut buffer).unwrap();
1384 match Invoice::try_from(buffer) {
1386 let mut features = Bolt12InvoiceFeatures::empty();
1387 features.set_basic_mpp_optional();
1388 assert_eq!(invoice.features(), &features);
1390 Err(e) => panic!("error parsing invoice: {:?}", e),
1395 fn parses_invoice_with_fallback_address() {
1396 let script = Script::new();
1397 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1398 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1399 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1401 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1404 let invoice_request = offer
1405 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1407 .sign(payer_sign).unwrap();
1408 let mut unsigned_invoice = invoice_request
1409 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1410 .fallback_v0_p2wsh(&script.wscript_hash())
1411 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1412 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1415 // Only standard addresses will be included.
1416 let mut fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1417 // Non-standard addresses
1418 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1419 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1420 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1422 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1423 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1425 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1426 let mut buffer = Vec::new();
1427 invoice.write(&mut buffer).unwrap();
1429 match Invoice::try_from(buffer) {
1432 invoice.fallbacks(),
1434 Address::p2wsh(&script, Network::Bitcoin),
1435 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1436 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1438 payload: Payload::WitnessProgram {
1439 version: WitnessVersion::V1,
1440 program: vec![0u8; 33],
1442 network: Network::Bitcoin,
1445 payload: Payload::WitnessProgram {
1446 version: WitnessVersion::V2,
1447 program: vec![0u8; 40],
1449 network: Network::Bitcoin,
1454 Err(e) => panic!("error parsing invoice: {:?}", e),
1459 fn parses_invoice_with_node_id() {
1460 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1463 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1465 .sign(payer_sign).unwrap()
1466 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1468 .sign(recipient_sign).unwrap();
1470 let mut buffer = Vec::new();
1471 invoice.write(&mut buffer).unwrap();
1473 if let Err(e) = Invoice::try_from(buffer) {
1474 panic!("error parsing invoice: {:?}", e);
1477 let mut tlv_stream = invoice.as_tlv_stream();
1478 tlv_stream.3.node_id = None;
1480 match Invoice::try_from(tlv_stream.to_bytes()) {
1481 Ok(_) => panic!("expected error"),
1483 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1487 let invalid_pubkey = payer_pubkey();
1488 let mut tlv_stream = invoice.as_tlv_stream();
1489 tlv_stream.3.node_id = Some(&invalid_pubkey);
1491 match Invoice::try_from(tlv_stream.to_bytes()) {
1492 Ok(_) => panic!("expected error"),
1494 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1500 fn fails_parsing_invoice_without_signature() {
1501 let mut buffer = Vec::new();
1502 OfferBuilder::new("foo".into(), recipient_pubkey())
1505 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1507 .sign(payer_sign).unwrap()
1508 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1511 .write(&mut buffer).unwrap();
1513 match Invoice::try_from(buffer) {
1514 Ok(_) => panic!("expected error"),
1515 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1520 fn fails_parsing_invoice_with_invalid_signature() {
1521 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1524 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1526 .sign(payer_sign).unwrap()
1527 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1529 .sign(recipient_sign).unwrap();
1530 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1531 *last_signature_byte = last_signature_byte.wrapping_add(1);
1533 let mut buffer = Vec::new();
1534 invoice.write(&mut buffer).unwrap();
1536 match Invoice::try_from(buffer) {
1537 Ok(_) => panic!("expected error"),
1539 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1545 fn fails_parsing_invoice_with_extra_tlv_records() {
1546 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1549 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1551 .sign(payer_sign).unwrap()
1552 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1554 .sign(recipient_sign).unwrap();
1556 let mut encoded_invoice = Vec::new();
1557 invoice.write(&mut encoded_invoice).unwrap();
1558 BigSize(1002).write(&mut encoded_invoice).unwrap();
1559 BigSize(32).write(&mut encoded_invoice).unwrap();
1560 [42u8; 32].write(&mut encoded_invoice).unwrap();
1562 match Invoice::try_from(encoded_invoice) {
1563 Ok(_) => panic!("expected error"),
1564 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),