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 keys: Option<KeyPair>,
151 signing_pubkey_strategy: core::marker::PhantomData<S>,
154 /// Indicates how [`Bolt12Invoice::signing_pubkey`] was set.
156 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
157 pub trait SigningPubkeyStrategy {}
159 /// [`Bolt12Invoice::signing_pubkey`] was explicitly set.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub struct ExplicitSigningPubkey {}
164 /// [`Bolt12Invoice::signing_pubkey`] was derived.
166 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
167 pub struct DerivedSigningPubkey {}
169 impl SigningPubkeyStrategy for ExplicitSigningPubkey {}
170 impl SigningPubkeyStrategy for DerivedSigningPubkey {}
172 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
173 pub(super) fn for_offer(
174 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
175 created_at: Duration, payment_hash: PaymentHash
176 ) -> Result<Self, Bolt12SemanticError> {
177 let amount_msats = Self::check_amount_msats(invoice_request)?;
178 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
179 let contents = InvoiceContents::ForOffer {
180 invoice_request: invoice_request.contents.clone(),
181 fields: Self::fields(
182 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
186 Self::new(&invoice_request.bytes, contents, None)
189 pub(super) fn for_refund(
190 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
191 payment_hash: PaymentHash, signing_pubkey: PublicKey
192 ) -> Result<Self, Bolt12SemanticError> {
193 let amount_msats = refund.amount_msats();
194 let contents = InvoiceContents::ForRefund {
195 refund: refund.contents.clone(),
196 fields: Self::fields(
197 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
201 Self::new(&refund.bytes, contents, None)
205 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
206 pub(super) fn for_offer_using_keys(
207 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
208 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
209 ) -> Result<Self, Bolt12SemanticError> {
210 let amount_msats = Self::check_amount_msats(invoice_request)?;
211 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
212 let contents = InvoiceContents::ForOffer {
213 invoice_request: invoice_request.contents.clone(),
214 fields: Self::fields(
215 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
219 Self::new(&invoice_request.bytes, contents, Some(keys))
222 pub(super) fn for_refund_using_keys(
223 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
224 payment_hash: PaymentHash, keys: KeyPair,
225 ) -> Result<Self, Bolt12SemanticError> {
226 let amount_msats = refund.amount_msats();
227 let signing_pubkey = keys.public_key();
228 let contents = InvoiceContents::ForRefund {
229 refund: refund.contents.clone(),
230 fields: Self::fields(
231 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
235 Self::new(&refund.bytes, contents, Some(keys))
239 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
240 fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, Bolt12SemanticError> {
241 match invoice_request.amount_msats() {
242 Some(amount_msats) => Ok(amount_msats),
243 None => match invoice_request.contents.inner.offer.amount() {
244 Some(Amount::Bitcoin { amount_msats }) => {
245 amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
246 .ok_or(Bolt12SemanticError::InvalidAmount)
248 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
249 None => Err(Bolt12SemanticError::MissingAmount),
255 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
256 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
259 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
260 fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
265 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, keys: Option<KeyPair>
266 ) -> Result<Self, Bolt12SemanticError> {
267 if contents.fields().payment_paths.is_empty() {
268 return Err(Bolt12SemanticError::MissingPaths);
275 signing_pubkey_strategy: core::marker::PhantomData,
279 /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
280 /// Any expiry that has already passed is valid and can be checked for using
281 /// [`Bolt12Invoice::is_expired`].
283 /// Successive calls to this method will override the previous setting.
284 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
285 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
286 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
290 /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
292 /// Successive calls to this method will add another address. Caller is responsible for not
293 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
294 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
295 let address = FallbackAddress {
296 version: WitnessVersion::V0.to_num(),
297 program: Vec::from(&script_hash.into_inner()[..]),
299 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
303 /// Adds a P2WPKH address to [`Bolt12Invoice::fallbacks`].
305 /// Successive calls to this method will add another address. Caller is responsible for not
306 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
307 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
308 let address = FallbackAddress {
309 version: WitnessVersion::V0.to_num(),
310 program: Vec::from(&pubkey_hash.into_inner()[..]),
312 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
316 /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
318 /// Successive calls to this method will add another address. Caller is responsible for not
319 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
320 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
321 let address = FallbackAddress {
322 version: WitnessVersion::V1.to_num(),
323 program: Vec::from(&output_key.serialize()[..]),
325 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
329 /// Sets [`Bolt12Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
330 pub fn allow_mpp(mut self) -> Self {
331 self.invoice.fields_mut().features.set_basic_mpp_optional();
336 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
337 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
338 /// [`UnsignedBolt12Invoice::sign`].
339 pub fn build(self) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
340 #[cfg(feature = "std")] {
341 if self.invoice.is_offer_or_refund_expired() {
342 return Err(Bolt12SemanticError::AlreadyExpired);
346 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
347 Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
351 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
352 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
353 pub fn build_and_sign<T: secp256k1::Signing>(
354 self, secp_ctx: &Secp256k1<T>
355 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
356 #[cfg(feature = "std")] {
357 if self.invoice.is_offer_or_refund_expired() {
358 return Err(Bolt12SemanticError::AlreadyExpired);
362 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
363 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
365 let keys = keys.unwrap();
366 let invoice = unsigned_invoice
367 .sign::<_, Infallible>(
368 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
375 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
376 pub struct UnsignedBolt12Invoice {
378 invoice: InvoiceContents,
379 tagged_hash: TaggedHash,
382 impl UnsignedBolt12Invoice {
383 fn new(invreq_bytes: &[u8], invoice: InvoiceContents) -> Self {
384 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
385 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
387 let (_, _, _, invoice_tlv_stream) = invoice.as_tlv_stream();
388 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
389 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
391 let mut bytes = Vec::new();
392 unsigned_tlv_stream.write(&mut bytes).unwrap();
394 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
396 Self { bytes, invoice, tagged_hash }
399 /// The public key corresponding to the key needed to sign the invoice.
400 pub fn signing_pubkey(&self) -> PublicKey {
401 self.invoice.fields().signing_pubkey
404 /// Signs the invoice using the given function.
406 /// This is not exported to bindings users as functions aren't currently mapped.
407 pub fn sign<F, E>(mut self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
409 F: FnOnce(&Self) -> Result<Signature, E>
411 let pubkey = self.invoice.fields().signing_pubkey;
412 let signature = merkle::sign_message(sign, &self, pubkey)?;
414 // Append the signature TLV record to the bytes.
415 let signature_tlv_stream = SignatureTlvStreamRef {
416 signature: Some(&signature),
418 signature_tlv_stream.write(&mut self.bytes).unwrap();
422 contents: self.invoice,
428 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
429 fn as_ref(&self) -> &TaggedHash {
434 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
436 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
437 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
439 /// [`Offer`]: crate::offers::offer::Offer
440 /// [`Refund`]: crate::offers::refund::Refund
441 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
442 #[derive(Clone, Debug)]
443 #[cfg_attr(test, derive(PartialEq))]
444 pub struct Bolt12Invoice {
446 contents: InvoiceContents,
447 signature: Signature,
450 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
452 /// [`Offer`]: crate::offers::offer::Offer
453 /// [`Refund`]: crate::offers::refund::Refund
454 #[derive(Clone, Debug)]
455 #[cfg_attr(test, derive(PartialEq))]
456 enum InvoiceContents {
457 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
459 /// [`Offer`]: crate::offers::offer::Offer
461 invoice_request: InvoiceRequestContents,
462 fields: InvoiceFields,
464 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
466 /// [`Refund`]: crate::offers::refund::Refund
468 refund: RefundContents,
469 fields: InvoiceFields,
473 /// Invoice-specific fields for an `invoice` message.
474 #[derive(Clone, Debug, PartialEq)]
475 struct InvoiceFields {
476 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
477 created_at: Duration,
478 relative_expiry: Option<Duration>,
479 payment_hash: PaymentHash,
481 fallbacks: Option<Vec<FallbackAddress>>,
482 features: Bolt12InvoiceFeatures,
483 signing_pubkey: PublicKey,
487 /// A complete description of the purpose of the originating offer or refund. Intended to be
488 /// displayed to the user but with the caveat that it has not been verified in any way.
489 pub fn description(&self) -> PrintableString {
490 self.contents.description()
493 /// Paths to the recipient originating from publicly reachable nodes, including information
494 /// needed for routing payments across them.
496 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
497 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
499 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
500 /// matched in another language.
501 pub fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
502 &self.contents.fields().payment_paths[..]
505 /// Duration since the Unix epoch when the invoice was created.
506 pub fn created_at(&self) -> Duration {
507 self.contents.fields().created_at
510 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
511 /// should no longer be paid.
512 pub fn relative_expiry(&self) -> Duration {
513 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
516 /// Whether the invoice has expired.
517 #[cfg(feature = "std")]
518 pub fn is_expired(&self) -> bool {
519 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
520 match absolute_expiry {
521 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
522 Ok(elapsed) => elapsed > seconds_from_epoch,
529 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
530 pub fn payment_hash(&self) -> PaymentHash {
531 self.contents.fields().payment_hash
534 /// The minimum amount required for a successful payment of the invoice.
535 pub fn amount_msats(&self) -> u64 {
536 self.contents.fields().amount_msats
539 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
541 pub fn fallbacks(&self) -> Vec<Address> {
542 let network = match self.network() {
543 None => return Vec::new(),
544 Some(network) => network,
547 let to_valid_address = |address: &FallbackAddress| {
548 let version = match WitnessVersion::try_from(address.version) {
549 Ok(version) => version,
550 Err(_) => return None,
553 let program = &address.program;
554 if program.len() < 2 || program.len() > 40 {
558 let address = Address {
559 payload: Payload::WitnessProgram {
561 program: address.program.clone(),
566 if !address.is_standard() && version == WitnessVersion::V0 {
573 self.contents.fields().fallbacks
575 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
576 .unwrap_or_else(Vec::new)
579 fn network(&self) -> Option<Network> {
580 let chain = self.contents.chain();
581 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
582 Some(Network::Bitcoin)
583 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
584 Some(Network::Testnet)
585 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
586 Some(Network::Signet)
587 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
588 Some(Network::Regtest)
594 /// Features pertaining to paying an invoice.
595 pub fn features(&self) -> &Bolt12InvoiceFeatures {
596 &self.contents.fields().features
599 /// The public key corresponding to the key used to sign the invoice.
600 pub fn signing_pubkey(&self) -> PublicKey {
601 self.contents.fields().signing_pubkey
604 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
605 pub fn signature(&self) -> Signature {
609 /// Hash that was used for signing the invoice.
610 pub fn signable_hash(&self) -> [u8; 32] {
611 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
614 /// Verifies that the invoice was for a request or refund created using the given key.
615 pub fn verify<T: secp256k1::Signing>(
616 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
618 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
622 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
623 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
624 self.contents.as_tlv_stream();
625 let signature_tlv_stream = SignatureTlvStreamRef {
626 signature: Some(&self.signature),
628 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
629 signature_tlv_stream)
633 impl InvoiceContents {
634 /// Whether the original offer or refund has expired.
635 #[cfg(feature = "std")]
636 fn is_offer_or_refund_expired(&self) -> bool {
638 InvoiceContents::ForOffer { invoice_request, .. } =>
639 invoice_request.inner.offer.is_expired(),
640 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
644 fn chain(&self) -> ChainHash {
646 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
647 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
651 fn description(&self) -> PrintableString {
653 InvoiceContents::ForOffer { invoice_request, .. } => {
654 invoice_request.inner.offer.description()
656 InvoiceContents::ForRefund { refund, .. } => refund.description(),
660 fn fields(&self) -> &InvoiceFields {
662 InvoiceContents::ForOffer { fields, .. } => fields,
663 InvoiceContents::ForRefund { fields, .. } => fields,
667 fn fields_mut(&mut self) -> &mut InvoiceFields {
669 InvoiceContents::ForOffer { fields, .. } => fields,
670 InvoiceContents::ForRefund { fields, .. } => fields,
674 fn verify<T: secp256k1::Signing>(
675 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
677 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
678 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
679 match record.r#type {
680 PAYER_METADATA_TYPE => false, // Should be outside range
681 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
685 let tlv_stream = offer_records.chain(invreq_records);
687 let (metadata, payer_id, iv_bytes) = match self {
688 InvoiceContents::ForOffer { invoice_request, .. } => {
689 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
691 InvoiceContents::ForRefund { refund, .. } => {
692 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
696 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
702 fn derives_keys(&self) -> bool {
704 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
705 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
709 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
710 let (payer, offer, invoice_request) = match self {
711 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
712 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
714 let invoice = self.fields().as_tlv_stream();
716 (payer, offer, invoice_request, invoice)
721 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
723 if self.features == Bolt12InvoiceFeatures::empty() { None }
724 else { Some(&self.features) }
727 InvoiceTlvStreamRef {
728 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
729 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
730 created_at: Some(self.created_at.as_secs()),
731 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
732 payment_hash: Some(&self.payment_hash),
733 amount: Some(self.amount_msats),
734 fallbacks: self.fallbacks.as_ref(),
736 node_id: Some(&self.signing_pubkey),
741 impl Writeable for Bolt12Invoice {
742 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
743 WithoutLength(&self.bytes).write(writer)
747 impl Writeable for InvoiceContents {
748 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
749 self.as_tlv_stream().write(writer)
753 impl TryFrom<Vec<u8>> for Bolt12Invoice {
754 type Error = Bolt12ParseError;
756 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
757 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
758 Bolt12Invoice::try_from(parsed_invoice)
762 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
763 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
764 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
765 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
766 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
767 (168, payment_hash: PaymentHash),
768 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
769 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
770 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
771 (176, node_id: PublicKey),
774 type BlindedPathIter<'a> = core::iter::Map<
775 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
776 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
779 type BlindedPayInfoIter<'a> = core::iter::Map<
780 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
781 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
784 /// Information needed to route a payment across a [`BlindedPath`].
785 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
786 pub struct BlindedPayInfo {
787 /// Base fee charged (in millisatoshi) for the entire blinded path.
788 pub fee_base_msat: u32,
790 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
791 /// (i.e., 10,000 is 1%).
792 pub fee_proportional_millionths: u32,
794 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
796 pub cltv_expiry_delta: u16,
798 /// The minimum 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_minimum_msat: u64,
803 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
804 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
805 /// seen by the recipient.
806 pub htlc_maximum_msat: u64,
808 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
810 pub features: BlindedHopFeatures,
813 impl_writeable!(BlindedPayInfo, {
815 fee_proportional_millionths,
822 /// Wire representation for an on-chain fallback address.
823 #[derive(Clone, Debug, PartialEq)]
824 pub(super) struct FallbackAddress {
829 impl_writeable!(FallbackAddress, { version, program });
831 type FullInvoiceTlvStream =
832 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
835 type FullInvoiceTlvStreamRef<'a> = (
836 PayerTlvStreamRef<'a>,
837 OfferTlvStreamRef<'a>,
838 InvoiceRequestTlvStreamRef<'a>,
839 InvoiceTlvStreamRef<'a>,
840 SignatureTlvStreamRef<'a>,
843 impl SeekReadable for FullInvoiceTlvStream {
844 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
845 let payer = SeekReadable::read(r)?;
846 let offer = SeekReadable::read(r)?;
847 let invoice_request = SeekReadable::read(r)?;
848 let invoice = SeekReadable::read(r)?;
849 let signature = SeekReadable::read(r)?;
851 Ok((payer, offer, invoice_request, invoice, signature))
855 type PartialInvoiceTlvStream =
856 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
858 type PartialInvoiceTlvStreamRef<'a> = (
859 PayerTlvStreamRef<'a>,
860 OfferTlvStreamRef<'a>,
861 InvoiceRequestTlvStreamRef<'a>,
862 InvoiceTlvStreamRef<'a>,
865 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
866 type Error = Bolt12ParseError;
868 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
869 let ParsedMessage { bytes, tlv_stream } = invoice;
871 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
872 SignatureTlvStream { signature },
874 let contents = InvoiceContents::try_from(
875 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
878 let signature = match signature {
879 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
880 Some(signature) => signature,
882 let pubkey = contents.fields().signing_pubkey;
883 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
885 Ok(Bolt12Invoice { bytes, contents, signature })
889 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
890 type Error = Bolt12SemanticError;
892 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
896 invoice_request_tlv_stream,
898 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
903 let payment_paths = match (blindedpay, paths) {
904 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
905 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
906 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
907 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
908 return Err(Bolt12SemanticError::InvalidPayInfo);
910 (Some(blindedpay), Some(paths)) => {
911 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
915 let created_at = match created_at {
916 None => return Err(Bolt12SemanticError::MissingCreationTime),
917 Some(timestamp) => Duration::from_secs(timestamp),
920 let relative_expiry = relative_expiry
921 .map(Into::<u64>::into)
922 .map(Duration::from_secs);
924 let payment_hash = match payment_hash {
925 None => return Err(Bolt12SemanticError::MissingPaymentHash),
926 Some(payment_hash) => payment_hash,
929 let amount_msats = match amount {
930 None => return Err(Bolt12SemanticError::MissingAmount),
931 Some(amount) => amount,
934 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
936 let signing_pubkey = match node_id {
937 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
938 Some(node_id) => node_id,
941 let fields = InvoiceFields {
942 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
943 features, signing_pubkey,
946 match offer_tlv_stream.node_id {
947 Some(expected_signing_pubkey) => {
948 if fields.signing_pubkey != expected_signing_pubkey {
949 return Err(Bolt12SemanticError::InvalidSigningPubkey);
952 let invoice_request = InvoiceRequestContents::try_from(
953 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
955 Ok(InvoiceContents::ForOffer { invoice_request, fields })
958 let refund = RefundContents::try_from(
959 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
961 Ok(InvoiceContents::ForRefund { refund, fields })
969 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG};
971 use bitcoin::blockdata::script::Script;
972 use bitcoin::hashes::Hash;
973 use bitcoin::network::constants::Network;
974 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
975 use bitcoin::util::address::{Address, Payload, WitnessVersion};
976 use bitcoin::util::schnorr::TweakedPublicKey;
977 use core::convert::TryFrom;
978 use core::time::Duration;
979 use crate::blinded_path::{BlindedHop, BlindedPath};
980 use crate::sign::KeyMaterial;
981 use crate::ln::features::Bolt12InvoiceFeatures;
982 use crate::ln::inbound_payment::ExpandedKey;
983 use crate::ln::msgs::DecodeError;
984 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
985 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
986 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
987 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
988 use crate::offers::payer::PayerTlvStreamRef;
989 use crate::offers::refund::RefundBuilder;
990 use crate::offers::test_utils::*;
991 use crate::util::ser::{BigSize, Iterable, Writeable};
992 use crate::util::string::PrintableString;
995 fn to_bytes(&self) -> Vec<u8>;
998 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
999 fn to_bytes(&self) -> Vec<u8> {
1000 let mut buffer = Vec::new();
1001 self.0.write(&mut buffer).unwrap();
1002 self.1.write(&mut buffer).unwrap();
1003 self.2.write(&mut buffer).unwrap();
1004 self.3.write(&mut buffer).unwrap();
1005 self.4.write(&mut buffer).unwrap();
1011 fn builds_invoice_for_offer_with_defaults() {
1012 let payment_paths = payment_paths();
1013 let payment_hash = payment_hash();
1015 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1018 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1020 .sign(payer_sign).unwrap()
1021 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1023 .sign(recipient_sign).unwrap();
1025 let mut buffer = Vec::new();
1026 invoice.write(&mut buffer).unwrap();
1028 assert_eq!(invoice.bytes, buffer.as_slice());
1029 assert_eq!(invoice.description(), PrintableString("foo"));
1030 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1031 assert_eq!(invoice.created_at(), now);
1032 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1033 #[cfg(feature = "std")]
1034 assert!(!invoice.is_expired());
1035 assert_eq!(invoice.payment_hash(), payment_hash);
1036 assert_eq!(invoice.amount_msats(), 1000);
1037 assert_eq!(invoice.fallbacks(), vec![]);
1038 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1039 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1041 merkle::verify_signature(
1042 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1046 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1047 let pubkey = recipient_pubkey().into();
1048 let secp_ctx = Secp256k1::verification_only();
1049 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1052 invoice.as_tlv_stream(),
1054 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1060 description: Some(&String::from("foo")),
1062 absolute_expiry: None,
1066 node_id: Some(&recipient_pubkey()),
1068 InvoiceRequestTlvStreamRef {
1073 payer_id: Some(&payer_pubkey()),
1076 InvoiceTlvStreamRef {
1077 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1078 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1079 created_at: Some(now.as_secs()),
1080 relative_expiry: None,
1081 payment_hash: Some(&payment_hash),
1085 node_id: Some(&recipient_pubkey()),
1087 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1091 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1092 panic!("error parsing invoice: {:?}", e);
1097 fn builds_invoice_for_refund_with_defaults() {
1098 let payment_paths = payment_paths();
1099 let payment_hash = payment_hash();
1101 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1103 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1106 .sign(recipient_sign).unwrap();
1108 let mut buffer = Vec::new();
1109 invoice.write(&mut buffer).unwrap();
1111 assert_eq!(invoice.bytes, buffer.as_slice());
1112 assert_eq!(invoice.description(), PrintableString("foo"));
1113 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1114 assert_eq!(invoice.created_at(), now);
1115 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1116 #[cfg(feature = "std")]
1117 assert!(!invoice.is_expired());
1118 assert_eq!(invoice.payment_hash(), payment_hash);
1119 assert_eq!(invoice.amount_msats(), 1000);
1120 assert_eq!(invoice.fallbacks(), vec![]);
1121 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1122 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1124 merkle::verify_signature(
1125 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1130 invoice.as_tlv_stream(),
1132 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1138 description: Some(&String::from("foo")),
1140 absolute_expiry: None,
1146 InvoiceRequestTlvStreamRef {
1151 payer_id: Some(&payer_pubkey()),
1154 InvoiceTlvStreamRef {
1155 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1156 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1157 created_at: Some(now.as_secs()),
1158 relative_expiry: None,
1159 payment_hash: Some(&payment_hash),
1163 node_id: Some(&recipient_pubkey()),
1165 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1169 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1170 panic!("error parsing invoice: {:?}", e);
1174 #[cfg(feature = "std")]
1176 fn builds_invoice_from_offer_with_expiration() {
1177 let future_expiry = Duration::from_secs(u64::max_value());
1178 let past_expiry = Duration::from_secs(0);
1180 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1182 .absolute_expiry(future_expiry)
1184 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186 .sign(payer_sign).unwrap()
1187 .respond_with(payment_paths(), payment_hash())
1191 panic!("error building invoice: {:?}", e);
1194 match OfferBuilder::new("foo".into(), recipient_pubkey())
1196 .absolute_expiry(past_expiry)
1198 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1200 .sign(payer_sign).unwrap()
1201 .respond_with(payment_paths(), payment_hash())
1205 Ok(_) => panic!("expected error"),
1206 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1210 #[cfg(feature = "std")]
1212 fn builds_invoice_from_refund_with_expiration() {
1213 let future_expiry = Duration::from_secs(u64::max_value());
1214 let past_expiry = Duration::from_secs(0);
1216 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1217 .absolute_expiry(future_expiry)
1219 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1223 panic!("error building invoice: {:?}", e);
1226 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1227 .absolute_expiry(past_expiry)
1229 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1233 Ok(_) => panic!("expected error"),
1234 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1239 fn builds_invoice_from_offer_using_derived_keys() {
1240 let desc = "foo".to_string();
1241 let node_id = recipient_pubkey();
1242 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1243 let entropy = FixedEntropy {};
1244 let secp_ctx = Secp256k1::new();
1246 let blinded_path = BlindedPath {
1247 introduction_node_id: pubkey(40),
1248 blinding_point: pubkey(41),
1250 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1251 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1255 let offer = OfferBuilder
1256 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1260 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1262 .sign(payer_sign).unwrap();
1264 if let Err(e) = invoice_request
1265 .verify_and_respond_using_derived_keys_no_std(
1266 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1269 .build_and_sign(&secp_ctx)
1271 panic!("error building invoice: {:?}", e);
1274 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
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),
1282 let desc = "foo".to_string();
1283 let offer = OfferBuilder
1284 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1287 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1289 .sign(payer_sign).unwrap();
1291 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1292 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1294 Ok(_) => panic!("expected error"),
1295 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1300 fn builds_invoice_from_refund_using_derived_keys() {
1301 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1302 let entropy = FixedEntropy {};
1303 let secp_ctx = Secp256k1::new();
1305 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1308 if let Err(e) = refund
1309 .respond_using_derived_keys_no_std(
1310 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1313 .build_and_sign(&secp_ctx)
1315 panic!("error building invoice: {:?}", e);
1320 fn builds_invoice_with_relative_expiry() {
1322 let one_hour = Duration::from_secs(3600);
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).unwrap()
1331 .relative_expiry(one_hour.as_secs() as u32)
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);
1338 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1340 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1345 .sign(payer_sign).unwrap()
1346 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1347 .relative_expiry(one_hour.as_secs() as u32 - 1)
1349 .sign(recipient_sign).unwrap();
1350 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1351 #[cfg(feature = "std")]
1352 assert!(invoice.is_expired());
1353 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1354 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1358 fn builds_invoice_with_amount_from_request() {
1359 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1362 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1363 .amount_msats(1001).unwrap()
1365 .sign(payer_sign).unwrap()
1366 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1368 .sign(recipient_sign).unwrap();
1369 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1370 assert_eq!(invoice.amount_msats(), 1001);
1371 assert_eq!(tlv_stream.amount, Some(1001));
1375 fn builds_invoice_with_quantity_from_request() {
1376 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1378 .supported_quantity(Quantity::Unbounded)
1380 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1381 .quantity(2).unwrap()
1383 .sign(payer_sign).unwrap()
1384 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1386 .sign(recipient_sign).unwrap();
1387 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1388 assert_eq!(invoice.amount_msats(), 2000);
1389 assert_eq!(tlv_stream.amount, Some(2000));
1391 match OfferBuilder::new("foo".into(), recipient_pubkey())
1393 .supported_quantity(Quantity::Unbounded)
1395 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1396 .quantity(u64::max_value()).unwrap()
1398 .sign(payer_sign).unwrap()
1399 .respond_with_no_std(payment_paths(), payment_hash(), now())
1401 Ok(_) => panic!("expected error"),
1402 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1407 fn builds_invoice_with_fallback_address() {
1408 let script = Script::new();
1409 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1410 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1411 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1413 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1416 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1418 .sign(payer_sign).unwrap()
1419 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1420 .fallback_v0_p2wsh(&script.wscript_hash())
1421 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1422 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1424 .sign(recipient_sign).unwrap();
1425 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1427 invoice.fallbacks(),
1429 Address::p2wsh(&script, Network::Bitcoin),
1430 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1431 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1435 tlv_stream.fallbacks,
1438 version: WitnessVersion::V0.to_num(),
1439 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1442 version: WitnessVersion::V0.to_num(),
1443 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1446 version: WitnessVersion::V1.to_num(),
1447 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1454 fn builds_invoice_with_allow_mpp() {
1455 let mut features = Bolt12InvoiceFeatures::empty();
1456 features.set_basic_mpp_optional();
1458 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1461 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1463 .sign(payer_sign).unwrap()
1464 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1467 .sign(recipient_sign).unwrap();
1468 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1469 assert_eq!(invoice.features(), &features);
1470 assert_eq!(tlv_stream.features, Some(&features));
1474 fn fails_signing_invoice() {
1475 match OfferBuilder::new("foo".into(), recipient_pubkey())
1478 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1480 .sign(payer_sign).unwrap()
1481 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1485 Ok(_) => panic!("expected error"),
1486 Err(e) => assert_eq!(e, SignError::Signing(())),
1489 match OfferBuilder::new("foo".into(), recipient_pubkey())
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1494 .sign(payer_sign).unwrap()
1495 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1499 Ok(_) => panic!("expected error"),
1500 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1505 fn parses_invoice_with_payment_paths() {
1506 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1509 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1511 .sign(payer_sign).unwrap()
1512 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1514 .sign(recipient_sign).unwrap();
1516 let mut buffer = Vec::new();
1517 invoice.write(&mut buffer).unwrap();
1519 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1520 panic!("error parsing invoice: {:?}", e);
1523 let mut tlv_stream = invoice.as_tlv_stream();
1524 tlv_stream.3.paths = None;
1526 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1527 Ok(_) => panic!("expected error"),
1528 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1531 let mut tlv_stream = invoice.as_tlv_stream();
1532 tlv_stream.3.blindedpay = None;
1534 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1535 Ok(_) => panic!("expected error"),
1536 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1539 let empty_payment_paths = vec![];
1540 let mut tlv_stream = invoice.as_tlv_stream();
1541 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1543 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1544 Ok(_) => panic!("expected error"),
1545 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1548 let mut payment_paths = payment_paths();
1549 payment_paths.pop();
1550 let mut tlv_stream = invoice.as_tlv_stream();
1551 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1553 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1554 Ok(_) => panic!("expected error"),
1555 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1560 fn parses_invoice_with_created_at() {
1561 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1564 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1566 .sign(payer_sign).unwrap()
1567 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1569 .sign(recipient_sign).unwrap();
1571 let mut buffer = Vec::new();
1572 invoice.write(&mut buffer).unwrap();
1574 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1575 panic!("error parsing invoice: {:?}", e);
1578 let mut tlv_stream = invoice.as_tlv_stream();
1579 tlv_stream.3.created_at = None;
1581 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1582 Ok(_) => panic!("expected error"),
1584 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1590 fn parses_invoice_with_relative_expiry() {
1591 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1594 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1596 .sign(payer_sign).unwrap()
1597 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1598 .relative_expiry(3600)
1600 .sign(recipient_sign).unwrap();
1602 let mut buffer = Vec::new();
1603 invoice.write(&mut buffer).unwrap();
1605 match Bolt12Invoice::try_from(buffer) {
1606 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1607 Err(e) => panic!("error parsing invoice: {:?}", e),
1612 fn parses_invoice_with_payment_hash() {
1613 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1616 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1618 .sign(payer_sign).unwrap()
1619 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1621 .sign(recipient_sign).unwrap();
1623 let mut buffer = Vec::new();
1624 invoice.write(&mut buffer).unwrap();
1626 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1627 panic!("error parsing invoice: {:?}", e);
1630 let mut tlv_stream = invoice.as_tlv_stream();
1631 tlv_stream.3.payment_hash = None;
1633 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1634 Ok(_) => panic!("expected error"),
1636 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1642 fn parses_invoice_with_amount() {
1643 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1646 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1648 .sign(payer_sign).unwrap()
1649 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1651 .sign(recipient_sign).unwrap();
1653 let mut buffer = Vec::new();
1654 invoice.write(&mut buffer).unwrap();
1656 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1657 panic!("error parsing invoice: {:?}", e);
1660 let mut tlv_stream = invoice.as_tlv_stream();
1661 tlv_stream.3.amount = None;
1663 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1664 Ok(_) => panic!("expected error"),
1665 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1670 fn parses_invoice_with_allow_mpp() {
1671 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1674 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1676 .sign(payer_sign).unwrap()
1677 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1680 .sign(recipient_sign).unwrap();
1682 let mut buffer = Vec::new();
1683 invoice.write(&mut buffer).unwrap();
1685 match Bolt12Invoice::try_from(buffer) {
1687 let mut features = Bolt12InvoiceFeatures::empty();
1688 features.set_basic_mpp_optional();
1689 assert_eq!(invoice.features(), &features);
1691 Err(e) => panic!("error parsing invoice: {:?}", e),
1696 fn parses_invoice_with_fallback_address() {
1697 let script = Script::new();
1698 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1699 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1700 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1702 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1705 let invoice_request = offer
1706 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1708 .sign(payer_sign).unwrap();
1709 let mut invoice_builder = invoice_request
1710 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1711 .fallback_v0_p2wsh(&script.wscript_hash())
1712 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1713 .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
1715 // Only standard addresses will be included.
1716 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
1717 // Non-standard addresses
1718 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1719 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1720 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1722 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1723 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1725 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
1726 let mut buffer = Vec::new();
1727 invoice.write(&mut buffer).unwrap();
1729 match Bolt12Invoice::try_from(buffer) {
1732 invoice.fallbacks(),
1734 Address::p2wsh(&script, Network::Bitcoin),
1735 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1736 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1738 payload: Payload::WitnessProgram {
1739 version: WitnessVersion::V1,
1740 program: vec![0u8; 33],
1742 network: Network::Bitcoin,
1745 payload: Payload::WitnessProgram {
1746 version: WitnessVersion::V2,
1747 program: vec![0u8; 40],
1749 network: Network::Bitcoin,
1754 Err(e) => panic!("error parsing invoice: {:?}", e),
1759 fn parses_invoice_with_node_id() {
1760 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1763 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1765 .sign(payer_sign).unwrap()
1766 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1768 .sign(recipient_sign).unwrap();
1770 let mut buffer = Vec::new();
1771 invoice.write(&mut buffer).unwrap();
1773 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1774 panic!("error parsing invoice: {:?}", e);
1777 let mut tlv_stream = invoice.as_tlv_stream();
1778 tlv_stream.3.node_id = None;
1780 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1781 Ok(_) => panic!("expected error"),
1783 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1787 let invalid_pubkey = payer_pubkey();
1788 let mut tlv_stream = invoice.as_tlv_stream();
1789 tlv_stream.3.node_id = Some(&invalid_pubkey);
1791 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1792 Ok(_) => panic!("expected error"),
1794 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1800 fn fails_parsing_invoice_without_signature() {
1801 let mut buffer = Vec::new();
1802 OfferBuilder::new("foo".into(), recipient_pubkey())
1805 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .sign(payer_sign).unwrap()
1808 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1811 .write(&mut buffer).unwrap();
1813 match Bolt12Invoice::try_from(buffer) {
1814 Ok(_) => panic!("expected error"),
1815 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1820 fn fails_parsing_invoice_with_invalid_signature() {
1821 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1824 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1826 .sign(payer_sign).unwrap()
1827 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1829 .sign(recipient_sign).unwrap();
1830 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1831 *last_signature_byte = last_signature_byte.wrapping_add(1);
1833 let mut buffer = Vec::new();
1834 invoice.write(&mut buffer).unwrap();
1836 match Bolt12Invoice::try_from(buffer) {
1837 Ok(_) => panic!("expected error"),
1839 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1845 fn fails_parsing_invoice_with_extra_tlv_records() {
1846 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1849 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1851 .sign(payer_sign).unwrap()
1852 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1854 .sign(recipient_sign).unwrap();
1856 let mut encoded_invoice = Vec::new();
1857 invoice.write(&mut encoded_invoice).unwrap();
1858 BigSize(1002).write(&mut encoded_invoice).unwrap();
1859 BigSize(32).write(&mut encoded_invoice).unwrap();
1860 [42u8; 32].write(&mut encoded_invoice).unwrap();
1862 match Bolt12Invoice::try_from(encoded_invoice) {
1863 Ok(_) => panic!("expected error"),
1864 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),