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 //! A [`Bolt12Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid"
13 //! flow or from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment
14 //! then sends 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::blinded_path::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPayInfo, BlindedPath)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
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>(
59 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
61 //! .expect("failed verifying signature")
62 //! .write(&mut buffer)
67 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
68 //! # let payment_paths = create_payment_paths();
69 //! # let payment_hash = create_payment_hash();
70 //! # let secp_ctx = Secp256k1::new();
71 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
72 //! # let pubkey = PublicKey::from(keys);
73 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
74 //! # let mut buffer = Vec::new();
76 //! // Invoice for the "offer for money" flow.
78 //! .parse::<Refund>()?
79 #![cfg_attr(feature = "std", doc = "
80 .respond_with(payment_paths, payment_hash, pubkey)?
82 #![cfg_attr(not(feature = "std"), doc = "
83 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
85 //! .relative_expiry(3600)
87 //! .fallback_v0_p2wpkh(&wpubkey_hash)
89 //! .sign::<_, Infallible>(
90 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
92 //! .expect("failed verifying signature")
93 //! .write(&mut buffer)
100 use bitcoin::blockdata::constants::ChainHash;
101 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
102 use bitcoin::hashes::Hash;
103 use bitcoin::network::constants::Network;
104 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
105 use bitcoin::secp256k1::schnorr::Signature;
106 use bitcoin::util::address::{Address, Payload, WitnessVersion};
107 use bitcoin::util::schnorr::TweakedPublicKey;
108 use core::convert::{AsRef, Infallible, TryFrom};
109 use core::time::Duration;
111 use crate::blinded_path::BlindedPath;
112 use crate::ln::PaymentHash;
113 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
114 use crate::ln::inbound_payment::ExpandedKey;
115 use crate::ln::msgs::DecodeError;
116 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
117 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
118 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef, Quantity};
119 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
120 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
121 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
122 use crate::offers::signer;
123 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
124 use crate::util::string::PrintableString;
126 use crate::prelude::*;
128 #[cfg(feature = "std")]
129 use std::time::SystemTime;
131 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
133 /// Tag for the hash function used when signing a [`Bolt12Invoice`]'s merkle root.
134 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
136 /// Builds a [`Bolt12Invoice`] from either:
137 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
138 /// - a [`Refund`] for the "offer for money" flow.
140 /// See [module-level documentation] for usage.
142 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
144 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
145 /// [`Refund`]: crate::offers::refund::Refund
146 /// [module-level documentation]: self
147 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
148 invreq_bytes: &'a Vec<u8>,
149 invoice: InvoiceContents,
150 signing_pubkey_strategy: S,
153 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
155 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
156 pub trait SigningPubkeyStrategy {}
158 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
160 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
161 pub struct ExplicitSigningPubkey {}
163 /// [`Bolt12Invoice::signing_pubkey`] was derived.
165 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
166 pub struct DerivedSigningPubkey(KeyPair);
168 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
169 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
171 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
172 pub(super) fn for_offer(
173 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
174 created_at: Duration, payment_hash: PaymentHash
175 ) -> Result<Self, Bolt12SemanticError> {
176 let amount_msats = Self::check_amount_msats(invoice_request)?;
177 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
178 let contents = InvoiceContents::ForOffer {
179 invoice_request: invoice_request.contents.clone(),
180 fields: Self::fields(
181 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
185 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
188 pub(super) fn for_refund(
189 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
190 payment_hash: PaymentHash, signing_pubkey: PublicKey
191 ) -> Result<Self, Bolt12SemanticError> {
192 let amount_msats = refund.amount_msats();
193 let contents = InvoiceContents::ForRefund {
194 refund: refund.contents.clone(),
195 fields: Self::fields(
196 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
200 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
204 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
205 pub(super) fn for_offer_using_keys(
206 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
207 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
208 ) -> Result<Self, Bolt12SemanticError> {
209 let amount_msats = Self::check_amount_msats(invoice_request)?;
210 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
211 let contents = InvoiceContents::ForOffer {
212 invoice_request: invoice_request.contents.clone(),
213 fields: Self::fields(
214 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
218 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
221 pub(super) fn for_refund_using_keys(
222 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
223 payment_hash: PaymentHash, keys: KeyPair,
224 ) -> Result<Self, Bolt12SemanticError> {
225 let amount_msats = refund.amount_msats();
226 let signing_pubkey = keys.public_key();
227 let contents = InvoiceContents::ForRefund {
228 refund: refund.contents.clone(),
229 fields: Self::fields(
230 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
234 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
238 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
239 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, Bolt12SemanticError> {
240 match invoice_request.amount_msats() {
241 Some(amount_msats) => Ok(amount_msats),
242 None => match invoice_request.contents.inner.offer.amount() {
243 Some(Amount::Bitcoin { amount_msats }) => {
244 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
245 .ok_or(Bolt12SemanticError::InvalidAmount)
247 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
248 None => Err(Bolt12SemanticError::MissingAmount),
254 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
255 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
258 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
259 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
264 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: S
265 ) -> Result<Self, Bolt12SemanticError> {
266 if contents.fields().payment_paths.is_empty() {
267 return Err(Bolt12SemanticError::MissingPaths);
270 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
273 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
274 /// Any expiry that has already passed is valid and can be checked for using
275 /// [`Bolt12Invoice::is_expired`].
277 /// Successive calls to this method will override the previous setting.
278 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
279 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
280 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
284 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
286 /// Successive calls to this method will add another address. Caller is responsible for not
287 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
288 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
289 let address = FallbackAddress {
290 version: WitnessVersion::V0.to_num(),
291 program: Vec::from(&script_hash.into_inner()[..]),
293 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
297 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
299 /// Successive calls to this method will add another address. Caller is responsible for not
300 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
301 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
302 let address = FallbackAddress {
303 version: WitnessVersion::V0.to_num(),
304 program: Vec::from(&pubkey_hash.into_inner()[..]),
306 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
310 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
312 /// Successive calls to this method will add another address. Caller is responsible for not
313 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
314 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
315 let address = FallbackAddress {
316 version: WitnessVersion::V1.to_num(),
317 program: Vec::from(&output_key.serialize()[..]),
319 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
323 /// Sets [`Bolt12Invoice::invoice_features`] to indicate MPP may be used. Otherwise, MPP is
325 pub fn allow_mpp(mut self) -> Self {
326 self.invoice.fields_mut().features.set_basic_mpp_optional();
331 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
332 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
333 /// [`UnsignedBolt12Invoice::sign`].
334 pub fn build(self) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
335 #[cfg(feature = "std")] {
336 if self.invoice.is_offer_or_refund_expired() {
337 return Err(Bolt12SemanticError::AlreadyExpired);
341 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
342 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
346 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
347 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
348 pub fn build_and_sign<T: secp256k1::Signing>(
349 self, secp_ctx: &Secp256k1<T>
350 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
351 #[cfg(feature = "std")] {
352 if self.invoice.is_offer_or_refund_expired() {
353 return Err(Bolt12SemanticError::AlreadyExpired);
358 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
360 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
362 let invoice = unsigned_invoice
363 .sign::<_, Infallible>(
364 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
371 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
375 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
376 /// such, it may include unknown, odd TLV records.
377 pub struct UnsignedBolt12Invoice {
379 contents: InvoiceContents,
380 tagged_hash: TaggedHash,
383 impl UnsignedBolt12Invoice {
384 fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
385 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
386 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
388 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
389 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
390 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
392 let mut bytes = Vec::new();
393 unsigned_tlv_stream.write(&mut bytes).unwrap();
395 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
397 Self { bytes, contents, tagged_hash }
400 /// Signs the [`TaggedHash`] of the invoice using the given function.
402 /// Note: The hash computation may have included unknown, odd TLV records.
404 /// This is not exported to bindings users as functions aren't currently mapped.
405 pub fn sign<F, E>(mut self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
407 F: FnOnce(&Self) -> Result<Signature, E>
409 let pubkey = self.contents.fields().signing_pubkey;
410 let signature = merkle::sign_message(sign, &self, pubkey)?;
412 // Append the signature TLV record to the bytes.
413 let signature_tlv_stream = SignatureTlvStreamRef {
414 signature: Some(&signature),
416 signature_tlv_stream.write(&mut self.bytes).unwrap();
420 contents: self.contents,
426 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
427 fn as_ref(&self) -> &TaggedHash {
432 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
434 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
435 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
437 /// [`Offer`]: crate::offers::offer::Offer
438 /// [`Refund`]: crate::offers::refund::Refund
439 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
440 #[derive(Clone, Debug)]
441 #[cfg_attr(test, derive(PartialEq))]
442 pub struct Bolt12Invoice {
444 contents: InvoiceContents,
445 signature: Signature,
448 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
450 /// [`Offer`]: crate::offers::offer::Offer
451 /// [`Refund`]: crate::offers::refund::Refund
452 #[derive(Clone, Debug)]
453 #[cfg_attr(test, derive(PartialEq))]
454 enum InvoiceContents {
455 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
457 /// [`Offer`]: crate::offers::offer::Offer
459 invoice_request: InvoiceRequestContents,
460 fields: InvoiceFields,
462 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
464 /// [`Refund`]: crate::offers::refund::Refund
466 refund: RefundContents,
467 fields: InvoiceFields,
471 /// Invoice-specific fields for an `invoice` message.
472 #[derive(Clone, Debug, PartialEq)]
473 struct InvoiceFields {
474 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
475 created_at: Duration,
476 relative_expiry: Option<Duration>,
477 payment_hash: PaymentHash,
479 fallbacks: Option<Vec<FallbackAddress>>,
480 features: Bolt12InvoiceFeatures,
481 signing_pubkey: PublicKey,
484 macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
485 /// The chains that may be used when paying a requested invoice.
487 /// From [`Offer::chains`]; `None` if the invoice was created in response to a [`Refund`].
489 /// [`Offer::chains`]: crate::offers::offer::Offer::chains
490 pub fn offer_chains(&$self) -> Option<Vec<ChainHash>> {
491 $contents.offer_chains()
494 /// The chain that must be used when paying the invoice; selected from [`offer_chains`] if the
495 /// invoice originated from an offer.
497 /// From [`InvoiceRequest::chain`] or [`Refund::chain`].
499 /// [`offer_chains`]: Self::offer_chains
500 /// [`InvoiceRequest::chain`]: crate::offers::invoice_request::InvoiceRequest::chain
501 pub fn chain(&$self) -> ChainHash {
505 /// Opaque bytes set by the originating [`Offer`].
507 /// From [`Offer::metadata`]; `None` if the invoice was created in response to a [`Refund`] or
508 /// if the [`Offer`] did not set it.
510 /// [`Offer`]: crate::offers::offer::Offer
511 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
512 pub fn metadata(&$self) -> Option<&Vec<u8>> {
516 /// The minimum amount required for a successful payment of a single item.
518 /// From [`Offer::amount`]; `None` if the invoice was created in response to a [`Refund`] or if
519 /// the [`Offer`] did not set it.
521 /// [`Offer`]: crate::offers::offer::Offer
522 /// [`Offer::amount`]: crate::offers::offer::Offer::amount
523 pub fn amount(&$self) -> Option<&Amount> {
527 /// Features pertaining to the originating [`Offer`].
529 /// From [`Offer::offer_features`]; `None` if the invoice was created in response to a
532 /// [`Offer`]: crate::offers::offer::Offer
533 /// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features
534 pub fn offer_features(&$self) -> Option<&OfferFeatures> {
535 $contents.offer_features()
538 /// A complete description of the purpose of the originating offer or refund.
540 /// From [`Offer::description`] or [`Refund::description`].
542 /// [`Offer::description`]: crate::offers::offer::Offer::description
543 pub fn description(&$self) -> PrintableString {
544 $contents.description()
547 /// Duration since the Unix epoch when an invoice should no longer be requested.
549 /// From [`Offer::absolute_expiry`] or [`Refund::absolute_expiry`].
551 /// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry
552 pub fn absolute_expiry(&$self) -> Option<Duration> {
553 $contents.absolute_expiry()
556 /// The issuer of the offer or refund.
558 /// From [`Offer::issuer`] or [`Refund::issuer`].
560 /// [`Offer::issuer`]: crate::offers::offer::Offer::issuer
561 pub fn issuer(&$self) -> Option<PrintableString> {
565 /// Paths to the recipient originating from publicly reachable nodes.
567 /// From [`Offer::paths`] or [`Refund::paths`].
569 /// [`Offer::paths`]: crate::offers::offer::Offer::paths
570 pub fn message_paths(&$self) -> &[BlindedPath] {
571 $contents.message_paths()
574 /// The quantity of items supported.
576 /// From [`Offer::supported_quantity`]; `None` if the invoice was created in response to a
579 /// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
580 pub fn supported_quantity(&$self) -> Option<Quantity> {
581 $contents.supported_quantity()
584 /// An unpredictable series of bytes from the payer.
586 /// From [`InvoiceRequest::payer_metadata`] or [`Refund::payer_metadata`].
587 pub fn payer_metadata(&$self) -> &[u8] {
588 $contents.payer_metadata()
591 /// Features pertaining to requesting an invoice.
593 /// From [`InvoiceRequest::invoice_request_features`] or [`Refund::features`].
594 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
595 &$contents.invoice_request_features()
598 /// The quantity of items requested or refunded for.
600 /// From [`InvoiceRequest::quantity`] or [`Refund::quantity`].
601 pub fn quantity(&$self) -> Option<u64> {
605 /// A possibly transient pubkey used to sign the invoice request or to send an invoice for a
606 /// refund in case there are no [`message_paths`].
608 /// [`message_paths`]: Self::message_paths
609 pub fn payer_id(&$self) -> PublicKey {
613 /// A payer-provided note reflected back in the invoice.
615 /// From [`InvoiceRequest::payer_note`] or [`Refund::payer_note`].
616 pub fn payer_note(&$self) -> Option<PrintableString> {
617 $contents.payer_note()
620 /// Paths to the recipient originating from publicly reachable nodes, including information
621 /// needed for routing payments across them.
623 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
624 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
626 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
627 /// matched in another language.
628 pub fn payment_paths(&$self) -> &[(BlindedPayInfo, BlindedPath)] {
629 $contents.payment_paths()
632 /// Duration since the Unix epoch when the invoice was created.
633 pub fn created_at(&$self) -> Duration {
634 $contents.created_at()
637 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
638 /// should no longer be paid.
639 pub fn relative_expiry(&$self) -> Duration {
640 $contents.relative_expiry()
643 /// Whether the invoice has expired.
644 #[cfg(feature = "std")]
645 pub fn is_expired(&$self) -> bool {
646 $contents.is_expired()
649 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
650 pub fn payment_hash(&$self) -> PaymentHash {
651 $contents.payment_hash()
654 /// The minimum amount required for a successful payment of the invoice.
655 pub fn amount_msats(&$self) -> u64 {
656 $contents.amount_msats()
659 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
661 pub fn fallbacks(&$self) -> Vec<Address> {
662 $contents.fallbacks()
665 /// Features pertaining to paying an invoice.
666 pub fn invoice_features(&$self) -> &Bolt12InvoiceFeatures {
670 /// The public key corresponding to the key used to sign the invoice.
671 pub fn signing_pubkey(&$self) -> PublicKey {
672 $contents.signing_pubkey()
676 impl UnsignedBolt12Invoice {
677 invoice_accessors!(self, self.contents);
681 invoice_accessors!(self, self.contents);
683 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
684 pub fn signature(&self) -> Signature {
688 /// Hash that was used for signing the invoice.
689 pub fn signable_hash(&self) -> [u8; 32] {
690 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
693 /// Verifies that the invoice was for a request or refund created using the given key.
694 pub fn verify<T: secp256k1::Signing>(
695 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
697 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
701 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
702 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
703 self.contents.as_tlv_stream();
704 let signature_tlv_stream = SignatureTlvStreamRef {
705 signature: Some(&self.signature),
707 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
708 signature_tlv_stream)
712 impl InvoiceContents {
713 /// Whether the original offer or refund has expired.
714 #[cfg(feature = "std")]
715 fn is_offer_or_refund_expired(&self) -> bool {
717 InvoiceContents::ForOffer { invoice_request, .. } =>
718 invoice_request.inner.offer.is_expired(),
719 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
723 fn offer_chains(&self) -> Option<Vec<ChainHash>> {
725 InvoiceContents::ForOffer { invoice_request, .. } =>
726 Some(invoice_request.inner.offer.chains()),
727 InvoiceContents::ForRefund { .. } => None,
731 fn chain(&self) -> ChainHash {
733 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
734 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
738 fn metadata(&self) -> Option<&Vec<u8>> {
740 InvoiceContents::ForOffer { invoice_request, .. } =>
741 invoice_request.inner.offer.metadata(),
742 InvoiceContents::ForRefund { .. } => None,
746 fn amount(&self) -> Option<&Amount> {
748 InvoiceContents::ForOffer { invoice_request, .. } =>
749 invoice_request.inner.offer.amount(),
750 InvoiceContents::ForRefund { .. } => None,
754 fn description(&self) -> PrintableString {
756 InvoiceContents::ForOffer { invoice_request, .. } => {
757 invoice_request.inner.offer.description()
759 InvoiceContents::ForRefund { refund, .. } => refund.description(),
763 fn offer_features(&self) -> Option<&OfferFeatures> {
765 InvoiceContents::ForOffer { invoice_request, .. } => {
766 Some(invoice_request.inner.offer.features())
768 InvoiceContents::ForRefund { .. } => None,
772 fn absolute_expiry(&self) -> Option<Duration> {
774 InvoiceContents::ForOffer { invoice_request, .. } => {
775 invoice_request.inner.offer.absolute_expiry()
777 InvoiceContents::ForRefund { refund, .. } => refund.absolute_expiry(),
781 fn issuer(&self) -> Option<PrintableString> {
783 InvoiceContents::ForOffer { invoice_request, .. } => {
784 invoice_request.inner.offer.issuer()
786 InvoiceContents::ForRefund { refund, .. } => refund.issuer(),
790 fn message_paths(&self) -> &[BlindedPath] {
792 InvoiceContents::ForOffer { invoice_request, .. } => {
793 invoice_request.inner.offer.paths()
795 InvoiceContents::ForRefund { refund, .. } => refund.paths(),
799 fn supported_quantity(&self) -> Option<Quantity> {
801 InvoiceContents::ForOffer { invoice_request, .. } => {
802 Some(invoice_request.inner.offer.supported_quantity())
804 InvoiceContents::ForRefund { .. } => None,
808 fn payer_metadata(&self) -> &[u8] {
810 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.metadata(),
811 InvoiceContents::ForRefund { refund, .. } => refund.metadata(),
815 fn invoice_request_features(&self) -> &InvoiceRequestFeatures {
817 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.features(),
818 InvoiceContents::ForRefund { refund, .. } => refund.features(),
822 fn quantity(&self) -> Option<u64> {
824 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.quantity(),
825 InvoiceContents::ForRefund { refund, .. } => refund.quantity(),
829 fn payer_id(&self) -> PublicKey {
831 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_id(),
832 InvoiceContents::ForRefund { refund, .. } => refund.payer_id(),
836 fn payer_note(&self) -> Option<PrintableString> {
838 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_note(),
839 InvoiceContents::ForRefund { refund, .. } => refund.payer_note(),
843 fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
844 &self.fields().payment_paths[..]
847 fn created_at(&self) -> Duration {
848 self.fields().created_at
851 fn relative_expiry(&self) -> Duration {
852 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
855 #[cfg(feature = "std")]
856 fn is_expired(&self) -> bool {
857 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
858 match absolute_expiry {
859 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
860 Ok(elapsed) => elapsed > seconds_from_epoch,
867 fn payment_hash(&self) -> PaymentHash {
868 self.fields().payment_hash
871 fn amount_msats(&self) -> u64 {
872 self.fields().amount_msats
875 fn fallbacks(&self) -> Vec<Address> {
876 let chain = self.chain();
877 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
879 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
881 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
883 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
889 let to_valid_address = |address: &FallbackAddress| {
890 let version = match WitnessVersion::try_from(address.version) {
891 Ok(version) => version,
892 Err(_) => return None,
895 let program = &address.program;
896 if program.len() < 2 || program.len() > 40 {
900 let address = Address {
901 payload: Payload::WitnessProgram {
903 program: program.clone(),
908 if !address.is_standard() && version == WitnessVersion::V0 {
915 self.fields().fallbacks
917 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
918 .unwrap_or_else(Vec::new)
921 fn features(&self) -> &Bolt12InvoiceFeatures {
922 &self.fields().features
925 fn signing_pubkey(&self) -> PublicKey {
926 self.fields().signing_pubkey
929 fn fields(&self) -> &InvoiceFields {
931 InvoiceContents::ForOffer { fields, .. } => fields,
932 InvoiceContents::ForRefund { fields, .. } => fields,
936 fn fields_mut(&mut self) -> &mut InvoiceFields {
938 InvoiceContents::ForOffer { fields, .. } => fields,
939 InvoiceContents::ForRefund { fields, .. } => fields,
943 fn verify<T: secp256k1::Signing>(
944 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
946 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
947 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
948 match record.r#type {
949 PAYER_METADATA_TYPE => false, // Should be outside range
950 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
954 let tlv_stream = offer_records.chain(invreq_records);
956 let (metadata, payer_id, iv_bytes) = match self {
957 InvoiceContents::ForOffer { invoice_request, .. } => {
958 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
960 InvoiceContents::ForRefund { refund, .. } => {
961 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
965 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
971 fn derives_keys(&self) -> bool {
973 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
974 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
978 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
979 let (payer, offer, invoice_request) = match self {
980 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
981 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
983 let invoice = self.fields().as_tlv_stream();
985 (payer, offer, invoice_request, invoice)
990 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
992 if self.features == Bolt12InvoiceFeatures::empty() { None }
993 else { Some(&self.features) }
996 InvoiceTlvStreamRef {
997 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
998 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
999 created_at: Some(self.created_at.as_secs()),
1000 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
1001 payment_hash: Some(&self.payment_hash),
1002 amount: Some(self.amount_msats),
1003 fallbacks: self.fallbacks.as_ref(),
1005 node_id: Some(&self.signing_pubkey),
1010 impl Writeable for UnsignedBolt12Invoice {
1011 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1012 WithoutLength(&self.bytes).write(writer)
1016 impl Writeable for Bolt12Invoice {
1017 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1018 WithoutLength(&self.bytes).write(writer)
1022 impl Writeable for InvoiceContents {
1023 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1024 self.as_tlv_stream().write(writer)
1028 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
1029 type Error = Bolt12ParseError;
1031 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1032 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
1033 let ParsedMessage { bytes, tlv_stream } = invoice;
1035 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1037 let contents = InvoiceContents::try_from(
1038 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1041 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1043 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
1047 impl TryFrom<Vec<u8>> for Bolt12Invoice {
1048 type Error = Bolt12ParseError;
1050 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1051 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
1052 Bolt12Invoice::try_from(parsed_invoice)
1056 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
1057 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
1058 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
1059 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
1060 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
1061 (168, payment_hash: PaymentHash),
1062 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
1063 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
1064 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
1065 (176, node_id: PublicKey),
1068 type BlindedPathIter<'a> = core::iter::Map<
1069 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1070 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
1073 type BlindedPayInfoIter<'a> = core::iter::Map<
1074 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1075 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
1078 /// Information needed to route a payment across a [`BlindedPath`].
1079 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
1080 pub struct BlindedPayInfo {
1081 /// Base fee charged (in millisatoshi) for the entire blinded path.
1082 pub fee_base_msat: u32,
1084 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
1085 /// (i.e., 10,000 is 1%).
1086 pub fee_proportional_millionths: u32,
1088 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
1090 pub cltv_expiry_delta: u16,
1092 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1093 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1094 /// seen by the recipient.
1095 pub htlc_minimum_msat: u64,
1097 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1098 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1099 /// seen by the recipient.
1100 pub htlc_maximum_msat: u64,
1102 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
1104 pub features: BlindedHopFeatures,
1107 impl_writeable!(BlindedPayInfo, {
1109 fee_proportional_millionths,
1116 /// Wire representation for an on-chain fallback address.
1117 #[derive(Clone, Debug, PartialEq)]
1118 pub(super) struct FallbackAddress {
1123 impl_writeable!(FallbackAddress, { version, program });
1125 type FullInvoiceTlvStream =
1126 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
1129 type FullInvoiceTlvStreamRef<'a> = (
1130 PayerTlvStreamRef<'a>,
1131 OfferTlvStreamRef<'a>,
1132 InvoiceRequestTlvStreamRef<'a>,
1133 InvoiceTlvStreamRef<'a>,
1134 SignatureTlvStreamRef<'a>,
1137 impl SeekReadable for FullInvoiceTlvStream {
1138 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1139 let payer = SeekReadable::read(r)?;
1140 let offer = SeekReadable::read(r)?;
1141 let invoice_request = SeekReadable::read(r)?;
1142 let invoice = SeekReadable::read(r)?;
1143 let signature = SeekReadable::read(r)?;
1145 Ok((payer, offer, invoice_request, invoice, signature))
1149 type PartialInvoiceTlvStream =
1150 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
1152 type PartialInvoiceTlvStreamRef<'a> = (
1153 PayerTlvStreamRef<'a>,
1154 OfferTlvStreamRef<'a>,
1155 InvoiceRequestTlvStreamRef<'a>,
1156 InvoiceTlvStreamRef<'a>,
1159 impl SeekReadable for PartialInvoiceTlvStream {
1160 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1161 let payer = SeekReadable::read(r)?;
1162 let offer = SeekReadable::read(r)?;
1163 let invoice_request = SeekReadable::read(r)?;
1164 let invoice = SeekReadable::read(r)?;
1166 Ok((payer, offer, invoice_request, invoice))
1170 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
1171 type Error = Bolt12ParseError;
1173 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
1174 let ParsedMessage { bytes, tlv_stream } = invoice;
1176 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1177 SignatureTlvStream { signature },
1179 let contents = InvoiceContents::try_from(
1180 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1183 let signature = match signature {
1184 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1185 Some(signature) => signature,
1187 let pubkey = contents.fields().signing_pubkey;
1188 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
1190 Ok(Bolt12Invoice { bytes, contents, signature })
1194 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
1195 type Error = Bolt12SemanticError;
1197 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
1201 invoice_request_tlv_stream,
1203 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
1208 let payment_paths = match (blindedpay, paths) {
1209 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
1210 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
1211 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1212 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
1213 return Err(Bolt12SemanticError::InvalidPayInfo);
1215 (Some(blindedpay), Some(paths)) => {
1216 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
1220 let created_at = match created_at {
1221 None => return Err(Bolt12SemanticError::MissingCreationTime),
1222 Some(timestamp) => Duration::from_secs(timestamp),
1225 let relative_expiry = relative_expiry
1226 .map(Into::<u64>::into)
1227 .map(Duration::from_secs);
1229 let payment_hash = match payment_hash {
1230 None => return Err(Bolt12SemanticError::MissingPaymentHash),
1231 Some(payment_hash) => payment_hash,
1234 let amount_msats = match amount {
1235 None => return Err(Bolt12SemanticError::MissingAmount),
1236 Some(amount) => amount,
1239 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1241 let signing_pubkey = match node_id {
1242 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1243 Some(node_id) => node_id,
1246 let fields = InvoiceFields {
1247 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1248 features, signing_pubkey,
1251 match offer_tlv_stream.node_id {
1252 Some(expected_signing_pubkey) => {
1253 if fields.signing_pubkey != expected_signing_pubkey {
1254 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1257 let invoice_request = InvoiceRequestContents::try_from(
1258 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1260 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1263 let refund = RefundContents::try_from(
1264 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1266 Ok(InvoiceContents::ForRefund { refund, fields })
1274 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1276 use bitcoin::blockdata::constants::ChainHash;
1277 use bitcoin::blockdata::script::Script;
1278 use bitcoin::hashes::Hash;
1279 use bitcoin::network::constants::Network;
1280 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
1281 use bitcoin::util::address::{Address, Payload, WitnessVersion};
1282 use bitcoin::util::schnorr::TweakedPublicKey;
1283 use core::convert::TryFrom;
1284 use core::time::Duration;
1285 use crate::blinded_path::{BlindedHop, BlindedPath};
1286 use crate::sign::KeyMaterial;
1287 use crate::ln::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
1288 use crate::ln::inbound_payment::ExpandedKey;
1289 use crate::ln::msgs::DecodeError;
1290 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1291 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
1292 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
1293 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1294 use crate::offers::payer::PayerTlvStreamRef;
1295 use crate::offers::refund::RefundBuilder;
1296 use crate::offers::test_utils::*;
1297 use crate::util::ser::{BigSize, Iterable, Writeable};
1298 use crate::util::string::PrintableString;
1301 fn to_bytes(&self) -> Vec<u8>;
1304 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1305 fn to_bytes(&self) -> Vec<u8> {
1306 let mut buffer = Vec::new();
1307 self.0.write(&mut buffer).unwrap();
1308 self.1.write(&mut buffer).unwrap();
1309 self.2.write(&mut buffer).unwrap();
1310 self.3.write(&mut buffer).unwrap();
1311 self.4.write(&mut buffer).unwrap();
1317 fn builds_invoice_for_offer_with_defaults() {
1318 let payment_paths = payment_paths();
1319 let payment_hash = payment_hash();
1321 let unsigned_invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1324 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1326 .sign(payer_sign).unwrap()
1327 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1330 let mut buffer = Vec::new();
1331 unsigned_invoice.write(&mut buffer).unwrap();
1333 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1334 assert_eq!(unsigned_invoice.payer_metadata(), &[1; 32]);
1335 assert_eq!(unsigned_invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1336 assert_eq!(unsigned_invoice.metadata(), None);
1337 assert_eq!(unsigned_invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1338 assert_eq!(unsigned_invoice.description(), PrintableString("foo"));
1339 assert_eq!(unsigned_invoice.offer_features(), Some(&OfferFeatures::empty()));
1340 assert_eq!(unsigned_invoice.absolute_expiry(), None);
1341 assert_eq!(unsigned_invoice.message_paths(), &[]);
1342 assert_eq!(unsigned_invoice.issuer(), None);
1343 assert_eq!(unsigned_invoice.supported_quantity(), Some(Quantity::One));
1344 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1345 assert_eq!(unsigned_invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1346 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1347 assert_eq!(unsigned_invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1348 assert_eq!(unsigned_invoice.quantity(), None);
1349 assert_eq!(unsigned_invoice.payer_id(), payer_pubkey());
1350 assert_eq!(unsigned_invoice.payer_note(), None);
1351 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1352 assert_eq!(unsigned_invoice.created_at(), now);
1353 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1354 #[cfg(feature = "std")]
1355 assert!(!unsigned_invoice.is_expired());
1356 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1357 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1358 assert_eq!(unsigned_invoice.fallbacks(), vec![]);
1359 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1360 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1362 match UnsignedBolt12Invoice::try_from(buffer) {
1363 Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1365 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1366 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1370 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1372 let mut buffer = Vec::new();
1373 invoice.write(&mut buffer).unwrap();
1375 assert_eq!(invoice.bytes, buffer.as_slice());
1376 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1377 assert_eq!(invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1378 assert_eq!(invoice.metadata(), None);
1379 assert_eq!(invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1380 assert_eq!(invoice.description(), PrintableString("foo"));
1381 assert_eq!(invoice.offer_features(), Some(&OfferFeatures::empty()));
1382 assert_eq!(invoice.absolute_expiry(), None);
1383 assert_eq!(invoice.message_paths(), &[]);
1384 assert_eq!(invoice.issuer(), None);
1385 assert_eq!(invoice.supported_quantity(), Some(Quantity::One));
1386 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1387 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1388 assert_eq!(invoice.amount_msats(), 1000);
1389 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1390 assert_eq!(invoice.quantity(), None);
1391 assert_eq!(invoice.payer_id(), payer_pubkey());
1392 assert_eq!(invoice.payer_note(), None);
1393 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1394 assert_eq!(invoice.created_at(), now);
1395 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1396 #[cfg(feature = "std")]
1397 assert!(!invoice.is_expired());
1398 assert_eq!(invoice.payment_hash(), payment_hash);
1399 assert_eq!(invoice.amount_msats(), 1000);
1400 assert_eq!(invoice.fallbacks(), vec![]);
1401 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1402 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1404 merkle::verify_signature(
1405 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1409 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1410 let pubkey = recipient_pubkey().into();
1411 let secp_ctx = Secp256k1::verification_only();
1412 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1415 invoice.as_tlv_stream(),
1417 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1423 description: Some(&String::from("foo")),
1425 absolute_expiry: None,
1429 node_id: Some(&recipient_pubkey()),
1431 InvoiceRequestTlvStreamRef {
1436 payer_id: Some(&payer_pubkey()),
1439 InvoiceTlvStreamRef {
1440 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1441 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1442 created_at: Some(now.as_secs()),
1443 relative_expiry: None,
1444 payment_hash: Some(&payment_hash),
1448 node_id: Some(&recipient_pubkey()),
1450 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1454 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1455 panic!("error parsing invoice: {:?}", e);
1460 fn builds_invoice_for_refund_with_defaults() {
1461 let payment_paths = payment_paths();
1462 let payment_hash = payment_hash();
1464 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1466 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1469 .sign(recipient_sign).unwrap();
1471 let mut buffer = Vec::new();
1472 invoice.write(&mut buffer).unwrap();
1474 assert_eq!(invoice.bytes, buffer.as_slice());
1475 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1476 assert_eq!(invoice.offer_chains(), None);
1477 assert_eq!(invoice.metadata(), None);
1478 assert_eq!(invoice.amount(), None);
1479 assert_eq!(invoice.description(), PrintableString("foo"));
1480 assert_eq!(invoice.offer_features(), None);
1481 assert_eq!(invoice.absolute_expiry(), None);
1482 assert_eq!(invoice.message_paths(), &[]);
1483 assert_eq!(invoice.issuer(), None);
1484 assert_eq!(invoice.supported_quantity(), None);
1485 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1486 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1487 assert_eq!(invoice.amount_msats(), 1000);
1488 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1489 assert_eq!(invoice.quantity(), None);
1490 assert_eq!(invoice.payer_id(), payer_pubkey());
1491 assert_eq!(invoice.payer_note(), None);
1492 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1493 assert_eq!(invoice.created_at(), now);
1494 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1495 #[cfg(feature = "std")]
1496 assert!(!invoice.is_expired());
1497 assert_eq!(invoice.payment_hash(), payment_hash);
1498 assert_eq!(invoice.amount_msats(), 1000);
1499 assert_eq!(invoice.fallbacks(), vec![]);
1500 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1501 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1503 merkle::verify_signature(
1504 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1509 invoice.as_tlv_stream(),
1511 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1517 description: Some(&String::from("foo")),
1519 absolute_expiry: None,
1525 InvoiceRequestTlvStreamRef {
1530 payer_id: Some(&payer_pubkey()),
1533 InvoiceTlvStreamRef {
1534 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1535 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1536 created_at: Some(now.as_secs()),
1537 relative_expiry: None,
1538 payment_hash: Some(&payment_hash),
1542 node_id: Some(&recipient_pubkey()),
1544 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1548 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1549 panic!("error parsing invoice: {:?}", e);
1553 #[cfg(feature = "std")]
1555 fn builds_invoice_from_offer_with_expiration() {
1556 let future_expiry = Duration::from_secs(u64::max_value());
1557 let past_expiry = Duration::from_secs(0);
1559 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1561 .absolute_expiry(future_expiry)
1563 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1565 .sign(payer_sign).unwrap()
1566 .respond_with(payment_paths(), payment_hash())
1570 panic!("error building invoice: {:?}", e);
1573 match OfferBuilder::new("foo".into(), recipient_pubkey())
1575 .absolute_expiry(past_expiry)
1577 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1579 .sign(payer_sign).unwrap()
1580 .respond_with(payment_paths(), payment_hash())
1584 Ok(_) => panic!("expected error"),
1585 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1589 #[cfg(feature = "std")]
1591 fn builds_invoice_from_refund_with_expiration() {
1592 let future_expiry = Duration::from_secs(u64::max_value());
1593 let past_expiry = Duration::from_secs(0);
1595 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1596 .absolute_expiry(future_expiry)
1598 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1602 panic!("error building invoice: {:?}", e);
1605 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1606 .absolute_expiry(past_expiry)
1608 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1612 Ok(_) => panic!("expected error"),
1613 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1618 fn builds_invoice_from_offer_using_derived_keys() {
1619 let desc = "foo".to_string();
1620 let node_id = recipient_pubkey();
1621 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1622 let entropy = FixedEntropy {};
1623 let secp_ctx = Secp256k1::new();
1625 let blinded_path = BlindedPath {
1626 introduction_node_id: pubkey(40),
1627 blinding_point: pubkey(41),
1629 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1630 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1634 let offer = OfferBuilder
1635 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1639 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1641 .sign(payer_sign).unwrap();
1643 if let Err(e) = invoice_request
1644 .verify_and_respond_using_derived_keys_no_std(
1645 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1648 .build_and_sign(&secp_ctx)
1650 panic!("error building invoice: {:?}", e);
1653 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1654 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1655 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1657 Ok(_) => panic!("expected error"),
1658 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1661 let desc = "foo".to_string();
1662 let offer = OfferBuilder
1663 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1666 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1668 .sign(payer_sign).unwrap();
1670 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1671 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1673 Ok(_) => panic!("expected error"),
1674 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1679 fn builds_invoice_from_refund_using_derived_keys() {
1680 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1681 let entropy = FixedEntropy {};
1682 let secp_ctx = Secp256k1::new();
1684 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1687 if let Err(e) = refund
1688 .respond_using_derived_keys_no_std(
1689 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1692 .build_and_sign(&secp_ctx)
1694 panic!("error building invoice: {:?}", e);
1699 fn builds_invoice_with_relative_expiry() {
1701 let one_hour = Duration::from_secs(3600);
1703 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1706 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1708 .sign(payer_sign).unwrap()
1709 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1710 .relative_expiry(one_hour.as_secs() as u32)
1712 .sign(recipient_sign).unwrap();
1713 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1714 #[cfg(feature = "std")]
1715 assert!(!invoice.is_expired());
1716 assert_eq!(invoice.relative_expiry(), one_hour);
1717 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1719 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1722 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1724 .sign(payer_sign).unwrap()
1725 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1726 .relative_expiry(one_hour.as_secs() as u32 - 1)
1728 .sign(recipient_sign).unwrap();
1729 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1730 #[cfg(feature = "std")]
1731 assert!(invoice.is_expired());
1732 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1733 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1737 fn builds_invoice_with_amount_from_request() {
1738 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1741 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1742 .amount_msats(1001).unwrap()
1744 .sign(payer_sign).unwrap()
1745 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1747 .sign(recipient_sign).unwrap();
1748 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1749 assert_eq!(invoice.amount_msats(), 1001);
1750 assert_eq!(tlv_stream.amount, Some(1001));
1754 fn builds_invoice_with_quantity_from_request() {
1755 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1757 .supported_quantity(Quantity::Unbounded)
1759 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1760 .quantity(2).unwrap()
1762 .sign(payer_sign).unwrap()
1763 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1765 .sign(recipient_sign).unwrap();
1766 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1767 assert_eq!(invoice.amount_msats(), 2000);
1768 assert_eq!(tlv_stream.amount, Some(2000));
1770 match OfferBuilder::new("foo".into(), recipient_pubkey())
1772 .supported_quantity(Quantity::Unbounded)
1774 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1775 .quantity(u64::max_value()).unwrap()
1777 .sign(payer_sign).unwrap()
1778 .respond_with_no_std(payment_paths(), payment_hash(), now())
1780 Ok(_) => panic!("expected error"),
1781 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1786 fn builds_invoice_with_fallback_address() {
1787 let script = Script::new();
1788 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1789 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1790 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1792 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1795 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1797 .sign(payer_sign).unwrap()
1798 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1799 .fallback_v0_p2wsh(&script.wscript_hash())
1800 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1801 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1803 .sign(recipient_sign).unwrap();
1804 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1806 invoice.fallbacks(),
1808 Address::p2wsh(&script, Network::Bitcoin),
1809 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1810 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1814 tlv_stream.fallbacks,
1817 version: WitnessVersion::V0.to_num(),
1818 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1821 version: WitnessVersion::V0.to_num(),
1822 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1825 version: WitnessVersion::V1.to_num(),
1826 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1833 fn builds_invoice_with_allow_mpp() {
1834 let mut features = Bolt12InvoiceFeatures::empty();
1835 features.set_basic_mpp_optional();
1837 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1840 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1842 .sign(payer_sign).unwrap()
1843 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1846 .sign(recipient_sign).unwrap();
1847 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1848 assert_eq!(invoice.invoice_features(), &features);
1849 assert_eq!(tlv_stream.features, Some(&features));
1853 fn fails_signing_invoice() {
1854 match OfferBuilder::new("foo".into(), recipient_pubkey())
1857 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1859 .sign(payer_sign).unwrap()
1860 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1864 Ok(_) => panic!("expected error"),
1865 Err(e) => assert_eq!(e, SignError::Signing(())),
1868 match OfferBuilder::new("foo".into(), recipient_pubkey())
1871 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1873 .sign(payer_sign).unwrap()
1874 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1878 Ok(_) => panic!("expected error"),
1879 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1884 fn parses_invoice_with_payment_paths() {
1885 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1888 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1890 .sign(payer_sign).unwrap()
1891 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1893 .sign(recipient_sign).unwrap();
1895 let mut buffer = Vec::new();
1896 invoice.write(&mut buffer).unwrap();
1898 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1899 panic!("error parsing invoice: {:?}", e);
1902 let mut tlv_stream = invoice.as_tlv_stream();
1903 tlv_stream.3.paths = None;
1905 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1906 Ok(_) => panic!("expected error"),
1907 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1910 let mut tlv_stream = invoice.as_tlv_stream();
1911 tlv_stream.3.blindedpay = None;
1913 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1914 Ok(_) => panic!("expected error"),
1915 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1918 let empty_payment_paths = vec![];
1919 let mut tlv_stream = invoice.as_tlv_stream();
1920 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1922 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1923 Ok(_) => panic!("expected error"),
1924 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1927 let mut payment_paths = payment_paths();
1928 payment_paths.pop();
1929 let mut tlv_stream = invoice.as_tlv_stream();
1930 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1932 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1933 Ok(_) => panic!("expected error"),
1934 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1939 fn parses_invoice_with_created_at() {
1940 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1943 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1945 .sign(payer_sign).unwrap()
1946 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1948 .sign(recipient_sign).unwrap();
1950 let mut buffer = Vec::new();
1951 invoice.write(&mut buffer).unwrap();
1953 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1954 panic!("error parsing invoice: {:?}", e);
1957 let mut tlv_stream = invoice.as_tlv_stream();
1958 tlv_stream.3.created_at = None;
1960 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1961 Ok(_) => panic!("expected error"),
1963 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1969 fn parses_invoice_with_relative_expiry() {
1970 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1973 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1975 .sign(payer_sign).unwrap()
1976 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1977 .relative_expiry(3600)
1979 .sign(recipient_sign).unwrap();
1981 let mut buffer = Vec::new();
1982 invoice.write(&mut buffer).unwrap();
1984 match Bolt12Invoice::try_from(buffer) {
1985 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1986 Err(e) => panic!("error parsing invoice: {:?}", e),
1991 fn parses_invoice_with_payment_hash() {
1992 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1995 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1997 .sign(payer_sign).unwrap()
1998 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2000 .sign(recipient_sign).unwrap();
2002 let mut buffer = Vec::new();
2003 invoice.write(&mut buffer).unwrap();
2005 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2006 panic!("error parsing invoice: {:?}", e);
2009 let mut tlv_stream = invoice.as_tlv_stream();
2010 tlv_stream.3.payment_hash = None;
2012 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2013 Ok(_) => panic!("expected error"),
2015 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
2021 fn parses_invoice_with_amount() {
2022 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2025 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2027 .sign(payer_sign).unwrap()
2028 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2030 .sign(recipient_sign).unwrap();
2032 let mut buffer = Vec::new();
2033 invoice.write(&mut buffer).unwrap();
2035 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2036 panic!("error parsing invoice: {:?}", e);
2039 let mut tlv_stream = invoice.as_tlv_stream();
2040 tlv_stream.3.amount = None;
2042 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2043 Ok(_) => panic!("expected error"),
2044 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2049 fn parses_invoice_with_allow_mpp() {
2050 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2053 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2055 .sign(payer_sign).unwrap()
2056 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2059 .sign(recipient_sign).unwrap();
2061 let mut buffer = Vec::new();
2062 invoice.write(&mut buffer).unwrap();
2064 match Bolt12Invoice::try_from(buffer) {
2066 let mut features = Bolt12InvoiceFeatures::empty();
2067 features.set_basic_mpp_optional();
2068 assert_eq!(invoice.invoice_features(), &features);
2070 Err(e) => panic!("error parsing invoice: {:?}", e),
2075 fn parses_invoice_with_fallback_address() {
2076 let script = Script::new();
2077 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
2078 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
2079 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
2081 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2084 let invoice_request = offer
2085 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2087 .sign(payer_sign).unwrap();
2088 let mut invoice_builder = invoice_request
2089 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2090 .fallback_v0_p2wsh(&script.wscript_hash())
2091 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
2092 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
2094 // Only standard addresses will be included.
2095 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
2096 // Non-standard addresses
2097 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
2098 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
2099 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
2101 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
2102 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
2104 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
2105 let mut buffer = Vec::new();
2106 invoice.write(&mut buffer).unwrap();
2108 match Bolt12Invoice::try_from(buffer) {
2111 invoice.fallbacks(),
2113 Address::p2wsh(&script, Network::Bitcoin),
2114 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
2115 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
2117 payload: Payload::WitnessProgram {
2118 version: WitnessVersion::V1,
2119 program: vec![0u8; 33],
2121 network: Network::Bitcoin,
2124 payload: Payload::WitnessProgram {
2125 version: WitnessVersion::V2,
2126 program: vec![0u8; 40],
2128 network: Network::Bitcoin,
2133 Err(e) => panic!("error parsing invoice: {:?}", e),
2138 fn parses_invoice_with_node_id() {
2139 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2142 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2144 .sign(payer_sign).unwrap()
2145 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2147 .sign(recipient_sign).unwrap();
2149 let mut buffer = Vec::new();
2150 invoice.write(&mut buffer).unwrap();
2152 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2153 panic!("error parsing invoice: {:?}", e);
2156 let mut tlv_stream = invoice.as_tlv_stream();
2157 tlv_stream.3.node_id = None;
2159 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2160 Ok(_) => panic!("expected error"),
2162 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2166 let invalid_pubkey = payer_pubkey();
2167 let mut tlv_stream = invoice.as_tlv_stream();
2168 tlv_stream.3.node_id = Some(&invalid_pubkey);
2170 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2171 Ok(_) => panic!("expected error"),
2173 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
2179 fn fails_parsing_invoice_without_signature() {
2180 let mut buffer = Vec::new();
2181 OfferBuilder::new("foo".into(), recipient_pubkey())
2184 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2186 .sign(payer_sign).unwrap()
2187 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2190 .write(&mut buffer).unwrap();
2192 match Bolt12Invoice::try_from(buffer) {
2193 Ok(_) => panic!("expected error"),
2194 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2199 fn fails_parsing_invoice_with_invalid_signature() {
2200 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2203 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2205 .sign(payer_sign).unwrap()
2206 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2208 .sign(recipient_sign).unwrap();
2209 let last_signature_byte = invoice.bytes.last_mut().unwrap();
2210 *last_signature_byte = last_signature_byte.wrapping_add(1);
2212 let mut buffer = Vec::new();
2213 invoice.write(&mut buffer).unwrap();
2215 match Bolt12Invoice::try_from(buffer) {
2216 Ok(_) => panic!("expected error"),
2218 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2224 fn fails_parsing_invoice_with_extra_tlv_records() {
2225 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2228 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2230 .sign(payer_sign).unwrap()
2231 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2233 .sign(recipient_sign).unwrap();
2235 let mut encoded_invoice = Vec::new();
2236 invoice.write(&mut encoded_invoice).unwrap();
2237 BigSize(1002).write(&mut encoded_invoice).unwrap();
2238 BigSize(32).write(&mut encoded_invoice).unwrap();
2239 [42u8; 32].write(&mut encoded_invoice).unwrap();
2241 match Bolt12Invoice::try_from(encoded_invoice) {
2242 Ok(_) => panic!("expected error"),
2243 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),