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`].
478 pub fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
479 &self.contents.fields().payment_paths[..]
482 /// Duration since the Unix epoch when the invoice was created.
483 pub fn created_at(&self) -> Duration {
484 self.contents.fields().created_at
487 /// Duration since [`Bolt12Invoice::created_at`] when the invoice has expired and therefore
488 /// should no longer be paid.
489 pub fn relative_expiry(&self) -> Duration {
490 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
493 /// Whether the invoice has expired.
494 #[cfg(feature = "std")]
495 pub fn is_expired(&self) -> bool {
496 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
497 match absolute_expiry {
498 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
499 Ok(elapsed) => elapsed > seconds_from_epoch,
506 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
507 pub fn payment_hash(&self) -> PaymentHash {
508 self.contents.fields().payment_hash
511 /// The minimum amount required for a successful payment of the invoice.
512 pub fn amount_msats(&self) -> u64 {
513 self.contents.fields().amount_msats
516 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
518 pub fn fallbacks(&self) -> Vec<Address> {
519 let network = match self.network() {
520 None => return Vec::new(),
521 Some(network) => network,
524 let to_valid_address = |address: &FallbackAddress| {
525 let version = match WitnessVersion::try_from(address.version) {
526 Ok(version) => version,
527 Err(_) => return None,
530 let program = &address.program;
531 if program.len() < 2 || program.len() > 40 {
535 let address = Address {
536 payload: Payload::WitnessProgram {
538 program: address.program.clone(),
543 if !address.is_standard() && version == WitnessVersion::V0 {
550 self.contents.fields().fallbacks
552 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
553 .unwrap_or_else(Vec::new)
556 fn network(&self) -> Option<Network> {
557 let chain = self.contents.chain();
558 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
559 Some(Network::Bitcoin)
560 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
561 Some(Network::Testnet)
562 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
563 Some(Network::Signet)
564 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
565 Some(Network::Regtest)
571 /// Features pertaining to paying an invoice.
572 pub fn features(&self) -> &Bolt12InvoiceFeatures {
573 &self.contents.fields().features
576 /// The public key corresponding to the key used to sign the invoice.
577 pub fn signing_pubkey(&self) -> PublicKey {
578 self.contents.fields().signing_pubkey
581 /// Signature of the invoice verified using [`Bolt12Invoice::signing_pubkey`].
582 pub fn signature(&self) -> Signature {
586 /// Hash that was used for signing the invoice.
587 pub fn signable_hash(&self) -> [u8; 32] {
588 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
591 /// Verifies that the invoice was for a request or refund created using the given key.
592 pub fn verify<T: secp256k1::Signing>(
593 &self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
595 self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
599 pub(super) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
600 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
601 self.contents.as_tlv_stream();
602 let signature_tlv_stream = SignatureTlvStreamRef {
603 signature: Some(&self.signature),
605 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
606 signature_tlv_stream)
610 impl InvoiceContents {
611 /// Whether the original offer or refund has expired.
612 #[cfg(feature = "std")]
613 fn is_offer_or_refund_expired(&self) -> bool {
615 InvoiceContents::ForOffer { invoice_request, .. } =>
616 invoice_request.inner.offer.is_expired(),
617 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
621 fn chain(&self) -> ChainHash {
623 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
624 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
628 fn description(&self) -> PrintableString {
630 InvoiceContents::ForOffer { invoice_request, .. } => {
631 invoice_request.inner.offer.description()
633 InvoiceContents::ForRefund { refund, .. } => refund.description(),
637 fn fields(&self) -> &InvoiceFields {
639 InvoiceContents::ForOffer { fields, .. } => fields,
640 InvoiceContents::ForRefund { fields, .. } => fields,
644 fn fields_mut(&mut self) -> &mut InvoiceFields {
646 InvoiceContents::ForOffer { fields, .. } => fields,
647 InvoiceContents::ForRefund { fields, .. } => fields,
651 fn verify<T: secp256k1::Signing>(
652 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
654 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
655 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
656 match record.r#type {
657 PAYER_METADATA_TYPE => false, // Should be outside range
658 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
662 let tlv_stream = offer_records.chain(invreq_records);
664 let (metadata, payer_id, iv_bytes) = match self {
665 InvoiceContents::ForOffer { invoice_request, .. } => {
666 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
668 InvoiceContents::ForRefund { refund, .. } => {
669 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
673 match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
679 fn derives_keys(&self) -> bool {
681 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
682 InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
686 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
687 let (payer, offer, invoice_request) = match self {
688 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
689 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
691 let invoice = self.fields().as_tlv_stream();
693 (payer, offer, invoice_request, invoice)
698 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
700 if self.features == Bolt12InvoiceFeatures::empty() { None }
701 else { Some(&self.features) }
704 InvoiceTlvStreamRef {
705 paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
706 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
707 created_at: Some(self.created_at.as_secs()),
708 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
709 payment_hash: Some(&self.payment_hash),
710 amount: Some(self.amount_msats),
711 fallbacks: self.fallbacks.as_ref(),
713 node_id: Some(&self.signing_pubkey),
718 impl Writeable for Bolt12Invoice {
719 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
720 WithoutLength(&self.bytes).write(writer)
724 impl Writeable for InvoiceContents {
725 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
726 self.as_tlv_stream().write(writer)
730 impl TryFrom<Vec<u8>> for Bolt12Invoice {
731 type Error = Bolt12ParseError;
733 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
734 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
735 Bolt12Invoice::try_from(parsed_invoice)
739 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
740 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
741 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
742 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
743 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
744 (168, payment_hash: PaymentHash),
745 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
746 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
747 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
748 (176, node_id: PublicKey),
751 type BlindedPathIter<'a> = core::iter::Map<
752 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
753 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
756 type BlindedPayInfoIter<'a> = core::iter::Map<
757 core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
758 for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
761 /// Information needed to route a payment across a [`BlindedPath`].
762 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
763 pub struct BlindedPayInfo {
764 /// Base fee charged (in millisatoshi) for the entire blinded path.
765 pub fee_base_msat: u32,
767 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
768 /// (i.e., 10,000 is 1%).
769 pub fee_proportional_millionths: u32,
771 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
773 pub cltv_expiry_delta: u16,
775 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
776 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
777 /// seen by the recipient.
778 pub htlc_minimum_msat: u64,
780 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
781 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
782 /// seen by the recipient.
783 pub htlc_maximum_msat: u64,
785 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
787 pub features: BlindedHopFeatures,
790 impl_writeable!(BlindedPayInfo, {
792 fee_proportional_millionths,
799 /// Wire representation for an on-chain fallback address.
800 #[derive(Clone, Debug, PartialEq)]
801 pub(super) struct FallbackAddress {
806 impl_writeable!(FallbackAddress, { version, program });
808 type FullInvoiceTlvStream =
809 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
812 type FullInvoiceTlvStreamRef<'a> = (
813 PayerTlvStreamRef<'a>,
814 OfferTlvStreamRef<'a>,
815 InvoiceRequestTlvStreamRef<'a>,
816 InvoiceTlvStreamRef<'a>,
817 SignatureTlvStreamRef<'a>,
820 impl SeekReadable for FullInvoiceTlvStream {
821 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
822 let payer = SeekReadable::read(r)?;
823 let offer = SeekReadable::read(r)?;
824 let invoice_request = SeekReadable::read(r)?;
825 let invoice = SeekReadable::read(r)?;
826 let signature = SeekReadable::read(r)?;
828 Ok((payer, offer, invoice_request, invoice, signature))
832 type PartialInvoiceTlvStream =
833 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
835 type PartialInvoiceTlvStreamRef<'a> = (
836 PayerTlvStreamRef<'a>,
837 OfferTlvStreamRef<'a>,
838 InvoiceRequestTlvStreamRef<'a>,
839 InvoiceTlvStreamRef<'a>,
842 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
843 type Error = Bolt12ParseError;
845 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
846 let ParsedMessage { bytes, tlv_stream } = invoice;
848 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
849 SignatureTlvStream { signature },
851 let contents = InvoiceContents::try_from(
852 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
855 let signature = match signature {
856 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
857 Some(signature) => signature,
859 let pubkey = contents.fields().signing_pubkey;
860 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
862 Ok(Bolt12Invoice { bytes, contents, signature })
866 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
867 type Error = Bolt12SemanticError;
869 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
873 invoice_request_tlv_stream,
875 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
880 let payment_paths = match (blindedpay, paths) {
881 (_, None) => return Err(Bolt12SemanticError::MissingPaths),
882 (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
883 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
884 (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
885 return Err(Bolt12SemanticError::InvalidPayInfo);
887 (Some(blindedpay), Some(paths)) => {
888 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
892 let created_at = match created_at {
893 None => return Err(Bolt12SemanticError::MissingCreationTime),
894 Some(timestamp) => Duration::from_secs(timestamp),
897 let relative_expiry = relative_expiry
898 .map(Into::<u64>::into)
899 .map(Duration::from_secs);
901 let payment_hash = match payment_hash {
902 None => return Err(Bolt12SemanticError::MissingPaymentHash),
903 Some(payment_hash) => payment_hash,
906 let amount_msats = match amount {
907 None => return Err(Bolt12SemanticError::MissingAmount),
908 Some(amount) => amount,
911 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
913 let signing_pubkey = match node_id {
914 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
915 Some(node_id) => node_id,
918 let fields = InvoiceFields {
919 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
920 features, signing_pubkey,
923 match offer_tlv_stream.node_id {
924 Some(expected_signing_pubkey) => {
925 if fields.signing_pubkey != expected_signing_pubkey {
926 return Err(Bolt12SemanticError::InvalidSigningPubkey);
929 let invoice_request = InvoiceRequestContents::try_from(
930 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
932 Ok(InvoiceContents::ForOffer { invoice_request, fields })
935 let refund = RefundContents::try_from(
936 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
938 Ok(InvoiceContents::ForRefund { refund, fields })
946 use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG};
948 use bitcoin::blockdata::script::Script;
949 use bitcoin::hashes::Hash;
950 use bitcoin::network::constants::Network;
951 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
952 use bitcoin::util::address::{Address, Payload, WitnessVersion};
953 use bitcoin::util::schnorr::TweakedPublicKey;
954 use core::convert::TryFrom;
955 use core::time::Duration;
956 use crate::blinded_path::{BlindedHop, BlindedPath};
957 use crate::sign::KeyMaterial;
958 use crate::ln::features::Bolt12InvoiceFeatures;
959 use crate::ln::inbound_payment::ExpandedKey;
960 use crate::ln::msgs::DecodeError;
961 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
962 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
963 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
964 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
965 use crate::offers::payer::PayerTlvStreamRef;
966 use crate::offers::refund::RefundBuilder;
967 use crate::offers::test_utils::*;
968 use crate::util::ser::{BigSize, Iterable, Writeable};
969 use crate::util::string::PrintableString;
972 fn to_bytes(&self) -> Vec<u8>;
975 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
976 fn to_bytes(&self) -> Vec<u8> {
977 let mut buffer = Vec::new();
978 self.0.write(&mut buffer).unwrap();
979 self.1.write(&mut buffer).unwrap();
980 self.2.write(&mut buffer).unwrap();
981 self.3.write(&mut buffer).unwrap();
982 self.4.write(&mut buffer).unwrap();
988 fn builds_invoice_for_offer_with_defaults() {
989 let payment_paths = payment_paths();
990 let payment_hash = payment_hash();
992 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
995 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
997 .sign(payer_sign).unwrap()
998 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1000 .sign(recipient_sign).unwrap();
1002 let mut buffer = Vec::new();
1003 invoice.write(&mut buffer).unwrap();
1005 assert_eq!(invoice.bytes, buffer.as_slice());
1006 assert_eq!(invoice.description(), PrintableString("foo"));
1007 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1008 assert_eq!(invoice.created_at(), now);
1009 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1010 #[cfg(feature = "std")]
1011 assert!(!invoice.is_expired());
1012 assert_eq!(invoice.payment_hash(), payment_hash);
1013 assert_eq!(invoice.amount_msats(), 1000);
1014 assert_eq!(invoice.fallbacks(), vec![]);
1015 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1016 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1018 merkle::verify_signature(
1019 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1023 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1024 let pubkey = recipient_pubkey().into();
1025 let secp_ctx = Secp256k1::verification_only();
1026 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1029 invoice.as_tlv_stream(),
1031 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1037 description: Some(&String::from("foo")),
1039 absolute_expiry: None,
1043 node_id: Some(&recipient_pubkey()),
1045 InvoiceRequestTlvStreamRef {
1050 payer_id: Some(&payer_pubkey()),
1053 InvoiceTlvStreamRef {
1054 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1055 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1056 created_at: Some(now.as_secs()),
1057 relative_expiry: None,
1058 payment_hash: Some(&payment_hash),
1062 node_id: Some(&recipient_pubkey()),
1064 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1068 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1069 panic!("error parsing invoice: {:?}", e);
1074 fn builds_invoice_for_refund_with_defaults() {
1075 let payment_paths = payment_paths();
1076 let payment_hash = payment_hash();
1078 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1080 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1083 .sign(recipient_sign).unwrap();
1085 let mut buffer = Vec::new();
1086 invoice.write(&mut buffer).unwrap();
1088 assert_eq!(invoice.bytes, buffer.as_slice());
1089 assert_eq!(invoice.description(), PrintableString("foo"));
1090 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1091 assert_eq!(invoice.created_at(), now);
1092 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1093 #[cfg(feature = "std")]
1094 assert!(!invoice.is_expired());
1095 assert_eq!(invoice.payment_hash(), payment_hash);
1096 assert_eq!(invoice.amount_msats(), 1000);
1097 assert_eq!(invoice.fallbacks(), vec![]);
1098 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1099 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1101 merkle::verify_signature(
1102 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1107 invoice.as_tlv_stream(),
1109 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1115 description: Some(&String::from("foo")),
1117 absolute_expiry: None,
1123 InvoiceRequestTlvStreamRef {
1128 payer_id: Some(&payer_pubkey()),
1131 InvoiceTlvStreamRef {
1132 paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1133 blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1134 created_at: Some(now.as_secs()),
1135 relative_expiry: None,
1136 payment_hash: Some(&payment_hash),
1140 node_id: Some(&recipient_pubkey()),
1142 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1146 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1147 panic!("error parsing invoice: {:?}", e);
1151 #[cfg(feature = "std")]
1153 fn builds_invoice_from_offer_with_expiration() {
1154 let future_expiry = Duration::from_secs(u64::max_value());
1155 let past_expiry = Duration::from_secs(0);
1157 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1159 .absolute_expiry(future_expiry)
1161 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1163 .sign(payer_sign).unwrap()
1164 .respond_with(payment_paths(), payment_hash())
1168 panic!("error building invoice: {:?}", e);
1171 match OfferBuilder::new("foo".into(), recipient_pubkey())
1173 .absolute_expiry(past_expiry)
1175 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1177 .sign(payer_sign).unwrap()
1178 .respond_with(payment_paths(), payment_hash())
1182 Ok(_) => panic!("expected error"),
1183 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1187 #[cfg(feature = "std")]
1189 fn builds_invoice_from_refund_with_expiration() {
1190 let future_expiry = Duration::from_secs(u64::max_value());
1191 let past_expiry = Duration::from_secs(0);
1193 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1194 .absolute_expiry(future_expiry)
1196 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1200 panic!("error building invoice: {:?}", e);
1203 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1204 .absolute_expiry(past_expiry)
1206 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1210 Ok(_) => panic!("expected error"),
1211 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1216 fn builds_invoice_from_offer_using_derived_keys() {
1217 let desc = "foo".to_string();
1218 let node_id = recipient_pubkey();
1219 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1220 let entropy = FixedEntropy {};
1221 let secp_ctx = Secp256k1::new();
1223 let blinded_path = BlindedPath {
1224 introduction_node_id: pubkey(40),
1225 blinding_point: pubkey(41),
1227 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1228 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1232 let offer = OfferBuilder
1233 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1237 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1239 .sign(payer_sign).unwrap();
1241 if let Err(e) = invoice_request
1242 .verify_and_respond_using_derived_keys_no_std(
1243 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1246 .build_and_sign(&secp_ctx)
1248 panic!("error building invoice: {:?}", e);
1251 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1252 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1253 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1255 Ok(_) => panic!("expected error"),
1256 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1259 let desc = "foo".to_string();
1260 let offer = OfferBuilder
1261 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1264 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1266 .sign(payer_sign).unwrap();
1268 match invoice_request.verify_and_respond_using_derived_keys_no_std(
1269 payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
1271 Ok(_) => panic!("expected error"),
1272 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1277 fn builds_invoice_from_refund_using_derived_keys() {
1278 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1279 let entropy = FixedEntropy {};
1280 let secp_ctx = Secp256k1::new();
1282 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1285 if let Err(e) = refund
1286 .respond_using_derived_keys_no_std(
1287 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1290 .build_and_sign(&secp_ctx)
1292 panic!("error building invoice: {:?}", e);
1297 fn builds_invoice_with_relative_expiry() {
1299 let one_hour = Duration::from_secs(3600);
1301 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1304 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1306 .sign(payer_sign).unwrap()
1307 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1308 .relative_expiry(one_hour.as_secs() as u32)
1310 .sign(recipient_sign).unwrap();
1311 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1312 #[cfg(feature = "std")]
1313 assert!(!invoice.is_expired());
1314 assert_eq!(invoice.relative_expiry(), one_hour);
1315 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1317 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1320 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1322 .sign(payer_sign).unwrap()
1323 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1324 .relative_expiry(one_hour.as_secs() as u32 - 1)
1326 .sign(recipient_sign).unwrap();
1327 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1328 #[cfg(feature = "std")]
1329 assert!(invoice.is_expired());
1330 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1331 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1335 fn builds_invoice_with_amount_from_request() {
1336 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1339 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1340 .amount_msats(1001).unwrap()
1342 .sign(payer_sign).unwrap()
1343 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1345 .sign(recipient_sign).unwrap();
1346 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1347 assert_eq!(invoice.amount_msats(), 1001);
1348 assert_eq!(tlv_stream.amount, Some(1001));
1352 fn builds_invoice_with_quantity_from_request() {
1353 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1355 .supported_quantity(Quantity::Unbounded)
1357 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1358 .quantity(2).unwrap()
1360 .sign(payer_sign).unwrap()
1361 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1363 .sign(recipient_sign).unwrap();
1364 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1365 assert_eq!(invoice.amount_msats(), 2000);
1366 assert_eq!(tlv_stream.amount, Some(2000));
1368 match OfferBuilder::new("foo".into(), recipient_pubkey())
1370 .supported_quantity(Quantity::Unbounded)
1372 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1373 .quantity(u64::max_value()).unwrap()
1375 .sign(payer_sign).unwrap()
1376 .respond_with_no_std(payment_paths(), payment_hash(), now())
1378 Ok(_) => panic!("expected error"),
1379 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1384 fn builds_invoice_with_fallback_address() {
1385 let script = Script::new();
1386 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1387 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1388 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1390 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1393 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1395 .sign(payer_sign).unwrap()
1396 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1397 .fallback_v0_p2wsh(&script.wscript_hash())
1398 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1399 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1401 .sign(recipient_sign).unwrap();
1402 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1404 invoice.fallbacks(),
1406 Address::p2wsh(&script, Network::Bitcoin),
1407 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1408 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1412 tlv_stream.fallbacks,
1415 version: WitnessVersion::V0.to_num(),
1416 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1419 version: WitnessVersion::V0.to_num(),
1420 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1423 version: WitnessVersion::V1.to_num(),
1424 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1431 fn builds_invoice_with_allow_mpp() {
1432 let mut features = Bolt12InvoiceFeatures::empty();
1433 features.set_basic_mpp_optional();
1435 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1438 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1440 .sign(payer_sign).unwrap()
1441 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1444 .sign(recipient_sign).unwrap();
1445 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1446 assert_eq!(invoice.features(), &features);
1447 assert_eq!(tlv_stream.features, Some(&features));
1451 fn fails_signing_invoice() {
1452 match OfferBuilder::new("foo".into(), recipient_pubkey())
1455 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1457 .sign(payer_sign).unwrap()
1458 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1462 Ok(_) => panic!("expected error"),
1463 Err(e) => assert_eq!(e, SignError::Signing(())),
1466 match OfferBuilder::new("foo".into(), recipient_pubkey())
1469 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1471 .sign(payer_sign).unwrap()
1472 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1476 Ok(_) => panic!("expected error"),
1477 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1482 fn parses_invoice_with_payment_paths() {
1483 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1486 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1488 .sign(payer_sign).unwrap()
1489 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1491 .sign(recipient_sign).unwrap();
1493 let mut buffer = Vec::new();
1494 invoice.write(&mut buffer).unwrap();
1496 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1497 panic!("error parsing invoice: {:?}", e);
1500 let mut tlv_stream = invoice.as_tlv_stream();
1501 tlv_stream.3.paths = None;
1503 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1504 Ok(_) => panic!("expected error"),
1505 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1508 let mut tlv_stream = invoice.as_tlv_stream();
1509 tlv_stream.3.blindedpay = None;
1511 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1516 let empty_payment_paths = vec![];
1517 let mut tlv_stream = invoice.as_tlv_stream();
1518 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
1520 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1521 Ok(_) => panic!("expected error"),
1522 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
1525 let mut payment_paths = payment_paths();
1526 payment_paths.pop();
1527 let mut tlv_stream = invoice.as_tlv_stream();
1528 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
1530 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1531 Ok(_) => panic!("expected error"),
1532 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
1537 fn parses_invoice_with_created_at() {
1538 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1541 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1543 .sign(payer_sign).unwrap()
1544 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1546 .sign(recipient_sign).unwrap();
1548 let mut buffer = Vec::new();
1549 invoice.write(&mut buffer).unwrap();
1551 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1552 panic!("error parsing invoice: {:?}", e);
1555 let mut tlv_stream = invoice.as_tlv_stream();
1556 tlv_stream.3.created_at = None;
1558 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1559 Ok(_) => panic!("expected error"),
1561 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
1567 fn parses_invoice_with_relative_expiry() {
1568 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1571 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1573 .sign(payer_sign).unwrap()
1574 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1575 .relative_expiry(3600)
1577 .sign(recipient_sign).unwrap();
1579 let mut buffer = Vec::new();
1580 invoice.write(&mut buffer).unwrap();
1582 match Bolt12Invoice::try_from(buffer) {
1583 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1584 Err(e) => panic!("error parsing invoice: {:?}", e),
1589 fn parses_invoice_with_payment_hash() {
1590 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1593 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1595 .sign(payer_sign).unwrap()
1596 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1598 .sign(recipient_sign).unwrap();
1600 let mut buffer = Vec::new();
1601 invoice.write(&mut buffer).unwrap();
1603 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1604 panic!("error parsing invoice: {:?}", e);
1607 let mut tlv_stream = invoice.as_tlv_stream();
1608 tlv_stream.3.payment_hash = None;
1610 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1611 Ok(_) => panic!("expected error"),
1613 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
1619 fn parses_invoice_with_amount() {
1620 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1623 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1625 .sign(payer_sign).unwrap()
1626 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1628 .sign(recipient_sign).unwrap();
1630 let mut buffer = Vec::new();
1631 invoice.write(&mut buffer).unwrap();
1633 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1634 panic!("error parsing invoice: {:?}", e);
1637 let mut tlv_stream = invoice.as_tlv_stream();
1638 tlv_stream.3.amount = None;
1640 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1641 Ok(_) => panic!("expected error"),
1642 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1647 fn parses_invoice_with_allow_mpp() {
1648 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1651 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1653 .sign(payer_sign).unwrap()
1654 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1657 .sign(recipient_sign).unwrap();
1659 let mut buffer = Vec::new();
1660 invoice.write(&mut buffer).unwrap();
1662 match Bolt12Invoice::try_from(buffer) {
1664 let mut features = Bolt12InvoiceFeatures::empty();
1665 features.set_basic_mpp_optional();
1666 assert_eq!(invoice.features(), &features);
1668 Err(e) => panic!("error parsing invoice: {:?}", e),
1673 fn parses_invoice_with_fallback_address() {
1674 let script = Script::new();
1675 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1676 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1677 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1679 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1682 let invoice_request = offer
1683 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1685 .sign(payer_sign).unwrap();
1686 let mut unsigned_invoice = invoice_request
1687 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1688 .fallback_v0_p2wsh(&script.wscript_hash())
1689 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1690 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1693 // Only standard addresses will be included.
1694 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1695 // Non-standard addresses
1696 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1697 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1698 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1700 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1701 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1703 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1704 let mut buffer = Vec::new();
1705 invoice.write(&mut buffer).unwrap();
1707 match Bolt12Invoice::try_from(buffer) {
1710 invoice.fallbacks(),
1712 Address::p2wsh(&script, Network::Bitcoin),
1713 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1714 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1716 payload: Payload::WitnessProgram {
1717 version: WitnessVersion::V1,
1718 program: vec![0u8; 33],
1720 network: Network::Bitcoin,
1723 payload: Payload::WitnessProgram {
1724 version: WitnessVersion::V2,
1725 program: vec![0u8; 40],
1727 network: Network::Bitcoin,
1732 Err(e) => panic!("error parsing invoice: {:?}", e),
1737 fn parses_invoice_with_node_id() {
1738 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1741 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1743 .sign(payer_sign).unwrap()
1744 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1746 .sign(recipient_sign).unwrap();
1748 let mut buffer = Vec::new();
1749 invoice.write(&mut buffer).unwrap();
1751 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1752 panic!("error parsing invoice: {:?}", e);
1755 let mut tlv_stream = invoice.as_tlv_stream();
1756 tlv_stream.3.node_id = None;
1758 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1759 Ok(_) => panic!("expected error"),
1761 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1765 let invalid_pubkey = payer_pubkey();
1766 let mut tlv_stream = invoice.as_tlv_stream();
1767 tlv_stream.3.node_id = Some(&invalid_pubkey);
1769 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
1770 Ok(_) => panic!("expected error"),
1772 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
1778 fn fails_parsing_invoice_without_signature() {
1779 let mut buffer = Vec::new();
1780 OfferBuilder::new("foo".into(), recipient_pubkey())
1783 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1785 .sign(payer_sign).unwrap()
1786 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1789 .write(&mut buffer).unwrap();
1791 match Bolt12Invoice::try_from(buffer) {
1792 Ok(_) => panic!("expected error"),
1793 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1798 fn fails_parsing_invoice_with_invalid_signature() {
1799 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1802 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1804 .sign(payer_sign).unwrap()
1805 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1807 .sign(recipient_sign).unwrap();
1808 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1809 *last_signature_byte = last_signature_byte.wrapping_add(1);
1811 let mut buffer = Vec::new();
1812 invoice.write(&mut buffer).unwrap();
1814 match Bolt12Invoice::try_from(buffer) {
1815 Ok(_) => panic!("expected error"),
1817 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1823 fn fails_parsing_invoice_with_extra_tlv_records() {
1824 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1827 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1829 .sign(payer_sign).unwrap()
1830 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1832 .sign(recipient_sign).unwrap();
1834 let mut encoded_invoice = Vec::new();
1835 invoice.write(&mut encoded_invoice).unwrap();
1836 BigSize(1002).write(&mut encoded_invoice).unwrap();
1837 BigSize(32).write(&mut encoded_invoice).unwrap();
1838 [42u8; 32].write(&mut encoded_invoice).unwrap();
1840 match Bolt12Invoice::try_from(encoded_invoice) {
1841 Ok(_) => panic!("expected error"),
1842 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),