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};
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};
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::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
324 pub fn allow_mpp(mut self) -> Self {
325 self.invoice.fields_mut().features.set_basic_mpp_optional();
330 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
331 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
332 /// [`UnsignedBolt12Invoice::sign`].
333 pub fn build(self) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
334 #[cfg(feature = "std")] {
335 if self.invoice.is_offer_or_refund_expired() {
336 return Err(Bolt12SemanticError::AlreadyExpired);
340 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
341 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
345 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
346 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
347 pub fn build_and_sign<T: secp256k1::Signing>(
348 self, secp_ctx: &Secp256k1<T>
349 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
350 #[cfg(feature = "std")] {
351 if self.invoice.is_offer_or_refund_expired() {
352 return Err(Bolt12SemanticError::AlreadyExpired);
357 invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
359 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
361 let invoice = unsigned_invoice
362 .sign::<_, Infallible>(
363 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
370 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
371 pub struct UnsignedBolt12Invoice {
373 invoice: InvoiceContents,
374 tagged_hash: TaggedHash,
377 impl UnsignedBolt12Invoice {
378 fn new(invreq_bytes: &[u8], invoice: InvoiceContents) -> Self {
379 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
380 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
382 let (_, _, _, invoice_tlv_stream) = invoice.as_tlv_stream();
383 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
384 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
386 let mut bytes = Vec::new();
387 unsigned_tlv_stream.write(&mut bytes).unwrap();
389 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
391 Self { bytes, invoice, tagged_hash }
394 /// The public key corresponding to the key needed to sign the invoice.
395 pub fn signing_pubkey(&self) -> PublicKey {
396 self.invoice.fields().signing_pubkey
399 /// Signs the invoice using the given function.
401 /// This is not exported to bindings users as functions aren't currently mapped.
402 pub fn sign<F, E>(mut self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
404 F: FnOnce(&Self) -> Result<Signature, E>
406 let pubkey = self.invoice.fields().signing_pubkey;
407 let signature = merkle::sign_message(sign, &self, pubkey)?;
409 // Append the signature TLV record to the bytes.
410 let signature_tlv_stream = SignatureTlvStreamRef {
411 signature: Some(&signature),
413 signature_tlv_stream.write(&mut self.bytes).unwrap();
417 contents: self.invoice,
423 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
424 fn as_ref(&self) -> &TaggedHash {
429 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
431 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
432 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
434 /// [`Offer`]: crate::offers::offer::Offer
435 /// [`Refund`]: crate::offers::refund::Refund
436 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
437 #[derive(Clone, Debug)]
438 #[cfg_attr(test, derive(PartialEq))]
439 pub struct Bolt12Invoice {
441 contents: InvoiceContents,
442 signature: Signature,
445 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
447 /// [`Offer`]: crate::offers::offer::Offer
448 /// [`Refund`]: crate::offers::refund::Refund
449 #[derive(Clone, Debug)]
450 #[cfg_attr(test, derive(PartialEq))]
451 enum InvoiceContents {
452 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
454 /// [`Offer`]: crate::offers::offer::Offer
456 invoice_request: InvoiceRequestContents,
457 fields: InvoiceFields,
459 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
461 /// [`Refund`]: crate::offers::refund::Refund
463 refund: RefundContents,
464 fields: InvoiceFields,
468 /// Invoice-specific fields for an `invoice` message.
469 #[derive(Clone, Debug, PartialEq)]
470 struct InvoiceFields {
471 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
472 created_at: Duration,
473 relative_expiry: Option<Duration>,
474 payment_hash: PaymentHash,
476 fallbacks: Option<Vec<FallbackAddress>>,
477 features: Bolt12InvoiceFeatures,
478 signing_pubkey: PublicKey,
482 /// A complete description of the purpose of the originating offer or refund. Intended to be
483 /// displayed to the user but with the caveat that it has not been verified in any way.
484 pub fn description(&self) -> PrintableString {
485 self.contents.description()
488 /// Paths to the recipient originating from publicly reachable nodes, including information
489 /// needed for routing payments across them.
491 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
492 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
494 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
495 /// matched in another language.
496 pub fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
497 &self.contents.fields().payment_paths[..]
500 /// Duration since the Unix epoch when the invoice was created.
501 pub fn created_at(&self) -> Duration {
502 self.contents.fields().created_at
505 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
506 /// should no longer be paid.
507 pub fn relative_expiry(&self) -> Duration {
508 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
511 /// Whether the invoice has expired.
512 #[cfg(feature = "std")]
513 pub fn is_expired(&self) -> bool {
514 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
515 match absolute_expiry {
516 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
517 Ok(elapsed) => elapsed > seconds_from_epoch,
524 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
525 pub fn payment_hash(&self) -> PaymentHash {
526 self.contents.fields().payment_hash
529 /// The minimum amount required for a successful payment of the invoice.
530 pub fn amount_msats(&self) -> u64 {
531 self.contents.fields().amount_msats
534 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
536 pub fn fallbacks(&self) -> Vec<Address> {
537 let network = match self.network() {
538 None => return Vec::new(),
539 Some(network) => network,
542 let to_valid_address = |address: &FallbackAddress| {
543 let version = match WitnessVersion::try_from(address.version) {
544 Ok(version) => version,
545 Err(_) => return None,
548 let program = &address.program;
549 if program.len() < 2 || program.len() > 40 {
553 let address = Address {
554 payload: Payload::WitnessProgram {
556 program: address.program.clone(),
561 if !address.is_standard() && version == WitnessVersion::V0 {
568 self.contents.fields().fallbacks
570 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
571 .unwrap_or_else(Vec::new)
574 fn network(&self) -> Option<Network> {
575 let chain = self.contents.chain();
576 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
577 Some(Network::Bitcoin)
578 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
579 Some(Network::Testnet)
580 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
581 Some(Network::Signet)
582 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
583 Some(Network::Regtest)
589 /// Features pertaining to paying an invoice.
590 pub fn features(&self) -> &Bolt12InvoiceFeatures {
591 &self.contents.fields().features
594 /// The public key corresponding to the key used to sign the invoice.
595 pub fn signing_pubkey(&self) -> PublicKey {
596 self.contents.fields().signing_pubkey
599 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
600 pub fn signature(&self) -> Signature {
604 /// Hash that was used for signing the invoice.
605 pub fn signable_hash(&self) -> [u8; 32] {
606 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
609 /// Verifies that the invoice was for a request or refund created using the given key.
610 pub fn verify<T: secp256k1::Signing>(
611 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
613 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
617 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
618 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
619 self.contents.as_tlv_stream();
620 let signature_tlv_stream = SignatureTlvStreamRef {
621 signature: Some(&self.signature),
623 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
624 signature_tlv_stream)
628 impl InvoiceContents {
629 /// Whether the original offer or refund has expired.
630 #[cfg(feature = "std")]
631 fn is_offer_or_refund_expired(&self) -> bool {
633 InvoiceContents::ForOffer { invoice_request, .. } =>
634 invoice_request.inner.offer.is_expired(),
635 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
639 fn chain(&self) -> ChainHash {
641 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
642 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
646 fn description(&self) -> PrintableString {
648 InvoiceContents::ForOffer { invoice_request, .. } => {
649 invoice_request.inner.offer.description()
651 InvoiceContents::ForRefund { refund, .. } => refund.description(),
655 fn fields(&self) -> &InvoiceFields {
657 InvoiceContents::ForOffer { fields, .. } => fields,
658 InvoiceContents::ForRefund { fields, .. } => fields,
662 fn fields_mut(&mut self) -> &mut InvoiceFields {
664 InvoiceContents::ForOffer { fields, .. } => fields,
665 InvoiceContents::ForRefund { fields, .. } => fields,
669 fn verify<T: secp256k1::Signing>(
670 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
672 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
673 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
674 match record.r#type {
675 PAYER_METADATA_TYPE => false, // Should be outside range
676 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
680 let tlv_stream = offer_records.chain(invreq_records);
682 let (metadata, payer_id, iv_bytes) = match self {
683 InvoiceContents::ForOffer { invoice_request, .. } => {
684 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
686 InvoiceContents::ForRefund { refund, .. } => {
687 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
691 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
697 fn derives_keys(&self) -> bool {
699 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
700 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
704 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
705 let (payer, offer, invoice_request) = match self {
706 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
707 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
709 let invoice = self.fields().as_tlv_stream();
711 (payer, offer, invoice_request, invoice)
716 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
718 if self.features == Bolt12InvoiceFeatures::empty() { None }
719 else { Some(&self.features) }
722 InvoiceTlvStreamRef {
723 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
724 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
725 created_at: Some(self.created_at.as_secs()),
726 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
727 payment_hash: Some(&self.payment_hash),
728 amount: Some(self.amount_msats),
729 fallbacks: self.fallbacks.as_ref(),
731 node_id: Some(&self.signing_pubkey),
736 impl Writeable for Bolt12Invoice {
737 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
738 WithoutLength(&self.bytes).write(writer)
742 impl Writeable for InvoiceContents {
743 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
744 self.as_tlv_stream().write(writer)
748 impl TryFrom<Vec<u8>> for Bolt12Invoice {
749 type Error = Bolt12ParseError;
751 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
752 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
753 Bolt12Invoice::try_from(parsed_invoice)
757 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
758 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
759 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
760 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
761 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
762 (168, payment_hash: PaymentHash),
763 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
764 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
765 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
766 (176, node_id: PublicKey),
769 type BlindedPathIter<'a> = core::iter::Map<
770 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
771 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
774 type BlindedPayInfoIter<'a> = core::iter::Map<
775 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
776 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
779 /// Information needed to route a payment across a [`BlindedPath`].
780 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
781 pub struct BlindedPayInfo {
782 /// Base fee charged (in millisatoshi) for the entire blinded path.
783 pub fee_base_msat: u32,
785 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
786 /// (i.e., 10,000 is 1%).
787 pub fee_proportional_millionths: u32,
789 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
791 pub cltv_expiry_delta: u16,
793 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
794 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
795 /// seen by the recipient.
796 pub htlc_minimum_msat: u64,
798 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
799 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
800 /// seen by the recipient.
801 pub htlc_maximum_msat: u64,
803 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
805 pub features: BlindedHopFeatures,
808 impl_writeable!(BlindedPayInfo, {
810 fee_proportional_millionths,
817 /// Wire representation for an on-chain fallback address.
818 #[derive(Clone, Debug, PartialEq)]
819 pub(super) struct FallbackAddress {
824 impl_writeable!(FallbackAddress, { version, program });
826 type FullInvoiceTlvStream =
827 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
830 type FullInvoiceTlvStreamRef<'a> = (
831 PayerTlvStreamRef<'a>,
832 OfferTlvStreamRef<'a>,
833 InvoiceRequestTlvStreamRef<'a>,
834 InvoiceTlvStreamRef<'a>,
835 SignatureTlvStreamRef<'a>,
838 impl SeekReadable for FullInvoiceTlvStream {
839 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
840 let payer = SeekReadable::read(r)?;
841 let offer = SeekReadable::read(r)?;
842 let invoice_request = SeekReadable::read(r)?;
843 let invoice = SeekReadable::read(r)?;
844 let signature = SeekReadable::read(r)?;
846 Ok((payer, offer, invoice_request, invoice, signature))
850 type PartialInvoiceTlvStream =
851 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
853 type PartialInvoiceTlvStreamRef<'a> = (
854 PayerTlvStreamRef<'a>,
855 OfferTlvStreamRef<'a>,
856 InvoiceRequestTlvStreamRef<'a>,
857 InvoiceTlvStreamRef<'a>,
860 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
861 type Error = Bolt12ParseError;
863 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
864 let ParsedMessage { bytes, tlv_stream } = invoice;
866 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
867 SignatureTlvStream { signature },
869 let contents = InvoiceContents::try_from(
870 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
873 let signature = match signature {
874 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
875 Some(signature) => signature,
877 let pubkey = contents.fields().signing_pubkey;
878 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
880 Ok(Bolt12Invoice { bytes, contents, signature })
884 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
885 type Error = Bolt12SemanticError;
887 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
891 invoice_request_tlv_stream,
893 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
898 let payment_paths = match (blindedpay, paths) {
899 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
900 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
901 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
902 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
903 return Err(Bolt12SemanticError::InvalidPayInfo);
905 (Some(blindedpay), Some(paths)) => {
906 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
910 let created_at = match created_at {
911 None => return Err(Bolt12SemanticError::MissingCreationTime),
912 Some(timestamp) => Duration::from_secs(timestamp),
915 let relative_expiry = relative_expiry
916 .map(Into::<u64>::into)
917 .map(Duration::from_secs);
919 let payment_hash = match payment_hash {
920 None => return Err(Bolt12SemanticError::MissingPaymentHash),
921 Some(payment_hash) => payment_hash,
924 let amount_msats = match amount {
925 None => return Err(Bolt12SemanticError::MissingAmount),
926 Some(amount) => amount,
929 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
931 let signing_pubkey = match node_id {
932 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
933 Some(node_id) => node_id,
936 let fields = InvoiceFields {
937 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
938 features, signing_pubkey,
941 match offer_tlv_stream.node_id {
942 Some(expected_signing_pubkey) => {
943 if fields.signing_pubkey != expected_signing_pubkey {
944 return Err(Bolt12SemanticError::InvalidSigningPubkey);
947 let invoice_request = InvoiceRequestContents::try_from(
948 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
950 Ok(InvoiceContents::ForOffer { invoice_request, fields })
953 let refund = RefundContents::try_from(
954 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
956 Ok(InvoiceContents::ForRefund { refund, fields })
964 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG};
966 use bitcoin::blockdata::script::Script;
967 use bitcoin::hashes::Hash;
968 use bitcoin::network::constants::Network;
969 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
970 use bitcoin::util::address::{Address, Payload, WitnessVersion};
971 use bitcoin::util::schnorr::TweakedPublicKey;
972 use core::convert::TryFrom;
973 use core::time::Duration;
974 use crate::blinded_path::{BlindedHop, BlindedPath};
975 use crate::sign::KeyMaterial;
976 use crate::ln::features::Bolt12InvoiceFeatures;
977 use crate::ln::inbound_payment::ExpandedKey;
978 use crate::ln::msgs::DecodeError;
979 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
980 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
981 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
982 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
983 use crate::offers::payer::PayerTlvStreamRef;
984 use crate::offers::refund::RefundBuilder;
985 use crate::offers::test_utils::*;
986 use crate::util::ser::{BigSize, Iterable, Writeable};
987 use crate::util::string::PrintableString;
990 fn to_bytes(&self) -> Vec<u8>;
993 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
994 fn to_bytes(&self) -> Vec<u8> {
995 let mut buffer = Vec::new();
996 self.0.write(&mut buffer).unwrap();
997 self.1.write(&mut buffer).unwrap();
998 self.2.write(&mut buffer).unwrap();
999 self.3.write(&mut buffer).unwrap();
1000 self.4.write(&mut buffer).unwrap();
1006 fn builds_invoice_for_offer_with_defaults() {
1007 let payment_paths = payment_paths();
1008 let payment_hash = payment_hash();
1010 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1013 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1015 .sign(payer_sign).unwrap()
1016 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1018 .sign(recipient_sign).unwrap();
1020 let mut buffer = Vec::new();
1021 invoice.write(&mut buffer).unwrap();
1023 assert_eq!(invoice.bytes, buffer.as_slice());
1024 assert_eq!(invoice.description(), PrintableString("foo"));
1025 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1026 assert_eq!(invoice.created_at(), now);
1027 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1028 #[cfg(feature = "std")]
1029 assert!(!invoice.is_expired());
1030 assert_eq!(invoice.payment_hash(), payment_hash);
1031 assert_eq!(invoice.amount_msats(), 1000);
1032 assert_eq!(invoice.fallbacks(), vec![]);
1033 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1034 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1036 merkle::verify_signature(
1037 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1041 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1042 let pubkey = recipient_pubkey().into();
1043 let secp_ctx = Secp256k1::verification_only();
1044 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1047 invoice.as_tlv_stream(),
1049 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1055 description: Some(&String::from("foo")),
1057 absolute_expiry: None,
1061 node_id: Some(&recipient_pubkey()),
1063 InvoiceRequestTlvStreamRef {
1068 payer_id: Some(&payer_pubkey()),
1071 InvoiceTlvStreamRef {
1072 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1073 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1074 created_at: Some(now.as_secs()),
1075 relative_expiry: None,
1076 payment_hash: Some(&payment_hash),
1080 node_id: Some(&recipient_pubkey()),
1082 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1086 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1087 panic!("error parsing invoice: {:?}", e);
1092 fn builds_invoice_for_refund_with_defaults() {
1093 let payment_paths = payment_paths();
1094 let payment_hash = payment_hash();
1096 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1098 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1101 .sign(recipient_sign).unwrap();
1103 let mut buffer = Vec::new();
1104 invoice.write(&mut buffer).unwrap();
1106 assert_eq!(invoice.bytes, buffer.as_slice());
1107 assert_eq!(invoice.description(), PrintableString("foo"));
1108 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1109 assert_eq!(invoice.created_at(), now);
1110 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1111 #[cfg(feature = "std")]
1112 assert!(!invoice.is_expired());
1113 assert_eq!(invoice.payment_hash(), payment_hash);
1114 assert_eq!(invoice.amount_msats(), 1000);
1115 assert_eq!(invoice.fallbacks(), vec![]);
1116 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1117 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1119 merkle::verify_signature(
1120 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1125 invoice.as_tlv_stream(),
1127 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1133 description: Some(&String::from("foo")),
1135 absolute_expiry: None,
1141 InvoiceRequestTlvStreamRef {
1146 payer_id: Some(&payer_pubkey()),
1149 InvoiceTlvStreamRef {
1150 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1151 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1152 created_at: Some(now.as_secs()),
1153 relative_expiry: None,
1154 payment_hash: Some(&payment_hash),
1158 node_id: Some(&recipient_pubkey()),
1160 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1164 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1165 panic!("error parsing invoice: {:?}", e);
1169 #[cfg(feature = "std")]
1171 fn builds_invoice_from_offer_with_expiration() {
1172 let future_expiry = Duration::from_secs(u64::max_value());
1173 let past_expiry = Duration::from_secs(0);
1175 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1177 .absolute_expiry(future_expiry)
1179 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1181 .sign(payer_sign).unwrap()
1182 .respond_with(payment_paths(), payment_hash())
1186 panic!("error building invoice: {:?}", e);
1189 match OfferBuilder::new("foo".into(), recipient_pubkey())
1191 .absolute_expiry(past_expiry)
1193 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1195 .sign(payer_sign).unwrap()
1196 .respond_with(payment_paths(), payment_hash())
1200 Ok(_) => panic!("expected error"),
1201 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1205 #[cfg(feature = "std")]
1207 fn builds_invoice_from_refund_with_expiration() {
1208 let future_expiry = Duration::from_secs(u64::max_value());
1209 let past_expiry = Duration::from_secs(0);
1211 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1212 .absolute_expiry(future_expiry)
1214 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1218 panic!("error building invoice: {:?}", e);
1221 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1222 .absolute_expiry(past_expiry)
1224 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1228 Ok(_) => panic!("expected error"),
1229 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1234 fn builds_invoice_from_offer_using_derived_keys() {
1235 let desc = "foo".to_string();
1236 let node_id = recipient_pubkey();
1237 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1238 let entropy = FixedEntropy {};
1239 let secp_ctx = Secp256k1::new();
1241 let blinded_path = BlindedPath {
1242 introduction_node_id: pubkey(40),
1243 blinding_point: pubkey(41),
1245 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1246 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1250 let offer = OfferBuilder
1251 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1255 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1257 .sign(payer_sign).unwrap();
1259 if let Err(e) = invoice_request
1260 .verify_and_respond_using_derived_keys_no_std(
1261 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1264 .build_and_sign(&secp_ctx)
1266 panic!("error building invoice: {:?}", e);
1269 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1270 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1271 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1273 Ok(_) => panic!("expected error"),
1274 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1277 let desc = "foo".to_string();
1278 let offer = OfferBuilder
1279 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1282 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1284 .sign(payer_sign).unwrap();
1286 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1287 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1289 Ok(_) => panic!("expected error"),
1290 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1295 fn builds_invoice_from_refund_using_derived_keys() {
1296 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1297 let entropy = FixedEntropy {};
1298 let secp_ctx = Secp256k1::new();
1300 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1303 if let Err(e) = refund
1304 .respond_using_derived_keys_no_std(
1305 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1308 .build_and_sign(&secp_ctx)
1310 panic!("error building invoice: {:?}", e);
1315 fn builds_invoice_with_relative_expiry() {
1317 let one_hour = Duration::from_secs(3600);
1319 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1322 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1324 .sign(payer_sign).unwrap()
1325 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1326 .relative_expiry(one_hour.as_secs() as u32)
1328 .sign(recipient_sign).unwrap();
1329 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1330 #[cfg(feature = "std")]
1331 assert!(!invoice.is_expired());
1332 assert_eq!(invoice.relative_expiry(), one_hour);
1333 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1335 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1338 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1340 .sign(payer_sign).unwrap()
1341 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1342 .relative_expiry(one_hour.as_secs() as u32 - 1)
1344 .sign(recipient_sign).unwrap();
1345 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1346 #[cfg(feature = "std")]
1347 assert!(invoice.is_expired());
1348 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1349 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1353 fn builds_invoice_with_amount_from_request() {
1354 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1357 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1358 .amount_msats(1001).unwrap()
1360 .sign(payer_sign).unwrap()
1361 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1363 .sign(recipient_sign).unwrap();
1364 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1365 assert_eq!(invoice.amount_msats(), 1001);
1366 assert_eq!(tlv_stream.amount, Some(1001));
1370 fn builds_invoice_with_quantity_from_request() {
1371 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1373 .supported_quantity(Quantity::Unbounded)
1375 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1376 .quantity(2).unwrap()
1378 .sign(payer_sign).unwrap()
1379 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1381 .sign(recipient_sign).unwrap();
1382 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1383 assert_eq!(invoice.amount_msats(), 2000);
1384 assert_eq!(tlv_stream.amount, Some(2000));
1386 match OfferBuilder::new("foo".into(), recipient_pubkey())
1388 .supported_quantity(Quantity::Unbounded)
1390 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1391 .quantity(u64::max_value()).unwrap()
1393 .sign(payer_sign).unwrap()
1394 .respond_with_no_std(payment_paths(), payment_hash(), now())
1396 Ok(_) => panic!("expected error"),
1397 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1402 fn builds_invoice_with_fallback_address() {
1403 let script = Script::new();
1404 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1405 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1406 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1408 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1411 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1413 .sign(payer_sign).unwrap()
1414 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1415 .fallback_v0_p2wsh(&script.wscript_hash())
1416 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1417 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1419 .sign(recipient_sign).unwrap();
1420 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1422 invoice.fallbacks(),
1424 Address::p2wsh(&script, Network::Bitcoin),
1425 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1426 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1430 tlv_stream.fallbacks,
1433 version: WitnessVersion::V0.to_num(),
1434 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1437 version: WitnessVersion::V0.to_num(),
1438 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1441 version: WitnessVersion::V1.to_num(),
1442 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1449 fn builds_invoice_with_allow_mpp() {
1450 let mut features = Bolt12InvoiceFeatures::empty();
1451 features.set_basic_mpp_optional();
1453 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1456 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1458 .sign(payer_sign).unwrap()
1459 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1462 .sign(recipient_sign).unwrap();
1463 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1464 assert_eq!(invoice.features(), &features);
1465 assert_eq!(tlv_stream.features, Some(&features));
1469 fn fails_signing_invoice() {
1470 match OfferBuilder::new("foo".into(), recipient_pubkey())
1473 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1475 .sign(payer_sign).unwrap()
1476 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1480 Ok(_) => panic!("expected error"),
1481 Err(e) => assert_eq!(e, SignError::Signing(())),
1484 match OfferBuilder::new("foo".into(), recipient_pubkey())
1487 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1489 .sign(payer_sign).unwrap()
1490 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1494 Ok(_) => panic!("expected error"),
1495 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1500 fn parses_invoice_with_payment_paths() {
1501 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1504 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 .sign(payer_sign).unwrap()
1507 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1509 .sign(recipient_sign).unwrap();
1511 let mut buffer = Vec::new();
1512 invoice.write(&mut buffer).unwrap();
1514 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1515 panic!("error parsing invoice: {:?}", e);
1518 let mut tlv_stream = invoice.as_tlv_stream();
1519 tlv_stream.3.paths = None;
1521 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1522 Ok(_) => panic!("expected error"),
1523 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1526 let mut tlv_stream = invoice.as_tlv_stream();
1527 tlv_stream.3.blindedpay = None;
1529 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1530 Ok(_) => panic!("expected error"),
1531 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1534 let empty_payment_paths = vec![];
1535 let mut tlv_stream = invoice.as_tlv_stream();
1536 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1538 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1539 Ok(_) => panic!("expected error"),
1540 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1543 let mut payment_paths = payment_paths();
1544 payment_paths.pop();
1545 let mut tlv_stream = invoice.as_tlv_stream();
1546 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1548 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1549 Ok(_) => panic!("expected error"),
1550 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1555 fn parses_invoice_with_created_at() {
1556 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1559 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1561 .sign(payer_sign).unwrap()
1562 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1564 .sign(recipient_sign).unwrap();
1566 let mut buffer = Vec::new();
1567 invoice.write(&mut buffer).unwrap();
1569 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1570 panic!("error parsing invoice: {:?}", e);
1573 let mut tlv_stream = invoice.as_tlv_stream();
1574 tlv_stream.3.created_at = None;
1576 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1577 Ok(_) => panic!("expected error"),
1579 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1585 fn parses_invoice_with_relative_expiry() {
1586 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1589 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1591 .sign(payer_sign).unwrap()
1592 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1593 .relative_expiry(3600)
1595 .sign(recipient_sign).unwrap();
1597 let mut buffer = Vec::new();
1598 invoice.write(&mut buffer).unwrap();
1600 match Bolt12Invoice::try_from(buffer) {
1601 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1602 Err(e) => panic!("error parsing invoice: {:?}", e),
1607 fn parses_invoice_with_payment_hash() {
1608 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1611 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1613 .sign(payer_sign).unwrap()
1614 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1616 .sign(recipient_sign).unwrap();
1618 let mut buffer = Vec::new();
1619 invoice.write(&mut buffer).unwrap();
1621 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1622 panic!("error parsing invoice: {:?}", e);
1625 let mut tlv_stream = invoice.as_tlv_stream();
1626 tlv_stream.3.payment_hash = None;
1628 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1629 Ok(_) => panic!("expected error"),
1631 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1637 fn parses_invoice_with_amount() {
1638 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1641 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1643 .sign(payer_sign).unwrap()
1644 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1646 .sign(recipient_sign).unwrap();
1648 let mut buffer = Vec::new();
1649 invoice.write(&mut buffer).unwrap();
1651 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1652 panic!("error parsing invoice: {:?}", e);
1655 let mut tlv_stream = invoice.as_tlv_stream();
1656 tlv_stream.3.amount = None;
1658 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1659 Ok(_) => panic!("expected error"),
1660 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1665 fn parses_invoice_with_allow_mpp() {
1666 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1669 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1671 .sign(payer_sign).unwrap()
1672 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1675 .sign(recipient_sign).unwrap();
1677 let mut buffer = Vec::new();
1678 invoice.write(&mut buffer).unwrap();
1680 match Bolt12Invoice::try_from(buffer) {
1682 let mut features = Bolt12InvoiceFeatures::empty();
1683 features.set_basic_mpp_optional();
1684 assert_eq!(invoice.features(), &features);
1686 Err(e) => panic!("error parsing invoice: {:?}", e),
1691 fn parses_invoice_with_fallback_address() {
1692 let script = Script::new();
1693 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1694 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1695 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1697 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1700 let invoice_request = offer
1701 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1703 .sign(payer_sign).unwrap();
1704 let mut invoice_builder = invoice_request
1705 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1706 .fallback_v0_p2wsh(&script.wscript_hash())
1707 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1708 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
1710 // Only standard addresses will be included.
1711 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
1712 // Non-standard addresses
1713 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1714 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1715 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1717 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1718 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1720 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
1721 let mut buffer = Vec::new();
1722 invoice.write(&mut buffer).unwrap();
1724 match Bolt12Invoice::try_from(buffer) {
1727 invoice.fallbacks(),
1729 Address::p2wsh(&script, Network::Bitcoin),
1730 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1731 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1733 payload: Payload::WitnessProgram {
1734 version: WitnessVersion::V1,
1735 program: vec![0u8; 33],
1737 network: Network::Bitcoin,
1740 payload: Payload::WitnessProgram {
1741 version: WitnessVersion::V2,
1742 program: vec![0u8; 40],
1744 network: Network::Bitcoin,
1749 Err(e) => panic!("error parsing invoice: {:?}", e),
1754 fn parses_invoice_with_node_id() {
1755 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1758 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1760 .sign(payer_sign).unwrap()
1761 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1763 .sign(recipient_sign).unwrap();
1765 let mut buffer = Vec::new();
1766 invoice.write(&mut buffer).unwrap();
1768 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1769 panic!("error parsing invoice: {:?}", e);
1772 let mut tlv_stream = invoice.as_tlv_stream();
1773 tlv_stream.3.node_id = None;
1775 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1776 Ok(_) => panic!("expected error"),
1778 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1782 let invalid_pubkey = payer_pubkey();
1783 let mut tlv_stream = invoice.as_tlv_stream();
1784 tlv_stream.3.node_id = Some(&invalid_pubkey);
1786 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1787 Ok(_) => panic!("expected error"),
1789 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1795 fn fails_parsing_invoice_without_signature() {
1796 let mut buffer = Vec::new();
1797 OfferBuilder::new("foo".into(), recipient_pubkey())
1800 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1802 .sign(payer_sign).unwrap()
1803 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1806 .write(&mut buffer).unwrap();
1808 match Bolt12Invoice::try_from(buffer) {
1809 Ok(_) => panic!("expected error"),
1810 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1815 fn fails_parsing_invoice_with_invalid_signature() {
1816 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1819 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1821 .sign(payer_sign).unwrap()
1822 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1824 .sign(recipient_sign).unwrap();
1825 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1826 *last_signature_byte = last_signature_byte.wrapping_add(1);
1828 let mut buffer = Vec::new();
1829 invoice.write(&mut buffer).unwrap();
1831 match Bolt12Invoice::try_from(buffer) {
1832 Ok(_) => panic!("expected error"),
1834 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1840 fn fails_parsing_invoice_with_extra_tlv_records() {
1841 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1844 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1846 .sign(payer_sign).unwrap()
1847 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1849 .sign(recipient_sign).unwrap();
1851 let mut encoded_invoice = Vec::new();
1852 invoice.write(&mut encoded_invoice).unwrap();
1853 BigSize(1002).write(&mut encoded_invoice).unwrap();
1854 BigSize(32).write(&mut encoded_invoice).unwrap();
1855 [42u8; 32].write(&mut encoded_invoice).unwrap();
1857 match Bolt12Invoice::try_from(encoded_invoice) {
1858 Ok(_) => panic!("expected error"),
1859 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),