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>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //! .expect("failed verifying signature")
60 //! .write(&mut buffer)
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::Bolt12ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
74 //! // Invoice for the "offer for money" flow.
76 //! .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78 .respond_with(payment_paths, payment_hash, pubkey)?
80 #![cfg_attr(not(feature = "std"), doc = "
81 .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
83 //! .relative_expiry(3600)
85 //! .fallback_v0_p2wpkh(&wpubkey_hash)
87 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //! .expect("failed verifying signature")
89 //! .write(&mut buffer)
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, self};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::{Infallible, TryFrom};
105 use core::time::Duration;
107 use crate::blinded_path::BlindedPath;
108 use crate::ln::PaymentHash;
109 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
110 use crate::ln::inbound_payment::ExpandedKey;
111 use crate::ln::msgs::DecodeError;
112 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
113 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TlvStream, WithoutSignatures, self};
114 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
115 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
116 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
117 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
118 use crate::offers::signer;
119 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
120 use crate::util::string::PrintableString;
122 use crate::prelude::*;
124 #[cfg(feature = "std")]
125 use std::time::SystemTime;
127 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
129 pub(super) const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
131 /// Builds a [`Bolt12Invoice`] from either:
132 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
133 /// - a [`Refund`] for the "offer for money" flow.
135 /// See [module-level documentation] for usage.
137 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
139 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
140 /// [`Refund`]: crate::offers::refund::Refund
141 /// [module-level documentation]: self
142 pub struct InvoiceBuilder<'a, S: SigningPubkeyStrategy> {
143 invreq_bytes: &'a Vec<u8>,
144 invoice: InvoiceContents,
145 keys: Option<KeyPair>,
146 signing_pubkey_strategy: core::marker::PhantomData<S>,
149 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
151 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
152 pub trait SigningPubkeyStrategy {}
154 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
156 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
157 pub struct ExplicitSigningPubkey {}
159 /// [`Bolt12Invoice::signing_pubkey`] was derived.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub struct DerivedSigningPubkey {}
164 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
165 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
167 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
168 pub(super) fn for_offer(
169 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
170 created_at: Duration, payment_hash: PaymentHash
171 ) -> Result<Self, Bolt12SemanticError> {
172 let amount_msats = Self::check_amount_msats(invoice_request)?;
173 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
174 let contents = InvoiceContents::ForOffer {
175 invoice_request: invoice_request.contents.clone(),
176 fields: Self::fields(
177 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
181 Self::new(&invoice_request.bytes, contents, None)
184 pub(super) fn for_refund(
185 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
186 payment_hash: PaymentHash, signing_pubkey: PublicKey
187 ) -> Result<Self, Bolt12SemanticError> {
188 let amount_msats = refund.amount_msats();
189 let contents = InvoiceContents::ForRefund {
190 refund: refund.contents.clone(),
191 fields: Self::fields(
192 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
196 Self::new(&refund.bytes, contents, None)
200 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
201 pub(super) fn for_offer_using_keys(
202 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
203 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
204 ) -> Result<Self, Bolt12SemanticError> {
205 let amount_msats = Self::check_amount_msats(invoice_request)?;
206 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
207 let contents = InvoiceContents::ForOffer {
208 invoice_request: invoice_request.contents.clone(),
209 fields: Self::fields(
210 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
214 Self::new(&invoice_request.bytes, contents, Some(keys))
217 pub(super) fn for_refund_using_keys(
218 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
219 payment_hash: PaymentHash, keys: KeyPair,
220 ) -> Result<Self, Bolt12SemanticError> {
221 let amount_msats = refund.amount_msats();
222 let signing_pubkey = keys.public_key();
223 let contents = InvoiceContents::ForRefund {
224 refund: refund.contents.clone(),
225 fields: Self::fields(
226 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
230 Self::new(&refund.bytes, contents, Some(keys))
234 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
235 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, Bolt12SemanticError> {
236 match invoice_request.amount_msats() {
237 Some(amount_msats) => Ok(amount_msats),
238 None => match invoice_request.contents.inner.offer.amount() {
239 Some(Amount::Bitcoin { amount_msats }) => {
240 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
241 .ok_or(Bolt12SemanticError::InvalidAmount)
243 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
244 None => Err(Bolt12SemanticError::MissingAmount),
250 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
251 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
254 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
255 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
260 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
261 ) -> Result<Self, Bolt12SemanticError> {
262 if contents.fields().payment_paths.is_empty() {
263 return Err(Bolt12SemanticError::MissingPaths);
270 signing_pubkey_strategy: core::marker::PhantomData,
274 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
275 /// Any expiry that has already passed is valid and can be checked for using
276 /// [`Bolt12Invoice::is_expired`].
278 /// Successive calls to this method will override the previous setting.
279 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
280 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
281 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
285 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
287 /// Successive calls to this method will add another address. Caller is responsible for not
288 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
289 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
290 let address = FallbackAddress {
291 version: WitnessVersion::V0.to_num(),
292 program: Vec::from(&script_hash.into_inner()[..]),
294 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
298 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
300 /// Successive calls to this method will add another address. Caller is responsible for not
301 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
302 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
303 let address = FallbackAddress {
304 version: WitnessVersion::V0.to_num(),
305 program: Vec::from(&pubkey_hash.into_inner()[..]),
307 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
311 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
313 /// Successive calls to this method will add another address. Caller is responsible for not
314 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
316 /// This is not exported to bindings users as TweakedPublicKey isn't yet mapped.
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::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
327 pub fn allow_mpp(mut self) -> Self {
328 self.invoice.fields_mut().features.set_basic_mpp_optional();
333 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
334 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
335 /// [`UnsignedBolt12Invoice::sign`].
336 pub fn build(self) -> Result<UnsignedBolt12Invoice<'a>, Bolt12SemanticError> {
337 #[cfg(feature = "std")] {
338 if self.invoice.is_offer_or_refund_expired() {
339 return Err(Bolt12SemanticError::AlreadyExpired);
343 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
344 Ok(UnsignedBolt12Invoice { invreq_bytes, invoice })
348 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
349 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
350 pub fn build_and_sign<T: secp256k1::Signing>(
351 self, secp_ctx: &Secp256k1<T>
352 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
353 #[cfg(feature = "std")] {
354 if self.invoice.is_offer_or_refund_expired() {
355 return Err(Bolt12SemanticError::AlreadyExpired);
359 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
360 let unsigned_invoice = UnsignedBolt12Invoice { invreq_bytes, invoice };
362 let keys = keys.unwrap();
363 let invoice = unsigned_invoice
364 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
370 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
371 pub struct UnsignedBolt12Invoice<'a> {
372 invreq_bytes: &'a Vec<u8>,
373 invoice: InvoiceContents,
376 impl<'a> UnsignedBolt12Invoice<'a> {
377 /// The public key corresponding to the key needed to sign the invoice.
378 pub fn signing_pubkey(&self) -> PublicKey {
379 self.invoice.fields().signing_pubkey
382 /// Signs the invoice using the given function.
384 /// This is not exported to bindings users as functions aren't currently mapped.
385 pub fn sign<F, E>(self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
387 F: FnOnce(&Message) -> Result<Signature, E>
389 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
390 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
392 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
393 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
394 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
396 let mut bytes = Vec::new();
397 unsigned_tlv_stream.write(&mut bytes).unwrap();
399 let pubkey = self.invoice.fields().signing_pubkey;
400 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
402 // Append the signature TLV record to the bytes.
403 let signature_tlv_stream = SignatureTlvStreamRef {
404 signature: Some(&signature),
406 signature_tlv_stream.write(&mut bytes).unwrap();
410 contents: self.invoice,
416 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
418 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
419 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
421 /// [`Offer`]: crate::offers::offer::Offer
422 /// [`Refund`]: crate::offers::refund::Refund
423 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
424 #[derive(Clone, Debug)]
425 #[cfg_attr(test, derive(PartialEq))]
426 pub struct Bolt12Invoice {
428 contents: InvoiceContents,
429 signature: Signature,
432 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
434 /// [`Offer`]: crate::offers::offer::Offer
435 /// [`Refund`]: crate::offers::refund::Refund
436 #[derive(Clone, Debug)]
437 #[cfg_attr(test, derive(PartialEq))]
438 enum InvoiceContents {
439 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
441 /// [`Offer`]: crate::offers::offer::Offer
443 invoice_request: InvoiceRequestContents,
444 fields: InvoiceFields,
446 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
448 /// [`Refund`]: crate::offers::refund::Refund
450 refund: RefundContents,
451 fields: InvoiceFields,
455 /// Invoice-specific fields for an `invoice` message.
456 #[derive(Clone, Debug, PartialEq)]
457 struct InvoiceFields {
458 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
459 created_at: Duration,
460 relative_expiry: Option<Duration>,
461 payment_hash: PaymentHash,
463 fallbacks: Option<Vec<FallbackAddress>>,
464 features: Bolt12InvoiceFeatures,
465 signing_pubkey: PublicKey,
469 /// A complete description of the purpose of the originating offer or refund. Intended to be
470 /// displayed to the user but with the caveat that it has not been verified in any way.
471 pub fn description(&self) -> PrintableString {
472 self.contents.description()
475 /// Paths to the recipient originating from publicly reachable nodes, including information
476 /// needed for routing payments across them.
478 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
479 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
481 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
482 /// matched in another language.
483 pub fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
484 &self.contents.fields().payment_paths[..]
487 /// Duration since the Unix epoch when the invoice was created.
488 pub fn created_at(&self) -> Duration {
489 self.contents.fields().created_at
492 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
493 /// should no longer be paid.
494 pub fn relative_expiry(&self) -> Duration {
495 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
498 /// Whether the invoice has expired.
499 #[cfg(feature = "std")]
500 pub fn is_expired(&self) -> bool {
501 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
502 match absolute_expiry {
503 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
504 Ok(elapsed) => elapsed > seconds_from_epoch,
511 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
512 pub fn payment_hash(&self) -> PaymentHash {
513 self.contents.fields().payment_hash
516 /// The minimum amount required for a successful payment of the invoice.
517 pub fn amount_msats(&self) -> u64 {
518 self.contents.fields().amount_msats
521 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
524 /// This is not exported to bindings users as Address is not yet mapped
525 pub fn fallbacks(&self) -> Vec<Address> {
526 let network = match self.network() {
527 None => return Vec::new(),
528 Some(network) => network,
531 let to_valid_address = |address: &FallbackAddress| {
532 let version = match WitnessVersion::try_from(address.version) {
533 Ok(version) => version,
534 Err(_) => return None,
537 let program = &address.program;
538 if program.len() < 2 || program.len() > 40 {
542 let address = Address {
543 payload: Payload::WitnessProgram {
545 program: address.program.clone(),
550 if !address.is_standard() && version == WitnessVersion::V0 {
557 self.contents.fields().fallbacks
559 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
560 .unwrap_or_else(Vec::new)
563 fn network(&self) -> Option<Network> {
564 let chain = self.contents.chain();
565 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
566 Some(Network::Bitcoin)
567 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
568 Some(Network::Testnet)
569 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
570 Some(Network::Signet)
571 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
572 Some(Network::Regtest)
578 /// Features pertaining to paying an invoice.
579 pub fn features(&self) -> &Bolt12InvoiceFeatures {
580 &self.contents.fields().features
583 /// The public key corresponding to the key used to sign the invoice.
584 pub fn signing_pubkey(&self) -> PublicKey {
585 self.contents.fields().signing_pubkey
588 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
589 pub fn signature(&self) -> Signature {
593 /// Hash that was used for signing the invoice.
594 pub fn signable_hash(&self) -> [u8; 32] {
595 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
598 /// Verifies that the invoice was for a request or refund created using the given key.
599 pub fn verify<T: secp256k1::Signing>(
600 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
602 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
606 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
607 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
608 self.contents.as_tlv_stream();
609 let signature_tlv_stream = SignatureTlvStreamRef {
610 signature: Some(&self.signature),
612 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
613 signature_tlv_stream)
617 impl InvoiceContents {
618 /// Whether the original offer or refund has expired.
619 #[cfg(feature = "std")]
620 fn is_offer_or_refund_expired(&self) -> bool {
622 InvoiceContents::ForOffer { invoice_request, .. } =>
623 invoice_request.inner.offer.is_expired(),
624 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
628 fn chain(&self) -> ChainHash {
630 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
631 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
635 fn description(&self) -> PrintableString {
637 InvoiceContents::ForOffer { invoice_request, .. } => {
638 invoice_request.inner.offer.description()
640 InvoiceContents::ForRefund { refund, .. } => refund.description(),
644 fn fields(&self) -> &InvoiceFields {
646 InvoiceContents::ForOffer { fields, .. } => fields,
647 InvoiceContents::ForRefund { fields, .. } => fields,
651 fn fields_mut(&mut self) -> &mut InvoiceFields {
653 InvoiceContents::ForOffer { fields, .. } => fields,
654 InvoiceContents::ForRefund { fields, .. } => fields,
658 fn verify<T: secp256k1::Signing>(
659 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
661 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
662 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
663 match record.r#type {
664 PAYER_METADATA_TYPE => false, // Should be outside range
665 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
669 let tlv_stream = offer_records.chain(invreq_records);
671 let (metadata, payer_id, iv_bytes) = match self {
672 InvoiceContents::ForOffer { invoice_request, .. } => {
673 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
675 InvoiceContents::ForRefund { refund, .. } => {
676 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
680 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
686 fn derives_keys(&self) -> bool {
688 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
689 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
693 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
694 let (payer, offer, invoice_request) = match self {
695 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
696 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
698 let invoice = self.fields().as_tlv_stream();
700 (payer, offer, invoice_request, invoice)
705 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
707 if self.features == Bolt12InvoiceFeatures::empty() { None }
708 else { Some(&self.features) }
711 InvoiceTlvStreamRef {
712 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
713 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
714 created_at: Some(self.created_at.as_secs()),
715 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
716 payment_hash: Some(&self.payment_hash),
717 amount: Some(self.amount_msats),
718 fallbacks: self.fallbacks.as_ref(),
720 node_id: Some(&self.signing_pubkey),
725 impl Writeable for Bolt12Invoice {
726 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
727 WithoutLength(&self.bytes).write(writer)
731 impl Writeable for InvoiceContents {
732 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
733 self.as_tlv_stream().write(writer)
737 impl TryFrom<Vec<u8>> for Bolt12Invoice {
738 type Error = Bolt12ParseError;
740 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
741 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
742 Bolt12Invoice::try_from(parsed_invoice)
746 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
747 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
748 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
749 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
750 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
751 (168, payment_hash: PaymentHash),
752 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
753 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
754 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
755 (176, node_id: PublicKey),
758 type BlindedPathIter<'a> = core::iter::Map<
759 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
760 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
763 type BlindedPayInfoIter<'a> = core::iter::Map<
764 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
765 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
768 /// Information needed to route a payment across a [`BlindedPath`].
769 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
770 pub struct BlindedPayInfo {
771 /// Base fee charged (in millisatoshi) for the entire blinded path.
772 pub fee_base_msat: u32,
774 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
775 /// (i.e., 10,000 is 1%).
776 pub fee_proportional_millionths: u32,
778 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
780 pub cltv_expiry_delta: u16,
782 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
783 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
784 /// seen by the recipient.
785 pub htlc_minimum_msat: u64,
787 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
788 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
789 /// seen by the recipient.
790 pub htlc_maximum_msat: u64,
792 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
794 pub features: BlindedHopFeatures,
797 impl_writeable!(BlindedPayInfo, {
799 fee_proportional_millionths,
806 /// Wire representation for an on-chain fallback address.
807 #[derive(Clone, Debug, PartialEq)]
808 pub(super) struct FallbackAddress {
813 impl_writeable!(FallbackAddress, { version, program });
815 type FullInvoiceTlvStream =
816 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
819 type FullInvoiceTlvStreamRef<'a> = (
820 PayerTlvStreamRef<'a>,
821 OfferTlvStreamRef<'a>,
822 InvoiceRequestTlvStreamRef<'a>,
823 InvoiceTlvStreamRef<'a>,
824 SignatureTlvStreamRef<'a>,
827 impl SeekReadable for FullInvoiceTlvStream {
828 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
829 let payer = SeekReadable::read(r)?;
830 let offer = SeekReadable::read(r)?;
831 let invoice_request = SeekReadable::read(r)?;
832 let invoice = SeekReadable::read(r)?;
833 let signature = SeekReadable::read(r)?;
835 Ok((payer, offer, invoice_request, invoice, signature))
839 type PartialInvoiceTlvStream =
840 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
842 type PartialInvoiceTlvStreamRef<'a> = (
843 PayerTlvStreamRef<'a>,
844 OfferTlvStreamRef<'a>,
845 InvoiceRequestTlvStreamRef<'a>,
846 InvoiceTlvStreamRef<'a>,
849 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
850 type Error = Bolt12ParseError;
852 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
853 let ParsedMessage { bytes, tlv_stream } = invoice;
855 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
856 SignatureTlvStream { signature },
858 let contents = InvoiceContents::try_from(
859 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
862 let signature = match signature {
863 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
864 Some(signature) => signature,
866 let pubkey = contents.fields().signing_pubkey;
867 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
869 Ok(Bolt12Invoice { bytes, contents, signature })
873 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
874 type Error = Bolt12SemanticError;
876 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
880 invoice_request_tlv_stream,
882 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
887 let payment_paths = match (blindedpay, paths) {
888 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
889 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
890 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
891 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
892 return Err(Bolt12SemanticError::InvalidPayInfo);
894 (Some(blindedpay), Some(paths)) => {
895 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
899 let created_at = match created_at {
900 None => return Err(Bolt12SemanticError::MissingCreationTime),
901 Some(timestamp) => Duration::from_secs(timestamp),
904 let relative_expiry = relative_expiry
905 .map(Into::<u64>::into)
906 .map(Duration::from_secs);
908 let payment_hash = match payment_hash {
909 None => return Err(Bolt12SemanticError::MissingPaymentHash),
910 Some(payment_hash) => payment_hash,
913 let amount_msats = match amount {
914 None => return Err(Bolt12SemanticError::MissingAmount),
915 Some(amount) => amount,
918 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
920 let signing_pubkey = match node_id {
921 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
922 Some(node_id) => node_id,
925 let fields = InvoiceFields {
926 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
927 features, signing_pubkey,
930 match offer_tlv_stream.node_id {
931 Some(expected_signing_pubkey) => {
932 if fields.signing_pubkey != expected_signing_pubkey {
933 return Err(Bolt12SemanticError::InvalidSigningPubkey);
936 let invoice_request = InvoiceRequestContents::try_from(
937 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
939 Ok(InvoiceContents::ForOffer { invoice_request, fields })
942 let refund = RefundContents::try_from(
943 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
945 Ok(InvoiceContents::ForRefund { refund, fields })
953 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG};
955 use bitcoin::blockdata::script::Script;
956 use bitcoin::hashes::Hash;
957 use bitcoin::network::constants::Network;
958 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
959 use bitcoin::util::address::{Address, Payload, WitnessVersion};
960 use bitcoin::util::schnorr::TweakedPublicKey;
961 use core::convert::TryFrom;
962 use core::time::Duration;
963 use crate::blinded_path::{BlindedHop, BlindedPath};
964 use crate::sign::KeyMaterial;
965 use crate::ln::features::Bolt12InvoiceFeatures;
966 use crate::ln::inbound_payment::ExpandedKey;
967 use crate::ln::msgs::DecodeError;
968 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
969 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
970 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
971 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
972 use crate::offers::payer::PayerTlvStreamRef;
973 use crate::offers::refund::RefundBuilder;
974 use crate::offers::test_utils::*;
975 use crate::util::ser::{BigSize, Iterable, Writeable};
976 use crate::util::string::PrintableString;
979 fn to_bytes(&self) -> Vec<u8>;
982 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
983 fn to_bytes(&self) -> Vec<u8> {
984 let mut buffer = Vec::new();
985 self.0.write(&mut buffer).unwrap();
986 self.1.write(&mut buffer).unwrap();
987 self.2.write(&mut buffer).unwrap();
988 self.3.write(&mut buffer).unwrap();
989 self.4.write(&mut buffer).unwrap();
995 fn builds_invoice_for_offer_with_defaults() {
996 let payment_paths = payment_paths();
997 let payment_hash = payment_hash();
999 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1002 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1004 .sign(payer_sign).unwrap()
1005 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1007 .sign(recipient_sign).unwrap();
1009 let mut buffer = Vec::new();
1010 invoice.write(&mut buffer).unwrap();
1012 assert_eq!(invoice.bytes, buffer.as_slice());
1013 assert_eq!(invoice.description(), PrintableString("foo"));
1014 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1015 assert_eq!(invoice.created_at(), now);
1016 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1017 #[cfg(feature = "std")]
1018 assert!(!invoice.is_expired());
1019 assert_eq!(invoice.payment_hash(), payment_hash);
1020 assert_eq!(invoice.amount_msats(), 1000);
1021 assert_eq!(invoice.fallbacks(), vec![]);
1022 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1023 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1025 merkle::verify_signature(
1026 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1030 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1031 let pubkey = recipient_pubkey().into();
1032 let secp_ctx = Secp256k1::verification_only();
1033 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1036 invoice.as_tlv_stream(),
1038 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1044 description: Some(&String::from("foo")),
1046 absolute_expiry: None,
1050 node_id: Some(&recipient_pubkey()),
1052 InvoiceRequestTlvStreamRef {
1057 payer_id: Some(&payer_pubkey()),
1060 InvoiceTlvStreamRef {
1061 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1062 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1063 created_at: Some(now.as_secs()),
1064 relative_expiry: None,
1065 payment_hash: Some(&payment_hash),
1069 node_id: Some(&recipient_pubkey()),
1071 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1075 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1076 panic!("error parsing invoice: {:?}", e);
1081 fn builds_invoice_for_refund_with_defaults() {
1082 let payment_paths = payment_paths();
1083 let payment_hash = payment_hash();
1085 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1087 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1090 .sign(recipient_sign).unwrap();
1092 let mut buffer = Vec::new();
1093 invoice.write(&mut buffer).unwrap();
1095 assert_eq!(invoice.bytes, buffer.as_slice());
1096 assert_eq!(invoice.description(), PrintableString("foo"));
1097 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1098 assert_eq!(invoice.created_at(), now);
1099 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1100 #[cfg(feature = "std")]
1101 assert!(!invoice.is_expired());
1102 assert_eq!(invoice.payment_hash(), payment_hash);
1103 assert_eq!(invoice.amount_msats(), 1000);
1104 assert_eq!(invoice.fallbacks(), vec![]);
1105 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1106 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1108 merkle::verify_signature(
1109 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1114 invoice.as_tlv_stream(),
1116 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1122 description: Some(&String::from("foo")),
1124 absolute_expiry: None,
1130 InvoiceRequestTlvStreamRef {
1135 payer_id: Some(&payer_pubkey()),
1138 InvoiceTlvStreamRef {
1139 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1140 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1141 created_at: Some(now.as_secs()),
1142 relative_expiry: None,
1143 payment_hash: Some(&payment_hash),
1147 node_id: Some(&recipient_pubkey()),
1149 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1153 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1154 panic!("error parsing invoice: {:?}", e);
1158 #[cfg(feature = "std")]
1160 fn builds_invoice_from_offer_with_expiration() {
1161 let future_expiry = Duration::from_secs(u64::max_value());
1162 let past_expiry = Duration::from_secs(0);
1164 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1166 .absolute_expiry(future_expiry)
1168 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1170 .sign(payer_sign).unwrap()
1171 .respond_with(payment_paths(), payment_hash())
1175 panic!("error building invoice: {:?}", e);
1178 match OfferBuilder::new("foo".into(), recipient_pubkey())
1180 .absolute_expiry(past_expiry)
1182 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1184 .sign(payer_sign).unwrap()
1185 .respond_with(payment_paths(), payment_hash())
1189 Ok(_) => panic!("expected error"),
1190 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1194 #[cfg(feature = "std")]
1196 fn builds_invoice_from_refund_with_expiration() {
1197 let future_expiry = Duration::from_secs(u64::max_value());
1198 let past_expiry = Duration::from_secs(0);
1200 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1201 .absolute_expiry(future_expiry)
1203 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1207 panic!("error building invoice: {:?}", e);
1210 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1211 .absolute_expiry(past_expiry)
1213 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1217 Ok(_) => panic!("expected error"),
1218 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1223 fn builds_invoice_from_offer_using_derived_keys() {
1224 let desc = "foo".to_string();
1225 let node_id = recipient_pubkey();
1226 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1227 let entropy = FixedEntropy {};
1228 let secp_ctx = Secp256k1::new();
1230 let blinded_path = BlindedPath {
1231 introduction_node_id: pubkey(40),
1232 blinding_point: pubkey(41),
1234 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1235 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1239 let offer = OfferBuilder
1240 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1244 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1246 .sign(payer_sign).unwrap();
1248 if let Err(e) = invoice_request
1249 .verify_and_respond_using_derived_keys_no_std(
1250 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1253 .build_and_sign(&secp_ctx)
1255 panic!("error building invoice: {:?}", e);
1258 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1259 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1260 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1262 Ok(_) => panic!("expected error"),
1263 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1266 let desc = "foo".to_string();
1267 let offer = OfferBuilder
1268 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1271 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1273 .sign(payer_sign).unwrap();
1275 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1276 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1278 Ok(_) => panic!("expected error"),
1279 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1284 fn builds_invoice_from_refund_using_derived_keys() {
1285 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1286 let entropy = FixedEntropy {};
1287 let secp_ctx = Secp256k1::new();
1289 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1292 if let Err(e) = refund
1293 .respond_using_derived_keys_no_std(
1294 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1297 .build_and_sign(&secp_ctx)
1299 panic!("error building invoice: {:?}", e);
1304 fn builds_invoice_with_relative_expiry() {
1306 let one_hour = Duration::from_secs(3600);
1308 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1311 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1313 .sign(payer_sign).unwrap()
1314 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1315 .relative_expiry(one_hour.as_secs() as u32)
1317 .sign(recipient_sign).unwrap();
1318 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1319 #[cfg(feature = "std")]
1320 assert!(!invoice.is_expired());
1321 assert_eq!(invoice.relative_expiry(), one_hour);
1322 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1324 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1327 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1329 .sign(payer_sign).unwrap()
1330 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1331 .relative_expiry(one_hour.as_secs() as u32 - 1)
1333 .sign(recipient_sign).unwrap();
1334 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1335 #[cfg(feature = "std")]
1336 assert!(invoice.is_expired());
1337 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1338 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1342 fn builds_invoice_with_amount_from_request() {
1343 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1346 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .amount_msats(1001).unwrap()
1349 .sign(payer_sign).unwrap()
1350 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1352 .sign(recipient_sign).unwrap();
1353 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1354 assert_eq!(invoice.amount_msats(), 1001);
1355 assert_eq!(tlv_stream.amount, Some(1001));
1359 fn builds_invoice_with_quantity_from_request() {
1360 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1362 .supported_quantity(Quantity::Unbounded)
1364 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1365 .quantity(2).unwrap()
1367 .sign(payer_sign).unwrap()
1368 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1370 .sign(recipient_sign).unwrap();
1371 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1372 assert_eq!(invoice.amount_msats(), 2000);
1373 assert_eq!(tlv_stream.amount, Some(2000));
1375 match OfferBuilder::new("foo".into(), recipient_pubkey())
1377 .supported_quantity(Quantity::Unbounded)
1379 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1380 .quantity(u64::max_value()).unwrap()
1382 .sign(payer_sign).unwrap()
1383 .respond_with_no_std(payment_paths(), payment_hash(), now())
1385 Ok(_) => panic!("expected error"),
1386 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1391 fn builds_invoice_with_fallback_address() {
1392 let script = Script::new();
1393 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1394 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1395 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1397 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1400 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1402 .sign(payer_sign).unwrap()
1403 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1404 .fallback_v0_p2wsh(&script.wscript_hash())
1405 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1406 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1408 .sign(recipient_sign).unwrap();
1409 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1411 invoice.fallbacks(),
1413 Address::p2wsh(&script, Network::Bitcoin),
1414 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1415 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1419 tlv_stream.fallbacks,
1422 version: WitnessVersion::V0.to_num(),
1423 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1426 version: WitnessVersion::V0.to_num(),
1427 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1430 version: WitnessVersion::V1.to_num(),
1431 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1438 fn builds_invoice_with_allow_mpp() {
1439 let mut features = Bolt12InvoiceFeatures::empty();
1440 features.set_basic_mpp_optional();
1442 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1447 .sign(payer_sign).unwrap()
1448 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1451 .sign(recipient_sign).unwrap();
1452 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1453 assert_eq!(invoice.features(), &features);
1454 assert_eq!(tlv_stream.features, Some(&features));
1458 fn fails_signing_invoice() {
1459 match OfferBuilder::new("foo".into(), recipient_pubkey())
1462 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1464 .sign(payer_sign).unwrap()
1465 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1469 Ok(_) => panic!("expected error"),
1470 Err(e) => assert_eq!(e, SignError::Signing(())),
1473 match OfferBuilder::new("foo".into(), recipient_pubkey())
1476 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1478 .sign(payer_sign).unwrap()
1479 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1483 Ok(_) => panic!("expected error"),
1484 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1489 fn parses_invoice_with_payment_paths() {
1490 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1493 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1495 .sign(payer_sign).unwrap()
1496 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1498 .sign(recipient_sign).unwrap();
1500 let mut buffer = Vec::new();
1501 invoice.write(&mut buffer).unwrap();
1503 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1504 panic!("error parsing invoice: {:?}", e);
1507 let mut tlv_stream = invoice.as_tlv_stream();
1508 tlv_stream.3.paths = None;
1510 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1511 Ok(_) => panic!("expected error"),
1512 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1515 let mut tlv_stream = invoice.as_tlv_stream();
1516 tlv_stream.3.blindedpay = None;
1518 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1519 Ok(_) => panic!("expected error"),
1520 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1523 let empty_payment_paths = vec![];
1524 let mut tlv_stream = invoice.as_tlv_stream();
1525 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1527 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1528 Ok(_) => panic!("expected error"),
1529 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1532 let mut payment_paths = payment_paths();
1533 payment_paths.pop();
1534 let mut tlv_stream = invoice.as_tlv_stream();
1535 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1537 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1538 Ok(_) => panic!("expected error"),
1539 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1544 fn parses_invoice_with_created_at() {
1545 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1548 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1550 .sign(payer_sign).unwrap()
1551 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1553 .sign(recipient_sign).unwrap();
1555 let mut buffer = Vec::new();
1556 invoice.write(&mut buffer).unwrap();
1558 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1559 panic!("error parsing invoice: {:?}", e);
1562 let mut tlv_stream = invoice.as_tlv_stream();
1563 tlv_stream.3.created_at = None;
1565 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1566 Ok(_) => panic!("expected error"),
1568 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1574 fn parses_invoice_with_relative_expiry() {
1575 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1578 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1580 .sign(payer_sign).unwrap()
1581 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1582 .relative_expiry(3600)
1584 .sign(recipient_sign).unwrap();
1586 let mut buffer = Vec::new();
1587 invoice.write(&mut buffer).unwrap();
1589 match Bolt12Invoice::try_from(buffer) {
1590 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1591 Err(e) => panic!("error parsing invoice: {:?}", e),
1596 fn parses_invoice_with_payment_hash() {
1597 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1600 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1602 .sign(payer_sign).unwrap()
1603 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1605 .sign(recipient_sign).unwrap();
1607 let mut buffer = Vec::new();
1608 invoice.write(&mut buffer).unwrap();
1610 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1611 panic!("error parsing invoice: {:?}", e);
1614 let mut tlv_stream = invoice.as_tlv_stream();
1615 tlv_stream.3.payment_hash = None;
1617 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1618 Ok(_) => panic!("expected error"),
1620 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1626 fn parses_invoice_with_amount() {
1627 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1630 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1632 .sign(payer_sign).unwrap()
1633 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1635 .sign(recipient_sign).unwrap();
1637 let mut buffer = Vec::new();
1638 invoice.write(&mut buffer).unwrap();
1640 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1641 panic!("error parsing invoice: {:?}", e);
1644 let mut tlv_stream = invoice.as_tlv_stream();
1645 tlv_stream.3.amount = None;
1647 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1648 Ok(_) => panic!("expected error"),
1649 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1654 fn parses_invoice_with_allow_mpp() {
1655 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1660 .sign(payer_sign).unwrap()
1661 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1664 .sign(recipient_sign).unwrap();
1666 let mut buffer = Vec::new();
1667 invoice.write(&mut buffer).unwrap();
1669 match Bolt12Invoice::try_from(buffer) {
1671 let mut features = Bolt12InvoiceFeatures::empty();
1672 features.set_basic_mpp_optional();
1673 assert_eq!(invoice.features(), &features);
1675 Err(e) => panic!("error parsing invoice: {:?}", e),
1680 fn parses_invoice_with_fallback_address() {
1681 let script = Script::new();
1682 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1683 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1684 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1686 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1689 let invoice_request = offer
1690 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1692 .sign(payer_sign).unwrap();
1693 let mut unsigned_invoice = invoice_request
1694 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1695 .fallback_v0_p2wsh(&script.wscript_hash())
1696 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1697 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1700 // Only standard addresses will be included.
1701 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1702 // Non-standard addresses
1703 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1704 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1705 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1707 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1708 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1710 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1711 let mut buffer = Vec::new();
1712 invoice.write(&mut buffer).unwrap();
1714 match Bolt12Invoice::try_from(buffer) {
1717 invoice.fallbacks(),
1719 Address::p2wsh(&script, Network::Bitcoin),
1720 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1721 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1723 payload: Payload::WitnessProgram {
1724 version: WitnessVersion::V1,
1725 program: vec![0u8; 33],
1727 network: Network::Bitcoin,
1730 payload: Payload::WitnessProgram {
1731 version: WitnessVersion::V2,
1732 program: vec![0u8; 40],
1734 network: Network::Bitcoin,
1739 Err(e) => panic!("error parsing invoice: {:?}", e),
1744 fn parses_invoice_with_node_id() {
1745 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1748 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1750 .sign(payer_sign).unwrap()
1751 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1753 .sign(recipient_sign).unwrap();
1755 let mut buffer = Vec::new();
1756 invoice.write(&mut buffer).unwrap();
1758 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1759 panic!("error parsing invoice: {:?}", e);
1762 let mut tlv_stream = invoice.as_tlv_stream();
1763 tlv_stream.3.node_id = None;
1765 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1766 Ok(_) => panic!("expected error"),
1768 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1772 let invalid_pubkey = payer_pubkey();
1773 let mut tlv_stream = invoice.as_tlv_stream();
1774 tlv_stream.3.node_id = Some(&invalid_pubkey);
1776 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1777 Ok(_) => panic!("expected error"),
1779 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1785 fn fails_parsing_invoice_without_signature() {
1786 let mut buffer = Vec::new();
1787 OfferBuilder::new("foo".into(), recipient_pubkey())
1790 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1792 .sign(payer_sign).unwrap()
1793 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1796 .write(&mut buffer).unwrap();
1798 match Bolt12Invoice::try_from(buffer) {
1799 Ok(_) => panic!("expected error"),
1800 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1805 fn fails_parsing_invoice_with_invalid_signature() {
1806 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1809 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1811 .sign(payer_sign).unwrap()
1812 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1814 .sign(recipient_sign).unwrap();
1815 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1816 *last_signature_byte = last_signature_byte.wrapping_add(1);
1818 let mut buffer = Vec::new();
1819 invoice.write(&mut buffer).unwrap();
1821 match Bolt12Invoice::try_from(buffer) {
1822 Ok(_) => panic!("expected error"),
1824 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1830 fn fails_parsing_invoice_with_extra_tlv_records() {
1831 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1834 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1836 .sign(payer_sign).unwrap()
1837 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1839 .sign(recipient_sign).unwrap();
1841 let mut encoded_invoice = Vec::new();
1842 invoice.write(&mut encoded_invoice).unwrap();
1843 BigSize(1002).write(&mut encoded_invoice).unwrap();
1844 BigSize(32).write(&mut encoded_invoice).unwrap();
1845 [42u8; 32].write(&mut encoded_invoice).unwrap();
1847 match Bolt12Invoice::try_from(encoded_invoice) {
1848 Ok(_) => panic!("expected error"),
1849 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),