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. Blinded paths provide recipient privacy by
342 /// obfuscating its node id.
343 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
344 &self.contents.fields().payment_paths[..]
347 /// Duration since the Unix epoch when the invoice was created.
348 pub fn created_at(&self) -> Duration {
349 self.contents.fields().created_at
352 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
354 pub fn relative_expiry(&self) -> Duration {
355 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
358 /// Whether the invoice has expired.
359 #[cfg(feature = "std")]
360 pub fn is_expired(&self) -> bool {
361 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
362 match absolute_expiry {
363 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
364 Ok(elapsed) => elapsed > seconds_from_epoch,
371 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
372 pub fn payment_hash(&self) -> PaymentHash {
373 self.contents.fields().payment_hash
376 /// The minimum amount required for a successful payment of the invoice.
377 pub fn amount_msats(&self) -> u64 {
378 self.contents.fields().amount_msats
381 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
383 pub fn fallbacks(&self) -> Vec<Address> {
384 let network = match self.network() {
385 None => return Vec::new(),
386 Some(network) => network,
389 let to_valid_address = |address: &FallbackAddress| {
390 let version = match WitnessVersion::try_from(address.version) {
391 Ok(version) => version,
392 Err(_) => return None,
395 let program = &address.program;
396 if program.len() < 2 || program.len() > 40 {
400 let address = Address {
401 payload: Payload::WitnessProgram {
403 program: address.program.clone(),
408 if !address.is_standard() && version == WitnessVersion::V0 {
415 self.contents.fields().fallbacks
417 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
418 .unwrap_or_else(Vec::new)
421 fn network(&self) -> Option<Network> {
422 let chain = self.contents.chain();
423 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
424 Some(Network::Bitcoin)
425 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
426 Some(Network::Testnet)
427 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
428 Some(Network::Signet)
429 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
430 Some(Network::Regtest)
436 /// Features pertaining to paying an invoice.
437 pub fn features(&self) -> &Bolt12InvoiceFeatures {
438 &self.contents.fields().features
441 /// The public key used to sign invoices.
442 pub fn signing_pubkey(&self) -> PublicKey {
443 self.contents.fields().signing_pubkey
446 /// Signature of the invoice using [`Invoice::signing_pubkey`].
447 pub fn signature(&self) -> Signature {
452 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
453 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
454 self.contents.as_tlv_stream();
455 let signature_tlv_stream = SignatureTlvStreamRef {
456 signature: Some(&self.signature),
458 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
459 signature_tlv_stream)
463 impl InvoiceContents {
464 /// Whether the original offer or refund has expired.
465 #[cfg(feature = "std")]
466 fn is_offer_or_refund_expired(&self) -> bool {
468 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
469 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
473 fn chain(&self) -> ChainHash {
475 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
476 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
480 fn fields(&self) -> &InvoiceFields {
482 InvoiceContents::ForOffer { fields, .. } => fields,
483 InvoiceContents::ForRefund { fields, .. } => fields,
487 fn fields_mut(&mut self) -> &mut InvoiceFields {
489 InvoiceContents::ForOffer { fields, .. } => fields,
490 InvoiceContents::ForRefund { fields, .. } => fields,
494 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
495 let (payer, offer, invoice_request) = match self {
496 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
497 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
499 let invoice = self.fields().as_tlv_stream();
501 (payer, offer, invoice_request, invoice)
506 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
508 if self.features == Bolt12InvoiceFeatures::empty() { None }
509 else { Some(&self.features) }
512 InvoiceTlvStreamRef {
513 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
514 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
515 created_at: Some(self.created_at.as_secs()),
516 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
517 payment_hash: Some(&self.payment_hash),
518 amount: Some(self.amount_msats),
519 fallbacks: self.fallbacks.as_ref(),
521 node_id: Some(&self.signing_pubkey),
526 impl Writeable for Invoice {
527 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
528 WithoutLength(&self.bytes).write(writer)
532 impl Writeable for InvoiceContents {
533 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
534 self.as_tlv_stream().write(writer)
538 impl TryFrom<Vec<u8>> for Invoice {
539 type Error = ParseError;
541 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
542 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
543 Invoice::try_from(parsed_invoice)
547 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
548 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
549 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
550 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
551 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
552 (168, payment_hash: PaymentHash),
553 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
554 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
555 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
556 (176, node_id: PublicKey),
559 type BlindedPathIter<'a> = core::iter::Map<
560 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
561 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
564 type BlindedPayInfoIter<'a> = core::iter::Map<
565 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
566 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
569 /// Information needed to route a payment across a [`BlindedPath`].
570 #[derive(Clone, Debug, PartialEq)]
571 pub struct BlindedPayInfo {
573 fee_proportional_millionths: u32,
574 cltv_expiry_delta: u16,
575 htlc_minimum_msat: u64,
576 htlc_maximum_msat: u64,
577 features: BlindedHopFeatures,
580 impl_writeable!(BlindedPayInfo, {
582 fee_proportional_millionths,
589 /// Wire representation for an on-chain fallback address.
590 #[derive(Clone, Debug, PartialEq)]
591 pub(super) struct FallbackAddress {
596 impl_writeable!(FallbackAddress, { version, program });
598 type FullInvoiceTlvStream =
599 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
602 type FullInvoiceTlvStreamRef<'a> = (
603 PayerTlvStreamRef<'a>,
604 OfferTlvStreamRef<'a>,
605 InvoiceRequestTlvStreamRef<'a>,
606 InvoiceTlvStreamRef<'a>,
607 SignatureTlvStreamRef<'a>,
610 impl SeekReadable for FullInvoiceTlvStream {
611 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
612 let payer = SeekReadable::read(r)?;
613 let offer = SeekReadable::read(r)?;
614 let invoice_request = SeekReadable::read(r)?;
615 let invoice = SeekReadable::read(r)?;
616 let signature = SeekReadable::read(r)?;
618 Ok((payer, offer, invoice_request, invoice, signature))
622 type PartialInvoiceTlvStream =
623 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
625 type PartialInvoiceTlvStreamRef<'a> = (
626 PayerTlvStreamRef<'a>,
627 OfferTlvStreamRef<'a>,
628 InvoiceRequestTlvStreamRef<'a>,
629 InvoiceTlvStreamRef<'a>,
632 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
633 type Error = ParseError;
635 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
636 let ParsedMessage { bytes, tlv_stream } = invoice;
638 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
639 SignatureTlvStream { signature },
641 let contents = InvoiceContents::try_from(
642 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
645 let signature = match signature {
646 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
647 Some(signature) => signature,
649 let pubkey = contents.fields().signing_pubkey;
650 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
652 Ok(Invoice { bytes, contents, signature })
656 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
657 type Error = SemanticError;
659 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
663 invoice_request_tlv_stream,
665 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
670 let payment_paths = match (paths, blindedpay) {
671 (None, _) => return Err(SemanticError::MissingPaths),
672 (_, None) => return Err(SemanticError::InvalidPayInfo),
673 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
674 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
675 return Err(SemanticError::InvalidPayInfo);
677 (Some(paths), Some(blindedpay)) => {
678 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
682 let created_at = match created_at {
683 None => return Err(SemanticError::MissingCreationTime),
684 Some(timestamp) => Duration::from_secs(timestamp),
687 let relative_expiry = relative_expiry
688 .map(Into::<u64>::into)
689 .map(Duration::from_secs);
691 let payment_hash = match payment_hash {
692 None => return Err(SemanticError::MissingPaymentHash),
693 Some(payment_hash) => payment_hash,
696 let amount_msats = match amount {
697 None => return Err(SemanticError::MissingAmount),
698 Some(amount) => amount,
701 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
703 let signing_pubkey = match node_id {
704 None => return Err(SemanticError::MissingSigningPubkey),
705 Some(node_id) => node_id,
708 let fields = InvoiceFields {
709 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
710 features, signing_pubkey,
713 match offer_tlv_stream.node_id {
714 Some(expected_signing_pubkey) => {
715 if fields.signing_pubkey != expected_signing_pubkey {
716 return Err(SemanticError::InvalidSigningPubkey);
719 let invoice_request = InvoiceRequestContents::try_from(
720 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
722 Ok(InvoiceContents::ForOffer { invoice_request, fields })
725 let refund = RefundContents::try_from(
726 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
728 Ok(InvoiceContents::ForRefund { refund, fields })
736 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
738 use bitcoin::blockdata::script::Script;
739 use bitcoin::hashes::Hash;
740 use bitcoin::network::constants::Network;
741 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
742 use bitcoin::secp256k1::schnorr::Signature;
743 use bitcoin::util::address::{Address, Payload, WitnessVersion};
744 use bitcoin::util::schnorr::TweakedPublicKey;
745 use core::convert::{Infallible, TryFrom};
746 use core::time::Duration;
747 use crate::ln::PaymentHash;
748 use crate::ln::msgs::DecodeError;
749 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
750 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
751 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
752 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
753 use crate::offers::parse::{ParseError, SemanticError};
754 use crate::offers::payer::PayerTlvStreamRef;
755 use crate::offers::refund::RefundBuilder;
756 use crate::onion_message::{BlindedHop, BlindedPath};
757 use crate::util::ser::{BigSize, Iterable, Writeable};
759 fn payer_keys() -> KeyPair {
760 let secp_ctx = Secp256k1::new();
761 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
764 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
765 let secp_ctx = Secp256k1::new();
766 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
767 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
770 fn payer_pubkey() -> PublicKey {
771 payer_keys().public_key()
774 fn recipient_keys() -> KeyPair {
775 let secp_ctx = Secp256k1::new();
776 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
779 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
780 let secp_ctx = Secp256k1::new();
781 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
782 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
785 fn recipient_pubkey() -> PublicKey {
786 recipient_keys().public_key()
789 fn pubkey(byte: u8) -> PublicKey {
790 let secp_ctx = Secp256k1::new();
791 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
794 fn privkey(byte: u8) -> SecretKey {
795 SecretKey::from_slice(&[byte; 32]).unwrap()
799 fn to_bytes(&self) -> Vec<u8>;
802 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
803 fn to_bytes(&self) -> Vec<u8> {
804 let mut buffer = Vec::new();
805 self.0.write(&mut buffer).unwrap();
806 self.1.write(&mut buffer).unwrap();
807 self.2.write(&mut buffer).unwrap();
808 self.3.write(&mut buffer).unwrap();
809 self.4.write(&mut buffer).unwrap();
814 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
817 introduction_node_id: pubkey(40),
818 blinding_point: pubkey(41),
820 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
821 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
825 introduction_node_id: pubkey(40),
826 blinding_point: pubkey(41),
828 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
829 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
837 fee_proportional_millionths: 1_000,
838 cltv_expiry_delta: 42,
839 htlc_minimum_msat: 100,
840 htlc_maximum_msat: 1_000_000_000_000,
841 features: BlindedHopFeatures::empty(),
845 fee_proportional_millionths: 1_000,
846 cltv_expiry_delta: 42,
847 htlc_minimum_msat: 100,
848 htlc_maximum_msat: 1_000_000_000_000,
849 features: BlindedHopFeatures::empty(),
853 paths.into_iter().zip(payinfo.into_iter()).collect()
856 fn payment_hash() -> PaymentHash {
857 PaymentHash([42; 32])
860 fn now() -> Duration {
861 std::time::SystemTime::now()
862 .duration_since(std::time::SystemTime::UNIX_EPOCH)
863 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
867 fn builds_invoice_for_offer_with_defaults() {
868 let payment_paths = payment_paths();
869 let payment_hash = payment_hash();
871 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
874 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
876 .sign(payer_sign).unwrap()
877 .respond_with(payment_paths.clone(), payment_hash, now).unwrap()
879 .sign(recipient_sign).unwrap();
881 let mut buffer = Vec::new();
882 invoice.write(&mut buffer).unwrap();
884 assert_eq!(invoice.bytes, buffer.as_slice());
885 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
886 assert_eq!(invoice.created_at(), now);
887 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
888 #[cfg(feature = "std")]
889 assert!(!invoice.is_expired());
890 assert_eq!(invoice.payment_hash(), payment_hash);
891 assert_eq!(invoice.amount_msats(), 1000);
892 assert_eq!(invoice.fallbacks(), vec![]);
893 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
894 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
896 merkle::verify_signature(
897 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
902 invoice.as_tlv_stream(),
904 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
910 description: Some(&String::from("foo")),
912 absolute_expiry: None,
916 node_id: Some(&recipient_pubkey()),
918 InvoiceRequestTlvStreamRef {
923 payer_id: Some(&payer_pubkey()),
926 InvoiceTlvStreamRef {
927 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
928 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
929 created_at: Some(now.as_secs()),
930 relative_expiry: None,
931 payment_hash: Some(&payment_hash),
935 node_id: Some(&recipient_pubkey()),
937 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
941 if let Err(e) = Invoice::try_from(buffer) {
942 panic!("error parsing invoice: {:?}", e);
947 fn builds_invoice_for_refund_with_defaults() {
948 let payment_paths = payment_paths();
949 let payment_hash = payment_hash();
951 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
953 .respond_with(payment_paths.clone(), payment_hash, recipient_pubkey(), now).unwrap()
955 .sign(recipient_sign).unwrap();
957 let mut buffer = Vec::new();
958 invoice.write(&mut buffer).unwrap();
960 assert_eq!(invoice.bytes, buffer.as_slice());
961 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
962 assert_eq!(invoice.created_at(), now);
963 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
964 #[cfg(feature = "std")]
965 assert!(!invoice.is_expired());
966 assert_eq!(invoice.payment_hash(), payment_hash);
967 assert_eq!(invoice.amount_msats(), 1000);
968 assert_eq!(invoice.fallbacks(), vec![]);
969 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
970 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
972 merkle::verify_signature(
973 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
978 invoice.as_tlv_stream(),
980 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
986 description: Some(&String::from("foo")),
988 absolute_expiry: None,
994 InvoiceRequestTlvStreamRef {
999 payer_id: Some(&payer_pubkey()),
1002 InvoiceTlvStreamRef {
1003 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1004 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1005 created_at: Some(now.as_secs()),
1006 relative_expiry: None,
1007 payment_hash: Some(&payment_hash),
1011 node_id: Some(&recipient_pubkey()),
1013 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1017 if let Err(e) = Invoice::try_from(buffer) {
1018 panic!("error parsing invoice: {:?}", e);
1022 #[cfg(feature = "std")]
1024 fn builds_invoice_from_refund_with_expiration() {
1025 let future_expiry = Duration::from_secs(u64::max_value());
1026 let past_expiry = Duration::from_secs(0);
1028 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1029 .absolute_expiry(future_expiry)
1031 .respond_with(payment_paths(), payment_hash(), recipient_pubkey(), now()).unwrap()
1034 panic!("error building invoice: {:?}", e);
1037 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1038 .absolute_expiry(past_expiry)
1040 .respond_with(payment_paths(), payment_hash(), recipient_pubkey(), now()).unwrap()
1043 Ok(_) => panic!("expected error"),
1044 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1049 fn builds_invoice_with_relative_expiry() {
1051 let one_hour = Duration::from_secs(3600);
1053 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1056 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1058 .sign(payer_sign).unwrap()
1059 .respond_with(payment_paths(), payment_hash(), now).unwrap()
1060 .relative_expiry(one_hour.as_secs() as u32)
1062 .sign(recipient_sign).unwrap();
1063 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1064 #[cfg(feature = "std")]
1065 assert!(!invoice.is_expired());
1066 assert_eq!(invoice.relative_expiry(), one_hour);
1067 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1069 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1072 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1074 .sign(payer_sign).unwrap()
1075 .respond_with(payment_paths(), payment_hash(), now - one_hour).unwrap()
1076 .relative_expiry(one_hour.as_secs() as u32 - 1)
1078 .sign(recipient_sign).unwrap();
1079 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1080 #[cfg(feature = "std")]
1081 assert!(invoice.is_expired());
1082 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1083 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1087 fn builds_invoice_with_amount_from_request() {
1088 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1091 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1092 .amount_msats(1001).unwrap()
1094 .sign(payer_sign).unwrap()
1095 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1097 .sign(recipient_sign).unwrap();
1098 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1099 assert_eq!(invoice.amount_msats(), 1001);
1100 assert_eq!(tlv_stream.amount, Some(1001));
1104 fn builds_invoice_with_fallback_address() {
1105 let script = Script::new();
1106 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1107 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1108 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1110 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1113 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1115 .sign(payer_sign).unwrap()
1116 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1117 .fallback_v0_p2wsh(&script.wscript_hash())
1118 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1119 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1121 .sign(recipient_sign).unwrap();
1122 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1124 invoice.fallbacks(),
1126 Address::p2wsh(&script, Network::Bitcoin),
1127 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1128 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1132 tlv_stream.fallbacks,
1135 version: WitnessVersion::V0.to_num(),
1136 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1139 version: WitnessVersion::V0.to_num(),
1140 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1143 version: WitnessVersion::V1.to_num(),
1144 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1151 fn builds_invoice_with_allow_mpp() {
1152 let mut features = Bolt12InvoiceFeatures::empty();
1153 features.set_basic_mpp_optional();
1155 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1158 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1160 .sign(payer_sign).unwrap()
1161 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1164 .sign(recipient_sign).unwrap();
1165 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1166 assert_eq!(invoice.features(), &features);
1167 assert_eq!(tlv_stream.features, Some(&features));
1171 fn fails_signing_invoice() {
1172 match OfferBuilder::new("foo".into(), recipient_pubkey())
1175 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1177 .sign(payer_sign).unwrap()
1178 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1182 Ok(_) => panic!("expected error"),
1183 Err(e) => assert_eq!(e, SignError::Signing(())),
1186 match OfferBuilder::new("foo".into(), recipient_pubkey())
1189 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1191 .sign(payer_sign).unwrap()
1192 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1196 Ok(_) => panic!("expected error"),
1197 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1202 fn parses_invoice_with_payment_paths() {
1203 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1206 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1208 .sign(payer_sign).unwrap()
1209 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1211 .sign(recipient_sign).unwrap();
1213 let mut buffer = Vec::new();
1214 invoice.write(&mut buffer).unwrap();
1216 if let Err(e) = Invoice::try_from(buffer) {
1217 panic!("error parsing invoice: {:?}", e);
1220 let mut tlv_stream = invoice.as_tlv_stream();
1221 tlv_stream.3.paths = None;
1223 match Invoice::try_from(tlv_stream.to_bytes()) {
1224 Ok(_) => panic!("expected error"),
1225 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1228 let mut tlv_stream = invoice.as_tlv_stream();
1229 tlv_stream.3.blindedpay = None;
1231 match Invoice::try_from(tlv_stream.to_bytes()) {
1232 Ok(_) => panic!("expected error"),
1233 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1236 let empty_payment_paths = vec![];
1237 let mut tlv_stream = invoice.as_tlv_stream();
1238 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1240 match Invoice::try_from(tlv_stream.to_bytes()) {
1241 Ok(_) => panic!("expected error"),
1242 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1245 let mut payment_paths = payment_paths();
1246 payment_paths.pop();
1247 let mut tlv_stream = invoice.as_tlv_stream();
1248 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1250 match Invoice::try_from(tlv_stream.to_bytes()) {
1251 Ok(_) => panic!("expected error"),
1252 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1257 fn parses_invoice_with_created_at() {
1258 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1261 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1263 .sign(payer_sign).unwrap()
1264 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1266 .sign(recipient_sign).unwrap();
1268 let mut buffer = Vec::new();
1269 invoice.write(&mut buffer).unwrap();
1271 if let Err(e) = Invoice::try_from(buffer) {
1272 panic!("error parsing invoice: {:?}", e);
1275 let mut tlv_stream = invoice.as_tlv_stream();
1276 tlv_stream.3.created_at = None;
1278 match Invoice::try_from(tlv_stream.to_bytes()) {
1279 Ok(_) => panic!("expected error"),
1281 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1287 fn parses_invoice_with_relative_expiry() {
1288 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1291 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1293 .sign(payer_sign).unwrap()
1294 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1295 .relative_expiry(3600)
1297 .sign(recipient_sign).unwrap();
1299 let mut buffer = Vec::new();
1300 invoice.write(&mut buffer).unwrap();
1302 match Invoice::try_from(buffer) {
1303 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1304 Err(e) => panic!("error parsing invoice: {:?}", e),
1309 fn parses_invoice_with_payment_hash() {
1310 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1313 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 .sign(payer_sign).unwrap()
1316 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1318 .sign(recipient_sign).unwrap();
1320 let mut buffer = Vec::new();
1321 invoice.write(&mut buffer).unwrap();
1323 if let Err(e) = Invoice::try_from(buffer) {
1324 panic!("error parsing invoice: {:?}", e);
1327 let mut tlv_stream = invoice.as_tlv_stream();
1328 tlv_stream.3.payment_hash = None;
1330 match Invoice::try_from(tlv_stream.to_bytes()) {
1331 Ok(_) => panic!("expected error"),
1333 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1339 fn parses_invoice_with_amount() {
1340 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1345 .sign(payer_sign).unwrap()
1346 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1348 .sign(recipient_sign).unwrap();
1350 let mut buffer = Vec::new();
1351 invoice.write(&mut buffer).unwrap();
1353 if let Err(e) = Invoice::try_from(buffer) {
1354 panic!("error parsing invoice: {:?}", e);
1357 let mut tlv_stream = invoice.as_tlv_stream();
1358 tlv_stream.3.amount = None;
1360 match Invoice::try_from(tlv_stream.to_bytes()) {
1361 Ok(_) => panic!("expected error"),
1362 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1367 fn parses_invoice_with_allow_mpp() {
1368 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1371 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1373 .sign(payer_sign).unwrap()
1374 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1377 .sign(recipient_sign).unwrap();
1379 let mut buffer = Vec::new();
1380 invoice.write(&mut buffer).unwrap();
1382 match Invoice::try_from(buffer) {
1384 let mut features = Bolt12InvoiceFeatures::empty();
1385 features.set_basic_mpp_optional();
1386 assert_eq!(invoice.features(), &features);
1388 Err(e) => panic!("error parsing invoice: {:?}", e),
1393 fn parses_invoice_with_fallback_address() {
1394 let script = Script::new();
1395 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1396 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1397 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1399 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1402 let invoice_request = offer
1403 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .sign(payer_sign).unwrap();
1406 let mut unsigned_invoice = invoice_request
1407 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1408 .fallback_v0_p2wsh(&script.wscript_hash())
1409 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1410 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1413 // Only standard addresses will be included.
1414 let mut fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1415 // Non-standard addresses
1416 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1417 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1418 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1420 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1421 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1423 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1424 let mut buffer = Vec::new();
1425 invoice.write(&mut buffer).unwrap();
1427 match Invoice::try_from(buffer) {
1430 invoice.fallbacks(),
1432 Address::p2wsh(&script, Network::Bitcoin),
1433 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1434 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1436 payload: Payload::WitnessProgram {
1437 version: WitnessVersion::V1,
1438 program: vec![0u8; 33],
1440 network: Network::Bitcoin,
1443 payload: Payload::WitnessProgram {
1444 version: WitnessVersion::V2,
1445 program: vec![0u8; 40],
1447 network: Network::Bitcoin,
1452 Err(e) => panic!("error parsing invoice: {:?}", e),
1457 fn parses_invoice_with_node_id() {
1458 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1461 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1463 .sign(payer_sign).unwrap()
1464 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1466 .sign(recipient_sign).unwrap();
1468 let mut buffer = Vec::new();
1469 invoice.write(&mut buffer).unwrap();
1471 if let Err(e) = Invoice::try_from(buffer) {
1472 panic!("error parsing invoice: {:?}", e);
1475 let mut tlv_stream = invoice.as_tlv_stream();
1476 tlv_stream.3.node_id = None;
1478 match Invoice::try_from(tlv_stream.to_bytes()) {
1479 Ok(_) => panic!("expected error"),
1481 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1485 let invalid_pubkey = payer_pubkey();
1486 let mut tlv_stream = invoice.as_tlv_stream();
1487 tlv_stream.3.node_id = Some(&invalid_pubkey);
1489 match Invoice::try_from(tlv_stream.to_bytes()) {
1490 Ok(_) => panic!("expected error"),
1492 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1498 fn fails_parsing_invoice_without_signature() {
1499 let mut buffer = Vec::new();
1500 OfferBuilder::new("foo".into(), recipient_pubkey())
1503 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1505 .sign(payer_sign).unwrap()
1506 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1509 .write(&mut buffer).unwrap();
1511 match Invoice::try_from(buffer) {
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1518 fn fails_parsing_invoice_with_invalid_signature() {
1519 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1522 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1524 .sign(payer_sign).unwrap()
1525 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1527 .sign(recipient_sign).unwrap();
1528 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1529 *last_signature_byte = last_signature_byte.wrapping_add(1);
1531 let mut buffer = Vec::new();
1532 invoice.write(&mut buffer).unwrap();
1534 match Invoice::try_from(buffer) {
1535 Ok(_) => panic!("expected error"),
1537 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1543 fn fails_parsing_invoice_with_extra_tlv_records() {
1544 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1547 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1549 .sign(payer_sign).unwrap()
1550 .respond_with(payment_paths(), payment_hash(), now()).unwrap()
1552 .sign(recipient_sign).unwrap();
1554 let mut encoded_invoice = Vec::new();
1555 invoice.write(&mut encoded_invoice).unwrap();
1556 BigSize(1002).write(&mut encoded_invoice).unwrap();
1557 BigSize(32).write(&mut encoded_invoice).unwrap();
1558 [42u8; 32].write(&mut encoded_invoice).unwrap();
1560 match Invoice::try_from(encoded_invoice) {
1561 Ok(_) => panic!("expected error"),
1562 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),