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 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! 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::onion_message::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
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::ParseError> {
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::{Message, PublicKey};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::TryFrom;
105 use core::time::Duration;
107 use crate::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
119 use crate::prelude::*;
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
132 /// See [module-level documentation] for usage.
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138 invreq_bytes: &'a Vec<u8>,
139 invoice: InvoiceContents,
142 impl<'a> InvoiceBuilder<'a> {
143 pub(super) fn for_offer(
144 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145 created_at: Duration, payment_hash: PaymentHash
146 ) -> Result<Self, SemanticError> {
147 let amount_msats = match invoice_request.amount_msats() {
148 Some(amount_msats) => amount_msats,
149 None => match invoice_request.contents.offer.amount() {
150 Some(Amount::Bitcoin { amount_msats }) => {
151 amount_msats * invoice_request.quantity().unwrap_or(1)
153 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
154 None => return Err(SemanticError::MissingAmount),
158 let contents = InvoiceContents::ForOffer {
159 invoice_request: invoice_request.contents.clone(),
160 fields: InvoiceFields {
161 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
162 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
163 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
167 Self::new(&invoice_request.bytes, contents)
170 pub(super) fn for_refund(
171 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
172 payment_hash: PaymentHash, signing_pubkey: PublicKey
173 ) -> Result<Self, SemanticError> {
174 let contents = InvoiceContents::ForRefund {
175 refund: refund.contents.clone(),
176 fields: InvoiceFields {
177 payment_paths, created_at, relative_expiry: None, payment_hash,
178 amount_msats: refund.amount_msats(), fallbacks: None,
179 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
183 Self::new(&refund.bytes, contents)
186 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
187 if contents.fields().payment_paths.is_empty() {
188 return Err(SemanticError::MissingPaths);
191 Ok(Self { invreq_bytes, invoice: contents })
194 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
195 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
197 /// Successive calls to this method will override the previous setting.
198 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
199 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
200 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
204 /// Adds a P2WSH address to [`Invoice::fallbacks`].
206 /// Successive calls to this method will add another address. Caller is responsible for not
207 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
208 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
209 let address = FallbackAddress {
210 version: WitnessVersion::V0.to_num(),
211 program: Vec::from(&script_hash.into_inner()[..]),
213 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
217 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
219 /// Successive calls to this method will add another address. Caller is responsible for not
220 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
221 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
222 let address = FallbackAddress {
223 version: WitnessVersion::V0.to_num(),
224 program: Vec::from(&pubkey_hash.into_inner()[..]),
226 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
230 /// Adds a P2TR address to [`Invoice::fallbacks`].
232 /// Successive calls to this method will add another address. Caller is responsible for not
233 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
234 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
235 let address = FallbackAddress {
236 version: WitnessVersion::V1.to_num(),
237 program: Vec::from(&output_key.serialize()[..]),
239 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
243 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
244 pub fn allow_mpp(mut self) -> Self {
245 self.invoice.fields_mut().features.set_basic_mpp_optional();
249 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
250 /// [`UnsignedInvoice::sign`].
251 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
252 #[cfg(feature = "std")] {
253 if self.invoice.is_offer_or_refund_expired() {
254 return Err(SemanticError::AlreadyExpired);
258 let InvoiceBuilder { invreq_bytes, invoice } = self;
259 Ok(UnsignedInvoice { invreq_bytes, invoice })
263 /// A semantically valid [`Invoice`] that hasn't been signed.
264 pub struct UnsignedInvoice<'a> {
265 invreq_bytes: &'a Vec<u8>,
266 invoice: InvoiceContents,
269 impl<'a> UnsignedInvoice<'a> {
270 /// The public key corresponding to the key needed to sign the invoice.
271 pub fn signing_pubkey(&self) -> PublicKey {
272 self.invoice.fields().signing_pubkey
275 /// Signs the invoice using the given function.
276 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
278 F: FnOnce(&Message) -> Result<Signature, E>
280 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
281 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
283 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
284 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
285 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
287 let mut bytes = Vec::new();
288 unsigned_tlv_stream.write(&mut bytes).unwrap();
290 let pubkey = self.invoice.fields().signing_pubkey;
291 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
293 // Append the signature TLV record to the bytes.
294 let signature_tlv_stream = SignatureTlvStreamRef {
295 signature: Some(&signature),
297 signature_tlv_stream.write(&mut bytes).unwrap();
301 contents: self.invoice,
307 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
309 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
310 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
312 /// [`Offer`]: crate::offers::offer::Offer
313 /// [`Refund`]: crate::offers::refund::Refund
314 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
315 #[derive(Clone, Debug, PartialEq)]
318 contents: InvoiceContents,
319 signature: Signature,
322 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
324 /// [`Offer`]: crate::offers::offer::Offer
325 /// [`Refund`]: crate::offers::refund::Refund
326 #[derive(Clone, Debug, PartialEq)]
327 enum InvoiceContents {
328 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
330 /// [`Offer`]: crate::offers::offer::Offer
332 invoice_request: InvoiceRequestContents,
333 fields: InvoiceFields,
335 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
337 /// [`Refund`]: crate::offers::refund::Refund
339 refund: RefundContents,
340 fields: InvoiceFields,
344 /// Invoice-specific fields for an `invoice` message.
345 #[derive(Clone, Debug, PartialEq)]
346 struct InvoiceFields {
347 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
348 created_at: Duration,
349 relative_expiry: Option<Duration>,
350 payment_hash: PaymentHash,
352 fallbacks: Option<Vec<FallbackAddress>>,
353 features: Bolt12InvoiceFeatures,
354 signing_pubkey: PublicKey,
358 /// Paths to the recipient originating from publicly reachable nodes, including information
359 /// needed for routing payments across them.
361 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
362 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
363 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
364 &self.contents.fields().payment_paths[..]
367 /// Duration since the Unix epoch when the invoice was created.
368 pub fn created_at(&self) -> Duration {
369 self.contents.fields().created_at
372 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
374 pub fn relative_expiry(&self) -> Duration {
375 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
378 /// Whether the invoice has expired.
379 #[cfg(feature = "std")]
380 pub fn is_expired(&self) -> bool {
381 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
382 match absolute_expiry {
383 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
384 Ok(elapsed) => elapsed > seconds_from_epoch,
391 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
392 pub fn payment_hash(&self) -> PaymentHash {
393 self.contents.fields().payment_hash
396 /// The minimum amount required for a successful payment of the invoice.
397 pub fn amount_msats(&self) -> u64 {
398 self.contents.fields().amount_msats
401 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
403 pub fn fallbacks(&self) -> Vec<Address> {
404 let network = match self.network() {
405 None => return Vec::new(),
406 Some(network) => network,
409 let to_valid_address = |address: &FallbackAddress| {
410 let version = match WitnessVersion::try_from(address.version) {
411 Ok(version) => version,
412 Err(_) => return None,
415 let program = &address.program;
416 if program.len() < 2 || program.len() > 40 {
420 let address = Address {
421 payload: Payload::WitnessProgram {
423 program: address.program.clone(),
428 if !address.is_standard() && version == WitnessVersion::V0 {
435 self.contents.fields().fallbacks
437 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
438 .unwrap_or_else(Vec::new)
441 fn network(&self) -> Option<Network> {
442 let chain = self.contents.chain();
443 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
444 Some(Network::Bitcoin)
445 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
446 Some(Network::Testnet)
447 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
448 Some(Network::Signet)
449 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
450 Some(Network::Regtest)
456 /// Features pertaining to paying an invoice.
457 pub fn features(&self) -> &Bolt12InvoiceFeatures {
458 &self.contents.fields().features
461 /// The public key corresponding to the key used to sign the invoice.
462 pub fn signing_pubkey(&self) -> PublicKey {
463 self.contents.fields().signing_pubkey
466 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
467 pub fn signature(&self) -> Signature {
472 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
473 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
474 self.contents.as_tlv_stream();
475 let signature_tlv_stream = SignatureTlvStreamRef {
476 signature: Some(&self.signature),
478 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
479 signature_tlv_stream)
483 impl InvoiceContents {
484 /// Whether the original offer or refund has expired.
485 #[cfg(feature = "std")]
486 fn is_offer_or_refund_expired(&self) -> bool {
488 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
489 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
493 fn chain(&self) -> ChainHash {
495 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
496 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
500 fn fields(&self) -> &InvoiceFields {
502 InvoiceContents::ForOffer { fields, .. } => fields,
503 InvoiceContents::ForRefund { fields, .. } => fields,
507 fn fields_mut(&mut self) -> &mut InvoiceFields {
509 InvoiceContents::ForOffer { fields, .. } => fields,
510 InvoiceContents::ForRefund { fields, .. } => fields,
514 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
515 let (payer, offer, invoice_request) = match self {
516 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
517 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
519 let invoice = self.fields().as_tlv_stream();
521 (payer, offer, invoice_request, invoice)
526 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
528 if self.features == Bolt12InvoiceFeatures::empty() { None }
529 else { Some(&self.features) }
532 InvoiceTlvStreamRef {
533 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
534 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
535 created_at: Some(self.created_at.as_secs()),
536 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
537 payment_hash: Some(&self.payment_hash),
538 amount: Some(self.amount_msats),
539 fallbacks: self.fallbacks.as_ref(),
541 node_id: Some(&self.signing_pubkey),
546 impl Writeable for Invoice {
547 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
548 WithoutLength(&self.bytes).write(writer)
552 impl Writeable for InvoiceContents {
553 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
554 self.as_tlv_stream().write(writer)
558 impl TryFrom<Vec<u8>> for Invoice {
559 type Error = ParseError;
561 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
562 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
563 Invoice::try_from(parsed_invoice)
567 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
568 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
569 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
570 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
571 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
572 (168, payment_hash: PaymentHash),
573 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
574 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
575 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
576 (176, node_id: PublicKey),
579 type BlindedPathIter<'a> = core::iter::Map<
580 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
581 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
584 type BlindedPayInfoIter<'a> = core::iter::Map<
585 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
586 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
589 /// Information needed to route a payment across a [`BlindedPath`].
590 #[derive(Clone, Debug, PartialEq)]
591 pub struct BlindedPayInfo {
592 /// Base fee charged (in millisatoshi) for the entire blinded path.
593 pub fee_base_msat: u32,
595 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
596 /// (i.e., 10,000 is 1%).
597 pub fee_proportional_millionths: u32,
599 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
601 pub cltv_expiry_delta: u16,
603 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
604 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
605 /// seen by the recipient.
606 pub htlc_minimum_msat: u64,
608 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
609 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
610 /// seen by the recipient.
611 pub htlc_maximum_msat: u64,
613 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
615 pub features: BlindedHopFeatures,
618 impl_writeable!(BlindedPayInfo, {
620 fee_proportional_millionths,
627 /// Wire representation for an on-chain fallback address.
628 #[derive(Clone, Debug, PartialEq)]
629 pub(super) struct FallbackAddress {
634 impl_writeable!(FallbackAddress, { version, program });
636 type FullInvoiceTlvStream =
637 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
640 type FullInvoiceTlvStreamRef<'a> = (
641 PayerTlvStreamRef<'a>,
642 OfferTlvStreamRef<'a>,
643 InvoiceRequestTlvStreamRef<'a>,
644 InvoiceTlvStreamRef<'a>,
645 SignatureTlvStreamRef<'a>,
648 impl SeekReadable for FullInvoiceTlvStream {
649 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
650 let payer = SeekReadable::read(r)?;
651 let offer = SeekReadable::read(r)?;
652 let invoice_request = SeekReadable::read(r)?;
653 let invoice = SeekReadable::read(r)?;
654 let signature = SeekReadable::read(r)?;
656 Ok((payer, offer, invoice_request, invoice, signature))
660 type PartialInvoiceTlvStream =
661 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
663 type PartialInvoiceTlvStreamRef<'a> = (
664 PayerTlvStreamRef<'a>,
665 OfferTlvStreamRef<'a>,
666 InvoiceRequestTlvStreamRef<'a>,
667 InvoiceTlvStreamRef<'a>,
670 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
671 type Error = ParseError;
673 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
674 let ParsedMessage { bytes, tlv_stream } = invoice;
676 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
677 SignatureTlvStream { signature },
679 let contents = InvoiceContents::try_from(
680 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
683 let signature = match signature {
684 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
685 Some(signature) => signature,
687 let pubkey = contents.fields().signing_pubkey;
688 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
690 Ok(Invoice { bytes, contents, signature })
694 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
695 type Error = SemanticError;
697 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
701 invoice_request_tlv_stream,
703 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
708 let payment_paths = match (paths, blindedpay) {
709 (None, _) => return Err(SemanticError::MissingPaths),
710 (_, None) => return Err(SemanticError::InvalidPayInfo),
711 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
712 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
713 return Err(SemanticError::InvalidPayInfo);
715 (Some(paths), Some(blindedpay)) => {
716 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
720 let created_at = match created_at {
721 None => return Err(SemanticError::MissingCreationTime),
722 Some(timestamp) => Duration::from_secs(timestamp),
725 let relative_expiry = relative_expiry
726 .map(Into::<u64>::into)
727 .map(Duration::from_secs);
729 let payment_hash = match payment_hash {
730 None => return Err(SemanticError::MissingPaymentHash),
731 Some(payment_hash) => payment_hash,
734 let amount_msats = match amount {
735 None => return Err(SemanticError::MissingAmount),
736 Some(amount) => amount,
739 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
741 let signing_pubkey = match node_id {
742 None => return Err(SemanticError::MissingSigningPubkey),
743 Some(node_id) => node_id,
746 let fields = InvoiceFields {
747 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
748 features, signing_pubkey,
751 match offer_tlv_stream.node_id {
752 Some(expected_signing_pubkey) => {
753 if fields.signing_pubkey != expected_signing_pubkey {
754 return Err(SemanticError::InvalidSigningPubkey);
757 let invoice_request = InvoiceRequestContents::try_from(
758 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
760 Ok(InvoiceContents::ForOffer { invoice_request, fields })
763 let refund = RefundContents::try_from(
764 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
766 Ok(InvoiceContents::ForRefund { refund, fields })
774 use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
776 use bitcoin::blockdata::script::Script;
777 use bitcoin::hashes::Hash;
778 use bitcoin::network::constants::Network;
779 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
780 use bitcoin::secp256k1::schnorr::Signature;
781 use bitcoin::util::address::{Address, Payload, WitnessVersion};
782 use bitcoin::util::schnorr::TweakedPublicKey;
783 use core::convert::{Infallible, TryFrom};
784 use core::time::Duration;
785 use crate::ln::PaymentHash;
786 use crate::ln::msgs::DecodeError;
787 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
788 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
789 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
790 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
791 use crate::offers::parse::{ParseError, SemanticError};
792 use crate::offers::payer::PayerTlvStreamRef;
793 use crate::offers::refund::RefundBuilder;
794 use crate::onion_message::{BlindedHop, BlindedPath};
795 use crate::util::ser::{BigSize, Iterable, Writeable};
797 fn payer_keys() -> KeyPair {
798 let secp_ctx = Secp256k1::new();
799 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
802 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
803 let secp_ctx = Secp256k1::new();
804 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
805 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
808 fn payer_pubkey() -> PublicKey {
809 payer_keys().public_key()
812 fn recipient_keys() -> KeyPair {
813 let secp_ctx = Secp256k1::new();
814 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
817 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
818 let secp_ctx = Secp256k1::new();
819 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
820 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
823 fn recipient_pubkey() -> PublicKey {
824 recipient_keys().public_key()
827 fn pubkey(byte: u8) -> PublicKey {
828 let secp_ctx = Secp256k1::new();
829 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
832 fn privkey(byte: u8) -> SecretKey {
833 SecretKey::from_slice(&[byte; 32]).unwrap()
837 fn to_bytes(&self) -> Vec<u8>;
840 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
841 fn to_bytes(&self) -> Vec<u8> {
842 let mut buffer = Vec::new();
843 self.0.write(&mut buffer).unwrap();
844 self.1.write(&mut buffer).unwrap();
845 self.2.write(&mut buffer).unwrap();
846 self.3.write(&mut buffer).unwrap();
847 self.4.write(&mut buffer).unwrap();
852 fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
855 introduction_node_id: pubkey(40),
856 blinding_point: pubkey(41),
858 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
859 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
863 introduction_node_id: pubkey(40),
864 blinding_point: pubkey(41),
866 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
867 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
875 fee_proportional_millionths: 1_000,
876 cltv_expiry_delta: 42,
877 htlc_minimum_msat: 100,
878 htlc_maximum_msat: 1_000_000_000_000,
879 features: BlindedHopFeatures::empty(),
883 fee_proportional_millionths: 1_000,
884 cltv_expiry_delta: 42,
885 htlc_minimum_msat: 100,
886 htlc_maximum_msat: 1_000_000_000_000,
887 features: BlindedHopFeatures::empty(),
891 paths.into_iter().zip(payinfo.into_iter()).collect()
894 fn payment_hash() -> PaymentHash {
895 PaymentHash([42; 32])
898 fn now() -> Duration {
899 std::time::SystemTime::now()
900 .duration_since(std::time::SystemTime::UNIX_EPOCH)
901 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
905 fn builds_invoice_for_offer_with_defaults() {
906 let payment_paths = payment_paths();
907 let payment_hash = payment_hash();
909 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
912 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
914 .sign(payer_sign).unwrap()
915 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
917 .sign(recipient_sign).unwrap();
919 let mut buffer = Vec::new();
920 invoice.write(&mut buffer).unwrap();
922 assert_eq!(invoice.bytes, buffer.as_slice());
923 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
924 assert_eq!(invoice.created_at(), now);
925 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
926 #[cfg(feature = "std")]
927 assert!(!invoice.is_expired());
928 assert_eq!(invoice.payment_hash(), payment_hash);
929 assert_eq!(invoice.amount_msats(), 1000);
930 assert_eq!(invoice.fallbacks(), vec![]);
931 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
932 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
934 merkle::verify_signature(
935 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
940 invoice.as_tlv_stream(),
942 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
948 description: Some(&String::from("foo")),
950 absolute_expiry: None,
954 node_id: Some(&recipient_pubkey()),
956 InvoiceRequestTlvStreamRef {
961 payer_id: Some(&payer_pubkey()),
964 InvoiceTlvStreamRef {
965 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
966 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
967 created_at: Some(now.as_secs()),
968 relative_expiry: None,
969 payment_hash: Some(&payment_hash),
973 node_id: Some(&recipient_pubkey()),
975 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
979 if let Err(e) = Invoice::try_from(buffer) {
980 panic!("error parsing invoice: {:?}", e);
985 fn builds_invoice_for_refund_with_defaults() {
986 let payment_paths = payment_paths();
987 let payment_hash = payment_hash();
989 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
991 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
994 .sign(recipient_sign).unwrap();
996 let mut buffer = Vec::new();
997 invoice.write(&mut buffer).unwrap();
999 assert_eq!(invoice.bytes, buffer.as_slice());
1000 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1001 assert_eq!(invoice.created_at(), now);
1002 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1003 #[cfg(feature = "std")]
1004 assert!(!invoice.is_expired());
1005 assert_eq!(invoice.payment_hash(), payment_hash);
1006 assert_eq!(invoice.amount_msats(), 1000);
1007 assert_eq!(invoice.fallbacks(), vec![]);
1008 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1009 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1011 merkle::verify_signature(
1012 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1017 invoice.as_tlv_stream(),
1019 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1025 description: Some(&String::from("foo")),
1027 absolute_expiry: None,
1033 InvoiceRequestTlvStreamRef {
1038 payer_id: Some(&payer_pubkey()),
1041 InvoiceTlvStreamRef {
1042 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1043 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1044 created_at: Some(now.as_secs()),
1045 relative_expiry: None,
1046 payment_hash: Some(&payment_hash),
1050 node_id: Some(&recipient_pubkey()),
1052 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1056 if let Err(e) = Invoice::try_from(buffer) {
1057 panic!("error parsing invoice: {:?}", e);
1061 #[cfg(feature = "std")]
1063 fn builds_invoice_from_offer_with_expiration() {
1064 let future_expiry = Duration::from_secs(u64::max_value());
1065 let past_expiry = Duration::from_secs(0);
1067 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1069 .absolute_expiry(future_expiry)
1071 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 .sign(payer_sign).unwrap()
1074 .respond_with(payment_paths(), payment_hash())
1078 panic!("error building invoice: {:?}", e);
1081 match OfferBuilder::new("foo".into(), recipient_pubkey())
1083 .absolute_expiry(past_expiry)
1085 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1087 .sign(payer_sign).unwrap()
1088 .respond_with(payment_paths(), payment_hash())
1092 Ok(_) => panic!("expected error"),
1093 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1097 #[cfg(feature = "std")]
1099 fn builds_invoice_from_refund_with_expiration() {
1100 let future_expiry = Duration::from_secs(u64::max_value());
1101 let past_expiry = Duration::from_secs(0);
1103 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1104 .absolute_expiry(future_expiry)
1106 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1110 panic!("error building invoice: {:?}", e);
1113 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1114 .absolute_expiry(past_expiry)
1116 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1120 Ok(_) => panic!("expected error"),
1121 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1126 fn builds_invoice_with_relative_expiry() {
1128 let one_hour = Duration::from_secs(3600);
1130 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1133 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1135 .sign(payer_sign).unwrap()
1136 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1137 .relative_expiry(one_hour.as_secs() as u32)
1139 .sign(recipient_sign).unwrap();
1140 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1141 #[cfg(feature = "std")]
1142 assert!(!invoice.is_expired());
1143 assert_eq!(invoice.relative_expiry(), one_hour);
1144 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1146 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1149 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1151 .sign(payer_sign).unwrap()
1152 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1153 .relative_expiry(one_hour.as_secs() as u32 - 1)
1155 .sign(recipient_sign).unwrap();
1156 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1157 #[cfg(feature = "std")]
1158 assert!(invoice.is_expired());
1159 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1160 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1164 fn builds_invoice_with_amount_from_request() {
1165 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1168 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1169 .amount_msats(1001).unwrap()
1171 .sign(payer_sign).unwrap()
1172 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1174 .sign(recipient_sign).unwrap();
1175 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1176 assert_eq!(invoice.amount_msats(), 1001);
1177 assert_eq!(tlv_stream.amount, Some(1001));
1181 fn builds_invoice_with_fallback_address() {
1182 let script = Script::new();
1183 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1184 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1185 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1187 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1190 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1192 .sign(payer_sign).unwrap()
1193 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1194 .fallback_v0_p2wsh(&script.wscript_hash())
1195 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1196 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1198 .sign(recipient_sign).unwrap();
1199 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1201 invoice.fallbacks(),
1203 Address::p2wsh(&script, Network::Bitcoin),
1204 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1205 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1209 tlv_stream.fallbacks,
1212 version: WitnessVersion::V0.to_num(),
1213 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1216 version: WitnessVersion::V0.to_num(),
1217 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1220 version: WitnessVersion::V1.to_num(),
1221 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1228 fn builds_invoice_with_allow_mpp() {
1229 let mut features = Bolt12InvoiceFeatures::empty();
1230 features.set_basic_mpp_optional();
1232 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1235 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1237 .sign(payer_sign).unwrap()
1238 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1241 .sign(recipient_sign).unwrap();
1242 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1243 assert_eq!(invoice.features(), &features);
1244 assert_eq!(tlv_stream.features, Some(&features));
1248 fn fails_signing_invoice() {
1249 match OfferBuilder::new("foo".into(), recipient_pubkey())
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1254 .sign(payer_sign).unwrap()
1255 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1259 Ok(_) => panic!("expected error"),
1260 Err(e) => assert_eq!(e, SignError::Signing(())),
1263 match OfferBuilder::new("foo".into(), recipient_pubkey())
1266 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1268 .sign(payer_sign).unwrap()
1269 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1273 Ok(_) => panic!("expected error"),
1274 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1279 fn parses_invoice_with_payment_paths() {
1280 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1285 .sign(payer_sign).unwrap()
1286 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1288 .sign(recipient_sign).unwrap();
1290 let mut buffer = Vec::new();
1291 invoice.write(&mut buffer).unwrap();
1293 if let Err(e) = Invoice::try_from(buffer) {
1294 panic!("error parsing invoice: {:?}", e);
1297 let mut tlv_stream = invoice.as_tlv_stream();
1298 tlv_stream.3.paths = None;
1300 match Invoice::try_from(tlv_stream.to_bytes()) {
1301 Ok(_) => panic!("expected error"),
1302 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1305 let mut tlv_stream = invoice.as_tlv_stream();
1306 tlv_stream.3.blindedpay = None;
1308 match Invoice::try_from(tlv_stream.to_bytes()) {
1309 Ok(_) => panic!("expected error"),
1310 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1313 let empty_payment_paths = vec![];
1314 let mut tlv_stream = invoice.as_tlv_stream();
1315 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1317 match Invoice::try_from(tlv_stream.to_bytes()) {
1318 Ok(_) => panic!("expected error"),
1319 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1322 let mut payment_paths = payment_paths();
1323 payment_paths.pop();
1324 let mut tlv_stream = invoice.as_tlv_stream();
1325 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1327 match Invoice::try_from(tlv_stream.to_bytes()) {
1328 Ok(_) => panic!("expected error"),
1329 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1334 fn parses_invoice_with_created_at() {
1335 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1338 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1340 .sign(payer_sign).unwrap()
1341 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1343 .sign(recipient_sign).unwrap();
1345 let mut buffer = Vec::new();
1346 invoice.write(&mut buffer).unwrap();
1348 if let Err(e) = Invoice::try_from(buffer) {
1349 panic!("error parsing invoice: {:?}", e);
1352 let mut tlv_stream = invoice.as_tlv_stream();
1353 tlv_stream.3.created_at = None;
1355 match Invoice::try_from(tlv_stream.to_bytes()) {
1356 Ok(_) => panic!("expected error"),
1358 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1364 fn parses_invoice_with_relative_expiry() {
1365 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1368 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1370 .sign(payer_sign).unwrap()
1371 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1372 .relative_expiry(3600)
1374 .sign(recipient_sign).unwrap();
1376 let mut buffer = Vec::new();
1377 invoice.write(&mut buffer).unwrap();
1379 match Invoice::try_from(buffer) {
1380 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1381 Err(e) => panic!("error parsing invoice: {:?}", e),
1386 fn parses_invoice_with_payment_hash() {
1387 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1390 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1392 .sign(payer_sign).unwrap()
1393 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1395 .sign(recipient_sign).unwrap();
1397 let mut buffer = Vec::new();
1398 invoice.write(&mut buffer).unwrap();
1400 if let Err(e) = Invoice::try_from(buffer) {
1401 panic!("error parsing invoice: {:?}", e);
1404 let mut tlv_stream = invoice.as_tlv_stream();
1405 tlv_stream.3.payment_hash = None;
1407 match Invoice::try_from(tlv_stream.to_bytes()) {
1408 Ok(_) => panic!("expected error"),
1410 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1416 fn parses_invoice_with_amount() {
1417 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1420 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1422 .sign(payer_sign).unwrap()
1423 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1425 .sign(recipient_sign).unwrap();
1427 let mut buffer = Vec::new();
1428 invoice.write(&mut buffer).unwrap();
1430 if let Err(e) = Invoice::try_from(buffer) {
1431 panic!("error parsing invoice: {:?}", e);
1434 let mut tlv_stream = invoice.as_tlv_stream();
1435 tlv_stream.3.amount = None;
1437 match Invoice::try_from(tlv_stream.to_bytes()) {
1438 Ok(_) => panic!("expected error"),
1439 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1444 fn parses_invoice_with_allow_mpp() {
1445 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1448 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1450 .sign(payer_sign).unwrap()
1451 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1454 .sign(recipient_sign).unwrap();
1456 let mut buffer = Vec::new();
1457 invoice.write(&mut buffer).unwrap();
1459 match Invoice::try_from(buffer) {
1461 let mut features = Bolt12InvoiceFeatures::empty();
1462 features.set_basic_mpp_optional();
1463 assert_eq!(invoice.features(), &features);
1465 Err(e) => panic!("error parsing invoice: {:?}", e),
1470 fn parses_invoice_with_fallback_address() {
1471 let script = Script::new();
1472 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1473 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1474 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1476 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1479 let invoice_request = offer
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1482 .sign(payer_sign).unwrap();
1483 let mut unsigned_invoice = invoice_request
1484 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1485 .fallback_v0_p2wsh(&script.wscript_hash())
1486 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1487 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1490 // Only standard addresses will be included.
1491 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1492 // Non-standard addresses
1493 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1494 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1495 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1497 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1498 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1500 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1501 let mut buffer = Vec::new();
1502 invoice.write(&mut buffer).unwrap();
1504 match Invoice::try_from(buffer) {
1507 invoice.fallbacks(),
1509 Address::p2wsh(&script, Network::Bitcoin),
1510 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1511 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1513 payload: Payload::WitnessProgram {
1514 version: WitnessVersion::V1,
1515 program: vec![0u8; 33],
1517 network: Network::Bitcoin,
1520 payload: Payload::WitnessProgram {
1521 version: WitnessVersion::V2,
1522 program: vec![0u8; 40],
1524 network: Network::Bitcoin,
1529 Err(e) => panic!("error parsing invoice: {:?}", e),
1534 fn parses_invoice_with_node_id() {
1535 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1538 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1540 .sign(payer_sign).unwrap()
1541 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1543 .sign(recipient_sign).unwrap();
1545 let mut buffer = Vec::new();
1546 invoice.write(&mut buffer).unwrap();
1548 if let Err(e) = Invoice::try_from(buffer) {
1549 panic!("error parsing invoice: {:?}", e);
1552 let mut tlv_stream = invoice.as_tlv_stream();
1553 tlv_stream.3.node_id = None;
1555 match Invoice::try_from(tlv_stream.to_bytes()) {
1556 Ok(_) => panic!("expected error"),
1558 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1562 let invalid_pubkey = payer_pubkey();
1563 let mut tlv_stream = invoice.as_tlv_stream();
1564 tlv_stream.3.node_id = Some(&invalid_pubkey);
1566 match Invoice::try_from(tlv_stream.to_bytes()) {
1567 Ok(_) => panic!("expected error"),
1569 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1575 fn fails_parsing_invoice_without_signature() {
1576 let mut buffer = Vec::new();
1577 OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1582 .sign(payer_sign).unwrap()
1583 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1586 .write(&mut buffer).unwrap();
1588 match Invoice::try_from(buffer) {
1589 Ok(_) => panic!("expected error"),
1590 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1595 fn fails_parsing_invoice_with_invalid_signature() {
1596 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1599 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1601 .sign(payer_sign).unwrap()
1602 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1604 .sign(recipient_sign).unwrap();
1605 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1606 *last_signature_byte = last_signature_byte.wrapping_add(1);
1608 let mut buffer = Vec::new();
1609 invoice.write(&mut buffer).unwrap();
1611 match Invoice::try_from(buffer) {
1612 Ok(_) => panic!("expected error"),
1614 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1620 fn fails_parsing_invoice_with_extra_tlv_records() {
1621 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1624 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1626 .sign(payer_sign).unwrap()
1627 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1629 .sign(recipient_sign).unwrap();
1631 let mut encoded_invoice = Vec::new();
1632 invoice.write(&mut encoded_invoice).unwrap();
1633 BigSize(1002).write(&mut encoded_invoice).unwrap();
1634 BigSize(32).write(&mut encoded_invoice).unwrap();
1635 [42u8; 32].write(&mut encoded_invoice).unwrap();
1637 match Invoice::try_from(encoded_invoice) {
1638 Ok(_) => panic!("expected error"),
1639 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),