1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `invoice` messages.
12 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! the invoice to the intended payer, who will then pay it.
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
20 //! extern crate bitcoin;
21 //! extern crate lightning;
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::onion_message::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49 .respond_with(payment_paths, payment_hash)?
51 #![cfg_attr(not(feature = "std"), doc = "
52 .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
54 //! .relative_expiry(3600)
56 //! .fallback_v0_p2wpkh(&wpubkey_hash)
58 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //! .expect("failed verifying signature")
60 //! .write(&mut buffer)
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
74 //! // Invoice for the "offer for money" flow.
76 //! .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78 .respond_with(payment_paths, payment_hash, pubkey)?
80 #![cfg_attr(not(feature = "std"), doc = "
81 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
83 //! .relative_expiry(3600)
85 //! .fallback_v0_p2wpkh(&wpubkey_hash)
87 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //! .expect("failed verifying signature")
89 //! .write(&mut buffer)
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{Message, PublicKey};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::TryFrom;
105 use core::time::Duration;
107 use crate::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
119 use crate::prelude::*;
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
132 /// See [module-level documentation] for usage.
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138 invreq_bytes: &'a Vec<u8>,
139 invoice: InvoiceContents,
142 impl<'a> InvoiceBuilder<'a> {
143 pub(super) fn for_offer(
144 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145 created_at: Duration, payment_hash: PaymentHash
146 ) -> Result<Self, SemanticError> {
147 let amount_msats = match invoice_request.amount_msats() {
148 Some(amount_msats) => amount_msats,
149 None => match invoice_request.contents.offer.amount() {
150 Some(Amount::Bitcoin { amount_msats }) => {
151 amount_msats * invoice_request.quantity().unwrap_or(1)
153 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
154 None => return Err(SemanticError::MissingAmount),
158 let contents = InvoiceContents::ForOffer {
159 invoice_request: invoice_request.contents.clone(),
160 fields: InvoiceFields {
161 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
162 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
163 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
167 Self::new(&invoice_request.bytes, contents)
170 pub(super) fn for_refund(
171 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
172 payment_hash: PaymentHash, signing_pubkey: PublicKey
173 ) -> Result<Self, SemanticError> {
174 let contents = InvoiceContents::ForRefund {
175 refund: refund.contents.clone(),
176 fields: InvoiceFields {
177 payment_paths, created_at, relative_expiry: None, payment_hash,
178 amount_msats: refund.amount_msats(), fallbacks: None,
179 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
183 Self::new(&refund.bytes, contents)
186 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
187 if contents.fields().payment_paths.is_empty() {
188 return Err(SemanticError::MissingPaths);
191 Ok(Self { invreq_bytes, invoice: contents })
194 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
195 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
197 /// Successive calls to this method will override the previous setting.
198 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
199 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
200 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
204 /// Adds a P2WSH address to [`Invoice::fallbacks`].
206 /// Successive calls to this method will add another address. Caller is responsible for not
207 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
208 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
209 let address = FallbackAddress {
210 version: WitnessVersion::V0.to_num(),
211 program: Vec::from(&script_hash.into_inner()[..]),
213 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
217 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
219 /// Successive calls to this method will add another address. Caller is responsible for not
220 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
221 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
222 let address = FallbackAddress {
223 version: WitnessVersion::V0.to_num(),
224 program: Vec::from(&pubkey_hash.into_inner()[..]),
226 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
230 /// Adds a P2TR address to [`Invoice::fallbacks`].
232 /// Successive calls to this method will add another address. Caller is responsible for not
233 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
234 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
235 let address = FallbackAddress {
236 version: WitnessVersion::V1.to_num(),
237 program: Vec::from(&output_key.serialize()[..]),
239 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
243 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
244 pub fn allow_mpp(mut self) -> Self {
245 self.invoice.fields_mut().features.set_basic_mpp_optional();
249 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
250 /// [`UnsignedInvoice::sign`].
251 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
252 #[cfg(feature = "std")] {
253 if self.invoice.is_offer_or_refund_expired() {
254 return Err(SemanticError::AlreadyExpired);
258 let InvoiceBuilder { invreq_bytes, invoice } = self;
259 Ok(UnsignedInvoice { invreq_bytes, invoice })
263 /// A semantically valid [`Invoice`] that hasn't been signed.
264 pub struct UnsignedInvoice<'a> {
265 invreq_bytes: &'a Vec<u8>,
266 invoice: InvoiceContents,
269 impl<'a> UnsignedInvoice<'a> {
270 /// Signs the invoice using the given function.
271 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
273 F: FnOnce(&Message) -> Result<Signature, E>
275 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
276 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
278 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
279 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
280 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
282 let mut bytes = Vec::new();
283 unsigned_tlv_stream.write(&mut bytes).unwrap();
285 let pubkey = self.invoice.fields().signing_pubkey;
286 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
288 // Append the signature TLV record to the bytes.
289 let signature_tlv_stream = SignatureTlvStreamRef {
290 signature: Some(&signature),
292 signature_tlv_stream.write(&mut bytes).unwrap();
296 contents: self.invoice,
302 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
304 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
305 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
307 /// [`Offer`]: crate::offers::offer::Offer
308 /// [`Refund`]: crate::offers::refund::Refund
309 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
310 #[derive(Clone, Debug, PartialEq)]
313 contents: InvoiceContents,
314 signature: Signature,
317 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
319 /// [`Offer`]: crate::offers::offer::Offer
320 /// [`Refund`]: crate::offers::refund::Refund
321 #[derive(Clone, Debug, PartialEq)]
322 enum InvoiceContents {
323 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
325 /// [`Offer`]: crate::offers::offer::Offer
327 invoice_request: InvoiceRequestContents,
328 fields: InvoiceFields,
330 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
332 /// [`Refund`]: crate::offers::refund::Refund
334 refund: RefundContents,
335 fields: InvoiceFields,
339 /// Invoice-specific fields for an `invoice` message.
340 #[derive(Clone, Debug, PartialEq)]
341 struct InvoiceFields {
342 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
343 created_at: Duration,
344 relative_expiry: Option<Duration>,
345 payment_hash: PaymentHash,
347 fallbacks: Option<Vec<FallbackAddress>>,
348 features: Bolt12InvoiceFeatures,
349 signing_pubkey: PublicKey,
353 /// Paths to the recipient originating from publicly reachable nodes, including information
354 /// needed for routing payments across them.
356 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
357 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
358 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
359 &self.contents.fields().payment_paths[..]
362 /// Duration since the Unix epoch when the invoice was created.
363 pub fn created_at(&self) -> Duration {
364 self.contents.fields().created_at
367 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
369 pub fn relative_expiry(&self) -> Duration {
370 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
373 /// Whether the invoice has expired.
374 #[cfg(feature = "std")]
375 pub fn is_expired(&self) -> bool {
376 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
377 match absolute_expiry {
378 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
379 Ok(elapsed) => elapsed > seconds_from_epoch,
386 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
387 pub fn payment_hash(&self) -> PaymentHash {
388 self.contents.fields().payment_hash
391 /// The minimum amount required for a successful payment of the invoice.
392 pub fn amount_msats(&self) -> u64 {
393 self.contents.fields().amount_msats
396 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
398 pub fn fallbacks(&self) -> Vec<Address> {
399 let network = match self.network() {
400 None => return Vec::new(),
401 Some(network) => network,
404 let to_valid_address = |address: &FallbackAddress| {
405 let version = match WitnessVersion::try_from(address.version) {
406 Ok(version) => version,
407 Err(_) => return None,
410 let program = &address.program;
411 if program.len() < 2 || program.len() > 40 {
415 let address = Address {
416 payload: Payload::WitnessProgram {
418 program: address.program.clone(),
423 if !address.is_standard() && version == WitnessVersion::V0 {
430 self.contents.fields().fallbacks
432 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
433 .unwrap_or_else(Vec::new)
436 fn network(&self) -> Option<Network> {
437 let chain = self.contents.chain();
438 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
439 Some(Network::Bitcoin)
440 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
441 Some(Network::Testnet)
442 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
443 Some(Network::Signet)
444 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
445 Some(Network::Regtest)
451 /// Features pertaining to paying an invoice.
452 pub fn features(&self) -> &Bolt12InvoiceFeatures {
453 &self.contents.fields().features
456 /// The public key used to sign invoices.
457 pub fn signing_pubkey(&self) -> PublicKey {
458 self.contents.fields().signing_pubkey
461 /// Signature of the invoice using [`Invoice::signing_pubkey`].
462 pub fn signature(&self) -> Signature {
467 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
468 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
469 self.contents.as_tlv_stream();
470 let signature_tlv_stream = SignatureTlvStreamRef {
471 signature: Some(&self.signature),
473 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
474 signature_tlv_stream)
478 impl InvoiceContents {
479 /// Whether the original offer or refund has expired.
480 #[cfg(feature = "std")]
481 fn is_offer_or_refund_expired(&self) -> bool {
483 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
484 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
488 fn chain(&self) -> ChainHash {
490 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
491 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
495 fn fields(&self) -> &InvoiceFields {
497 InvoiceContents::ForOffer { fields, .. } => fields,
498 InvoiceContents::ForRefund { fields, .. } => fields,
502 fn fields_mut(&mut self) -> &mut InvoiceFields {
504 InvoiceContents::ForOffer { fields, .. } => fields,
505 InvoiceContents::ForRefund { fields, .. } => fields,
509 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
510 let (payer, offer, invoice_request) = match self {
511 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
512 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
514 let invoice = self.fields().as_tlv_stream();
516 (payer, offer, invoice_request, invoice)
521 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
523 if self.features == Bolt12InvoiceFeatures::empty() { None }
524 else { Some(&self.features) }
527 InvoiceTlvStreamRef {
528 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
529 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
530 created_at: Some(self.created_at.as_secs()),
531 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
532 payment_hash: Some(&self.payment_hash),
533 amount: Some(self.amount_msats),
534 fallbacks: self.fallbacks.as_ref(),
536 node_id: Some(&self.signing_pubkey),
541 impl Writeable for Invoice {
542 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
543 WithoutLength(&self.bytes).write(writer)
547 impl Writeable for InvoiceContents {
548 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
549 self.as_tlv_stream().write(writer)
553 impl TryFrom<Vec<u8>> for Invoice {
554 type Error = ParseError;
556 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
557 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
558 Invoice::try_from(parsed_invoice)
562 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
563 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
564 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
565 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
566 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
567 (168, payment_hash: PaymentHash),
568 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
569 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
570 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
571 (176, node_id: PublicKey),
574 type BlindedPathIter<'a> = core::iter::Map<
575 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
576 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
579 type BlindedPayInfoIter<'a> = core::iter::Map<
580 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
581 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
584 /// Information needed to route a payment across a [`BlindedPath`].
585 #[derive(Clone, Debug, PartialEq)]
586 pub struct BlindedPayInfo {
587 /// Base fee charged (in millisatoshi) for the entire blinded path.
588 pub fee_base_msat: u32,
590 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
591 /// (i.e., 10,000 is 1%).
592 pub fee_proportional_millionths: u32,
594 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
596 pub cltv_expiry_delta: u16,
598 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
599 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
600 /// seen by the recipient.
601 pub htlc_minimum_msat: u64,
603 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
604 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
605 /// seen by the recipient.
606 pub htlc_maximum_msat: u64,
608 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
610 pub features: BlindedHopFeatures,
613 impl_writeable!(BlindedPayInfo, {
615 fee_proportional_millionths,
622 /// Wire representation for an on-chain fallback address.
623 #[derive(Clone, Debug, PartialEq)]
624 pub(super) struct FallbackAddress {
629 impl_writeable!(FallbackAddress, { version, program });
631 type FullInvoiceTlvStream =
632 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
635 type FullInvoiceTlvStreamRef<'a> = (
636 PayerTlvStreamRef<'a>,
637 OfferTlvStreamRef<'a>,
638 InvoiceRequestTlvStreamRef<'a>,
639 InvoiceTlvStreamRef<'a>,
640 SignatureTlvStreamRef<'a>,
643 impl SeekReadable for FullInvoiceTlvStream {
644 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
645 let payer = SeekReadable::read(r)?;
646 let offer = SeekReadable::read(r)?;
647 let invoice_request = SeekReadable::read(r)?;
648 let invoice = SeekReadable::read(r)?;
649 let signature = SeekReadable::read(r)?;
651 Ok((payer, offer, invoice_request, invoice, signature))
655 type PartialInvoiceTlvStream =
656 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
658 type PartialInvoiceTlvStreamRef<'a> = (
659 PayerTlvStreamRef<'a>,
660 OfferTlvStreamRef<'a>,
661 InvoiceRequestTlvStreamRef<'a>,
662 InvoiceTlvStreamRef<'a>,
665 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
666 type Error = ParseError;
668 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
669 let ParsedMessage { bytes, tlv_stream } = invoice;
671 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
672 SignatureTlvStream { signature },
674 let contents = InvoiceContents::try_from(
675 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
678 let signature = match signature {
679 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
680 Some(signature) => signature,
682 let pubkey = contents.fields().signing_pubkey;
683 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
685 Ok(Invoice { bytes, contents, signature })
689 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
690 type Error = SemanticError;
692 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
696 invoice_request_tlv_stream,
698 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
703 let payment_paths = match (paths, blindedpay) {
704 (None, _) => return Err(SemanticError::MissingPaths),
705 (_, None) => return Err(SemanticError::InvalidPayInfo),
706 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
707 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
708 return Err(SemanticError::InvalidPayInfo);
710 (Some(paths), Some(blindedpay)) => {
711 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
715 let created_at = match created_at {
716 None => return Err(SemanticError::MissingCreationTime),
717 Some(timestamp) => Duration::from_secs(timestamp),
720 let relative_expiry = relative_expiry
721 .map(Into::<u64>::into)
722 .map(Duration::from_secs);
724 let payment_hash = match payment_hash {
725 None => return Err(SemanticError::MissingPaymentHash),
726 Some(payment_hash) => payment_hash,
729 let amount_msats = match amount {
730 None => return Err(SemanticError::MissingAmount),
731 Some(amount) => amount,
734 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
736 let signing_pubkey = match node_id {
737 None => return Err(SemanticError::MissingSigningPubkey),
738 Some(node_id) => node_id,
741 let fields = InvoiceFields {
742 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
743 features, signing_pubkey,
746 match offer_tlv_stream.node_id {
747 Some(expected_signing_pubkey) => {
748 if fields.signing_pubkey != expected_signing_pubkey {
749 return Err(SemanticError::InvalidSigningPubkey);
752 let invoice_request = InvoiceRequestContents::try_from(
753 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
755 Ok(InvoiceContents::ForOffer { invoice_request, fields })
758 let refund = RefundContents::try_from(
759 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
761 Ok(InvoiceContents::ForRefund { refund, fields })
769 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
771 use bitcoin::blockdata::script::Script;
772 use bitcoin::hashes::Hash;
773 use bitcoin::network::constants::Network;
774 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
775 use bitcoin::secp256k1::schnorr::Signature;
776 use bitcoin::util::address::{Address, Payload, WitnessVersion};
777 use bitcoin::util::schnorr::TweakedPublicKey;
778 use core::convert::{Infallible, TryFrom};
779 use core::time::Duration;
780 use crate::ln::PaymentHash;
781 use crate::ln::msgs::DecodeError;
782 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
783 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
784 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
785 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
786 use crate::offers::parse::{ParseError, SemanticError};
787 use crate::offers::payer::PayerTlvStreamRef;
788 use crate::offers::refund::RefundBuilder;
789 use crate::onion_message::{BlindedHop, BlindedPath};
790 use crate::util::ser::{BigSize, Iterable, Writeable};
792 fn payer_keys() -> KeyPair {
793 let secp_ctx = Secp256k1::new();
794 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
797 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
798 let secp_ctx = Secp256k1::new();
799 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
800 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
803 fn payer_pubkey() -> PublicKey {
804 payer_keys().public_key()
807 fn recipient_keys() -> KeyPair {
808 let secp_ctx = Secp256k1::new();
809 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
812 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
813 let secp_ctx = Secp256k1::new();
814 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
815 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
818 fn recipient_pubkey() -> PublicKey {
819 recipient_keys().public_key()
822 fn pubkey(byte: u8) -> PublicKey {
823 let secp_ctx = Secp256k1::new();
824 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
827 fn privkey(byte: u8) -> SecretKey {
828 SecretKey::from_slice(&[byte; 32]).unwrap()
832 fn to_bytes(&self) -> Vec<u8>;
835 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
836 fn to_bytes(&self) -> Vec<u8> {
837 let mut buffer = Vec::new();
838 self.0.write(&mut buffer).unwrap();
839 self.1.write(&mut buffer).unwrap();
840 self.2.write(&mut buffer).unwrap();
841 self.3.write(&mut buffer).unwrap();
842 self.4.write(&mut buffer).unwrap();
847 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
850 introduction_node_id: pubkey(40),
851 blinding_point: pubkey(41),
853 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
854 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
858 introduction_node_id: pubkey(40),
859 blinding_point: pubkey(41),
861 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
862 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
870 fee_proportional_millionths: 1_000,
871 cltv_expiry_delta: 42,
872 htlc_minimum_msat: 100,
873 htlc_maximum_msat: 1_000_000_000_000,
874 features: BlindedHopFeatures::empty(),
878 fee_proportional_millionths: 1_000,
879 cltv_expiry_delta: 42,
880 htlc_minimum_msat: 100,
881 htlc_maximum_msat: 1_000_000_000_000,
882 features: BlindedHopFeatures::empty(),
886 paths.into_iter().zip(payinfo.into_iter()).collect()
889 fn payment_hash() -> PaymentHash {
890 PaymentHash([42; 32])
893 fn now() -> Duration {
894 std::time::SystemTime::now()
895 .duration_since(std::time::SystemTime::UNIX_EPOCH)
896 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
900 fn builds_invoice_for_offer_with_defaults() {
901 let payment_paths = payment_paths();
902 let payment_hash = payment_hash();
904 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
907 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
909 .sign(payer_sign).unwrap()
910 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
912 .sign(recipient_sign).unwrap();
914 let mut buffer = Vec::new();
915 invoice.write(&mut buffer).unwrap();
917 assert_eq!(invoice.bytes, buffer.as_slice());
918 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
919 assert_eq!(invoice.created_at(), now);
920 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
921 #[cfg(feature = "std")]
922 assert!(!invoice.is_expired());
923 assert_eq!(invoice.payment_hash(), payment_hash);
924 assert_eq!(invoice.amount_msats(), 1000);
925 assert_eq!(invoice.fallbacks(), vec![]);
926 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
927 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
929 merkle::verify_signature(
930 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
935 invoice.as_tlv_stream(),
937 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
943 description: Some(&String::from("foo")),
945 absolute_expiry: None,
949 node_id: Some(&recipient_pubkey()),
951 InvoiceRequestTlvStreamRef {
956 payer_id: Some(&payer_pubkey()),
959 InvoiceTlvStreamRef {
960 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
961 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
962 created_at: Some(now.as_secs()),
963 relative_expiry: None,
964 payment_hash: Some(&payment_hash),
968 node_id: Some(&recipient_pubkey()),
970 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
974 if let Err(e) = Invoice::try_from(buffer) {
975 panic!("error parsing invoice: {:?}", e);
980 fn builds_invoice_for_refund_with_defaults() {
981 let payment_paths = payment_paths();
982 let payment_hash = payment_hash();
984 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
986 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
989 .sign(recipient_sign).unwrap();
991 let mut buffer = Vec::new();
992 invoice.write(&mut buffer).unwrap();
994 assert_eq!(invoice.bytes, buffer.as_slice());
995 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
996 assert_eq!(invoice.created_at(), now);
997 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
998 #[cfg(feature = "std")]
999 assert!(!invoice.is_expired());
1000 assert_eq!(invoice.payment_hash(), payment_hash);
1001 assert_eq!(invoice.amount_msats(), 1000);
1002 assert_eq!(invoice.fallbacks(), vec![]);
1003 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1004 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1006 merkle::verify_signature(
1007 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1012 invoice.as_tlv_stream(),
1014 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1020 description: Some(&String::from("foo")),
1022 absolute_expiry: None,
1028 InvoiceRequestTlvStreamRef {
1033 payer_id: Some(&payer_pubkey()),
1036 InvoiceTlvStreamRef {
1037 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1038 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1039 created_at: Some(now.as_secs()),
1040 relative_expiry: None,
1041 payment_hash: Some(&payment_hash),
1045 node_id: Some(&recipient_pubkey()),
1047 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1051 if let Err(e) = Invoice::try_from(buffer) {
1052 panic!("error parsing invoice: {:?}", e);
1056 #[cfg(feature = "std")]
1058 fn builds_invoice_from_offer_with_expiration() {
1059 let future_expiry = Duration::from_secs(u64::max_value());
1060 let past_expiry = Duration::from_secs(0);
1062 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1064 .absolute_expiry(future_expiry)
1066 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1068 .sign(payer_sign).unwrap()
1069 .respond_with(payment_paths(), payment_hash())
1073 panic!("error building invoice: {:?}", e);
1076 match OfferBuilder::new("foo".into(), recipient_pubkey())
1078 .absolute_expiry(past_expiry)
1080 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1082 .sign(payer_sign).unwrap()
1083 .respond_with(payment_paths(), payment_hash())
1087 Ok(_) => panic!("expected error"),
1088 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1092 #[cfg(feature = "std")]
1094 fn builds_invoice_from_refund_with_expiration() {
1095 let future_expiry = Duration::from_secs(u64::max_value());
1096 let past_expiry = Duration::from_secs(0);
1098 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1099 .absolute_expiry(future_expiry)
1101 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1105 panic!("error building invoice: {:?}", e);
1108 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1109 .absolute_expiry(past_expiry)
1111 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1115 Ok(_) => panic!("expected error"),
1116 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1121 fn builds_invoice_with_relative_expiry() {
1123 let one_hour = Duration::from_secs(3600);
1125 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1128 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1130 .sign(payer_sign).unwrap()
1131 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1132 .relative_expiry(one_hour.as_secs() as u32)
1134 .sign(recipient_sign).unwrap();
1135 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1136 #[cfg(feature = "std")]
1137 assert!(!invoice.is_expired());
1138 assert_eq!(invoice.relative_expiry(), one_hour);
1139 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1141 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1144 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1146 .sign(payer_sign).unwrap()
1147 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1148 .relative_expiry(one_hour.as_secs() as u32 - 1)
1150 .sign(recipient_sign).unwrap();
1151 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1152 #[cfg(feature = "std")]
1153 assert!(invoice.is_expired());
1154 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1155 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1159 fn builds_invoice_with_amount_from_request() {
1160 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1163 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .amount_msats(1001).unwrap()
1166 .sign(payer_sign).unwrap()
1167 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1169 .sign(recipient_sign).unwrap();
1170 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1171 assert_eq!(invoice.amount_msats(), 1001);
1172 assert_eq!(tlv_stream.amount, Some(1001));
1176 fn builds_invoice_with_fallback_address() {
1177 let script = Script::new();
1178 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1179 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1180 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1182 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1185 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1187 .sign(payer_sign).unwrap()
1188 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1189 .fallback_v0_p2wsh(&script.wscript_hash())
1190 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1191 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1193 .sign(recipient_sign).unwrap();
1194 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1196 invoice.fallbacks(),
1198 Address::p2wsh(&script, Network::Bitcoin),
1199 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1200 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1204 tlv_stream.fallbacks,
1207 version: WitnessVersion::V0.to_num(),
1208 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1211 version: WitnessVersion::V0.to_num(),
1212 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1215 version: WitnessVersion::V1.to_num(),
1216 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1223 fn builds_invoice_with_allow_mpp() {
1224 let mut features = Bolt12InvoiceFeatures::empty();
1225 features.set_basic_mpp_optional();
1227 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1230 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1232 .sign(payer_sign).unwrap()
1233 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1236 .sign(recipient_sign).unwrap();
1237 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1238 assert_eq!(invoice.features(), &features);
1239 assert_eq!(tlv_stream.features, Some(&features));
1243 fn fails_signing_invoice() {
1244 match OfferBuilder::new("foo".into(), recipient_pubkey())
1247 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 .sign(payer_sign).unwrap()
1250 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1254 Ok(_) => panic!("expected error"),
1255 Err(e) => assert_eq!(e, SignError::Signing(())),
1258 match OfferBuilder::new("foo".into(), recipient_pubkey())
1261 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1263 .sign(payer_sign).unwrap()
1264 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1268 Ok(_) => panic!("expected error"),
1269 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1274 fn parses_invoice_with_payment_paths() {
1275 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1278 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1280 .sign(payer_sign).unwrap()
1281 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1283 .sign(recipient_sign).unwrap();
1285 let mut buffer = Vec::new();
1286 invoice.write(&mut buffer).unwrap();
1288 if let Err(e) = Invoice::try_from(buffer) {
1289 panic!("error parsing invoice: {:?}", e);
1292 let mut tlv_stream = invoice.as_tlv_stream();
1293 tlv_stream.3.paths = None;
1295 match Invoice::try_from(tlv_stream.to_bytes()) {
1296 Ok(_) => panic!("expected error"),
1297 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1300 let mut tlv_stream = invoice.as_tlv_stream();
1301 tlv_stream.3.blindedpay = None;
1303 match Invoice::try_from(tlv_stream.to_bytes()) {
1304 Ok(_) => panic!("expected error"),
1305 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1308 let empty_payment_paths = vec![];
1309 let mut tlv_stream = invoice.as_tlv_stream();
1310 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1312 match Invoice::try_from(tlv_stream.to_bytes()) {
1313 Ok(_) => panic!("expected error"),
1314 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1317 let mut payment_paths = payment_paths();
1318 payment_paths.pop();
1319 let mut tlv_stream = invoice.as_tlv_stream();
1320 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1322 match Invoice::try_from(tlv_stream.to_bytes()) {
1323 Ok(_) => panic!("expected error"),
1324 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1329 fn parses_invoice_with_created_at() {
1330 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1333 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1335 .sign(payer_sign).unwrap()
1336 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1338 .sign(recipient_sign).unwrap();
1340 let mut buffer = Vec::new();
1341 invoice.write(&mut buffer).unwrap();
1343 if let Err(e) = Invoice::try_from(buffer) {
1344 panic!("error parsing invoice: {:?}", e);
1347 let mut tlv_stream = invoice.as_tlv_stream();
1348 tlv_stream.3.created_at = None;
1350 match Invoice::try_from(tlv_stream.to_bytes()) {
1351 Ok(_) => panic!("expected error"),
1353 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1359 fn parses_invoice_with_relative_expiry() {
1360 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1363 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1365 .sign(payer_sign).unwrap()
1366 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1367 .relative_expiry(3600)
1369 .sign(recipient_sign).unwrap();
1371 let mut buffer = Vec::new();
1372 invoice.write(&mut buffer).unwrap();
1374 match Invoice::try_from(buffer) {
1375 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1376 Err(e) => panic!("error parsing invoice: {:?}", e),
1381 fn parses_invoice_with_payment_hash() {
1382 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1385 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1387 .sign(payer_sign).unwrap()
1388 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1390 .sign(recipient_sign).unwrap();
1392 let mut buffer = Vec::new();
1393 invoice.write(&mut buffer).unwrap();
1395 if let Err(e) = Invoice::try_from(buffer) {
1396 panic!("error parsing invoice: {:?}", e);
1399 let mut tlv_stream = invoice.as_tlv_stream();
1400 tlv_stream.3.payment_hash = None;
1402 match Invoice::try_from(tlv_stream.to_bytes()) {
1403 Ok(_) => panic!("expected error"),
1405 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1411 fn parses_invoice_with_amount() {
1412 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1415 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1417 .sign(payer_sign).unwrap()
1418 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1420 .sign(recipient_sign).unwrap();
1422 let mut buffer = Vec::new();
1423 invoice.write(&mut buffer).unwrap();
1425 if let Err(e) = Invoice::try_from(buffer) {
1426 panic!("error parsing invoice: {:?}", e);
1429 let mut tlv_stream = invoice.as_tlv_stream();
1430 tlv_stream.3.amount = None;
1432 match Invoice::try_from(tlv_stream.to_bytes()) {
1433 Ok(_) => panic!("expected error"),
1434 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1439 fn parses_invoice_with_allow_mpp() {
1440 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1443 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1445 .sign(payer_sign).unwrap()
1446 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1449 .sign(recipient_sign).unwrap();
1451 let mut buffer = Vec::new();
1452 invoice.write(&mut buffer).unwrap();
1454 match Invoice::try_from(buffer) {
1456 let mut features = Bolt12InvoiceFeatures::empty();
1457 features.set_basic_mpp_optional();
1458 assert_eq!(invoice.features(), &features);
1460 Err(e) => panic!("error parsing invoice: {:?}", e),
1465 fn parses_invoice_with_fallback_address() {
1466 let script = Script::new();
1467 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1468 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1469 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1471 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1474 let invoice_request = offer
1475 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 .sign(payer_sign).unwrap();
1478 let mut unsigned_invoice = invoice_request
1479 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1480 .fallback_v0_p2wsh(&script.wscript_hash())
1481 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1482 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1485 // Only standard addresses will be included.
1486 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1487 // Non-standard addresses
1488 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1489 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1490 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1492 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1493 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1495 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1496 let mut buffer = Vec::new();
1497 invoice.write(&mut buffer).unwrap();
1499 match Invoice::try_from(buffer) {
1502 invoice.fallbacks(),
1504 Address::p2wsh(&script, Network::Bitcoin),
1505 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1506 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1508 payload: Payload::WitnessProgram {
1509 version: WitnessVersion::V1,
1510 program: vec![0u8; 33],
1512 network: Network::Bitcoin,
1515 payload: Payload::WitnessProgram {
1516 version: WitnessVersion::V2,
1517 program: vec![0u8; 40],
1519 network: Network::Bitcoin,
1524 Err(e) => panic!("error parsing invoice: {:?}", e),
1529 fn parses_invoice_with_node_id() {
1530 let invoice = 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()
1538 .sign(recipient_sign).unwrap();
1540 let mut buffer = Vec::new();
1541 invoice.write(&mut buffer).unwrap();
1543 if let Err(e) = Invoice::try_from(buffer) {
1544 panic!("error parsing invoice: {:?}", e);
1547 let mut tlv_stream = invoice.as_tlv_stream();
1548 tlv_stream.3.node_id = None;
1550 match Invoice::try_from(tlv_stream.to_bytes()) {
1551 Ok(_) => panic!("expected error"),
1553 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1557 let invalid_pubkey = payer_pubkey();
1558 let mut tlv_stream = invoice.as_tlv_stream();
1559 tlv_stream.3.node_id = Some(&invalid_pubkey);
1561 match Invoice::try_from(tlv_stream.to_bytes()) {
1562 Ok(_) => panic!("expected error"),
1564 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1570 fn fails_parsing_invoice_without_signature() {
1571 let mut buffer = Vec::new();
1572 OfferBuilder::new("foo".into(), recipient_pubkey())
1575 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1577 .sign(payer_sign).unwrap()
1578 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1581 .write(&mut buffer).unwrap();
1583 match Invoice::try_from(buffer) {
1584 Ok(_) => panic!("expected error"),
1585 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1590 fn fails_parsing_invoice_with_invalid_signature() {
1591 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1594 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1596 .sign(payer_sign).unwrap()
1597 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1599 .sign(recipient_sign).unwrap();
1600 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1601 *last_signature_byte = last_signature_byte.wrapping_add(1);
1603 let mut buffer = Vec::new();
1604 invoice.write(&mut buffer).unwrap();
1606 match Invoice::try_from(buffer) {
1607 Ok(_) => panic!("expected error"),
1609 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1615 fn fails_parsing_invoice_with_extra_tlv_records() {
1616 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1619 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1621 .sign(payer_sign).unwrap()
1622 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1624 .sign(recipient_sign).unwrap();
1626 let mut encoded_invoice = Vec::new();
1627 invoice.write(&mut encoded_invoice).unwrap();
1628 BigSize(1002).write(&mut encoded_invoice).unwrap();
1629 BigSize(32).write(&mut encoded_invoice).unwrap();
1630 [42u8; 32].write(&mut encoded_invoice).unwrap();
1632 match Invoice::try_from(encoded_invoice) {
1633 Ok(_) => panic!("expected error"),
1634 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),