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.checked_mul(invoice_request.quantity().unwrap_or(1))
152 .ok_or(SemanticError::InvalidAmount)?
154 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
155 None => return Err(SemanticError::MissingAmount),
159 let contents = InvoiceContents::ForOffer {
160 invoice_request: invoice_request.contents.clone(),
161 fields: InvoiceFields {
162 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
163 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
164 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
168 Self::new(&invoice_request.bytes, contents)
171 pub(super) fn for_refund(
172 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
173 payment_hash: PaymentHash, signing_pubkey: PublicKey
174 ) -> Result<Self, SemanticError> {
175 let contents = InvoiceContents::ForRefund {
176 refund: refund.contents.clone(),
177 fields: InvoiceFields {
178 payment_paths, created_at, relative_expiry: None, payment_hash,
179 amount_msats: refund.amount_msats(), fallbacks: None,
180 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
184 Self::new(&refund.bytes, contents)
187 fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
188 if contents.fields().payment_paths.is_empty() {
189 return Err(SemanticError::MissingPaths);
192 Ok(Self { invreq_bytes, invoice: contents })
195 /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
196 /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
198 /// Successive calls to this method will override the previous setting.
199 pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
200 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
201 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
205 /// Adds a P2WSH address to [`Invoice::fallbacks`].
207 /// Successive calls to this method will add another address. Caller is responsible for not
208 /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
209 pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
210 let address = FallbackAddress {
211 version: WitnessVersion::V0.to_num(),
212 program: Vec::from(&script_hash.into_inner()[..]),
214 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
218 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
220 /// Successive calls to this method will add another address. Caller is responsible for not
221 /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
222 pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
223 let address = FallbackAddress {
224 version: WitnessVersion::V0.to_num(),
225 program: Vec::from(&pubkey_hash.into_inner()[..]),
227 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
231 /// Adds a P2TR address to [`Invoice::fallbacks`].
233 /// Successive calls to this method will add another address. Caller is responsible for not
234 /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
235 pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
236 let address = FallbackAddress {
237 version: WitnessVersion::V1.to_num(),
238 program: Vec::from(&output_key.serialize()[..]),
240 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
244 /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
245 pub fn allow_mpp(mut self) -> Self {
246 self.invoice.fields_mut().features.set_basic_mpp_optional();
250 /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
251 /// [`UnsignedInvoice::sign`].
252 pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
253 #[cfg(feature = "std")] {
254 if self.invoice.is_offer_or_refund_expired() {
255 return Err(SemanticError::AlreadyExpired);
259 let InvoiceBuilder { invreq_bytes, invoice } = self;
260 Ok(UnsignedInvoice { invreq_bytes, invoice })
264 /// A semantically valid [`Invoice`] that hasn't been signed.
265 pub struct UnsignedInvoice<'a> {
266 invreq_bytes: &'a Vec<u8>,
267 invoice: InvoiceContents,
270 impl<'a> UnsignedInvoice<'a> {
271 /// The public key corresponding to the key needed to sign the invoice.
272 pub fn signing_pubkey(&self) -> PublicKey {
273 self.invoice.fields().signing_pubkey
276 /// Signs the invoice using the given function.
277 pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
279 F: FnOnce(&Message) -> Result<Signature, E>
281 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
282 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
284 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
285 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
286 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
288 let mut bytes = Vec::new();
289 unsigned_tlv_stream.write(&mut bytes).unwrap();
291 let pubkey = self.invoice.fields().signing_pubkey;
292 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
294 // Append the signature TLV record to the bytes.
295 let signature_tlv_stream = SignatureTlvStreamRef {
296 signature: Some(&signature),
298 signature_tlv_stream.write(&mut bytes).unwrap();
302 contents: self.invoice,
308 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
310 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
311 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
313 /// [`Offer`]: crate::offers::offer::Offer
314 /// [`Refund`]: crate::offers::refund::Refund
315 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
316 #[derive(Clone, Debug, PartialEq)]
319 contents: InvoiceContents,
320 signature: Signature,
323 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
325 /// [`Offer`]: crate::offers::offer::Offer
326 /// [`Refund`]: crate::offers::refund::Refund
327 #[derive(Clone, Debug, PartialEq)]
328 enum InvoiceContents {
329 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
331 /// [`Offer`]: crate::offers::offer::Offer
333 invoice_request: InvoiceRequestContents,
334 fields: InvoiceFields,
336 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
338 /// [`Refund`]: crate::offers::refund::Refund
340 refund: RefundContents,
341 fields: InvoiceFields,
345 /// Invoice-specific fields for an `invoice` message.
346 #[derive(Clone, Debug, PartialEq)]
347 struct InvoiceFields {
348 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
349 created_at: Duration,
350 relative_expiry: Option<Duration>,
351 payment_hash: PaymentHash,
353 fallbacks: Option<Vec<FallbackAddress>>,
354 features: Bolt12InvoiceFeatures,
355 signing_pubkey: PublicKey,
359 /// Paths to the recipient originating from publicly reachable nodes, including information
360 /// needed for routing payments across them.
362 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
363 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
364 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
365 &self.contents.fields().payment_paths[..]
368 /// Duration since the Unix epoch when the invoice was created.
369 pub fn created_at(&self) -> Duration {
370 self.contents.fields().created_at
373 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
375 pub fn relative_expiry(&self) -> Duration {
376 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
379 /// Whether the invoice has expired.
380 #[cfg(feature = "std")]
381 pub fn is_expired(&self) -> bool {
382 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
383 match absolute_expiry {
384 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
385 Ok(elapsed) => elapsed > seconds_from_epoch,
392 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
393 pub fn payment_hash(&self) -> PaymentHash {
394 self.contents.fields().payment_hash
397 /// The minimum amount required for a successful payment of the invoice.
398 pub fn amount_msats(&self) -> u64 {
399 self.contents.fields().amount_msats
402 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
404 pub fn fallbacks(&self) -> Vec<Address> {
405 let network = match self.network() {
406 None => return Vec::new(),
407 Some(network) => network,
410 let to_valid_address = |address: &FallbackAddress| {
411 let version = match WitnessVersion::try_from(address.version) {
412 Ok(version) => version,
413 Err(_) => return None,
416 let program = &address.program;
417 if program.len() < 2 || program.len() > 40 {
421 let address = Address {
422 payload: Payload::WitnessProgram {
424 program: address.program.clone(),
429 if !address.is_standard() && version == WitnessVersion::V0 {
436 self.contents.fields().fallbacks
438 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
439 .unwrap_or_else(Vec::new)
442 fn network(&self) -> Option<Network> {
443 let chain = self.contents.chain();
444 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
445 Some(Network::Bitcoin)
446 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
447 Some(Network::Testnet)
448 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
449 Some(Network::Signet)
450 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
451 Some(Network::Regtest)
457 /// Features pertaining to paying an invoice.
458 pub fn features(&self) -> &Bolt12InvoiceFeatures {
459 &self.contents.fields().features
462 /// The public key corresponding to the key used to sign the invoice.
463 pub fn signing_pubkey(&self) -> PublicKey {
464 self.contents.fields().signing_pubkey
467 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
468 pub fn signature(&self) -> Signature {
472 /// Hash that was used for signing the invoice.
473 pub fn signable_hash(&self) -> [u8; 32] {
474 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
478 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
479 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
480 self.contents.as_tlv_stream();
481 let signature_tlv_stream = SignatureTlvStreamRef {
482 signature: Some(&self.signature),
484 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
485 signature_tlv_stream)
489 impl InvoiceContents {
490 /// Whether the original offer or refund has expired.
491 #[cfg(feature = "std")]
492 fn is_offer_or_refund_expired(&self) -> bool {
494 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
495 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
499 fn chain(&self) -> ChainHash {
501 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
502 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
506 fn fields(&self) -> &InvoiceFields {
508 InvoiceContents::ForOffer { fields, .. } => fields,
509 InvoiceContents::ForRefund { fields, .. } => fields,
513 fn fields_mut(&mut self) -> &mut InvoiceFields {
515 InvoiceContents::ForOffer { fields, .. } => fields,
516 InvoiceContents::ForRefund { fields, .. } => fields,
520 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
521 let (payer, offer, invoice_request) = match self {
522 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
523 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
525 let invoice = self.fields().as_tlv_stream();
527 (payer, offer, invoice_request, invoice)
532 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
534 if self.features == Bolt12InvoiceFeatures::empty() { None }
535 else { Some(&self.features) }
538 InvoiceTlvStreamRef {
539 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
540 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
541 created_at: Some(self.created_at.as_secs()),
542 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
543 payment_hash: Some(&self.payment_hash),
544 amount: Some(self.amount_msats),
545 fallbacks: self.fallbacks.as_ref(),
547 node_id: Some(&self.signing_pubkey),
552 impl Writeable for Invoice {
553 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
554 WithoutLength(&self.bytes).write(writer)
558 impl Writeable for InvoiceContents {
559 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
560 self.as_tlv_stream().write(writer)
564 impl TryFrom<Vec<u8>> for Invoice {
565 type Error = ParseError;
567 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
568 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
569 Invoice::try_from(parsed_invoice)
573 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
574 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
575 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
576 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
577 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
578 (168, payment_hash: PaymentHash),
579 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
580 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
581 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
582 (176, node_id: PublicKey),
585 type BlindedPathIter<'a> = core::iter::Map<
586 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
587 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
590 type BlindedPayInfoIter<'a> = core::iter::Map<
591 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
592 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
595 /// Information needed to route a payment across a [`BlindedPath`].
596 #[derive(Clone, Debug, PartialEq)]
597 pub struct BlindedPayInfo {
598 /// Base fee charged (in millisatoshi) for the entire blinded path.
599 pub fee_base_msat: u32,
601 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
602 /// (i.e., 10,000 is 1%).
603 pub fee_proportional_millionths: u32,
605 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
607 pub cltv_expiry_delta: u16,
609 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
610 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
611 /// seen by the recipient.
612 pub htlc_minimum_msat: u64,
614 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
615 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
616 /// seen by the recipient.
617 pub htlc_maximum_msat: u64,
619 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
621 pub features: BlindedHopFeatures,
624 impl_writeable!(BlindedPayInfo, {
626 fee_proportional_millionths,
633 /// Wire representation for an on-chain fallback address.
634 #[derive(Clone, Debug, PartialEq)]
635 pub(super) struct FallbackAddress {
640 impl_writeable!(FallbackAddress, { version, program });
642 type FullInvoiceTlvStream =
643 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
646 type FullInvoiceTlvStreamRef<'a> = (
647 PayerTlvStreamRef<'a>,
648 OfferTlvStreamRef<'a>,
649 InvoiceRequestTlvStreamRef<'a>,
650 InvoiceTlvStreamRef<'a>,
651 SignatureTlvStreamRef<'a>,
654 impl SeekReadable for FullInvoiceTlvStream {
655 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
656 let payer = SeekReadable::read(r)?;
657 let offer = SeekReadable::read(r)?;
658 let invoice_request = SeekReadable::read(r)?;
659 let invoice = SeekReadable::read(r)?;
660 let signature = SeekReadable::read(r)?;
662 Ok((payer, offer, invoice_request, invoice, signature))
666 type PartialInvoiceTlvStream =
667 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
669 type PartialInvoiceTlvStreamRef<'a> = (
670 PayerTlvStreamRef<'a>,
671 OfferTlvStreamRef<'a>,
672 InvoiceRequestTlvStreamRef<'a>,
673 InvoiceTlvStreamRef<'a>,
676 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
677 type Error = ParseError;
679 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
680 let ParsedMessage { bytes, tlv_stream } = invoice;
682 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
683 SignatureTlvStream { signature },
685 let contents = InvoiceContents::try_from(
686 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
689 let signature = match signature {
690 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
691 Some(signature) => signature,
693 let pubkey = contents.fields().signing_pubkey;
694 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
696 Ok(Invoice { bytes, contents, signature })
700 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
701 type Error = SemanticError;
703 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
707 invoice_request_tlv_stream,
709 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
714 let payment_paths = match (paths, blindedpay) {
715 (None, _) => return Err(SemanticError::MissingPaths),
716 (_, None) => return Err(SemanticError::InvalidPayInfo),
717 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
718 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
719 return Err(SemanticError::InvalidPayInfo);
721 (Some(paths), Some(blindedpay)) => {
722 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
726 let created_at = match created_at {
727 None => return Err(SemanticError::MissingCreationTime),
728 Some(timestamp) => Duration::from_secs(timestamp),
731 let relative_expiry = relative_expiry
732 .map(Into::<u64>::into)
733 .map(Duration::from_secs);
735 let payment_hash = match payment_hash {
736 None => return Err(SemanticError::MissingPaymentHash),
737 Some(payment_hash) => payment_hash,
740 let amount_msats = match amount {
741 None => return Err(SemanticError::MissingAmount),
742 Some(amount) => amount,
745 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
747 let signing_pubkey = match node_id {
748 None => return Err(SemanticError::MissingSigningPubkey),
749 Some(node_id) => node_id,
752 let fields = InvoiceFields {
753 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
754 features, signing_pubkey,
757 match offer_tlv_stream.node_id {
758 Some(expected_signing_pubkey) => {
759 if fields.signing_pubkey != expected_signing_pubkey {
760 return Err(SemanticError::InvalidSigningPubkey);
763 let invoice_request = InvoiceRequestContents::try_from(
764 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
766 Ok(InvoiceContents::ForOffer { invoice_request, fields })
769 let refund = RefundContents::try_from(
770 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
772 Ok(InvoiceContents::ForRefund { refund, fields })
780 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
782 use bitcoin::blockdata::script::Script;
783 use bitcoin::hashes::Hash;
784 use bitcoin::network::constants::Network;
785 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
786 use bitcoin::util::address::{Address, Payload, WitnessVersion};
787 use bitcoin::util::schnorr::TweakedPublicKey;
788 use core::convert::TryFrom;
789 use core::time::Duration;
790 use crate::ln::msgs::DecodeError;
791 use crate::ln::features::Bolt12InvoiceFeatures;
792 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
793 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
794 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
795 use crate::offers::parse::{ParseError, SemanticError};
796 use crate::offers::payer::PayerTlvStreamRef;
797 use crate::offers::refund::RefundBuilder;
798 use crate::offers::test_utils::*;
799 use crate::util::ser::{BigSize, Iterable, Writeable};
802 fn to_bytes(&self) -> Vec<u8>;
805 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
806 fn to_bytes(&self) -> Vec<u8> {
807 let mut buffer = Vec::new();
808 self.0.write(&mut buffer).unwrap();
809 self.1.write(&mut buffer).unwrap();
810 self.2.write(&mut buffer).unwrap();
811 self.3.write(&mut buffer).unwrap();
812 self.4.write(&mut buffer).unwrap();
818 fn builds_invoice_for_offer_with_defaults() {
819 let payment_paths = payment_paths();
820 let payment_hash = payment_hash();
822 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
825 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
827 .sign(payer_sign).unwrap()
828 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
830 .sign(recipient_sign).unwrap();
832 let mut buffer = Vec::new();
833 invoice.write(&mut buffer).unwrap();
835 assert_eq!(invoice.bytes, buffer.as_slice());
836 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
837 assert_eq!(invoice.created_at(), now);
838 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
839 #[cfg(feature = "std")]
840 assert!(!invoice.is_expired());
841 assert_eq!(invoice.payment_hash(), payment_hash);
842 assert_eq!(invoice.amount_msats(), 1000);
843 assert_eq!(invoice.fallbacks(), vec![]);
844 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
845 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
847 merkle::verify_signature(
848 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
852 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
853 let pubkey = recipient_pubkey().into();
854 let secp_ctx = Secp256k1::verification_only();
855 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
858 invoice.as_tlv_stream(),
860 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
866 description: Some(&String::from("foo")),
868 absolute_expiry: None,
872 node_id: Some(&recipient_pubkey()),
874 InvoiceRequestTlvStreamRef {
879 payer_id: Some(&payer_pubkey()),
882 InvoiceTlvStreamRef {
883 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
884 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
885 created_at: Some(now.as_secs()),
886 relative_expiry: None,
887 payment_hash: Some(&payment_hash),
891 node_id: Some(&recipient_pubkey()),
893 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
897 if let Err(e) = Invoice::try_from(buffer) {
898 panic!("error parsing invoice: {:?}", e);
903 fn builds_invoice_for_refund_with_defaults() {
904 let payment_paths = payment_paths();
905 let payment_hash = payment_hash();
907 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
909 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
912 .sign(recipient_sign).unwrap();
914 let mut buffer = Vec::new();
915 invoice.write(&mut buffer).unwrap();
917 assert_eq!(invoice.bytes, buffer.as_slice());
918 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
919 assert_eq!(invoice.created_at(), now);
920 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
921 #[cfg(feature = "std")]
922 assert!(!invoice.is_expired());
923 assert_eq!(invoice.payment_hash(), payment_hash);
924 assert_eq!(invoice.amount_msats(), 1000);
925 assert_eq!(invoice.fallbacks(), vec![]);
926 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
927 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
929 merkle::verify_signature(
930 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
935 invoice.as_tlv_stream(),
937 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
943 description: Some(&String::from("foo")),
945 absolute_expiry: None,
951 InvoiceRequestTlvStreamRef {
956 payer_id: Some(&payer_pubkey()),
959 InvoiceTlvStreamRef {
960 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
961 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
962 created_at: Some(now.as_secs()),
963 relative_expiry: None,
964 payment_hash: Some(&payment_hash),
968 node_id: Some(&recipient_pubkey()),
970 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
974 if let Err(e) = Invoice::try_from(buffer) {
975 panic!("error parsing invoice: {:?}", e);
979 #[cfg(feature = "std")]
981 fn builds_invoice_from_offer_with_expiration() {
982 let future_expiry = Duration::from_secs(u64::max_value());
983 let past_expiry = Duration::from_secs(0);
985 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
987 .absolute_expiry(future_expiry)
989 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
991 .sign(payer_sign).unwrap()
992 .respond_with(payment_paths(), payment_hash())
996 panic!("error building invoice: {:?}", e);
999 match OfferBuilder::new("foo".into(), recipient_pubkey())
1001 .absolute_expiry(past_expiry)
1003 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1005 .sign(payer_sign).unwrap()
1006 .respond_with(payment_paths(), payment_hash())
1010 Ok(_) => panic!("expected error"),
1011 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1015 #[cfg(feature = "std")]
1017 fn builds_invoice_from_refund_with_expiration() {
1018 let future_expiry = Duration::from_secs(u64::max_value());
1019 let past_expiry = Duration::from_secs(0);
1021 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1022 .absolute_expiry(future_expiry)
1024 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1028 panic!("error building invoice: {:?}", e);
1031 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1032 .absolute_expiry(past_expiry)
1034 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1038 Ok(_) => panic!("expected error"),
1039 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1044 fn builds_invoice_with_relative_expiry() {
1046 let one_hour = Duration::from_secs(3600);
1048 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1051 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1053 .sign(payer_sign).unwrap()
1054 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1055 .relative_expiry(one_hour.as_secs() as u32)
1057 .sign(recipient_sign).unwrap();
1058 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1059 #[cfg(feature = "std")]
1060 assert!(!invoice.is_expired());
1061 assert_eq!(invoice.relative_expiry(), one_hour);
1062 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1064 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1067 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1069 .sign(payer_sign).unwrap()
1070 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1071 .relative_expiry(one_hour.as_secs() as u32 - 1)
1073 .sign(recipient_sign).unwrap();
1074 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1075 #[cfg(feature = "std")]
1076 assert!(invoice.is_expired());
1077 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1078 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1082 fn builds_invoice_with_amount_from_request() {
1083 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1086 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1087 .amount_msats(1001).unwrap()
1089 .sign(payer_sign).unwrap()
1090 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1092 .sign(recipient_sign).unwrap();
1093 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1094 assert_eq!(invoice.amount_msats(), 1001);
1095 assert_eq!(tlv_stream.amount, Some(1001));
1099 fn builds_invoice_with_quantity_from_request() {
1100 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1102 .supported_quantity(Quantity::Unbounded)
1104 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1105 .quantity(2).unwrap()
1107 .sign(payer_sign).unwrap()
1108 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1110 .sign(recipient_sign).unwrap();
1111 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1112 assert_eq!(invoice.amount_msats(), 2000);
1113 assert_eq!(tlv_stream.amount, Some(2000));
1115 match OfferBuilder::new("foo".into(), recipient_pubkey())
1117 .supported_quantity(Quantity::Unbounded)
1119 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1120 .quantity(u64::max_value()).unwrap()
1122 .sign(payer_sign).unwrap()
1123 .respond_with_no_std(payment_paths(), payment_hash(), now())
1125 Ok(_) => panic!("expected error"),
1126 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1131 fn builds_invoice_with_fallback_address() {
1132 let script = Script::new();
1133 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1134 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1135 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1137 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1140 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142 .sign(payer_sign).unwrap()
1143 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1144 .fallback_v0_p2wsh(&script.wscript_hash())
1145 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1146 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1148 .sign(recipient_sign).unwrap();
1149 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1151 invoice.fallbacks(),
1153 Address::p2wsh(&script, Network::Bitcoin),
1154 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1155 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1159 tlv_stream.fallbacks,
1162 version: WitnessVersion::V0.to_num(),
1163 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1166 version: WitnessVersion::V0.to_num(),
1167 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1170 version: WitnessVersion::V1.to_num(),
1171 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1178 fn builds_invoice_with_allow_mpp() {
1179 let mut features = Bolt12InvoiceFeatures::empty();
1180 features.set_basic_mpp_optional();
1182 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1185 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1187 .sign(payer_sign).unwrap()
1188 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1191 .sign(recipient_sign).unwrap();
1192 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1193 assert_eq!(invoice.features(), &features);
1194 assert_eq!(tlv_stream.features, Some(&features));
1198 fn fails_signing_invoice() {
1199 match OfferBuilder::new("foo".into(), recipient_pubkey())
1202 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1204 .sign(payer_sign).unwrap()
1205 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1209 Ok(_) => panic!("expected error"),
1210 Err(e) => assert_eq!(e, SignError::Signing(())),
1213 match OfferBuilder::new("foo".into(), recipient_pubkey())
1216 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1218 .sign(payer_sign).unwrap()
1219 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1223 Ok(_) => panic!("expected error"),
1224 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1229 fn parses_invoice_with_payment_paths() {
1230 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1233 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1235 .sign(payer_sign).unwrap()
1236 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1238 .sign(recipient_sign).unwrap();
1240 let mut buffer = Vec::new();
1241 invoice.write(&mut buffer).unwrap();
1243 if let Err(e) = Invoice::try_from(buffer) {
1244 panic!("error parsing invoice: {:?}", e);
1247 let mut tlv_stream = invoice.as_tlv_stream();
1248 tlv_stream.3.paths = None;
1250 match Invoice::try_from(tlv_stream.to_bytes()) {
1251 Ok(_) => panic!("expected error"),
1252 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1255 let mut tlv_stream = invoice.as_tlv_stream();
1256 tlv_stream.3.blindedpay = None;
1258 match Invoice::try_from(tlv_stream.to_bytes()) {
1259 Ok(_) => panic!("expected error"),
1260 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1263 let empty_payment_paths = vec![];
1264 let mut tlv_stream = invoice.as_tlv_stream();
1265 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1267 match Invoice::try_from(tlv_stream.to_bytes()) {
1268 Ok(_) => panic!("expected error"),
1269 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1272 let mut payment_paths = payment_paths();
1273 payment_paths.pop();
1274 let mut tlv_stream = invoice.as_tlv_stream();
1275 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1277 match Invoice::try_from(tlv_stream.to_bytes()) {
1278 Ok(_) => panic!("expected error"),
1279 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1284 fn parses_invoice_with_created_at() {
1285 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1288 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1290 .sign(payer_sign).unwrap()
1291 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1293 .sign(recipient_sign).unwrap();
1295 let mut buffer = Vec::new();
1296 invoice.write(&mut buffer).unwrap();
1298 if let Err(e) = Invoice::try_from(buffer) {
1299 panic!("error parsing invoice: {:?}", e);
1302 let mut tlv_stream = invoice.as_tlv_stream();
1303 tlv_stream.3.created_at = None;
1305 match Invoice::try_from(tlv_stream.to_bytes()) {
1306 Ok(_) => panic!("expected error"),
1308 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1314 fn parses_invoice_with_relative_expiry() {
1315 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1318 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1320 .sign(payer_sign).unwrap()
1321 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1322 .relative_expiry(3600)
1324 .sign(recipient_sign).unwrap();
1326 let mut buffer = Vec::new();
1327 invoice.write(&mut buffer).unwrap();
1329 match Invoice::try_from(buffer) {
1330 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1331 Err(e) => panic!("error parsing invoice: {:?}", e),
1336 fn parses_invoice_with_payment_hash() {
1337 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1340 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1342 .sign(payer_sign).unwrap()
1343 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1345 .sign(recipient_sign).unwrap();
1347 let mut buffer = Vec::new();
1348 invoice.write(&mut buffer).unwrap();
1350 if let Err(e) = Invoice::try_from(buffer) {
1351 panic!("error parsing invoice: {:?}", e);
1354 let mut tlv_stream = invoice.as_tlv_stream();
1355 tlv_stream.3.payment_hash = None;
1357 match Invoice::try_from(tlv_stream.to_bytes()) {
1358 Ok(_) => panic!("expected error"),
1360 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1366 fn parses_invoice_with_amount() {
1367 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1370 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1372 .sign(payer_sign).unwrap()
1373 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1375 .sign(recipient_sign).unwrap();
1377 let mut buffer = Vec::new();
1378 invoice.write(&mut buffer).unwrap();
1380 if let Err(e) = Invoice::try_from(buffer) {
1381 panic!("error parsing invoice: {:?}", e);
1384 let mut tlv_stream = invoice.as_tlv_stream();
1385 tlv_stream.3.amount = None;
1387 match Invoice::try_from(tlv_stream.to_bytes()) {
1388 Ok(_) => panic!("expected error"),
1389 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1394 fn parses_invoice_with_allow_mpp() {
1395 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1398 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1400 .sign(payer_sign).unwrap()
1401 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1404 .sign(recipient_sign).unwrap();
1406 let mut buffer = Vec::new();
1407 invoice.write(&mut buffer).unwrap();
1409 match Invoice::try_from(buffer) {
1411 let mut features = Bolt12InvoiceFeatures::empty();
1412 features.set_basic_mpp_optional();
1413 assert_eq!(invoice.features(), &features);
1415 Err(e) => panic!("error parsing invoice: {:?}", e),
1420 fn parses_invoice_with_fallback_address() {
1421 let script = Script::new();
1422 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1423 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1424 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1426 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1429 let invoice_request = offer
1430 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1432 .sign(payer_sign).unwrap();
1433 let mut unsigned_invoice = invoice_request
1434 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1435 .fallback_v0_p2wsh(&script.wscript_hash())
1436 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1437 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1440 // Only standard addresses will be included.
1441 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1442 // Non-standard addresses
1443 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1444 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1445 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1447 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1448 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1450 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1451 let mut buffer = Vec::new();
1452 invoice.write(&mut buffer).unwrap();
1454 match Invoice::try_from(buffer) {
1457 invoice.fallbacks(),
1459 Address::p2wsh(&script, Network::Bitcoin),
1460 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1461 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1463 payload: Payload::WitnessProgram {
1464 version: WitnessVersion::V1,
1465 program: vec![0u8; 33],
1467 network: Network::Bitcoin,
1470 payload: Payload::WitnessProgram {
1471 version: WitnessVersion::V2,
1472 program: vec![0u8; 40],
1474 network: Network::Bitcoin,
1479 Err(e) => panic!("error parsing invoice: {:?}", e),
1484 fn parses_invoice_with_node_id() {
1485 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1488 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1490 .sign(payer_sign).unwrap()
1491 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1493 .sign(recipient_sign).unwrap();
1495 let mut buffer = Vec::new();
1496 invoice.write(&mut buffer).unwrap();
1498 if let Err(e) = Invoice::try_from(buffer) {
1499 panic!("error parsing invoice: {:?}", e);
1502 let mut tlv_stream = invoice.as_tlv_stream();
1503 tlv_stream.3.node_id = None;
1505 match Invoice::try_from(tlv_stream.to_bytes()) {
1506 Ok(_) => panic!("expected error"),
1508 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1512 let invalid_pubkey = payer_pubkey();
1513 let mut tlv_stream = invoice.as_tlv_stream();
1514 tlv_stream.3.node_id = Some(&invalid_pubkey);
1516 match Invoice::try_from(tlv_stream.to_bytes()) {
1517 Ok(_) => panic!("expected error"),
1519 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1525 fn fails_parsing_invoice_without_signature() {
1526 let mut buffer = Vec::new();
1527 OfferBuilder::new("foo".into(), recipient_pubkey())
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1532 .sign(payer_sign).unwrap()
1533 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1536 .write(&mut buffer).unwrap();
1538 match Invoice::try_from(buffer) {
1539 Ok(_) => panic!("expected error"),
1540 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1545 fn fails_parsing_invoice_with_invalid_signature() {
1546 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1549 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1551 .sign(payer_sign).unwrap()
1552 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1554 .sign(recipient_sign).unwrap();
1555 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1556 *last_signature_byte = last_signature_byte.wrapping_add(1);
1558 let mut buffer = Vec::new();
1559 invoice.write(&mut buffer).unwrap();
1561 match Invoice::try_from(buffer) {
1562 Ok(_) => panic!("expected error"),
1564 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1570 fn fails_parsing_invoice_with_extra_tlv_records() {
1571 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1574 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1576 .sign(payer_sign).unwrap()
1577 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1579 .sign(recipient_sign).unwrap();
1581 let mut encoded_invoice = Vec::new();
1582 invoice.write(&mut encoded_invoice).unwrap();
1583 BigSize(1002).write(&mut encoded_invoice).unwrap();
1584 BigSize(32).write(&mut encoded_invoice).unwrap();
1585 [42u8; 32].write(&mut encoded_invoice).unwrap();
1587 match Invoice::try_from(encoded_invoice) {
1588 Ok(_) => panic!("expected error"),
1589 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),