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::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::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::address::{Address, Payload, WitnessProgram, WitnessVersion};
107 use bitcoin::key::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::channelmanager::PaymentId;
114 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
115 use crate::ln::inbound_payment::ExpandedKey;
116 use crate::ln::msgs::DecodeError;
117 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
118 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
119 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef, Quantity};
120 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
121 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
122 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
123 use crate::offers::signer;
124 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
125 use crate::util::string::PrintableString;
127 use crate::prelude::*;
129 #[cfg(feature = "std")]
130 use std::time::SystemTime;
132 pub(crate) const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
134 /// Tag for the hash function used when signing a [`Bolt12Invoice`]'s merkle root.
135 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
137 /// Builds a [`Bolt12Invoice`] from either:
138 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
139 /// - a [`Refund`] for the "offer for money" flow.
141 /// See [module-level documentation] for usage.
143 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
145 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
146 /// [`Refund`]: crate::offers::refund::Refund
147 /// [module-level documentation]: self
148 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
149 invreq_bytes: &'a Vec<u8>,
150 invoice: InvoiceContents,
151 signing_pubkey_strategy: S,
154 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
156 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
157 pub trait SigningPubkeyStrategy {}
159 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub struct ExplicitSigningPubkey {}
164 /// [`Bolt12Invoice::signing_pubkey`] was derived.
166 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
167 pub struct DerivedSigningPubkey(KeyPair);
169 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
170 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
172 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
173 pub(super) fn for_offer(
174 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
175 created_at: Duration, payment_hash: PaymentHash
176 ) -> Result<Self, Bolt12SemanticError> {
177 let amount_msats = Self::amount_msats(invoice_request)?;
178 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
179 let contents = InvoiceContents::ForOffer {
180 invoice_request: invoice_request.contents.clone(),
181 fields: Self::fields(
182 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
186 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
189 pub(super) fn for_refund(
190 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
191 payment_hash: PaymentHash, signing_pubkey: PublicKey
192 ) -> Result<Self, Bolt12SemanticError> {
193 let amount_msats = refund.amount_msats();
194 let contents = InvoiceContents::ForRefund {
195 refund: refund.contents.clone(),
196 fields: Self::fields(
197 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
201 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
205 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
206 pub(super) fn for_offer_using_keys(
207 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
208 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
209 ) -> Result<Self, Bolt12SemanticError> {
210 let amount_msats = Self::amount_msats(invoice_request)?;
211 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
212 let contents = InvoiceContents::ForOffer {
213 invoice_request: invoice_request.contents.clone(),
214 fields: Self::fields(
215 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
219 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
222 pub(super) fn for_refund_using_keys(
223 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
224 payment_hash: PaymentHash, keys: KeyPair,
225 ) -> Result<Self, Bolt12SemanticError> {
226 let amount_msats = refund.amount_msats();
227 let signing_pubkey = keys.public_key();
228 let contents = InvoiceContents::ForRefund {
229 refund: refund.contents.clone(),
230 fields: Self::fields(
231 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
235 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
239 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
240 pub(crate) fn amount_msats(
241 invoice_request: &InvoiceRequest
242 ) -> Result<u64, Bolt12SemanticError> {
243 match invoice_request.amount_msats() {
244 Some(amount_msats) => Ok(amount_msats),
245 None => match invoice_request.contents.inner.offer.amount() {
246 Some(Amount::Bitcoin { amount_msats }) => {
247 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
248 .ok_or(Bolt12SemanticError::InvalidAmount)
250 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
251 None => Err(Bolt12SemanticError::MissingAmount),
257 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
258 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
261 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
262 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
267 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: S
268 ) -> Result<Self, Bolt12SemanticError> {
269 if contents.fields().payment_paths.is_empty() {
270 return Err(Bolt12SemanticError::MissingPaths);
273 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
276 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
277 /// Any expiry that has already passed is valid and can be checked for using
278 /// [`Bolt12Invoice::is_expired`].
280 /// Successive calls to this method will override the previous setting.
281 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
282 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
283 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
287 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
289 /// Successive calls to this method will add another address. Caller is responsible for not
290 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
291 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
292 let address = FallbackAddress {
293 version: WitnessVersion::V0.to_num(),
294 program: Vec::from(script_hash.to_byte_array()),
296 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
300 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
302 /// Successive calls to this method will add another address. Caller is responsible for not
303 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
304 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
305 let address = FallbackAddress {
306 version: WitnessVersion::V0.to_num(),
307 program: Vec::from(pubkey_hash.to_byte_array()),
309 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
313 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
315 /// Successive calls to this method will add another address. Caller is responsible for not
316 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
317 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
318 let address = FallbackAddress {
319 version: WitnessVersion::V1.to_num(),
320 program: Vec::from(&output_key.serialize()[..]),
322 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
326 /// Sets [`Bolt12Invoice::invoice_features`] to indicate MPP may be used. Otherwise, MPP is
328 pub fn allow_mpp(mut self) -> Self {
329 self.invoice.fields_mut().features.set_basic_mpp_optional();
334 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
335 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
336 /// [`UnsignedBolt12Invoice::sign`].
337 pub fn build(self) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
338 #[cfg(feature = "std")] {
339 if self.invoice.is_offer_or_refund_expired() {
340 return Err(Bolt12SemanticError::AlreadyExpired);
344 #[cfg(not(feature = "std"))] {
345 if self.invoice.is_offer_or_refund_expired_no_std(self.invoice.created_at()) {
346 return Err(Bolt12SemanticError::AlreadyExpired);
350 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
351 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
355 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
356 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
357 pub fn build_and_sign<T: secp256k1::Signing>(
358 self, secp_ctx: &Secp256k1<T>
359 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
360 #[cfg(feature = "std")] {
361 if self.invoice.is_offer_or_refund_expired() {
362 return Err(Bolt12SemanticError::AlreadyExpired);
366 #[cfg(not(feature = "std"))] {
367 if self.invoice.is_offer_or_refund_expired_no_std(self.invoice.created_at()) {
368 return Err(Bolt12SemanticError::AlreadyExpired);
373 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
375 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
377 let invoice = unsigned_invoice
378 .sign::<_, Infallible>(
379 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
386 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
390 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
391 /// such, it may include unknown, odd TLV records.
392 pub struct UnsignedBolt12Invoice {
394 contents: InvoiceContents,
395 tagged_hash: TaggedHash,
398 impl UnsignedBolt12Invoice {
399 fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
400 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
401 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
403 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
404 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
405 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
407 let mut bytes = Vec::new();
408 unsigned_tlv_stream.write(&mut bytes).unwrap();
410 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
412 Self { bytes, contents, tagged_hash }
415 /// Returns the [`TaggedHash`] of the invoice to sign.
416 pub fn tagged_hash(&self) -> &TaggedHash {
420 /// Signs the [`TaggedHash`] of the invoice using the given function.
422 /// Note: The hash computation may have included unknown, odd TLV records.
424 /// This is not exported to bindings users as functions aren't currently mapped.
425 pub fn sign<F, E>(mut self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
427 F: FnOnce(&Self) -> Result<Signature, E>
429 let pubkey = self.contents.fields().signing_pubkey;
430 let signature = merkle::sign_message(sign, &self, pubkey)?;
432 // Append the signature TLV record to the bytes.
433 let signature_tlv_stream = SignatureTlvStreamRef {
434 signature: Some(&signature),
436 signature_tlv_stream.write(&mut self.bytes).unwrap();
440 contents: self.contents,
442 tagged_hash: self.tagged_hash,
447 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
448 fn as_ref(&self) -> &TaggedHash {
453 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
455 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
456 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
458 /// [`Offer`]: crate::offers::offer::Offer
459 /// [`Refund`]: crate::offers::refund::Refund
460 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
461 #[derive(Clone, Debug)]
462 #[cfg_attr(test, derive(PartialEq))]
463 pub struct Bolt12Invoice {
465 contents: InvoiceContents,
466 signature: Signature,
467 tagged_hash: TaggedHash,
470 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
472 /// [`Offer`]: crate::offers::offer::Offer
473 /// [`Refund`]: crate::offers::refund::Refund
474 #[derive(Clone, Debug)]
475 #[cfg_attr(test, derive(PartialEq))]
476 enum InvoiceContents {
477 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
479 /// [`Offer`]: crate::offers::offer::Offer
481 invoice_request: InvoiceRequestContents,
482 fields: InvoiceFields,
484 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
486 /// [`Refund`]: crate::offers::refund::Refund
488 refund: RefundContents,
489 fields: InvoiceFields,
493 /// Invoice-specific fields for an `invoice` message.
494 #[derive(Clone, Debug, PartialEq)]
495 struct InvoiceFields {
496 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
497 created_at: Duration,
498 relative_expiry: Option<Duration>,
499 payment_hash: PaymentHash,
501 fallbacks: Option<Vec<FallbackAddress>>,
502 features: Bolt12InvoiceFeatures,
503 signing_pubkey: PublicKey,
506 macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
507 /// The chains that may be used when paying a requested invoice.
509 /// From [`Offer::chains`]; `None` if the invoice was created in response to a [`Refund`].
511 /// [`Offer::chains`]: crate::offers::offer::Offer::chains
512 pub fn offer_chains(&$self) -> Option<Vec<ChainHash>> {
513 $contents.offer_chains()
516 /// The chain that must be used when paying the invoice; selected from [`offer_chains`] if the
517 /// invoice originated from an offer.
519 /// From [`InvoiceRequest::chain`] or [`Refund::chain`].
521 /// [`offer_chains`]: Self::offer_chains
522 /// [`InvoiceRequest::chain`]: crate::offers::invoice_request::InvoiceRequest::chain
523 pub fn chain(&$self) -> ChainHash {
527 /// Opaque bytes set by the originating [`Offer`].
529 /// From [`Offer::metadata`]; `None` if the invoice was created in response to a [`Refund`] or
530 /// if the [`Offer`] did not set it.
532 /// [`Offer`]: crate::offers::offer::Offer
533 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
534 pub fn metadata(&$self) -> Option<&Vec<u8>> {
538 /// The minimum amount required for a successful payment of a single item.
540 /// From [`Offer::amount`]; `None` if the invoice was created in response to a [`Refund`] or if
541 /// the [`Offer`] did not set it.
543 /// [`Offer`]: crate::offers::offer::Offer
544 /// [`Offer::amount`]: crate::offers::offer::Offer::amount
545 pub fn amount(&$self) -> Option<&Amount> {
549 /// Features pertaining to the originating [`Offer`].
551 /// From [`Offer::offer_features`]; `None` if the invoice was created in response to a
554 /// [`Offer`]: crate::offers::offer::Offer
555 /// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features
556 pub fn offer_features(&$self) -> Option<&OfferFeatures> {
557 $contents.offer_features()
560 /// A complete description of the purpose of the originating offer or refund.
562 /// From [`Offer::description`] or [`Refund::description`].
564 /// [`Offer::description`]: crate::offers::offer::Offer::description
565 pub fn description(&$self) -> PrintableString {
566 $contents.description()
569 /// Duration since the Unix epoch when an invoice should no longer be requested.
571 /// From [`Offer::absolute_expiry`] or [`Refund::absolute_expiry`].
573 /// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry
574 pub fn absolute_expiry(&$self) -> Option<Duration> {
575 $contents.absolute_expiry()
578 /// The issuer of the offer or refund.
580 /// From [`Offer::issuer`] or [`Refund::issuer`].
582 /// [`Offer::issuer`]: crate::offers::offer::Offer::issuer
583 pub fn issuer(&$self) -> Option<PrintableString> {
587 /// Paths to the recipient originating from publicly reachable nodes.
589 /// From [`Offer::paths`] or [`Refund::paths`].
591 /// [`Offer::paths`]: crate::offers::offer::Offer::paths
592 pub fn message_paths(&$self) -> &[BlindedPath] {
593 $contents.message_paths()
596 /// The quantity of items supported.
598 /// From [`Offer::supported_quantity`]; `None` if the invoice was created in response to a
601 /// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
602 pub fn supported_quantity(&$self) -> Option<Quantity> {
603 $contents.supported_quantity()
606 /// An unpredictable series of bytes from the payer.
608 /// From [`InvoiceRequest::payer_metadata`] or [`Refund::payer_metadata`].
609 pub fn payer_metadata(&$self) -> &[u8] {
610 $contents.payer_metadata()
613 /// Features pertaining to requesting an invoice.
615 /// From [`InvoiceRequest::invoice_request_features`] or [`Refund::features`].
616 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
617 &$contents.invoice_request_features()
620 /// The quantity of items requested or refunded for.
622 /// From [`InvoiceRequest::quantity`] or [`Refund::quantity`].
623 pub fn quantity(&$self) -> Option<u64> {
627 /// A possibly transient pubkey used to sign the invoice request or to send an invoice for a
628 /// refund in case there are no [`message_paths`].
630 /// [`message_paths`]: Self::message_paths
631 pub fn payer_id(&$self) -> PublicKey {
635 /// A payer-provided note reflected back in the invoice.
637 /// From [`InvoiceRequest::payer_note`] or [`Refund::payer_note`].
638 pub fn payer_note(&$self) -> Option<PrintableString> {
639 $contents.payer_note()
642 /// Paths to the recipient originating from publicly reachable nodes, including information
643 /// needed for routing payments across them.
645 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
646 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
648 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
649 /// matched in another language.
650 pub fn payment_paths(&$self) -> &[(BlindedPayInfo, BlindedPath)] {
651 $contents.payment_paths()
654 /// Duration since the Unix epoch when the invoice was created.
655 pub fn created_at(&$self) -> Duration {
656 $contents.created_at()
659 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
660 /// should no longer be paid.
661 pub fn relative_expiry(&$self) -> Duration {
662 $contents.relative_expiry()
665 /// Whether the invoice has expired.
666 #[cfg(feature = "std")]
667 pub fn is_expired(&$self) -> bool {
668 $contents.is_expired()
671 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
672 pub fn payment_hash(&$self) -> PaymentHash {
673 $contents.payment_hash()
676 /// The minimum amount required for a successful payment of the invoice.
677 pub fn amount_msats(&$self) -> u64 {
678 $contents.amount_msats()
681 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
683 pub fn fallbacks(&$self) -> Vec<Address> {
684 $contents.fallbacks()
687 /// Features pertaining to paying an invoice.
688 pub fn invoice_features(&$self) -> &Bolt12InvoiceFeatures {
692 /// The public key corresponding to the key used to sign the invoice.
693 pub fn signing_pubkey(&$self) -> PublicKey {
694 $contents.signing_pubkey()
698 impl UnsignedBolt12Invoice {
699 invoice_accessors!(self, self.contents);
703 invoice_accessors!(self, self.contents);
705 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
706 pub fn signature(&self) -> Signature {
710 /// Hash that was used for signing the invoice.
711 pub fn signable_hash(&self) -> [u8; 32] {
712 self.tagged_hash.as_digest().as_ref().clone()
715 /// Verifies that the invoice was for a request or refund created using the given key. Returns
716 /// the associated [`PaymentId`] to use when sending the payment.
717 pub fn verify<T: secp256k1::Signing>(
718 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
719 ) -> Result<PaymentId, ()> {
720 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
724 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
725 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
726 self.contents.as_tlv_stream();
727 let signature_tlv_stream = SignatureTlvStreamRef {
728 signature: Some(&self.signature),
730 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
731 signature_tlv_stream)
735 impl InvoiceContents {
736 /// Whether the original offer or refund has expired.
737 #[cfg(feature = "std")]
738 fn is_offer_or_refund_expired(&self) -> bool {
740 InvoiceContents::ForOffer { invoice_request, .. } =>
741 invoice_request.inner.offer.is_expired(),
742 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
746 #[cfg(not(feature = "std"))]
747 fn is_offer_or_refund_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
749 InvoiceContents::ForOffer { invoice_request, .. } =>
750 invoice_request.inner.offer.is_expired_no_std(duration_since_epoch),
751 InvoiceContents::ForRefund { refund, .. } =>
752 refund.is_expired_no_std(duration_since_epoch),
756 fn offer_chains(&self) -> Option<Vec<ChainHash>> {
758 InvoiceContents::ForOffer { invoice_request, .. } =>
759 Some(invoice_request.inner.offer.chains()),
760 InvoiceContents::ForRefund { .. } => None,
764 fn chain(&self) -> ChainHash {
766 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
767 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
771 fn metadata(&self) -> Option<&Vec<u8>> {
773 InvoiceContents::ForOffer { invoice_request, .. } =>
774 invoice_request.inner.offer.metadata(),
775 InvoiceContents::ForRefund { .. } => None,
779 fn amount(&self) -> Option<&Amount> {
781 InvoiceContents::ForOffer { invoice_request, .. } =>
782 invoice_request.inner.offer.amount(),
783 InvoiceContents::ForRefund { .. } => None,
787 fn description(&self) -> PrintableString {
789 InvoiceContents::ForOffer { invoice_request, .. } => {
790 invoice_request.inner.offer.description()
792 InvoiceContents::ForRefund { refund, .. } => refund.description(),
796 fn offer_features(&self) -> Option<&OfferFeatures> {
798 InvoiceContents::ForOffer { invoice_request, .. } => {
799 Some(invoice_request.inner.offer.features())
801 InvoiceContents::ForRefund { .. } => None,
805 fn absolute_expiry(&self) -> Option<Duration> {
807 InvoiceContents::ForOffer { invoice_request, .. } => {
808 invoice_request.inner.offer.absolute_expiry()
810 InvoiceContents::ForRefund { refund, .. } => refund.absolute_expiry(),
814 fn issuer(&self) -> Option<PrintableString> {
816 InvoiceContents::ForOffer { invoice_request, .. } => {
817 invoice_request.inner.offer.issuer()
819 InvoiceContents::ForRefund { refund, .. } => refund.issuer(),
823 fn message_paths(&self) -> &[BlindedPath] {
825 InvoiceContents::ForOffer { invoice_request, .. } => {
826 invoice_request.inner.offer.paths()
828 InvoiceContents::ForRefund { refund, .. } => refund.paths(),
832 fn supported_quantity(&self) -> Option<Quantity> {
834 InvoiceContents::ForOffer { invoice_request, .. } => {
835 Some(invoice_request.inner.offer.supported_quantity())
837 InvoiceContents::ForRefund { .. } => None,
841 fn payer_metadata(&self) -> &[u8] {
843 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.metadata(),
844 InvoiceContents::ForRefund { refund, .. } => refund.metadata(),
848 fn invoice_request_features(&self) -> &InvoiceRequestFeatures {
850 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.features(),
851 InvoiceContents::ForRefund { refund, .. } => refund.features(),
855 fn quantity(&self) -> Option<u64> {
857 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.quantity(),
858 InvoiceContents::ForRefund { refund, .. } => refund.quantity(),
862 fn payer_id(&self) -> PublicKey {
864 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_id(),
865 InvoiceContents::ForRefund { refund, .. } => refund.payer_id(),
869 fn payer_note(&self) -> Option<PrintableString> {
871 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_note(),
872 InvoiceContents::ForRefund { refund, .. } => refund.payer_note(),
876 fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
877 &self.fields().payment_paths[..]
880 fn created_at(&self) -> Duration {
881 self.fields().created_at
884 fn relative_expiry(&self) -> Duration {
885 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
888 #[cfg(feature = "std")]
889 fn is_expired(&self) -> bool {
890 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
891 match absolute_expiry {
892 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
893 Ok(elapsed) => elapsed > seconds_from_epoch,
900 fn payment_hash(&self) -> PaymentHash {
901 self.fields().payment_hash
904 fn amount_msats(&self) -> u64 {
905 self.fields().amount_msats
908 fn fallbacks(&self) -> Vec<Address> {
909 let chain = self.chain();
910 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
912 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
914 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
916 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
922 let to_valid_address = |address: &FallbackAddress| {
923 let version = match WitnessVersion::try_from(address.version) {
924 Ok(version) => version,
925 Err(_) => return None,
928 let program = &address.program;
929 let witness_program = match WitnessProgram::new(version, program.clone()) {
930 Ok(witness_program) => witness_program,
931 Err(_) => return None,
933 Some(Address::new(network, Payload::WitnessProgram(witness_program)))
936 self.fields().fallbacks
938 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
939 .unwrap_or_else(Vec::new)
942 fn features(&self) -> &Bolt12InvoiceFeatures {
943 &self.fields().features
946 fn signing_pubkey(&self) -> PublicKey {
947 self.fields().signing_pubkey
950 fn fields(&self) -> &InvoiceFields {
952 InvoiceContents::ForOffer { fields, .. } => fields,
953 InvoiceContents::ForRefund { fields, .. } => fields,
957 fn fields_mut(&mut self) -> &mut InvoiceFields {
959 InvoiceContents::ForOffer { fields, .. } => fields,
960 InvoiceContents::ForRefund { fields, .. } => fields,
964 fn verify<T: secp256k1::Signing>(
965 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
966 ) -> Result<PaymentId, ()> {
967 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
968 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
969 match record.r#type {
970 PAYER_METADATA_TYPE => false, // Should be outside range
971 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
975 let tlv_stream = offer_records.chain(invreq_records);
977 let (metadata, payer_id, iv_bytes) = match self {
978 InvoiceContents::ForOffer { invoice_request, .. } => {
979 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
981 InvoiceContents::ForRefund { refund, .. } => {
982 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
986 signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
989 fn derives_keys(&self) -> bool {
991 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
992 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
996 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
997 let (payer, offer, invoice_request) = match self {
998 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
999 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
1001 let invoice = self.fields().as_tlv_stream();
1003 (payer, offer, invoice_request, invoice)
1007 impl InvoiceFields {
1008 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
1010 if self.features == Bolt12InvoiceFeatures::empty() { None }
1011 else { Some(&self.features) }
1014 InvoiceTlvStreamRef {
1015 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
1016 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
1017 created_at: Some(self.created_at.as_secs()),
1018 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
1019 payment_hash: Some(&self.payment_hash),
1020 amount: Some(self.amount_msats),
1021 fallbacks: self.fallbacks.as_ref(),
1023 node_id: Some(&self.signing_pubkey),
1028 impl Writeable for UnsignedBolt12Invoice {
1029 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1030 WithoutLength(&self.bytes).write(writer)
1034 impl Writeable for Bolt12Invoice {
1035 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1036 WithoutLength(&self.bytes).write(writer)
1040 impl Writeable for InvoiceContents {
1041 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1042 self.as_tlv_stream().write(writer)
1046 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
1047 type Error = Bolt12ParseError;
1049 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1050 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
1051 let ParsedMessage { bytes, tlv_stream } = invoice;
1053 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1055 let contents = InvoiceContents::try_from(
1056 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1059 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1061 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
1065 impl TryFrom<Vec<u8>> for Bolt12Invoice {
1066 type Error = Bolt12ParseError;
1068 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1069 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
1070 Bolt12Invoice::try_from(parsed_invoice)
1074 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
1075 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
1076 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
1077 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
1078 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
1079 (168, payment_hash: PaymentHash),
1080 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
1081 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
1082 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
1083 (176, node_id: PublicKey),
1086 type BlindedPathIter<'a> = core::iter::Map<
1087 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1088 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
1091 type BlindedPayInfoIter<'a> = core::iter::Map<
1092 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1093 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
1096 /// Information needed to route a payment across a [`BlindedPath`].
1097 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
1098 pub struct BlindedPayInfo {
1099 /// Base fee charged (in millisatoshi) for the entire blinded path.
1100 pub fee_base_msat: u32,
1102 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
1103 /// (i.e., 10,000 is 1%).
1104 pub fee_proportional_millionths: u32,
1106 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
1108 pub cltv_expiry_delta: u16,
1110 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1111 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1112 /// seen by the recipient.
1113 pub htlc_minimum_msat: u64,
1115 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1116 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1117 /// seen by the recipient.
1118 pub htlc_maximum_msat: u64,
1120 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
1122 pub features: BlindedHopFeatures,
1125 impl_writeable!(BlindedPayInfo, {
1127 fee_proportional_millionths,
1134 /// Wire representation for an on-chain fallback address.
1135 #[derive(Clone, Debug, PartialEq)]
1136 pub(super) struct FallbackAddress {
1141 impl_writeable!(FallbackAddress, { version, program });
1143 type FullInvoiceTlvStream =
1144 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
1147 type FullInvoiceTlvStreamRef<'a> = (
1148 PayerTlvStreamRef<'a>,
1149 OfferTlvStreamRef<'a>,
1150 InvoiceRequestTlvStreamRef<'a>,
1151 InvoiceTlvStreamRef<'a>,
1152 SignatureTlvStreamRef<'a>,
1155 impl SeekReadable for FullInvoiceTlvStream {
1156 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1157 let payer = SeekReadable::read(r)?;
1158 let offer = SeekReadable::read(r)?;
1159 let invoice_request = SeekReadable::read(r)?;
1160 let invoice = SeekReadable::read(r)?;
1161 let signature = SeekReadable::read(r)?;
1163 Ok((payer, offer, invoice_request, invoice, signature))
1167 type PartialInvoiceTlvStream =
1168 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
1170 type PartialInvoiceTlvStreamRef<'a> = (
1171 PayerTlvStreamRef<'a>,
1172 OfferTlvStreamRef<'a>,
1173 InvoiceRequestTlvStreamRef<'a>,
1174 InvoiceTlvStreamRef<'a>,
1177 impl SeekReadable for PartialInvoiceTlvStream {
1178 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1179 let payer = SeekReadable::read(r)?;
1180 let offer = SeekReadable::read(r)?;
1181 let invoice_request = SeekReadable::read(r)?;
1182 let invoice = SeekReadable::read(r)?;
1184 Ok((payer, offer, invoice_request, invoice))
1188 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
1189 type Error = Bolt12ParseError;
1191 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
1192 let ParsedMessage { bytes, tlv_stream } = invoice;
1194 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1195 SignatureTlvStream { signature },
1197 let contents = InvoiceContents::try_from(
1198 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1201 let signature = match signature {
1202 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1203 Some(signature) => signature,
1205 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1206 let pubkey = contents.fields().signing_pubkey;
1207 merkle::verify_signature(&signature, &tagged_hash, pubkey)?;
1209 Ok(Bolt12Invoice { bytes, contents, signature, tagged_hash })
1213 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
1214 type Error = Bolt12SemanticError;
1216 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
1220 invoice_request_tlv_stream,
1222 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
1227 let payment_paths = match (blindedpay, paths) {
1228 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
1229 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
1230 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1231 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
1232 return Err(Bolt12SemanticError::InvalidPayInfo);
1234 (Some(blindedpay), Some(paths)) => {
1235 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
1239 let created_at = match created_at {
1240 None => return Err(Bolt12SemanticError::MissingCreationTime),
1241 Some(timestamp) => Duration::from_secs(timestamp),
1244 let relative_expiry = relative_expiry
1245 .map(Into::<u64>::into)
1246 .map(Duration::from_secs);
1248 let payment_hash = match payment_hash {
1249 None => return Err(Bolt12SemanticError::MissingPaymentHash),
1250 Some(payment_hash) => payment_hash,
1253 let amount_msats = match amount {
1254 None => return Err(Bolt12SemanticError::MissingAmount),
1255 Some(amount) => amount,
1258 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1260 let signing_pubkey = match node_id {
1261 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1262 Some(node_id) => node_id,
1265 let fields = InvoiceFields {
1266 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1267 features, signing_pubkey,
1270 match offer_tlv_stream.node_id {
1271 Some(expected_signing_pubkey) => {
1272 if fields.signing_pubkey != expected_signing_pubkey {
1273 return Err(Bolt12SemanticError::InvalidSigningPubkey);
1276 let invoice_request = InvoiceRequestContents::try_from(
1277 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1279 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1282 let refund = RefundContents::try_from(
1283 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1285 Ok(InvoiceContents::ForRefund { refund, fields })
1293 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1295 use bitcoin::blockdata::constants::ChainHash;
1296 use bitcoin::blockdata::script::ScriptBuf;
1297 use bitcoin::hashes::Hash;
1298 use bitcoin::network::constants::Network;
1299 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
1300 use bitcoin::address::{Address, Payload, WitnessProgram, WitnessVersion};
1301 use bitcoin::key::TweakedPublicKey;
1302 use core::convert::TryFrom;
1303 use core::time::Duration;
1304 use crate::blinded_path::{BlindedHop, BlindedPath};
1305 use crate::sign::KeyMaterial;
1306 use crate::ln::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
1307 use crate::ln::inbound_payment::ExpandedKey;
1308 use crate::ln::msgs::DecodeError;
1309 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1310 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1311 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
1312 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1313 use crate::offers::payer::PayerTlvStreamRef;
1314 use crate::offers::refund::RefundBuilder;
1315 use crate::offers::test_utils::*;
1316 use crate::util::ser::{BigSize, Iterable, Writeable};
1317 use crate::util::string::PrintableString;
1320 fn to_bytes(&self) -> Vec<u8>;
1323 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1324 fn to_bytes(&self) -> Vec<u8> {
1325 let mut buffer = Vec::new();
1326 self.0.write(&mut buffer).unwrap();
1327 self.1.write(&mut buffer).unwrap();
1328 self.2.write(&mut buffer).unwrap();
1329 self.3.write(&mut buffer).unwrap();
1330 self.4.write(&mut buffer).unwrap();
1336 fn builds_invoice_for_offer_with_defaults() {
1337 let payment_paths = payment_paths();
1338 let payment_hash = payment_hash();
1340 let unsigned_invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1345 .sign(payer_sign).unwrap()
1346 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1349 let mut buffer = Vec::new();
1350 unsigned_invoice.write(&mut buffer).unwrap();
1352 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1353 assert_eq!(unsigned_invoice.payer_metadata(), &[1; 32]);
1354 assert_eq!(unsigned_invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1355 assert_eq!(unsigned_invoice.metadata(), None);
1356 assert_eq!(unsigned_invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1357 assert_eq!(unsigned_invoice.description(), PrintableString("foo"));
1358 assert_eq!(unsigned_invoice.offer_features(), Some(&OfferFeatures::empty()));
1359 assert_eq!(unsigned_invoice.absolute_expiry(), None);
1360 assert_eq!(unsigned_invoice.message_paths(), &[]);
1361 assert_eq!(unsigned_invoice.issuer(), None);
1362 assert_eq!(unsigned_invoice.supported_quantity(), Some(Quantity::One));
1363 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1364 assert_eq!(unsigned_invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1365 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1366 assert_eq!(unsigned_invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1367 assert_eq!(unsigned_invoice.quantity(), None);
1368 assert_eq!(unsigned_invoice.payer_id(), payer_pubkey());
1369 assert_eq!(unsigned_invoice.payer_note(), None);
1370 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1371 assert_eq!(unsigned_invoice.created_at(), now);
1372 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1373 #[cfg(feature = "std")]
1374 assert!(!unsigned_invoice.is_expired());
1375 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1376 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1377 assert_eq!(unsigned_invoice.fallbacks(), vec![]);
1378 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1379 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1381 match UnsignedBolt12Invoice::try_from(buffer) {
1382 Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1384 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1385 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1389 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1391 let mut buffer = Vec::new();
1392 invoice.write(&mut buffer).unwrap();
1394 assert_eq!(invoice.bytes, buffer.as_slice());
1395 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1396 assert_eq!(invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1397 assert_eq!(invoice.metadata(), None);
1398 assert_eq!(invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1399 assert_eq!(invoice.description(), PrintableString("foo"));
1400 assert_eq!(invoice.offer_features(), Some(&OfferFeatures::empty()));
1401 assert_eq!(invoice.absolute_expiry(), None);
1402 assert_eq!(invoice.message_paths(), &[]);
1403 assert_eq!(invoice.issuer(), None);
1404 assert_eq!(invoice.supported_quantity(), Some(Quantity::One));
1405 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1406 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1407 assert_eq!(invoice.amount_msats(), 1000);
1408 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1409 assert_eq!(invoice.quantity(), None);
1410 assert_eq!(invoice.payer_id(), payer_pubkey());
1411 assert_eq!(invoice.payer_note(), None);
1412 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1413 assert_eq!(invoice.created_at(), now);
1414 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1415 #[cfg(feature = "std")]
1416 assert!(!invoice.is_expired());
1417 assert_eq!(invoice.payment_hash(), payment_hash);
1418 assert_eq!(invoice.amount_msats(), 1000);
1419 assert_eq!(invoice.fallbacks(), vec![]);
1420 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1421 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1423 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1424 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1426 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1427 let pubkey = recipient_pubkey().into();
1428 let secp_ctx = Secp256k1::verification_only();
1429 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1432 invoice.as_tlv_stream(),
1434 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1440 description: Some(&String::from("foo")),
1442 absolute_expiry: None,
1446 node_id: Some(&recipient_pubkey()),
1448 InvoiceRequestTlvStreamRef {
1453 payer_id: Some(&payer_pubkey()),
1456 InvoiceTlvStreamRef {
1457 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1458 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1459 created_at: Some(now.as_secs()),
1460 relative_expiry: None,
1461 payment_hash: Some(&payment_hash),
1465 node_id: Some(&recipient_pubkey()),
1467 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1471 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1472 panic!("error parsing invoice: {:?}", e);
1477 fn builds_invoice_for_refund_with_defaults() {
1478 let payment_paths = payment_paths();
1479 let payment_hash = payment_hash();
1481 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1483 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1486 .sign(recipient_sign).unwrap();
1488 let mut buffer = Vec::new();
1489 invoice.write(&mut buffer).unwrap();
1491 assert_eq!(invoice.bytes, buffer.as_slice());
1492 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1493 assert_eq!(invoice.offer_chains(), None);
1494 assert_eq!(invoice.metadata(), None);
1495 assert_eq!(invoice.amount(), None);
1496 assert_eq!(invoice.description(), PrintableString("foo"));
1497 assert_eq!(invoice.offer_features(), None);
1498 assert_eq!(invoice.absolute_expiry(), None);
1499 assert_eq!(invoice.message_paths(), &[]);
1500 assert_eq!(invoice.issuer(), None);
1501 assert_eq!(invoice.supported_quantity(), None);
1502 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1503 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1504 assert_eq!(invoice.amount_msats(), 1000);
1505 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1506 assert_eq!(invoice.quantity(), None);
1507 assert_eq!(invoice.payer_id(), payer_pubkey());
1508 assert_eq!(invoice.payer_note(), None);
1509 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1510 assert_eq!(invoice.created_at(), now);
1511 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1512 #[cfg(feature = "std")]
1513 assert!(!invoice.is_expired());
1514 assert_eq!(invoice.payment_hash(), payment_hash);
1515 assert_eq!(invoice.amount_msats(), 1000);
1516 assert_eq!(invoice.fallbacks(), vec![]);
1517 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1518 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1520 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1521 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1524 invoice.as_tlv_stream(),
1526 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1532 description: Some(&String::from("foo")),
1534 absolute_expiry: None,
1540 InvoiceRequestTlvStreamRef {
1545 payer_id: Some(&payer_pubkey()),
1548 InvoiceTlvStreamRef {
1549 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1550 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1551 created_at: Some(now.as_secs()),
1552 relative_expiry: None,
1553 payment_hash: Some(&payment_hash),
1557 node_id: Some(&recipient_pubkey()),
1559 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1563 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1564 panic!("error parsing invoice: {:?}", e);
1568 #[cfg(feature = "std")]
1570 fn builds_invoice_from_offer_with_expiration() {
1571 let future_expiry = Duration::from_secs(u64::max_value());
1572 let past_expiry = Duration::from_secs(0);
1574 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1576 .absolute_expiry(future_expiry)
1578 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1580 .sign(payer_sign).unwrap()
1581 .respond_with(payment_paths(), payment_hash())
1585 panic!("error building invoice: {:?}", e);
1588 match OfferBuilder::new("foo".into(), recipient_pubkey())
1590 .absolute_expiry(past_expiry)
1592 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594 .sign(payer_sign).unwrap()
1595 .respond_with(payment_paths(), payment_hash())
1599 Ok(_) => panic!("expected error"),
1600 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1604 #[cfg(feature = "std")]
1606 fn builds_invoice_from_refund_with_expiration() {
1607 let future_expiry = Duration::from_secs(u64::max_value());
1608 let past_expiry = Duration::from_secs(0);
1610 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1611 .absolute_expiry(future_expiry)
1613 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1617 panic!("error building invoice: {:?}", e);
1620 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1621 .absolute_expiry(past_expiry)
1623 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1627 Ok(_) => panic!("expected error"),
1628 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1633 fn builds_invoice_from_offer_using_derived_keys() {
1634 let desc = "foo".to_string();
1635 let node_id = recipient_pubkey();
1636 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1637 let entropy = FixedEntropy {};
1638 let secp_ctx = Secp256k1::new();
1640 let blinded_path = BlindedPath {
1641 introduction_node_id: pubkey(40),
1642 blinding_point: pubkey(41),
1644 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1645 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1649 let offer = OfferBuilder
1650 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1654 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1656 .sign(payer_sign).unwrap();
1658 if let Err(e) = invoice_request.clone()
1659 .verify(&expanded_key, &secp_ctx).unwrap()
1660 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
1661 .build_and_sign(&secp_ctx)
1663 panic!("error building invoice: {:?}", e);
1666 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1667 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1669 let desc = "foo".to_string();
1670 let offer = OfferBuilder
1671 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1673 // Omit the path so that node_id is used for the signing pubkey instead of deriving
1675 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1677 .sign(payer_sign).unwrap();
1679 match invoice_request
1680 .verify(&expanded_key, &secp_ctx).unwrap()
1681 .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
1683 Ok(_) => panic!("expected error"),
1684 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1689 fn builds_invoice_from_refund_using_derived_keys() {
1690 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1691 let entropy = FixedEntropy {};
1692 let secp_ctx = Secp256k1::new();
1694 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1697 if let Err(e) = refund
1698 .respond_using_derived_keys_no_std(
1699 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1702 .build_and_sign(&secp_ctx)
1704 panic!("error building invoice: {:?}", e);
1709 fn builds_invoice_with_relative_expiry() {
1711 let one_hour = Duration::from_secs(3600);
1713 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1716 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1718 .sign(payer_sign).unwrap()
1719 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1720 .relative_expiry(one_hour.as_secs() as u32)
1722 .sign(recipient_sign).unwrap();
1723 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1724 #[cfg(feature = "std")]
1725 assert!(!invoice.is_expired());
1726 assert_eq!(invoice.relative_expiry(), one_hour);
1727 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1729 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1732 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1734 .sign(payer_sign).unwrap()
1735 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1736 .relative_expiry(one_hour.as_secs() as u32 - 1)
1738 .sign(recipient_sign).unwrap();
1739 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1740 #[cfg(feature = "std")]
1741 assert!(invoice.is_expired());
1742 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1743 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1747 fn builds_invoice_with_amount_from_request() {
1748 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1751 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1752 .amount_msats(1001).unwrap()
1754 .sign(payer_sign).unwrap()
1755 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1757 .sign(recipient_sign).unwrap();
1758 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1759 assert_eq!(invoice.amount_msats(), 1001);
1760 assert_eq!(tlv_stream.amount, Some(1001));
1764 fn builds_invoice_with_quantity_from_request() {
1765 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1767 .supported_quantity(Quantity::Unbounded)
1769 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1770 .quantity(2).unwrap()
1772 .sign(payer_sign).unwrap()
1773 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1775 .sign(recipient_sign).unwrap();
1776 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1777 assert_eq!(invoice.amount_msats(), 2000);
1778 assert_eq!(tlv_stream.amount, Some(2000));
1780 match OfferBuilder::new("foo".into(), recipient_pubkey())
1782 .supported_quantity(Quantity::Unbounded)
1784 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1785 .quantity(u64::max_value()).unwrap()
1787 .sign(payer_sign).unwrap()
1788 .respond_with_no_std(payment_paths(), payment_hash(), now())
1790 Ok(_) => panic!("expected error"),
1791 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1796 fn builds_invoice_with_fallback_address() {
1797 let script = ScriptBuf::new();
1798 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
1799 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1800 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1802 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1805 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .sign(payer_sign).unwrap()
1808 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1809 .fallback_v0_p2wsh(&script.wscript_hash())
1810 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1811 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1813 .sign(recipient_sign).unwrap();
1814 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1816 invoice.fallbacks(),
1818 Address::p2wsh(&script, Network::Bitcoin),
1819 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1820 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1824 tlv_stream.fallbacks,
1827 version: WitnessVersion::V0.to_num(),
1828 program: Vec::from(script.wscript_hash().to_byte_array()),
1831 version: WitnessVersion::V0.to_num(),
1832 program: Vec::from(pubkey.wpubkey_hash().unwrap().to_byte_array()),
1835 version: WitnessVersion::V1.to_num(),
1836 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1843 fn builds_invoice_with_allow_mpp() {
1844 let mut features = Bolt12InvoiceFeatures::empty();
1845 features.set_basic_mpp_optional();
1847 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1850 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1852 .sign(payer_sign).unwrap()
1853 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1856 .sign(recipient_sign).unwrap();
1857 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1858 assert_eq!(invoice.invoice_features(), &features);
1859 assert_eq!(tlv_stream.features, Some(&features));
1863 fn fails_signing_invoice() {
1864 match OfferBuilder::new("foo".into(), recipient_pubkey())
1867 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1869 .sign(payer_sign).unwrap()
1870 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1874 Ok(_) => panic!("expected error"),
1875 Err(e) => assert_eq!(e, SignError::Signing(())),
1878 match OfferBuilder::new("foo".into(), recipient_pubkey())
1881 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1883 .sign(payer_sign).unwrap()
1884 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1888 Ok(_) => panic!("expected error"),
1889 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1894 fn parses_invoice_with_payment_paths() {
1895 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1898 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1900 .sign(payer_sign).unwrap()
1901 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1903 .sign(recipient_sign).unwrap();
1905 let mut buffer = Vec::new();
1906 invoice.write(&mut buffer).unwrap();
1908 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1909 panic!("error parsing invoice: {:?}", e);
1912 let mut tlv_stream = invoice.as_tlv_stream();
1913 tlv_stream.3.paths = None;
1915 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1916 Ok(_) => panic!("expected error"),
1917 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1920 let mut tlv_stream = invoice.as_tlv_stream();
1921 tlv_stream.3.blindedpay = None;
1923 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1924 Ok(_) => panic!("expected error"),
1925 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1928 let empty_payment_paths = vec![];
1929 let mut tlv_stream = invoice.as_tlv_stream();
1930 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1932 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1933 Ok(_) => panic!("expected error"),
1934 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1937 let mut payment_paths = payment_paths();
1938 payment_paths.pop();
1939 let mut tlv_stream = invoice.as_tlv_stream();
1940 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1942 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1943 Ok(_) => panic!("expected error"),
1944 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1949 fn parses_invoice_with_created_at() {
1950 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1953 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1955 .sign(payer_sign).unwrap()
1956 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1958 .sign(recipient_sign).unwrap();
1960 let mut buffer = Vec::new();
1961 invoice.write(&mut buffer).unwrap();
1963 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1964 panic!("error parsing invoice: {:?}", e);
1967 let mut tlv_stream = invoice.as_tlv_stream();
1968 tlv_stream.3.created_at = None;
1970 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1971 Ok(_) => panic!("expected error"),
1973 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1979 fn parses_invoice_with_relative_expiry() {
1980 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1983 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1985 .sign(payer_sign).unwrap()
1986 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1987 .relative_expiry(3600)
1989 .sign(recipient_sign).unwrap();
1991 let mut buffer = Vec::new();
1992 invoice.write(&mut buffer).unwrap();
1994 match Bolt12Invoice::try_from(buffer) {
1995 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1996 Err(e) => panic!("error parsing invoice: {:?}", e),
2001 fn parses_invoice_with_payment_hash() {
2002 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2005 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2007 .sign(payer_sign).unwrap()
2008 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2010 .sign(recipient_sign).unwrap();
2012 let mut buffer = Vec::new();
2013 invoice.write(&mut buffer).unwrap();
2015 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2016 panic!("error parsing invoice: {:?}", e);
2019 let mut tlv_stream = invoice.as_tlv_stream();
2020 tlv_stream.3.payment_hash = None;
2022 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2023 Ok(_) => panic!("expected error"),
2025 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
2031 fn parses_invoice_with_amount() {
2032 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2035 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2037 .sign(payer_sign).unwrap()
2038 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2040 .sign(recipient_sign).unwrap();
2042 let mut buffer = Vec::new();
2043 invoice.write(&mut buffer).unwrap();
2045 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2046 panic!("error parsing invoice: {:?}", e);
2049 let mut tlv_stream = invoice.as_tlv_stream();
2050 tlv_stream.3.amount = None;
2052 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2053 Ok(_) => panic!("expected error"),
2054 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2059 fn parses_invoice_with_allow_mpp() {
2060 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2063 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2065 .sign(payer_sign).unwrap()
2066 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2069 .sign(recipient_sign).unwrap();
2071 let mut buffer = Vec::new();
2072 invoice.write(&mut buffer).unwrap();
2074 match Bolt12Invoice::try_from(buffer) {
2076 let mut features = Bolt12InvoiceFeatures::empty();
2077 features.set_basic_mpp_optional();
2078 assert_eq!(invoice.invoice_features(), &features);
2080 Err(e) => panic!("error parsing invoice: {:?}", e),
2085 fn parses_invoice_with_fallback_address() {
2086 let script = ScriptBuf::new();
2087 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
2088 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
2089 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
2091 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2094 let invoice_request = offer
2095 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2097 .sign(payer_sign).unwrap();
2098 let mut invoice_builder = invoice_request
2099 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2100 .fallback_v0_p2wsh(&script.wscript_hash())
2101 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
2102 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
2104 // Only standard addresses will be included.
2105 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
2106 // Non-standard addresses
2107 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
2108 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
2109 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
2111 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
2112 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
2114 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
2115 let mut buffer = Vec::new();
2116 invoice.write(&mut buffer).unwrap();
2118 match Bolt12Invoice::try_from(buffer) {
2120 let v1_witness_program = WitnessProgram::new(WitnessVersion::V1, vec![0u8; 33]).unwrap();
2121 let v2_witness_program = WitnessProgram::new(WitnessVersion::V2, vec![0u8; 40]).unwrap();
2123 invoice.fallbacks(),
2125 Address::p2wsh(&script, Network::Bitcoin),
2126 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
2127 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
2128 Address::new(Network::Bitcoin, Payload::WitnessProgram(v1_witness_program)),
2129 Address::new(Network::Bitcoin, Payload::WitnessProgram(v2_witness_program)),
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)),