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 use bitcoin::blockdata::constants::ChainHash;
13 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
14 use bitcoin::hashes::Hash;
15 use bitcoin::network::constants::Network;
16 use bitcoin::secp256k1::{Message, PublicKey};
17 use bitcoin::secp256k1::schnorr::Signature;
18 use bitcoin::util::address::{Address, Payload, WitnessVersion};
19 use bitcoin::util::schnorr::TweakedPublicKey;
20 use core::convert::TryFrom;
21 use core::time::Duration;
23 use crate::ln::PaymentHash;
24 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
25 use crate::ln::msgs::DecodeError;
26 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
27 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
28 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
29 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
30 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
31 use crate::offers::refund::{Refund, RefundContents};
32 use crate::onion_message::BlindedPath;
33 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
35 use crate::prelude::*;
37 #[cfg(feature = "std")]
38 use std::time::SystemTime;
40 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
42 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
44 /// Builds an [`Invoice`] from either:
45 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
46 /// - a [`Refund`] for the "offer for money" flow.
48 /// See [module-level documentation] for usage.
50 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
51 /// [`Refund`]: crate::offers::refund::Refund
52 /// [module-level documentation]: self
53 pub struct InvoiceBuilder<'a> {
54 invreq_bytes: &'a Vec<u8>,
55 invoice: InvoiceContents,
58 impl<'a> InvoiceBuilder<'a> {
59 pub(super) fn for_offer(
60 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
61 created_at: Duration, payment_hash: PaymentHash
62 ) -> Result<Self, SemanticError> {
63 let amount_msats = match invoice_request.amount_msats() {
64 Some(amount_msats) => amount_msats,
65 None => match invoice_request.contents.offer.amount() {
66 Some(Amount::Bitcoin { amount_msats }) => {
67 amount_msats * invoice_request.quantity().unwrap_or(1)
69 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
70 None => return Err(SemanticError::MissingAmount),
74 let contents = InvoiceContents::ForOffer {
75 invoice_request: invoice_request.contents.clone(),
76 fields: InvoiceFields {
77 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
78 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
79 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
83 Self::new(&invoice_request.bytes, contents)
86 pub(super) fn for_refund(
87 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
88 payment_hash: PaymentHash, signing_pubkey: PublicKey
89 ) -> Result<Self, SemanticError> {
90 let contents = InvoiceContents::ForRefund {
91 refund: refund.contents.clone(),
92 fields: InvoiceFields {
93 payment_paths, created_at, relative_expiry: None, payment_hash,
94 amount_msats: refund.amount_msats(), fallbacks: None,
95 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
99 Self::new(&refund.bytes, contents)
102 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
103 if contents.fields().payment_paths.is_empty() {
104 return Err(SemanticError::MissingPaths);
107 Ok(Self { invreq_bytes, invoice: contents })
110 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
111 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
113 /// Successive calls to this method will override the previous setting.
114 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
115 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
116 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
120 /// Adds a P2WSH address to [`Invoice::fallbacks`].
122 /// Successive calls to this method will add another address. Caller is responsible for not
123 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
124 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
125 let address = FallbackAddress {
126 version: WitnessVersion::V0.to_num(),
127 program: Vec::from(&script_hash.into_inner()[..]),
129 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
133 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
135 /// Successive calls to this method will add another address. Caller is responsible for not
136 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
137 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
138 let address = FallbackAddress {
139 version: WitnessVersion::V0.to_num(),
140 program: Vec::from(&pubkey_hash.into_inner()[..]),
142 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
146 /// Adds a P2TR address to [`Invoice::fallbacks`].
148 /// Successive calls to this method will add another address. Caller is responsible for not
149 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
150 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
151 let address = FallbackAddress {
152 version: WitnessVersion::V1.to_num(),
153 program: Vec::from(&output_key.serialize()[..]),
155 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
159 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
160 pub fn allow_mpp(mut self) -> Self {
161 self.invoice.fields_mut().features.set_basic_mpp_optional();
165 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
166 /// [`UnsignedInvoice::sign`].
167 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
168 #[cfg(feature = "std")] {
169 if self.invoice.is_offer_or_refund_expired() {
170 return Err(SemanticError::AlreadyExpired);
174 let InvoiceBuilder { invreq_bytes, invoice } = self;
175 Ok(UnsignedInvoice { invreq_bytes, invoice })
179 /// A semantically valid [`Invoice`] that hasn't been signed.
180 pub struct UnsignedInvoice<'a> {
181 invreq_bytes: &'a Vec<u8>,
182 invoice: InvoiceContents,
185 impl<'a> UnsignedInvoice<'a> {
186 /// Signs the invoice using the given function.
187 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
189 F: FnOnce(&Message) -> Result<Signature, E>
191 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
192 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
194 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
195 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
196 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
198 let mut bytes = Vec::new();
199 unsigned_tlv_stream.write(&mut bytes).unwrap();
201 let pubkey = self.invoice.fields().signing_pubkey;
202 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
204 // Append the signature TLV record to the bytes.
205 let signature_tlv_stream = SignatureTlvStreamRef {
206 signature: Some(&signature),
208 signature_tlv_stream.write(&mut bytes).unwrap();
212 contents: self.invoice,
218 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
220 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
221 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
223 /// [`Offer`]: crate::offers::offer::Offer
224 /// [`Refund`]: crate::offers::refund::Refund
225 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
228 contents: InvoiceContents,
229 signature: Signature,
232 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
234 /// [`Offer`]: crate::offers::offer::Offer
235 /// [`Refund`]: crate::offers::refund::Refund
236 enum InvoiceContents {
237 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
239 /// [`Offer`]: crate::offers::offer::Offer
241 invoice_request: InvoiceRequestContents,
242 fields: InvoiceFields,
244 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
246 /// [`Refund`]: crate::offers::refund::Refund
248 refund: RefundContents,
249 fields: InvoiceFields,
253 /// Invoice-specific fields for an `invoice` message.
254 struct InvoiceFields {
255 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
256 created_at: Duration,
257 relative_expiry: Option<Duration>,
258 payment_hash: PaymentHash,
260 fallbacks: Option<Vec<FallbackAddress>>,
261 features: Bolt12InvoiceFeatures,
262 signing_pubkey: PublicKey,
266 /// Paths to the recipient originating from publicly reachable nodes, including information
267 /// needed for routing payments across them. Blinded paths provide recipient privacy by
268 /// obfuscating its node id.
269 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
270 &self.contents.fields().payment_paths[..]
273 /// Duration since the Unix epoch when the invoice was created.
274 pub fn created_at(&self) -> Duration {
275 self.contents.fields().created_at
278 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
280 pub fn relative_expiry(&self) -> Duration {
281 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
284 /// Whether the invoice has expired.
285 #[cfg(feature = "std")]
286 pub fn is_expired(&self) -> bool {
287 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
288 match absolute_expiry {
289 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
290 Ok(elapsed) => elapsed > seconds_from_epoch,
297 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
298 pub fn payment_hash(&self) -> PaymentHash {
299 self.contents.fields().payment_hash
302 /// The minimum amount required for a successful payment of the invoice.
303 pub fn amount_msats(&self) -> u64 {
304 self.contents.fields().amount_msats
307 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
309 pub fn fallbacks(&self) -> Vec<Address> {
310 let network = match self.network() {
311 None => return Vec::new(),
312 Some(network) => network,
315 let to_valid_address = |address: &FallbackAddress| {
316 let version = match WitnessVersion::try_from(address.version) {
317 Ok(version) => version,
318 Err(_) => return None,
321 let program = &address.program;
322 if program.len() < 2 || program.len() > 40 {
326 let address = Address {
327 payload: Payload::WitnessProgram {
329 program: address.program.clone(),
334 if !address.is_standard() && version == WitnessVersion::V0 {
341 self.contents.fields().fallbacks
343 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
344 .unwrap_or_else(Vec::new)
347 fn network(&self) -> Option<Network> {
348 let chain = self.contents.chain();
349 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
350 Some(Network::Bitcoin)
351 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
352 Some(Network::Testnet)
353 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
354 Some(Network::Signet)
355 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
356 Some(Network::Regtest)
362 /// Features pertaining to paying an invoice.
363 pub fn features(&self) -> &Bolt12InvoiceFeatures {
364 &self.contents.fields().features
367 /// The public key used to sign invoices.
368 pub fn signing_pubkey(&self) -> PublicKey {
369 self.contents.fields().signing_pubkey
372 /// Signature of the invoice using [`Invoice::signing_pubkey`].
373 pub fn signature(&self) -> Signature {
378 impl InvoiceContents {
379 /// Whether the original offer or refund has expired.
380 #[cfg(feature = "std")]
381 fn is_offer_or_refund_expired(&self) -> bool {
383 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
384 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
388 fn chain(&self) -> ChainHash {
390 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
391 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
395 fn fields(&self) -> &InvoiceFields {
397 InvoiceContents::ForOffer { fields, .. } => fields,
398 InvoiceContents::ForRefund { fields, .. } => fields,
402 fn fields_mut(&mut self) -> &mut InvoiceFields {
404 InvoiceContents::ForOffer { fields, .. } => fields,
405 InvoiceContents::ForRefund { fields, .. } => fields,
409 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
410 let (payer, offer, invoice_request) = match self {
411 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
412 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
414 let invoice = self.fields().as_tlv_stream();
416 (payer, offer, invoice_request, invoice)
421 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
423 if self.features == Bolt12InvoiceFeatures::empty() { None }
424 else { Some(&self.features) }
427 InvoiceTlvStreamRef {
428 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
429 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
430 created_at: Some(self.created_at.as_secs()),
431 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
432 payment_hash: Some(&self.payment_hash),
433 amount: Some(self.amount_msats),
434 fallbacks: self.fallbacks.as_ref(),
436 node_id: Some(&self.signing_pubkey),
441 impl Writeable for Invoice {
442 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
443 WithoutLength(&self.bytes).write(writer)
447 impl TryFrom<Vec<u8>> for Invoice {
448 type Error = ParseError;
450 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
451 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
452 Invoice::try_from(parsed_invoice)
456 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
457 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
458 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
459 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
460 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
461 (168, payment_hash: PaymentHash),
462 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
463 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
464 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
465 (176, node_id: PublicKey),
468 type BlindedPathIter<'a> = core::iter::Map<
469 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
470 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
473 type BlindedPayInfoIter<'a> = core::iter::Map<
474 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
475 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
478 /// Information needed to route a payment across a [`BlindedPath`].
479 #[derive(Debug, PartialEq)]
480 pub struct BlindedPayInfo {
482 fee_proportional_millionths: u32,
483 cltv_expiry_delta: u16,
484 htlc_minimum_msat: u64,
485 htlc_maximum_msat: u64,
486 features: BlindedHopFeatures,
489 impl_writeable!(BlindedPayInfo, {
491 fee_proportional_millionths,
498 /// Wire representation for an on-chain fallback address.
499 #[derive(Debug, PartialEq)]
500 pub(super) struct FallbackAddress {
505 impl_writeable!(FallbackAddress, { version, program });
507 type FullInvoiceTlvStream =
508 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
510 impl SeekReadable for FullInvoiceTlvStream {
511 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
512 let payer = SeekReadable::read(r)?;
513 let offer = SeekReadable::read(r)?;
514 let invoice_request = SeekReadable::read(r)?;
515 let invoice = SeekReadable::read(r)?;
516 let signature = SeekReadable::read(r)?;
518 Ok((payer, offer, invoice_request, invoice, signature))
522 type PartialInvoiceTlvStream =
523 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
525 type PartialInvoiceTlvStreamRef<'a> = (
526 PayerTlvStreamRef<'a>,
527 OfferTlvStreamRef<'a>,
528 InvoiceRequestTlvStreamRef<'a>,
529 InvoiceTlvStreamRef<'a>,
532 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
533 type Error = ParseError;
535 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
536 let ParsedMessage { bytes, tlv_stream } = invoice;
538 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
539 SignatureTlvStream { signature },
541 let contents = InvoiceContents::try_from(
542 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
545 let signature = match signature {
546 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
547 Some(signature) => signature,
549 let pubkey = contents.fields().signing_pubkey;
550 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
552 Ok(Invoice { bytes, contents, signature })
556 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
557 type Error = SemanticError;
559 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
563 invoice_request_tlv_stream,
565 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
570 let payment_paths = match (paths, blindedpay) {
571 (None, _) => return Err(SemanticError::MissingPaths),
572 (_, None) => return Err(SemanticError::InvalidPayInfo),
573 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
574 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
575 return Err(SemanticError::InvalidPayInfo);
577 (Some(paths), Some(blindedpay)) => {
578 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
582 let created_at = match created_at {
583 None => return Err(SemanticError::MissingCreationTime),
584 Some(timestamp) => Duration::from_secs(timestamp),
587 let relative_expiry = relative_expiry
588 .map(Into::<u64>::into)
589 .map(Duration::from_secs);
591 let payment_hash = match payment_hash {
592 None => return Err(SemanticError::MissingPaymentHash),
593 Some(payment_hash) => payment_hash,
596 let amount_msats = match amount {
597 None => return Err(SemanticError::MissingAmount),
598 Some(amount) => amount,
601 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
603 let signing_pubkey = match node_id {
604 None => return Err(SemanticError::MissingSigningPubkey),
605 Some(node_id) => node_id,
608 let fields = InvoiceFields {
609 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
610 features, signing_pubkey,
613 match offer_tlv_stream.node_id {
614 Some(expected_signing_pubkey) => {
615 if fields.signing_pubkey != expected_signing_pubkey {
616 return Err(SemanticError::InvalidSigningPubkey);
619 let invoice_request = InvoiceRequestContents::try_from(
620 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
622 Ok(InvoiceContents::ForOffer { invoice_request, fields })
625 let refund = RefundContents::try_from(
626 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
628 Ok(InvoiceContents::ForRefund { refund, fields })