1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `invoice` messages.
12 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! the invoice to the intended payer, who will then pay it.
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
20 //! extern crate bitcoin;
21 //! extern crate lightning;
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::onion_message::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49 .respond_with(payment_paths, payment_hash)?
51 #![cfg_attr(not(feature = "std"), doc = "
52 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
54 //! .relative_expiry(3600)
56 //! .fallback_v0_p2wpkh(&wpubkey_hash)
58 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //! .expect("failed verifying signature")
60 //! .write(&mut buffer)
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
74 //! // Invoice for the "offer for money" flow.
76 //! .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78 .respond_with(payment_paths, payment_hash, pubkey)?
80 #![cfg_attr(not(feature = "std"), doc = "
81 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
83 //! .relative_expiry(3600)
85 //! .fallback_v0_p2wpkh(&wpubkey_hash)
87 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //! .expect("failed verifying signature")
89 //! .write(&mut buffer)
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{Message, PublicKey};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::TryFrom;
105 use core::time::Duration;
107 use crate::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
119 use crate::prelude::*;
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
132 /// See [module-level documentation] for usage.
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138 invreq_bytes: &'a Vec<u8>,
139 invoice: InvoiceContents,
142 impl<'a> InvoiceBuilder<'a> {
143 pub(super) fn for_offer(
144 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145 created_at: Duration, payment_hash: PaymentHash
146 ) -> Result<Self, SemanticError> {
147 let amount_msats = match invoice_request.amount_msats() {
148 Some(amount_msats) => amount_msats,
149 None => match invoice_request.contents.inner.offer.amount() {
150 Some(Amount::Bitcoin { amount_msats }) => {
151 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
152 .ok_or(SemanticError::InvalidAmount)?
154 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
155 None => return Err(SemanticError::MissingAmount),
159 let contents = InvoiceContents::ForOffer {
160 invoice_request: invoice_request.contents.clone(),
161 fields: InvoiceFields {
162 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
163 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
164 signing_pubkey: invoice_request.contents.inner.offer.signing_pubkey(),
168 Self::new(&invoice_request.bytes, contents)
171 pub(super) fn for_refund(
172 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
173 payment_hash: PaymentHash, signing_pubkey: PublicKey
174 ) -> Result<Self, SemanticError> {
175 let contents = InvoiceContents::ForRefund {
176 refund: refund.contents.clone(),
177 fields: InvoiceFields {
178 payment_paths, created_at, relative_expiry: None, payment_hash,
179 amount_msats: refund.amount_msats(), fallbacks: None,
180 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
184 Self::new(&refund.bytes, contents)
187 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
188 if contents.fields().payment_paths.is_empty() {
189 return Err(SemanticError::MissingPaths);
192 Ok(Self { invreq_bytes, invoice: contents })
195 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
196 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
198 /// Successive calls to this method will override the previous setting.
199 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
200 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
201 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
205 /// Adds a P2WSH address to [`Invoice::fallbacks`].
207 /// Successive calls to this method will add another address. Caller is responsible for not
208 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
209 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
210 let address = FallbackAddress {
211 version: WitnessVersion::V0.to_num(),
212 program: Vec::from(&script_hash.into_inner()[..]),
214 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
218 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
220 /// Successive calls to this method will add another address. Caller is responsible for not
221 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
222 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
223 let address = FallbackAddress {
224 version: WitnessVersion::V0.to_num(),
225 program: Vec::from(&pubkey_hash.into_inner()[..]),
227 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
231 /// Adds a P2TR address to [`Invoice::fallbacks`].
233 /// Successive calls to this method will add another address. Caller is responsible for not
234 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
235 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
236 let address = FallbackAddress {
237 version: WitnessVersion::V1.to_num(),
238 program: Vec::from(&output_key.serialize()[..]),
240 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
244 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
245 pub fn allow_mpp(mut self) -> Self {
246 self.invoice.fields_mut().features.set_basic_mpp_optional();
250 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
251 /// [`UnsignedInvoice::sign`].
252 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
253 #[cfg(feature = "std")] {
254 if self.invoice.is_offer_or_refund_expired() {
255 return Err(SemanticError::AlreadyExpired);
259 let InvoiceBuilder { invreq_bytes, invoice } = self;
260 Ok(UnsignedInvoice { invreq_bytes, invoice })
264 /// A semantically valid [`Invoice`] that hasn't been signed.
265 pub struct UnsignedInvoice<'a> {
266 invreq_bytes: &'a Vec<u8>,
267 invoice: InvoiceContents,
270 impl<'a> UnsignedInvoice<'a> {
271 /// The public key corresponding to the key needed to sign the invoice.
272 pub fn signing_pubkey(&self) -> PublicKey {
273 self.invoice.fields().signing_pubkey
276 /// Signs the invoice using the given function.
277 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
279 F: FnOnce(&Message) -> Result<Signature, E>
281 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
282 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
284 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
285 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
286 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
288 let mut bytes = Vec::new();
289 unsigned_tlv_stream.write(&mut bytes).unwrap();
291 let pubkey = self.invoice.fields().signing_pubkey;
292 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
294 // Append the signature TLV record to the bytes.
295 let signature_tlv_stream = SignatureTlvStreamRef {
296 signature: Some(&signature),
298 signature_tlv_stream.write(&mut bytes).unwrap();
302 contents: self.invoice,
308 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
310 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
311 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
313 /// [`Offer`]: crate::offers::offer::Offer
314 /// [`Refund`]: crate::offers::refund::Refund
315 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
316 #[derive(Clone, Debug)]
317 #[cfg_attr(test, derive(PartialEq))]
320 contents: InvoiceContents,
321 signature: Signature,
324 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
326 /// [`Offer`]: crate::offers::offer::Offer
327 /// [`Refund`]: crate::offers::refund::Refund
328 #[derive(Clone, Debug)]
329 #[cfg_attr(test, derive(PartialEq))]
330 enum InvoiceContents {
331 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
333 /// [`Offer`]: crate::offers::offer::Offer
335 invoice_request: InvoiceRequestContents,
336 fields: InvoiceFields,
338 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
340 /// [`Refund`]: crate::offers::refund::Refund
342 refund: RefundContents,
343 fields: InvoiceFields,
347 /// Invoice-specific fields for an `invoice` message.
348 #[derive(Clone, Debug, PartialEq)]
349 struct InvoiceFields {
350 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
351 created_at: Duration,
352 relative_expiry: Option<Duration>,
353 payment_hash: PaymentHash,
355 fallbacks: Option<Vec<FallbackAddress>>,
356 features: Bolt12InvoiceFeatures,
357 signing_pubkey: PublicKey,
361 /// Paths to the recipient originating from publicly reachable nodes, including information
362 /// needed for routing payments across them.
364 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
365 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
366 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
367 &self.contents.fields().payment_paths[..]
370 /// Duration since the Unix epoch when the invoice was created.
371 pub fn created_at(&self) -> Duration {
372 self.contents.fields().created_at
375 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
377 pub fn relative_expiry(&self) -> Duration {
378 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
381 /// Whether the invoice has expired.
382 #[cfg(feature = "std")]
383 pub fn is_expired(&self) -> bool {
384 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
385 match absolute_expiry {
386 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
387 Ok(elapsed) => elapsed > seconds_from_epoch,
394 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
395 pub fn payment_hash(&self) -> PaymentHash {
396 self.contents.fields().payment_hash
399 /// The minimum amount required for a successful payment of the invoice.
400 pub fn amount_msats(&self) -> u64 {
401 self.contents.fields().amount_msats
404 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
406 pub fn fallbacks(&self) -> Vec<Address> {
407 let network = match self.network() {
408 None => return Vec::new(),
409 Some(network) => network,
412 let to_valid_address = |address: &FallbackAddress| {
413 let version = match WitnessVersion::try_from(address.version) {
414 Ok(version) => version,
415 Err(_) => return None,
418 let program = &address.program;
419 if program.len() < 2 || program.len() > 40 {
423 let address = Address {
424 payload: Payload::WitnessProgram {
426 program: address.program.clone(),
431 if !address.is_standard() && version == WitnessVersion::V0 {
438 self.contents.fields().fallbacks
440 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
441 .unwrap_or_else(Vec::new)
444 fn network(&self) -> Option<Network> {
445 let chain = self.contents.chain();
446 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
447 Some(Network::Bitcoin)
448 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
449 Some(Network::Testnet)
450 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
451 Some(Network::Signet)
452 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
453 Some(Network::Regtest)
459 /// Features pertaining to paying an invoice.
460 pub fn features(&self) -> &Bolt12InvoiceFeatures {
461 &self.contents.fields().features
464 /// The public key corresponding to the key used to sign the invoice.
465 pub fn signing_pubkey(&self) -> PublicKey {
466 self.contents.fields().signing_pubkey
469 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
470 pub fn signature(&self) -> Signature {
474 /// Hash that was used for signing the invoice.
475 pub fn signable_hash(&self) -> [u8; 32] {
476 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
480 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
481 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
482 self.contents.as_tlv_stream();
483 let signature_tlv_stream = SignatureTlvStreamRef {
484 signature: Some(&self.signature),
486 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
487 signature_tlv_stream)
491 impl InvoiceContents {
492 /// Whether the original offer or refund has expired.
493 #[cfg(feature = "std")]
494 fn is_offer_or_refund_expired(&self) -> bool {
496 InvoiceContents::ForOffer { invoice_request, .. } =>
497 invoice_request.inner.offer.is_expired(),
498 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
502 fn chain(&self) -> ChainHash {
504 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
505 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
509 fn fields(&self) -> &InvoiceFields {
511 InvoiceContents::ForOffer { fields, .. } => fields,
512 InvoiceContents::ForRefund { fields, .. } => fields,
516 fn fields_mut(&mut self) -> &mut InvoiceFields {
518 InvoiceContents::ForOffer { fields, .. } => fields,
519 InvoiceContents::ForRefund { fields, .. } => fields,
523 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
524 let (payer, offer, invoice_request) = match self {
525 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
526 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
528 let invoice = self.fields().as_tlv_stream();
530 (payer, offer, invoice_request, invoice)
535 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
537 if self.features == Bolt12InvoiceFeatures::empty() { None }
538 else { Some(&self.features) }
541 InvoiceTlvStreamRef {
542 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
543 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
544 created_at: Some(self.created_at.as_secs()),
545 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
546 payment_hash: Some(&self.payment_hash),
547 amount: Some(self.amount_msats),
548 fallbacks: self.fallbacks.as_ref(),
550 node_id: Some(&self.signing_pubkey),
555 impl Writeable for Invoice {
556 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
557 WithoutLength(&self.bytes).write(writer)
561 impl Writeable for InvoiceContents {
562 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
563 self.as_tlv_stream().write(writer)
567 impl TryFrom<Vec<u8>> for Invoice {
568 type Error = ParseError;
570 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
571 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
572 Invoice::try_from(parsed_invoice)
576 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
577 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
578 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
579 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
580 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
581 (168, payment_hash: PaymentHash),
582 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
583 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
584 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
585 (176, node_id: PublicKey),
588 type BlindedPathIter<'a> = core::iter::Map<
589 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
590 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
593 type BlindedPayInfoIter<'a> = core::iter::Map<
594 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
595 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
598 /// Information needed to route a payment across a [`BlindedPath`].
599 #[derive(Clone, Debug, PartialEq)]
600 pub struct BlindedPayInfo {
601 /// Base fee charged (in millisatoshi) for the entire blinded path.
602 pub fee_base_msat: u32,
604 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
605 /// (i.e., 10,000 is 1%).
606 pub fee_proportional_millionths: u32,
608 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
610 pub cltv_expiry_delta: u16,
612 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
613 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
614 /// seen by the recipient.
615 pub htlc_minimum_msat: u64,
617 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
618 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
619 /// seen by the recipient.
620 pub htlc_maximum_msat: u64,
622 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
624 pub features: BlindedHopFeatures,
627 impl_writeable!(BlindedPayInfo, {
629 fee_proportional_millionths,
636 /// Wire representation for an on-chain fallback address.
637 #[derive(Clone, Debug, PartialEq)]
638 pub(super) struct FallbackAddress {
643 impl_writeable!(FallbackAddress, { version, program });
645 type FullInvoiceTlvStream =
646 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
649 type FullInvoiceTlvStreamRef<'a> = (
650 PayerTlvStreamRef<'a>,
651 OfferTlvStreamRef<'a>,
652 InvoiceRequestTlvStreamRef<'a>,
653 InvoiceTlvStreamRef<'a>,
654 SignatureTlvStreamRef<'a>,
657 impl SeekReadable for FullInvoiceTlvStream {
658 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
659 let payer = SeekReadable::read(r)?;
660 let offer = SeekReadable::read(r)?;
661 let invoice_request = SeekReadable::read(r)?;
662 let invoice = SeekReadable::read(r)?;
663 let signature = SeekReadable::read(r)?;
665 Ok((payer, offer, invoice_request, invoice, signature))
669 type PartialInvoiceTlvStream =
670 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
672 type PartialInvoiceTlvStreamRef<'a> = (
673 PayerTlvStreamRef<'a>,
674 OfferTlvStreamRef<'a>,
675 InvoiceRequestTlvStreamRef<'a>,
676 InvoiceTlvStreamRef<'a>,
679 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
680 type Error = ParseError;
682 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
683 let ParsedMessage { bytes, tlv_stream } = invoice;
685 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
686 SignatureTlvStream { signature },
688 let contents = InvoiceContents::try_from(
689 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
692 let signature = match signature {
693 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
694 Some(signature) => signature,
696 let pubkey = contents.fields().signing_pubkey;
697 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
699 Ok(Invoice { bytes, contents, signature })
703 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
704 type Error = SemanticError;
706 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
710 invoice_request_tlv_stream,
712 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
717 let payment_paths = match (paths, blindedpay) {
718 (None, _) => return Err(SemanticError::MissingPaths),
719 (_, None) => return Err(SemanticError::InvalidPayInfo),
720 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
721 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
722 return Err(SemanticError::InvalidPayInfo);
724 (Some(paths), Some(blindedpay)) => {
725 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
729 let created_at = match created_at {
730 None => return Err(SemanticError::MissingCreationTime),
731 Some(timestamp) => Duration::from_secs(timestamp),
734 let relative_expiry = relative_expiry
735 .map(Into::<u64>::into)
736 .map(Duration::from_secs);
738 let payment_hash = match payment_hash {
739 None => return Err(SemanticError::MissingPaymentHash),
740 Some(payment_hash) => payment_hash,
743 let amount_msats = match amount {
744 None => return Err(SemanticError::MissingAmount),
745 Some(amount) => amount,
748 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
750 let signing_pubkey = match node_id {
751 None => return Err(SemanticError::MissingSigningPubkey),
752 Some(node_id) => node_id,
755 let fields = InvoiceFields {
756 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
757 features, signing_pubkey,
760 match offer_tlv_stream.node_id {
761 Some(expected_signing_pubkey) => {
762 if fields.signing_pubkey != expected_signing_pubkey {
763 return Err(SemanticError::InvalidSigningPubkey);
766 let invoice_request = InvoiceRequestContents::try_from(
767 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
769 Ok(InvoiceContents::ForOffer { invoice_request, fields })
772 let refund = RefundContents::try_from(
773 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
775 Ok(InvoiceContents::ForRefund { refund, fields })
783 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
785 use bitcoin::blockdata::script::Script;
786 use bitcoin::hashes::Hash;
787 use bitcoin::network::constants::Network;
788 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
789 use bitcoin::util::address::{Address, Payload, WitnessVersion};
790 use bitcoin::util::schnorr::TweakedPublicKey;
791 use core::convert::TryFrom;
792 use core::time::Duration;
793 use crate::ln::msgs::DecodeError;
794 use crate::ln::features::Bolt12InvoiceFeatures;
795 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
796 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
797 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
798 use crate::offers::parse::{ParseError, SemanticError};
799 use crate::offers::payer::PayerTlvStreamRef;
800 use crate::offers::refund::RefundBuilder;
801 use crate::offers::test_utils::*;
802 use crate::util::ser::{BigSize, Iterable, Writeable};
805 fn to_bytes(&self) -> Vec<u8>;
808 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
809 fn to_bytes(&self) -> Vec<u8> {
810 let mut buffer = Vec::new();
811 self.0.write(&mut buffer).unwrap();
812 self.1.write(&mut buffer).unwrap();
813 self.2.write(&mut buffer).unwrap();
814 self.3.write(&mut buffer).unwrap();
815 self.4.write(&mut buffer).unwrap();
821 fn builds_invoice_for_offer_with_defaults() {
822 let payment_paths = payment_paths();
823 let payment_hash = payment_hash();
825 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
828 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
830 .sign(payer_sign).unwrap()
831 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
833 .sign(recipient_sign).unwrap();
835 let mut buffer = Vec::new();
836 invoice.write(&mut buffer).unwrap();
838 assert_eq!(invoice.bytes, buffer.as_slice());
839 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
840 assert_eq!(invoice.created_at(), now);
841 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
842 #[cfg(feature = "std")]
843 assert!(!invoice.is_expired());
844 assert_eq!(invoice.payment_hash(), payment_hash);
845 assert_eq!(invoice.amount_msats(), 1000);
846 assert_eq!(invoice.fallbacks(), vec![]);
847 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
848 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
850 merkle::verify_signature(
851 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
855 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
856 let pubkey = recipient_pubkey().into();
857 let secp_ctx = Secp256k1::verification_only();
858 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
861 invoice.as_tlv_stream(),
863 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
869 description: Some(&String::from("foo")),
871 absolute_expiry: None,
875 node_id: Some(&recipient_pubkey()),
877 InvoiceRequestTlvStreamRef {
882 payer_id: Some(&payer_pubkey()),
885 InvoiceTlvStreamRef {
886 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
887 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
888 created_at: Some(now.as_secs()),
889 relative_expiry: None,
890 payment_hash: Some(&payment_hash),
894 node_id: Some(&recipient_pubkey()),
896 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
900 if let Err(e) = Invoice::try_from(buffer) {
901 panic!("error parsing invoice: {:?}", e);
906 fn builds_invoice_for_refund_with_defaults() {
907 let payment_paths = payment_paths();
908 let payment_hash = payment_hash();
910 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
912 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
915 .sign(recipient_sign).unwrap();
917 let mut buffer = Vec::new();
918 invoice.write(&mut buffer).unwrap();
920 assert_eq!(invoice.bytes, buffer.as_slice());
921 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
922 assert_eq!(invoice.created_at(), now);
923 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
924 #[cfg(feature = "std")]
925 assert!(!invoice.is_expired());
926 assert_eq!(invoice.payment_hash(), payment_hash);
927 assert_eq!(invoice.amount_msats(), 1000);
928 assert_eq!(invoice.fallbacks(), vec![]);
929 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
930 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
932 merkle::verify_signature(
933 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
938 invoice.as_tlv_stream(),
940 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
946 description: Some(&String::from("foo")),
948 absolute_expiry: None,
954 InvoiceRequestTlvStreamRef {
959 payer_id: Some(&payer_pubkey()),
962 InvoiceTlvStreamRef {
963 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
964 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
965 created_at: Some(now.as_secs()),
966 relative_expiry: None,
967 payment_hash: Some(&payment_hash),
971 node_id: Some(&recipient_pubkey()),
973 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
977 if let Err(e) = Invoice::try_from(buffer) {
978 panic!("error parsing invoice: {:?}", e);
982 #[cfg(feature = "std")]
984 fn builds_invoice_from_offer_with_expiration() {
985 let future_expiry = Duration::from_secs(u64::max_value());
986 let past_expiry = Duration::from_secs(0);
988 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
990 .absolute_expiry(future_expiry)
992 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
994 .sign(payer_sign).unwrap()
995 .respond_with(payment_paths(), payment_hash())
999 panic!("error building invoice: {:?}", e);
1002 match OfferBuilder::new("foo".into(), recipient_pubkey())
1004 .absolute_expiry(past_expiry)
1006 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1008 .sign(payer_sign).unwrap()
1009 .respond_with(payment_paths(), payment_hash())
1013 Ok(_) => panic!("expected error"),
1014 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1018 #[cfg(feature = "std")]
1020 fn builds_invoice_from_refund_with_expiration() {
1021 let future_expiry = Duration::from_secs(u64::max_value());
1022 let past_expiry = Duration::from_secs(0);
1024 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1025 .absolute_expiry(future_expiry)
1027 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1031 panic!("error building invoice: {:?}", e);
1034 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1035 .absolute_expiry(past_expiry)
1037 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1041 Ok(_) => panic!("expected error"),
1042 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1047 fn builds_invoice_with_relative_expiry() {
1049 let one_hour = Duration::from_secs(3600);
1051 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1054 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1056 .sign(payer_sign).unwrap()
1057 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1058 .relative_expiry(one_hour.as_secs() as u32)
1060 .sign(recipient_sign).unwrap();
1061 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1062 #[cfg(feature = "std")]
1063 assert!(!invoice.is_expired());
1064 assert_eq!(invoice.relative_expiry(), one_hour);
1065 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1067 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1070 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1072 .sign(payer_sign).unwrap()
1073 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1074 .relative_expiry(one_hour.as_secs() as u32 - 1)
1076 .sign(recipient_sign).unwrap();
1077 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1078 #[cfg(feature = "std")]
1079 assert!(invoice.is_expired());
1080 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1081 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1085 fn builds_invoice_with_amount_from_request() {
1086 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1089 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1090 .amount_msats(1001).unwrap()
1092 .sign(payer_sign).unwrap()
1093 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1095 .sign(recipient_sign).unwrap();
1096 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1097 assert_eq!(invoice.amount_msats(), 1001);
1098 assert_eq!(tlv_stream.amount, Some(1001));
1102 fn builds_invoice_with_quantity_from_request() {
1103 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1105 .supported_quantity(Quantity::Unbounded)
1107 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1108 .quantity(2).unwrap()
1110 .sign(payer_sign).unwrap()
1111 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1113 .sign(recipient_sign).unwrap();
1114 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1115 assert_eq!(invoice.amount_msats(), 2000);
1116 assert_eq!(tlv_stream.amount, Some(2000));
1118 match OfferBuilder::new("foo".into(), recipient_pubkey())
1120 .supported_quantity(Quantity::Unbounded)
1122 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1123 .quantity(u64::max_value()).unwrap()
1125 .sign(payer_sign).unwrap()
1126 .respond_with_no_std(payment_paths(), payment_hash(), now())
1128 Ok(_) => panic!("expected error"),
1129 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1134 fn builds_invoice_with_fallback_address() {
1135 let script = Script::new();
1136 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1137 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1138 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1140 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1143 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1145 .sign(payer_sign).unwrap()
1146 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1147 .fallback_v0_p2wsh(&script.wscript_hash())
1148 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1149 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1151 .sign(recipient_sign).unwrap();
1152 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1154 invoice.fallbacks(),
1156 Address::p2wsh(&script, Network::Bitcoin),
1157 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1158 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1162 tlv_stream.fallbacks,
1165 version: WitnessVersion::V0.to_num(),
1166 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1169 version: WitnessVersion::V0.to_num(),
1170 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1173 version: WitnessVersion::V1.to_num(),
1174 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1181 fn builds_invoice_with_allow_mpp() {
1182 let mut features = Bolt12InvoiceFeatures::empty();
1183 features.set_basic_mpp_optional();
1185 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1188 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1190 .sign(payer_sign).unwrap()
1191 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1194 .sign(recipient_sign).unwrap();
1195 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1196 assert_eq!(invoice.features(), &features);
1197 assert_eq!(tlv_stream.features, Some(&features));
1201 fn fails_signing_invoice() {
1202 match OfferBuilder::new("foo".into(), recipient_pubkey())
1205 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1207 .sign(payer_sign).unwrap()
1208 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1212 Ok(_) => panic!("expected error"),
1213 Err(e) => assert_eq!(e, SignError::Signing(())),
1216 match OfferBuilder::new("foo".into(), recipient_pubkey())
1219 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1221 .sign(payer_sign).unwrap()
1222 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1226 Ok(_) => panic!("expected error"),
1227 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1232 fn parses_invoice_with_payment_paths() {
1233 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1238 .sign(payer_sign).unwrap()
1239 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1241 .sign(recipient_sign).unwrap();
1243 let mut buffer = Vec::new();
1244 invoice.write(&mut buffer).unwrap();
1246 if let Err(e) = Invoice::try_from(buffer) {
1247 panic!("error parsing invoice: {:?}", e);
1250 let mut tlv_stream = invoice.as_tlv_stream();
1251 tlv_stream.3.paths = None;
1253 match Invoice::try_from(tlv_stream.to_bytes()) {
1254 Ok(_) => panic!("expected error"),
1255 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1258 let mut tlv_stream = invoice.as_tlv_stream();
1259 tlv_stream.3.blindedpay = None;
1261 match Invoice::try_from(tlv_stream.to_bytes()) {
1262 Ok(_) => panic!("expected error"),
1263 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1266 let empty_payment_paths = vec![];
1267 let mut tlv_stream = invoice.as_tlv_stream();
1268 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1270 match Invoice::try_from(tlv_stream.to_bytes()) {
1271 Ok(_) => panic!("expected error"),
1272 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1275 let mut payment_paths = payment_paths();
1276 payment_paths.pop();
1277 let mut tlv_stream = invoice.as_tlv_stream();
1278 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1280 match Invoice::try_from(tlv_stream.to_bytes()) {
1281 Ok(_) => panic!("expected error"),
1282 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1287 fn parses_invoice_with_created_at() {
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_no_std(payment_paths(), payment_hash(), now()).unwrap()
1296 .sign(recipient_sign).unwrap();
1298 let mut buffer = Vec::new();
1299 invoice.write(&mut buffer).unwrap();
1301 if let Err(e) = Invoice::try_from(buffer) {
1302 panic!("error parsing invoice: {:?}", e);
1305 let mut tlv_stream = invoice.as_tlv_stream();
1306 tlv_stream.3.created_at = None;
1308 match Invoice::try_from(tlv_stream.to_bytes()) {
1309 Ok(_) => panic!("expected error"),
1311 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1317 fn parses_invoice_with_relative_expiry() {
1318 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1321 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1323 .sign(payer_sign).unwrap()
1324 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1325 .relative_expiry(3600)
1327 .sign(recipient_sign).unwrap();
1329 let mut buffer = Vec::new();
1330 invoice.write(&mut buffer).unwrap();
1332 match Invoice::try_from(buffer) {
1333 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1334 Err(e) => panic!("error parsing invoice: {:?}", e),
1339 fn parses_invoice_with_payment_hash() {
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_no_std(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.payment_hash = None;
1360 match Invoice::try_from(tlv_stream.to_bytes()) {
1361 Ok(_) => panic!("expected error"),
1363 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1369 fn parses_invoice_with_amount() {
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_no_std(payment_paths(), payment_hash(), now()).unwrap()
1378 .sign(recipient_sign).unwrap();
1380 let mut buffer = Vec::new();
1381 invoice.write(&mut buffer).unwrap();
1383 if let Err(e) = Invoice::try_from(buffer) {
1384 panic!("error parsing invoice: {:?}", e);
1387 let mut tlv_stream = invoice.as_tlv_stream();
1388 tlv_stream.3.amount = None;
1390 match Invoice::try_from(tlv_stream.to_bytes()) {
1391 Ok(_) => panic!("expected error"),
1392 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1397 fn parses_invoice_with_allow_mpp() {
1398 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1401 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1403 .sign(payer_sign).unwrap()
1404 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1407 .sign(recipient_sign).unwrap();
1409 let mut buffer = Vec::new();
1410 invoice.write(&mut buffer).unwrap();
1412 match Invoice::try_from(buffer) {
1414 let mut features = Bolt12InvoiceFeatures::empty();
1415 features.set_basic_mpp_optional();
1416 assert_eq!(invoice.features(), &features);
1418 Err(e) => panic!("error parsing invoice: {:?}", e),
1423 fn parses_invoice_with_fallback_address() {
1424 let script = Script::new();
1425 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1426 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1427 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1429 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1432 let invoice_request = offer
1433 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1435 .sign(payer_sign).unwrap();
1436 let mut unsigned_invoice = invoice_request
1437 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1438 .fallback_v0_p2wsh(&script.wscript_hash())
1439 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1440 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1443 // Only standard addresses will be included.
1444 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1445 // Non-standard addresses
1446 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1447 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1448 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1450 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1451 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1453 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1454 let mut buffer = Vec::new();
1455 invoice.write(&mut buffer).unwrap();
1457 match Invoice::try_from(buffer) {
1460 invoice.fallbacks(),
1462 Address::p2wsh(&script, Network::Bitcoin),
1463 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1464 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1466 payload: Payload::WitnessProgram {
1467 version: WitnessVersion::V1,
1468 program: vec![0u8; 33],
1470 network: Network::Bitcoin,
1473 payload: Payload::WitnessProgram {
1474 version: WitnessVersion::V2,
1475 program: vec![0u8; 40],
1477 network: Network::Bitcoin,
1482 Err(e) => panic!("error parsing invoice: {:?}", e),
1487 fn parses_invoice_with_node_id() {
1488 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1491 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .sign(payer_sign).unwrap()
1494 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1496 .sign(recipient_sign).unwrap();
1498 let mut buffer = Vec::new();
1499 invoice.write(&mut buffer).unwrap();
1501 if let Err(e) = Invoice::try_from(buffer) {
1502 panic!("error parsing invoice: {:?}", e);
1505 let mut tlv_stream = invoice.as_tlv_stream();
1506 tlv_stream.3.node_id = None;
1508 match Invoice::try_from(tlv_stream.to_bytes()) {
1509 Ok(_) => panic!("expected error"),
1511 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1515 let invalid_pubkey = payer_pubkey();
1516 let mut tlv_stream = invoice.as_tlv_stream();
1517 tlv_stream.3.node_id = Some(&invalid_pubkey);
1519 match Invoice::try_from(tlv_stream.to_bytes()) {
1520 Ok(_) => panic!("expected error"),
1522 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1528 fn fails_parsing_invoice_without_signature() {
1529 let mut buffer = Vec::new();
1530 OfferBuilder::new("foo".into(), recipient_pubkey())
1533 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1535 .sign(payer_sign).unwrap()
1536 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1539 .write(&mut buffer).unwrap();
1541 match Invoice::try_from(buffer) {
1542 Ok(_) => panic!("expected error"),
1543 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1548 fn fails_parsing_invoice_with_invalid_signature() {
1549 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1552 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1554 .sign(payer_sign).unwrap()
1555 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1557 .sign(recipient_sign).unwrap();
1558 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1559 *last_signature_byte = last_signature_byte.wrapping_add(1);
1561 let mut buffer = Vec::new();
1562 invoice.write(&mut buffer).unwrap();
1564 match Invoice::try_from(buffer) {
1565 Ok(_) => panic!("expected error"),
1567 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1573 fn fails_parsing_invoice_with_extra_tlv_records() {
1574 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1577 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1579 .sign(payer_sign).unwrap()
1580 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1582 .sign(recipient_sign).unwrap();
1584 let mut encoded_invoice = Vec::new();
1585 invoice.write(&mut encoded_invoice).unwrap();
1586 BigSize(1002).write(&mut encoded_invoice).unwrap();
1587 BigSize(32).write(&mut encoded_invoice).unwrap();
1588 [42u8; 32].write(&mut encoded_invoice).unwrap();
1590 match Invoice::try_from(encoded_invoice) {
1591 Ok(_) => panic!("expected error"),
1592 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),