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.
315 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
316 let address = FallbackAddress {
317 version: WitnessVersion::V1.to_num(),
318 program: Vec::from(&output_key.serialize()[..]),
320 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
324 /// Sets [`Bolt12Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
325 pub fn allow_mpp(mut self) -> Self {
326 self.invoice.fields_mut().features.set_basic_mpp_optional();
331 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
332 /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
333 /// [`UnsignedBolt12Invoice::sign`].
334 pub fn build(self) -> Result<UnsignedBolt12Invoice<'a>, Bolt12SemanticError> {
335 #[cfg(feature = "std")] {
336 if self.invoice.is_offer_or_refund_expired() {
337 return Err(Bolt12SemanticError::AlreadyExpired);
341 let InvoiceBuilder { invreq_bytes, invoice, .. } = self;
342 Ok(UnsignedBolt12Invoice { invreq_bytes, invoice })
346 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
347 /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
348 pub fn build_and_sign<T: secp256k1::Signing>(
349 self, secp_ctx: &Secp256k1<T>
350 ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
351 #[cfg(feature = "std")] {
352 if self.invoice.is_offer_or_refund_expired() {
353 return Err(Bolt12SemanticError::AlreadyExpired);
357 let InvoiceBuilder { invreq_bytes, invoice, keys, .. } = self;
358 let unsigned_invoice = UnsignedBolt12Invoice { invreq_bytes, invoice };
360 let keys = keys.unwrap();
361 let invoice = unsigned_invoice
362 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
368 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
369 pub struct UnsignedBolt12Invoice<'a> {
370 invreq_bytes: &'a Vec<u8>,
371 invoice: InvoiceContents,
374 impl<'a> UnsignedBolt12Invoice<'a> {
375 /// The public key corresponding to the key needed to sign the invoice.
376 pub fn signing_pubkey(&self) -> PublicKey {
377 self.invoice.fields().signing_pubkey
380 /// Signs the invoice using the given function.
382 /// This is not exported to bindings users as functions aren't currently mapped.
383 pub fn sign<F, E>(self, sign: F) -> Result<Bolt12Invoice, SignError<E>>
385 F: FnOnce(&Message) -> Result<Signature, E>
387 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
388 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
390 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
391 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
392 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
394 let mut bytes = Vec::new();
395 unsigned_tlv_stream.write(&mut bytes).unwrap();
397 let pubkey = self.invoice.fields().signing_pubkey;
398 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
400 // Append the signature TLV record to the bytes.
401 let signature_tlv_stream = SignatureTlvStreamRef {
402 signature: Some(&signature),
404 signature_tlv_stream.write(&mut bytes).unwrap();
408 contents: self.invoice,
414 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
416 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
417 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
419 /// [`Offer`]: crate::offers::offer::Offer
420 /// [`Refund`]: crate::offers::refund::Refund
421 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
422 #[derive(Clone, Debug)]
423 #[cfg_attr(test, derive(PartialEq))]
424 pub struct Bolt12Invoice {
426 contents: InvoiceContents,
427 signature: Signature,
430 /// The contents of an [`Bolt12Invoice`] for responding to either an [`Offer`] or a [`Refund`].
432 /// [`Offer`]: crate::offers::offer::Offer
433 /// [`Refund`]: crate::offers::refund::Refund
434 #[derive(Clone, Debug)]
435 #[cfg_attr(test, derive(PartialEq))]
436 enum InvoiceContents {
437 /// Contents for an [`Bolt12Invoice`] corresponding to an [`Offer`].
439 /// [`Offer`]: crate::offers::offer::Offer
441 invoice_request: InvoiceRequestContents,
442 fields: InvoiceFields,
444 /// Contents for an [`Bolt12Invoice`] corresponding to a [`Refund`].
446 /// [`Refund`]: crate::offers::refund::Refund
448 refund: RefundContents,
449 fields: InvoiceFields,
453 /// Invoice-specific fields for an `invoice` message.
454 #[derive(Clone, Debug, PartialEq)]
455 struct InvoiceFields {
456 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
457 created_at: Duration,
458 relative_expiry: Option<Duration>,
459 payment_hash: PaymentHash,
461 fallbacks: Option<Vec<FallbackAddress>>,
462 features: Bolt12InvoiceFeatures,
463 signing_pubkey: PublicKey,
467 /// A complete description of the purpose of the originating offer or refund. Intended to be
468 /// displayed to the user but with the caveat that it has not been verified in any way.
469 pub fn description(&self) -> PrintableString {
470 self.contents.description()
473 /// Paths to the recipient originating from publicly reachable nodes, including information
474 /// needed for routing payments across them.
476 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
477 /// privacy is lost if a public node id is used for [`Bolt12Invoice::signing_pubkey`].
479 /// This is not exported to bindings users as slices with non-reference types cannot be ABI
480 /// matched in another language.
481 pub fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
482 &self.contents.fields().payment_paths[..]
485 /// Duration since the Unix epoch when the invoice was created.
486 pub fn created_at(&self) -> Duration {
487 self.contents.fields().created_at
490 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
491 /// should no longer be paid.
492 pub fn relative_expiry(&self) -> Duration {
493 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
496 /// Whether the invoice has expired.
497 #[cfg(feature = "std")]
498 pub fn is_expired(&self) -> bool {
499 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
500 match absolute_expiry {
501 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
502 Ok(elapsed) => elapsed > seconds_from_epoch,
509 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
510 pub fn payment_hash(&self) -> PaymentHash {
511 self.contents.fields().payment_hash
514 /// The minimum amount required for a successful payment of the invoice.
515 pub fn amount_msats(&self) -> u64 {
516 self.contents.fields().amount_msats
519 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
521 pub fn fallbacks(&self) -> Vec<Address> {
522 let network = match self.network() {
523 None => return Vec::new(),
524 Some(network) => network,
527 let to_valid_address = |address: &FallbackAddress| {
528 let version = match WitnessVersion::try_from(address.version) {
529 Ok(version) => version,
530 Err(_) => return None,
533 let program = &address.program;
534 if program.len() < 2 || program.len() > 40 {
538 let address = Address {
539 payload: Payload::WitnessProgram {
541 program: address.program.clone(),
546 if !address.is_standard() && version == WitnessVersion::V0 {
553 self.contents.fields().fallbacks
555 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
556 .unwrap_or_else(Vec::new)
559 fn network(&self) -> Option<Network> {
560 let chain = self.contents.chain();
561 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
562 Some(Network::Bitcoin)
563 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
564 Some(Network::Testnet)
565 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
566 Some(Network::Signet)
567 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
568 Some(Network::Regtest)
574 /// Features pertaining to paying an invoice.
575 pub fn features(&self) -> &Bolt12InvoiceFeatures {
576 &self.contents.fields().features
579 /// The public key corresponding to the key used to sign the invoice.
580 pub fn signing_pubkey(&self) -> PublicKey {
581 self.contents.fields().signing_pubkey
584 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
585 pub fn signature(&self) -> Signature {
589 /// Hash that was used for signing the invoice.
590 pub fn signable_hash(&self) -> [u8; 32] {
591 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
594 /// Verifies that the invoice was for a request or refund created using the given key.
595 pub fn verify<T: secp256k1::Signing>(
596 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
598 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
602 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
603 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
604 self.contents.as_tlv_stream();
605 let signature_tlv_stream = SignatureTlvStreamRef {
606 signature: Some(&self.signature),
608 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
609 signature_tlv_stream)
613 impl InvoiceContents {
614 /// Whether the original offer or refund has expired.
615 #[cfg(feature = "std")]
616 fn is_offer_or_refund_expired(&self) -> bool {
618 InvoiceContents::ForOffer { invoice_request, .. } =>
619 invoice_request.inner.offer.is_expired(),
620 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
624 fn chain(&self) -> ChainHash {
626 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
627 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
631 fn description(&self) -> PrintableString {
633 InvoiceContents::ForOffer { invoice_request, .. } => {
634 invoice_request.inner.offer.description()
636 InvoiceContents::ForRefund { refund, .. } => refund.description(),
640 fn fields(&self) -> &InvoiceFields {
642 InvoiceContents::ForOffer { fields, .. } => fields,
643 InvoiceContents::ForRefund { fields, .. } => fields,
647 fn fields_mut(&mut self) -> &mut InvoiceFields {
649 InvoiceContents::ForOffer { fields, .. } => fields,
650 InvoiceContents::ForRefund { fields, .. } => fields,
654 fn verify<T: secp256k1::Signing>(
655 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
657 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
658 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
659 match record.r#type {
660 PAYER_METADATA_TYPE => false, // Should be outside range
661 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
665 let tlv_stream = offer_records.chain(invreq_records);
667 let (metadata, payer_id, iv_bytes) = match self {
668 InvoiceContents::ForOffer { invoice_request, .. } => {
669 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
671 InvoiceContents::ForRefund { refund, .. } => {
672 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
676 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
682 fn derives_keys(&self) -> bool {
684 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
685 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
689 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
690 let (payer, offer, invoice_request) = match self {
691 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
692 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
694 let invoice = self.fields().as_tlv_stream();
696 (payer, offer, invoice_request, invoice)
701 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
703 if self.features == Bolt12InvoiceFeatures::empty() { None }
704 else { Some(&self.features) }
707 InvoiceTlvStreamRef {
708 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
709 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
710 created_at: Some(self.created_at.as_secs()),
711 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
712 payment_hash: Some(&self.payment_hash),
713 amount: Some(self.amount_msats),
714 fallbacks: self.fallbacks.as_ref(),
716 node_id: Some(&self.signing_pubkey),
721 impl Writeable for Bolt12Invoice {
722 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
723 WithoutLength(&self.bytes).write(writer)
727 impl Writeable for InvoiceContents {
728 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
729 self.as_tlv_stream().write(writer)
733 impl TryFrom<Vec<u8>> for Bolt12Invoice {
734 type Error = Bolt12ParseError;
736 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
737 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
738 Bolt12Invoice::try_from(parsed_invoice)
742 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
743 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
744 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
745 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
746 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
747 (168, payment_hash: PaymentHash),
748 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
749 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
750 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
751 (176, node_id: PublicKey),
754 type BlindedPathIter<'a> = core::iter::Map<
755 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
756 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
759 type BlindedPayInfoIter<'a> = core::iter::Map<
760 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
761 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
764 /// Information needed to route a payment across a [`BlindedPath`].
765 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
766 pub struct BlindedPayInfo {
767 /// Base fee charged (in millisatoshi) for the entire blinded path.
768 pub fee_base_msat: u32,
770 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
771 /// (i.e., 10,000 is 1%).
772 pub fee_proportional_millionths: u32,
774 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
776 pub cltv_expiry_delta: u16,
778 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
779 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
780 /// seen by the recipient.
781 pub htlc_minimum_msat: u64,
783 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
784 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
785 /// seen by the recipient.
786 pub htlc_maximum_msat: u64,
788 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
790 pub features: BlindedHopFeatures,
793 impl_writeable!(BlindedPayInfo, {
795 fee_proportional_millionths,
802 /// Wire representation for an on-chain fallback address.
803 #[derive(Clone, Debug, PartialEq)]
804 pub(super) struct FallbackAddress {
809 impl_writeable!(FallbackAddress, { version, program });
811 type FullInvoiceTlvStream =
812 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
815 type FullInvoiceTlvStreamRef<'a> = (
816 PayerTlvStreamRef<'a>,
817 OfferTlvStreamRef<'a>,
818 InvoiceRequestTlvStreamRef<'a>,
819 InvoiceTlvStreamRef<'a>,
820 SignatureTlvStreamRef<'a>,
823 impl SeekReadable for FullInvoiceTlvStream {
824 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
825 let payer = SeekReadable::read(r)?;
826 let offer = SeekReadable::read(r)?;
827 let invoice_request = SeekReadable::read(r)?;
828 let invoice = SeekReadable::read(r)?;
829 let signature = SeekReadable::read(r)?;
831 Ok((payer, offer, invoice_request, invoice, signature))
835 type PartialInvoiceTlvStream =
836 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
838 type PartialInvoiceTlvStreamRef<'a> = (
839 PayerTlvStreamRef<'a>,
840 OfferTlvStreamRef<'a>,
841 InvoiceRequestTlvStreamRef<'a>,
842 InvoiceTlvStreamRef<'a>,
845 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
846 type Error = Bolt12ParseError;
848 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
849 let ParsedMessage { bytes, tlv_stream } = invoice;
851 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
852 SignatureTlvStream { signature },
854 let contents = InvoiceContents::try_from(
855 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
858 let signature = match signature {
859 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
860 Some(signature) => signature,
862 let pubkey = contents.fields().signing_pubkey;
863 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
865 Ok(Bolt12Invoice { bytes, contents, signature })
869 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
870 type Error = Bolt12SemanticError;
872 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
876 invoice_request_tlv_stream,
878 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
883 let payment_paths = match (blindedpay, paths) {
884 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
885 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
886 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
887 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
888 return Err(Bolt12SemanticError::InvalidPayInfo);
890 (Some(blindedpay), Some(paths)) => {
891 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
895 let created_at = match created_at {
896 None => return Err(Bolt12SemanticError::MissingCreationTime),
897 Some(timestamp) => Duration::from_secs(timestamp),
900 let relative_expiry = relative_expiry
901 .map(Into::<u64>::into)
902 .map(Duration::from_secs);
904 let payment_hash = match payment_hash {
905 None => return Err(Bolt12SemanticError::MissingPaymentHash),
906 Some(payment_hash) => payment_hash,
909 let amount_msats = match amount {
910 None => return Err(Bolt12SemanticError::MissingAmount),
911 Some(amount) => amount,
914 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
916 let signing_pubkey = match node_id {
917 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
918 Some(node_id) => node_id,
921 let fields = InvoiceFields {
922 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
923 features, signing_pubkey,
926 match offer_tlv_stream.node_id {
927 Some(expected_signing_pubkey) => {
928 if fields.signing_pubkey != expected_signing_pubkey {
929 return Err(Bolt12SemanticError::InvalidSigningPubkey);
932 let invoice_request = InvoiceRequestContents::try_from(
933 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
935 Ok(InvoiceContents::ForOffer { invoice_request, fields })
938 let refund = RefundContents::try_from(
939 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
941 Ok(InvoiceContents::ForRefund { refund, fields })
949 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG};
951 use bitcoin::blockdata::script::Script;
952 use bitcoin::hashes::Hash;
953 use bitcoin::network::constants::Network;
954 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
955 use bitcoin::util::address::{Address, Payload, WitnessVersion};
956 use bitcoin::util::schnorr::TweakedPublicKey;
957 use core::convert::TryFrom;
958 use core::time::Duration;
959 use crate::blinded_path::{BlindedHop, BlindedPath};
960 use crate::sign::KeyMaterial;
961 use crate::ln::features::Bolt12InvoiceFeatures;
962 use crate::ln::inbound_payment::ExpandedKey;
963 use crate::ln::msgs::DecodeError;
964 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
965 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
966 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
967 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
968 use crate::offers::payer::PayerTlvStreamRef;
969 use crate::offers::refund::RefundBuilder;
970 use crate::offers::test_utils::*;
971 use crate::util::ser::{BigSize, Iterable, Writeable};
972 use crate::util::string::PrintableString;
975 fn to_bytes(&self) -> Vec<u8>;
978 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
979 fn to_bytes(&self) -> Vec<u8> {
980 let mut buffer = Vec::new();
981 self.0.write(&mut buffer).unwrap();
982 self.1.write(&mut buffer).unwrap();
983 self.2.write(&mut buffer).unwrap();
984 self.3.write(&mut buffer).unwrap();
985 self.4.write(&mut buffer).unwrap();
991 fn builds_invoice_for_offer_with_defaults() {
992 let payment_paths = payment_paths();
993 let payment_hash = payment_hash();
995 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
998 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1000 .sign(payer_sign).unwrap()
1001 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1003 .sign(recipient_sign).unwrap();
1005 let mut buffer = Vec::new();
1006 invoice.write(&mut buffer).unwrap();
1008 assert_eq!(invoice.bytes, buffer.as_slice());
1009 assert_eq!(invoice.description(), PrintableString("foo"));
1010 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1011 assert_eq!(invoice.created_at(), now);
1012 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1013 #[cfg(feature = "std")]
1014 assert!(!invoice.is_expired());
1015 assert_eq!(invoice.payment_hash(), payment_hash);
1016 assert_eq!(invoice.amount_msats(), 1000);
1017 assert_eq!(invoice.fallbacks(), vec![]);
1018 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1019 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1021 merkle::verify_signature(
1022 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1026 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1027 let pubkey = recipient_pubkey().into();
1028 let secp_ctx = Secp256k1::verification_only();
1029 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1032 invoice.as_tlv_stream(),
1034 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1040 description: Some(&String::from("foo")),
1042 absolute_expiry: None,
1046 node_id: Some(&recipient_pubkey()),
1048 InvoiceRequestTlvStreamRef {
1053 payer_id: Some(&payer_pubkey()),
1056 InvoiceTlvStreamRef {
1057 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1058 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1059 created_at: Some(now.as_secs()),
1060 relative_expiry: None,
1061 payment_hash: Some(&payment_hash),
1065 node_id: Some(&recipient_pubkey()),
1067 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1071 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1072 panic!("error parsing invoice: {:?}", e);
1077 fn builds_invoice_for_refund_with_defaults() {
1078 let payment_paths = payment_paths();
1079 let payment_hash = payment_hash();
1081 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1083 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1086 .sign(recipient_sign).unwrap();
1088 let mut buffer = Vec::new();
1089 invoice.write(&mut buffer).unwrap();
1091 assert_eq!(invoice.bytes, buffer.as_slice());
1092 assert_eq!(invoice.description(), PrintableString("foo"));
1093 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1094 assert_eq!(invoice.created_at(), now);
1095 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1096 #[cfg(feature = "std")]
1097 assert!(!invoice.is_expired());
1098 assert_eq!(invoice.payment_hash(), payment_hash);
1099 assert_eq!(invoice.amount_msats(), 1000);
1100 assert_eq!(invoice.fallbacks(), vec![]);
1101 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1102 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1104 merkle::verify_signature(
1105 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1110 invoice.as_tlv_stream(),
1112 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1118 description: Some(&String::from("foo")),
1120 absolute_expiry: None,
1126 InvoiceRequestTlvStreamRef {
1131 payer_id: Some(&payer_pubkey()),
1134 InvoiceTlvStreamRef {
1135 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1136 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1137 created_at: Some(now.as_secs()),
1138 relative_expiry: None,
1139 payment_hash: Some(&payment_hash),
1143 node_id: Some(&recipient_pubkey()),
1145 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1149 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1150 panic!("error parsing invoice: {:?}", e);
1154 #[cfg(feature = "std")]
1156 fn builds_invoice_from_offer_with_expiration() {
1157 let future_expiry = Duration::from_secs(u64::max_value());
1158 let past_expiry = Duration::from_secs(0);
1160 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1162 .absolute_expiry(future_expiry)
1164 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1166 .sign(payer_sign).unwrap()
1167 .respond_with(payment_paths(), payment_hash())
1171 panic!("error building invoice: {:?}", e);
1174 match OfferBuilder::new("foo".into(), recipient_pubkey())
1176 .absolute_expiry(past_expiry)
1178 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1180 .sign(payer_sign).unwrap()
1181 .respond_with(payment_paths(), payment_hash())
1185 Ok(_) => panic!("expected error"),
1186 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1190 #[cfg(feature = "std")]
1192 fn builds_invoice_from_refund_with_expiration() {
1193 let future_expiry = Duration::from_secs(u64::max_value());
1194 let past_expiry = Duration::from_secs(0);
1196 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1197 .absolute_expiry(future_expiry)
1199 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1203 panic!("error building invoice: {:?}", e);
1206 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1207 .absolute_expiry(past_expiry)
1209 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1213 Ok(_) => panic!("expected error"),
1214 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1219 fn builds_invoice_from_offer_using_derived_keys() {
1220 let desc = "foo".to_string();
1221 let node_id = recipient_pubkey();
1222 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1223 let entropy = FixedEntropy {};
1224 let secp_ctx = Secp256k1::new();
1226 let blinded_path = BlindedPath {
1227 introduction_node_id: pubkey(40),
1228 blinding_point: pubkey(41),
1230 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1231 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1235 let offer = OfferBuilder
1236 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1240 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1242 .sign(payer_sign).unwrap();
1244 if let Err(e) = invoice_request
1245 .verify_and_respond_using_derived_keys_no_std(
1246 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1249 .build_and_sign(&secp_ctx)
1251 panic!("error building invoice: {:?}", e);
1254 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1255 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1256 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1258 Ok(_) => panic!("expected error"),
1259 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1262 let desc = "foo".to_string();
1263 let offer = OfferBuilder
1264 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1267 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1269 .sign(payer_sign).unwrap();
1271 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1272 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1274 Ok(_) => panic!("expected error"),
1275 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1280 fn builds_invoice_from_refund_using_derived_keys() {
1281 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1282 let entropy = FixedEntropy {};
1283 let secp_ctx = Secp256k1::new();
1285 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1288 if let Err(e) = refund
1289 .respond_using_derived_keys_no_std(
1290 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1293 .build_and_sign(&secp_ctx)
1295 panic!("error building invoice: {:?}", e);
1300 fn builds_invoice_with_relative_expiry() {
1302 let one_hour = Duration::from_secs(3600);
1304 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1307 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1309 .sign(payer_sign).unwrap()
1310 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1311 .relative_expiry(one_hour.as_secs() as u32)
1313 .sign(recipient_sign).unwrap();
1314 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1315 #[cfg(feature = "std")]
1316 assert!(!invoice.is_expired());
1317 assert_eq!(invoice.relative_expiry(), one_hour);
1318 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1320 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1323 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1325 .sign(payer_sign).unwrap()
1326 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1327 .relative_expiry(one_hour.as_secs() as u32 - 1)
1329 .sign(recipient_sign).unwrap();
1330 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1331 #[cfg(feature = "std")]
1332 assert!(invoice.is_expired());
1333 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1334 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1338 fn builds_invoice_with_amount_from_request() {
1339 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1343 .amount_msats(1001).unwrap()
1345 .sign(payer_sign).unwrap()
1346 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1348 .sign(recipient_sign).unwrap();
1349 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1350 assert_eq!(invoice.amount_msats(), 1001);
1351 assert_eq!(tlv_stream.amount, Some(1001));
1355 fn builds_invoice_with_quantity_from_request() {
1356 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1358 .supported_quantity(Quantity::Unbounded)
1360 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1361 .quantity(2).unwrap()
1363 .sign(payer_sign).unwrap()
1364 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1366 .sign(recipient_sign).unwrap();
1367 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1368 assert_eq!(invoice.amount_msats(), 2000);
1369 assert_eq!(tlv_stream.amount, Some(2000));
1371 match OfferBuilder::new("foo".into(), recipient_pubkey())
1373 .supported_quantity(Quantity::Unbounded)
1375 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1376 .quantity(u64::max_value()).unwrap()
1378 .sign(payer_sign).unwrap()
1379 .respond_with_no_std(payment_paths(), payment_hash(), now())
1381 Ok(_) => panic!("expected error"),
1382 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1387 fn builds_invoice_with_fallback_address() {
1388 let script = Script::new();
1389 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1390 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1391 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1393 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1396 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1398 .sign(payer_sign).unwrap()
1399 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1400 .fallback_v0_p2wsh(&script.wscript_hash())
1401 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1402 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1404 .sign(recipient_sign).unwrap();
1405 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1407 invoice.fallbacks(),
1409 Address::p2wsh(&script, Network::Bitcoin),
1410 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1411 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1415 tlv_stream.fallbacks,
1418 version: WitnessVersion::V0.to_num(),
1419 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1422 version: WitnessVersion::V0.to_num(),
1423 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1426 version: WitnessVersion::V1.to_num(),
1427 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1434 fn builds_invoice_with_allow_mpp() {
1435 let mut features = Bolt12InvoiceFeatures::empty();
1436 features.set_basic_mpp_optional();
1438 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1441 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1443 .sign(payer_sign).unwrap()
1444 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1447 .sign(recipient_sign).unwrap();
1448 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1449 assert_eq!(invoice.features(), &features);
1450 assert_eq!(tlv_stream.features, Some(&features));
1454 fn fails_signing_invoice() {
1455 match OfferBuilder::new("foo".into(), recipient_pubkey())
1458 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1460 .sign(payer_sign).unwrap()
1461 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1465 Ok(_) => panic!("expected error"),
1466 Err(e) => assert_eq!(e, SignError::Signing(())),
1469 match OfferBuilder::new("foo".into(), recipient_pubkey())
1472 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1474 .sign(payer_sign).unwrap()
1475 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1479 Ok(_) => panic!("expected error"),
1480 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1485 fn parses_invoice_with_payment_paths() {
1486 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1489 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1491 .sign(payer_sign).unwrap()
1492 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1494 .sign(recipient_sign).unwrap();
1496 let mut buffer = Vec::new();
1497 invoice.write(&mut buffer).unwrap();
1499 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1500 panic!("error parsing invoice: {:?}", e);
1503 let mut tlv_stream = invoice.as_tlv_stream();
1504 tlv_stream.3.paths = None;
1506 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1507 Ok(_) => panic!("expected error"),
1508 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1511 let mut tlv_stream = invoice.as_tlv_stream();
1512 tlv_stream.3.blindedpay = None;
1514 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1515 Ok(_) => panic!("expected error"),
1516 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1519 let empty_payment_paths = vec![];
1520 let mut tlv_stream = invoice.as_tlv_stream();
1521 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1523 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1524 Ok(_) => panic!("expected error"),
1525 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1528 let mut payment_paths = payment_paths();
1529 payment_paths.pop();
1530 let mut tlv_stream = invoice.as_tlv_stream();
1531 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1533 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1534 Ok(_) => panic!("expected error"),
1535 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1540 fn parses_invoice_with_created_at() {
1541 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1544 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1546 .sign(payer_sign).unwrap()
1547 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1549 .sign(recipient_sign).unwrap();
1551 let mut buffer = Vec::new();
1552 invoice.write(&mut buffer).unwrap();
1554 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1555 panic!("error parsing invoice: {:?}", e);
1558 let mut tlv_stream = invoice.as_tlv_stream();
1559 tlv_stream.3.created_at = None;
1561 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1562 Ok(_) => panic!("expected error"),
1564 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1570 fn parses_invoice_with_relative_expiry() {
1571 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1574 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1576 .sign(payer_sign).unwrap()
1577 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1578 .relative_expiry(3600)
1580 .sign(recipient_sign).unwrap();
1582 let mut buffer = Vec::new();
1583 invoice.write(&mut buffer).unwrap();
1585 match Bolt12Invoice::try_from(buffer) {
1586 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1587 Err(e) => panic!("error parsing invoice: {:?}", e),
1592 fn parses_invoice_with_payment_hash() {
1593 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1596 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598 .sign(payer_sign).unwrap()
1599 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1601 .sign(recipient_sign).unwrap();
1603 let mut buffer = Vec::new();
1604 invoice.write(&mut buffer).unwrap();
1606 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1607 panic!("error parsing invoice: {:?}", e);
1610 let mut tlv_stream = invoice.as_tlv_stream();
1611 tlv_stream.3.payment_hash = None;
1613 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1614 Ok(_) => panic!("expected error"),
1616 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1622 fn parses_invoice_with_amount() {
1623 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1626 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1628 .sign(payer_sign).unwrap()
1629 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1631 .sign(recipient_sign).unwrap();
1633 let mut buffer = Vec::new();
1634 invoice.write(&mut buffer).unwrap();
1636 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1637 panic!("error parsing invoice: {:?}", e);
1640 let mut tlv_stream = invoice.as_tlv_stream();
1641 tlv_stream.3.amount = None;
1643 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1644 Ok(_) => panic!("expected error"),
1645 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1650 fn parses_invoice_with_allow_mpp() {
1651 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1654 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1656 .sign(payer_sign).unwrap()
1657 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1660 .sign(recipient_sign).unwrap();
1662 let mut buffer = Vec::new();
1663 invoice.write(&mut buffer).unwrap();
1665 match Bolt12Invoice::try_from(buffer) {
1667 let mut features = Bolt12InvoiceFeatures::empty();
1668 features.set_basic_mpp_optional();
1669 assert_eq!(invoice.features(), &features);
1671 Err(e) => panic!("error parsing invoice: {:?}", e),
1676 fn parses_invoice_with_fallback_address() {
1677 let script = Script::new();
1678 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1679 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1680 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1682 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1685 let invoice_request = offer
1686 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1688 .sign(payer_sign).unwrap();
1689 let mut unsigned_invoice = invoice_request
1690 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1691 .fallback_v0_p2wsh(&script.wscript_hash())
1692 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1693 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1696 // Only standard addresses will be included.
1697 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1698 // Non-standard addresses
1699 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1700 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1701 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1703 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1704 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1706 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1707 let mut buffer = Vec::new();
1708 invoice.write(&mut buffer).unwrap();
1710 match Bolt12Invoice::try_from(buffer) {
1713 invoice.fallbacks(),
1715 Address::p2wsh(&script, Network::Bitcoin),
1716 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1717 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1719 payload: Payload::WitnessProgram {
1720 version: WitnessVersion::V1,
1721 program: vec![0u8; 33],
1723 network: Network::Bitcoin,
1726 payload: Payload::WitnessProgram {
1727 version: WitnessVersion::V2,
1728 program: vec![0u8; 40],
1730 network: Network::Bitcoin,
1735 Err(e) => panic!("error parsing invoice: {:?}", e),
1740 fn parses_invoice_with_node_id() {
1741 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1744 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1746 .sign(payer_sign).unwrap()
1747 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1749 .sign(recipient_sign).unwrap();
1751 let mut buffer = Vec::new();
1752 invoice.write(&mut buffer).unwrap();
1754 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1755 panic!("error parsing invoice: {:?}", e);
1758 let mut tlv_stream = invoice.as_tlv_stream();
1759 tlv_stream.3.node_id = None;
1761 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1762 Ok(_) => panic!("expected error"),
1764 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1768 let invalid_pubkey = payer_pubkey();
1769 let mut tlv_stream = invoice.as_tlv_stream();
1770 tlv_stream.3.node_id = Some(&invalid_pubkey);
1772 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1773 Ok(_) => panic!("expected error"),
1775 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1781 fn fails_parsing_invoice_without_signature() {
1782 let mut buffer = Vec::new();
1783 OfferBuilder::new("foo".into(), recipient_pubkey())
1786 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1788 .sign(payer_sign).unwrap()
1789 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1792 .write(&mut buffer).unwrap();
1794 match Bolt12Invoice::try_from(buffer) {
1795 Ok(_) => panic!("expected error"),
1796 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1801 fn fails_parsing_invoice_with_invalid_signature() {
1802 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1805 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .sign(payer_sign).unwrap()
1808 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1810 .sign(recipient_sign).unwrap();
1811 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1812 *last_signature_byte = last_signature_byte.wrapping_add(1);
1814 let mut buffer = Vec::new();
1815 invoice.write(&mut buffer).unwrap();
1817 match Bolt12Invoice::try_from(buffer) {
1818 Ok(_) => panic!("expected error"),
1820 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1826 fn fails_parsing_invoice_with_extra_tlv_records() {
1827 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1830 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1832 .sign(payer_sign).unwrap()
1833 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1835 .sign(recipient_sign).unwrap();
1837 let mut encoded_invoice = Vec::new();
1838 invoice.write(&mut encoded_invoice).unwrap();
1839 BigSize(1002).write(&mut encoded_invoice).unwrap();
1840 BigSize(32).write(&mut encoded_invoice).unwrap();
1841 [42u8; 32].write(&mut encoded_invoice).unwrap();
1843 match Bolt12Invoice::try_from(encoded_invoice) {
1844 Ok(_) => panic!("expected error"),
1845 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),