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)]
317 #[cfg_attr(test, derive(PartialEq))]
320 contents: InvoiceContents,
321 signature: Signature,
324 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
326 /// [`Offer`]: crate::offers::offer::Offer
327 /// [`Refund`]: crate::offers::refund::Refund
328 #[derive(Clone, Debug)]
329 #[cfg_attr(test, derive(PartialEq))]
330 enum InvoiceContents {
331 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
333 /// [`Offer`]: crate::offers::offer::Offer
335 invoice_request: InvoiceRequestContents,
336 fields: InvoiceFields,
338 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
340 /// [`Refund`]: crate::offers::refund::Refund
342 refund: RefundContents,
343 fields: InvoiceFields,
347 /// Invoice-specific fields for an `invoice` message.
348 #[derive(Clone, Debug, PartialEq)]
349 struct InvoiceFields {
350 payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
351 created_at: Duration,
352 relative_expiry: Option<Duration>,
353 payment_hash: PaymentHash,
355 fallbacks: Option<Vec<FallbackAddress>>,
356 features: Bolt12InvoiceFeatures,
357 signing_pubkey: PublicKey,
361 /// Paths to the recipient originating from publicly reachable nodes, including information
362 /// needed for routing payments across them.
364 /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
365 /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
366 pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
367 &self.contents.fields().payment_paths[..]
370 /// Duration since the Unix epoch when the invoice was created.
371 pub fn created_at(&self) -> Duration {
372 self.contents.fields().created_at
375 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
377 pub fn relative_expiry(&self) -> Duration {
378 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
381 /// Whether the invoice has expired.
382 #[cfg(feature = "std")]
383 pub fn is_expired(&self) -> bool {
384 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
385 match absolute_expiry {
386 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
387 Ok(elapsed) => elapsed > seconds_from_epoch,
394 /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
395 pub fn payment_hash(&self) -> PaymentHash {
396 self.contents.fields().payment_hash
399 /// The minimum amount required for a successful payment of the invoice.
400 pub fn amount_msats(&self) -> u64 {
401 self.contents.fields().amount_msats
404 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
406 pub fn fallbacks(&self) -> Vec<Address> {
407 let network = match self.network() {
408 None => return Vec::new(),
409 Some(network) => network,
412 let to_valid_address = |address: &FallbackAddress| {
413 let version = match WitnessVersion::try_from(address.version) {
414 Ok(version) => version,
415 Err(_) => return None,
418 let program = &address.program;
419 if program.len() < 2 || program.len() > 40 {
423 let address = Address {
424 payload: Payload::WitnessProgram {
426 program: address.program.clone(),
431 if !address.is_standard() && version == WitnessVersion::V0 {
438 self.contents.fields().fallbacks
440 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
441 .unwrap_or_else(Vec::new)
444 fn network(&self) -> Option<Network> {
445 let chain = self.contents.chain();
446 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
447 Some(Network::Bitcoin)
448 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
449 Some(Network::Testnet)
450 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
451 Some(Network::Signet)
452 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
453 Some(Network::Regtest)
459 /// Features pertaining to paying an invoice.
460 pub fn features(&self) -> &Bolt12InvoiceFeatures {
461 &self.contents.fields().features
464 /// The public key corresponding to the key used to sign the invoice.
465 pub fn signing_pubkey(&self) -> PublicKey {
466 self.contents.fields().signing_pubkey
469 /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
470 pub fn signature(&self) -> Signature {
474 /// Hash that was used for signing the invoice.
475 pub fn signable_hash(&self) -> [u8; 32] {
476 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
480 fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
481 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
482 self.contents.as_tlv_stream();
483 let signature_tlv_stream = SignatureTlvStreamRef {
484 signature: Some(&self.signature),
486 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
487 signature_tlv_stream)
491 impl InvoiceContents {
492 /// Whether the original offer or refund has expired.
493 #[cfg(feature = "std")]
494 fn is_offer_or_refund_expired(&self) -> bool {
496 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
497 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
501 fn chain(&self) -> ChainHash {
503 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
504 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
508 fn fields(&self) -> &InvoiceFields {
510 InvoiceContents::ForOffer { fields, .. } => fields,
511 InvoiceContents::ForRefund { fields, .. } => fields,
515 fn fields_mut(&mut self) -> &mut InvoiceFields {
517 InvoiceContents::ForOffer { fields, .. } => fields,
518 InvoiceContents::ForRefund { fields, .. } => fields,
522 fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
523 let (payer, offer, invoice_request) = match self {
524 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
525 InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
527 let invoice = self.fields().as_tlv_stream();
529 (payer, offer, invoice_request, invoice)
534 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
536 if self.features == Bolt12InvoiceFeatures::empty() { None }
537 else { Some(&self.features) }
540 InvoiceTlvStreamRef {
541 paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
542 blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
543 created_at: Some(self.created_at.as_secs()),
544 relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
545 payment_hash: Some(&self.payment_hash),
546 amount: Some(self.amount_msats),
547 fallbacks: self.fallbacks.as_ref(),
549 node_id: Some(&self.signing_pubkey),
554 impl Writeable for Invoice {
555 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
556 WithoutLength(&self.bytes).write(writer)
560 impl Writeable for InvoiceContents {
561 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
562 self.as_tlv_stream().write(writer)
566 impl TryFrom<Vec<u8>> for Invoice {
567 type Error = ParseError;
569 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
570 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
571 Invoice::try_from(parsed_invoice)
575 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
576 (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
577 (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
578 (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
579 (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
580 (168, payment_hash: PaymentHash),
581 (170, amount: (u64, HighZeroBytesDroppedBigSize)),
582 (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
583 (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
584 (176, node_id: PublicKey),
587 type BlindedPathIter<'a> = core::iter::Map<
588 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
589 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
592 type BlindedPayInfoIter<'a> = core::iter::Map<
593 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
594 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
597 /// Information needed to route a payment across a [`BlindedPath`].
598 #[derive(Clone, Debug, PartialEq)]
599 pub struct BlindedPayInfo {
600 /// Base fee charged (in millisatoshi) for the entire blinded path.
601 pub fee_base_msat: u32,
603 /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
604 /// (i.e., 10,000 is 1%).
605 pub fee_proportional_millionths: u32,
607 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
609 pub cltv_expiry_delta: u16,
611 /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
612 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
613 /// seen by the recipient.
614 pub htlc_minimum_msat: u64,
616 /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
617 /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
618 /// seen by the recipient.
619 pub htlc_maximum_msat: u64,
621 /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
623 pub features: BlindedHopFeatures,
626 impl_writeable!(BlindedPayInfo, {
628 fee_proportional_millionths,
635 /// Wire representation for an on-chain fallback address.
636 #[derive(Clone, Debug, PartialEq)]
637 pub(super) struct FallbackAddress {
642 impl_writeable!(FallbackAddress, { version, program });
644 type FullInvoiceTlvStream =
645 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
648 type FullInvoiceTlvStreamRef<'a> = (
649 PayerTlvStreamRef<'a>,
650 OfferTlvStreamRef<'a>,
651 InvoiceRequestTlvStreamRef<'a>,
652 InvoiceTlvStreamRef<'a>,
653 SignatureTlvStreamRef<'a>,
656 impl SeekReadable for FullInvoiceTlvStream {
657 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
658 let payer = SeekReadable::read(r)?;
659 let offer = SeekReadable::read(r)?;
660 let invoice_request = SeekReadable::read(r)?;
661 let invoice = SeekReadable::read(r)?;
662 let signature = SeekReadable::read(r)?;
664 Ok((payer, offer, invoice_request, invoice, signature))
668 type PartialInvoiceTlvStream =
669 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
671 type PartialInvoiceTlvStreamRef<'a> = (
672 PayerTlvStreamRef<'a>,
673 OfferTlvStreamRef<'a>,
674 InvoiceRequestTlvStreamRef<'a>,
675 InvoiceTlvStreamRef<'a>,
678 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
679 type Error = ParseError;
681 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
682 let ParsedMessage { bytes, tlv_stream } = invoice;
684 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
685 SignatureTlvStream { signature },
687 let contents = InvoiceContents::try_from(
688 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
691 let signature = match signature {
692 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
693 Some(signature) => signature,
695 let pubkey = contents.fields().signing_pubkey;
696 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
698 Ok(Invoice { bytes, contents, signature })
702 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
703 type Error = SemanticError;
705 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
709 invoice_request_tlv_stream,
711 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
716 let payment_paths = match (paths, blindedpay) {
717 (None, _) => return Err(SemanticError::MissingPaths),
718 (_, None) => return Err(SemanticError::InvalidPayInfo),
719 (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
720 (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
721 return Err(SemanticError::InvalidPayInfo);
723 (Some(paths), Some(blindedpay)) => {
724 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
728 let created_at = match created_at {
729 None => return Err(SemanticError::MissingCreationTime),
730 Some(timestamp) => Duration::from_secs(timestamp),
733 let relative_expiry = relative_expiry
734 .map(Into::<u64>::into)
735 .map(Duration::from_secs);
737 let payment_hash = match payment_hash {
738 None => return Err(SemanticError::MissingPaymentHash),
739 Some(payment_hash) => payment_hash,
742 let amount_msats = match amount {
743 None => return Err(SemanticError::MissingAmount),
744 Some(amount) => amount,
747 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
749 let signing_pubkey = match node_id {
750 None => return Err(SemanticError::MissingSigningPubkey),
751 Some(node_id) => node_id,
754 let fields = InvoiceFields {
755 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
756 features, signing_pubkey,
759 match offer_tlv_stream.node_id {
760 Some(expected_signing_pubkey) => {
761 if fields.signing_pubkey != expected_signing_pubkey {
762 return Err(SemanticError::InvalidSigningPubkey);
765 let invoice_request = InvoiceRequestContents::try_from(
766 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
768 Ok(InvoiceContents::ForOffer { invoice_request, fields })
771 let refund = RefundContents::try_from(
772 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
774 Ok(InvoiceContents::ForRefund { refund, fields })
782 use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
784 use bitcoin::blockdata::script::Script;
785 use bitcoin::hashes::Hash;
786 use bitcoin::network::constants::Network;
787 use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
788 use bitcoin::util::address::{Address, Payload, WitnessVersion};
789 use bitcoin::util::schnorr::TweakedPublicKey;
790 use core::convert::TryFrom;
791 use core::time::Duration;
792 use crate::ln::msgs::DecodeError;
793 use crate::ln::features::Bolt12InvoiceFeatures;
794 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
795 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
796 use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
797 use crate::offers::parse::{ParseError, SemanticError};
798 use crate::offers::payer::PayerTlvStreamRef;
799 use crate::offers::refund::RefundBuilder;
800 use crate::offers::test_utils::*;
801 use crate::util::ser::{BigSize, Iterable, Writeable};
804 fn to_bytes(&self) -> Vec<u8>;
807 impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
808 fn to_bytes(&self) -> Vec<u8> {
809 let mut buffer = Vec::new();
810 self.0.write(&mut buffer).unwrap();
811 self.1.write(&mut buffer).unwrap();
812 self.2.write(&mut buffer).unwrap();
813 self.3.write(&mut buffer).unwrap();
814 self.4.write(&mut buffer).unwrap();
820 fn builds_invoice_for_offer_with_defaults() {
821 let payment_paths = payment_paths();
822 let payment_hash = payment_hash();
824 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
827 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
829 .sign(payer_sign).unwrap()
830 .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
832 .sign(recipient_sign).unwrap();
834 let mut buffer = Vec::new();
835 invoice.write(&mut buffer).unwrap();
837 assert_eq!(invoice.bytes, buffer.as_slice());
838 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
839 assert_eq!(invoice.created_at(), now);
840 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
841 #[cfg(feature = "std")]
842 assert!(!invoice.is_expired());
843 assert_eq!(invoice.payment_hash(), payment_hash);
844 assert_eq!(invoice.amount_msats(), 1000);
845 assert_eq!(invoice.fallbacks(), vec![]);
846 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
847 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
849 merkle::verify_signature(
850 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
854 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
855 let pubkey = recipient_pubkey().into();
856 let secp_ctx = Secp256k1::verification_only();
857 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
860 invoice.as_tlv_stream(),
862 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
868 description: Some(&String::from("foo")),
870 absolute_expiry: None,
874 node_id: Some(&recipient_pubkey()),
876 InvoiceRequestTlvStreamRef {
881 payer_id: Some(&payer_pubkey()),
884 InvoiceTlvStreamRef {
885 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
886 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
887 created_at: Some(now.as_secs()),
888 relative_expiry: None,
889 payment_hash: Some(&payment_hash),
893 node_id: Some(&recipient_pubkey()),
895 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
899 if let Err(e) = Invoice::try_from(buffer) {
900 panic!("error parsing invoice: {:?}", e);
905 fn builds_invoice_for_refund_with_defaults() {
906 let payment_paths = payment_paths();
907 let payment_hash = payment_hash();
909 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
911 .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
914 .sign(recipient_sign).unwrap();
916 let mut buffer = Vec::new();
917 invoice.write(&mut buffer).unwrap();
919 assert_eq!(invoice.bytes, buffer.as_slice());
920 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
921 assert_eq!(invoice.created_at(), now);
922 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
923 #[cfg(feature = "std")]
924 assert!(!invoice.is_expired());
925 assert_eq!(invoice.payment_hash(), payment_hash);
926 assert_eq!(invoice.amount_msats(), 1000);
927 assert_eq!(invoice.fallbacks(), vec![]);
928 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
929 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
931 merkle::verify_signature(
932 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
937 invoice.as_tlv_stream(),
939 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
945 description: Some(&String::from("foo")),
947 absolute_expiry: None,
953 InvoiceRequestTlvStreamRef {
958 payer_id: Some(&payer_pubkey()),
961 InvoiceTlvStreamRef {
962 paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
963 blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
964 created_at: Some(now.as_secs()),
965 relative_expiry: None,
966 payment_hash: Some(&payment_hash),
970 node_id: Some(&recipient_pubkey()),
972 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
976 if let Err(e) = Invoice::try_from(buffer) {
977 panic!("error parsing invoice: {:?}", e);
981 #[cfg(feature = "std")]
983 fn builds_invoice_from_offer_with_expiration() {
984 let future_expiry = Duration::from_secs(u64::max_value());
985 let past_expiry = Duration::from_secs(0);
987 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
989 .absolute_expiry(future_expiry)
991 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
993 .sign(payer_sign).unwrap()
994 .respond_with(payment_paths(), payment_hash())
998 panic!("error building invoice: {:?}", e);
1001 match OfferBuilder::new("foo".into(), recipient_pubkey())
1003 .absolute_expiry(past_expiry)
1005 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1007 .sign(payer_sign).unwrap()
1008 .respond_with(payment_paths(), payment_hash())
1012 Ok(_) => panic!("expected error"),
1013 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1017 #[cfg(feature = "std")]
1019 fn builds_invoice_from_refund_with_expiration() {
1020 let future_expiry = Duration::from_secs(u64::max_value());
1021 let past_expiry = Duration::from_secs(0);
1023 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1024 .absolute_expiry(future_expiry)
1026 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1030 panic!("error building invoice: {:?}", e);
1033 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1034 .absolute_expiry(past_expiry)
1036 .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1040 Ok(_) => panic!("expected error"),
1041 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1046 fn builds_invoice_with_relative_expiry() {
1048 let one_hour = Duration::from_secs(3600);
1050 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1053 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1055 .sign(payer_sign).unwrap()
1056 .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1057 .relative_expiry(one_hour.as_secs() as u32)
1059 .sign(recipient_sign).unwrap();
1060 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1061 #[cfg(feature = "std")]
1062 assert!(!invoice.is_expired());
1063 assert_eq!(invoice.relative_expiry(), one_hour);
1064 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1066 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1069 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 .sign(payer_sign).unwrap()
1072 .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1073 .relative_expiry(one_hour.as_secs() as u32 - 1)
1075 .sign(recipient_sign).unwrap();
1076 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1077 #[cfg(feature = "std")]
1078 assert!(invoice.is_expired());
1079 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1080 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1084 fn builds_invoice_with_amount_from_request() {
1085 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1088 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1089 .amount_msats(1001).unwrap()
1091 .sign(payer_sign).unwrap()
1092 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1094 .sign(recipient_sign).unwrap();
1095 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1096 assert_eq!(invoice.amount_msats(), 1001);
1097 assert_eq!(tlv_stream.amount, Some(1001));
1101 fn builds_invoice_with_quantity_from_request() {
1102 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1104 .supported_quantity(Quantity::Unbounded)
1106 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1107 .quantity(2).unwrap()
1109 .sign(payer_sign).unwrap()
1110 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1112 .sign(recipient_sign).unwrap();
1113 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1114 assert_eq!(invoice.amount_msats(), 2000);
1115 assert_eq!(tlv_stream.amount, Some(2000));
1117 match OfferBuilder::new("foo".into(), recipient_pubkey())
1119 .supported_quantity(Quantity::Unbounded)
1121 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1122 .quantity(u64::max_value()).unwrap()
1124 .sign(payer_sign).unwrap()
1125 .respond_with_no_std(payment_paths(), payment_hash(), now())
1127 Ok(_) => panic!("expected error"),
1128 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1133 fn builds_invoice_with_fallback_address() {
1134 let script = Script::new();
1135 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1136 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1137 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1139 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1142 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1144 .sign(payer_sign).unwrap()
1145 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1146 .fallback_v0_p2wsh(&script.wscript_hash())
1147 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1148 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1150 .sign(recipient_sign).unwrap();
1151 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1153 invoice.fallbacks(),
1155 Address::p2wsh(&script, Network::Bitcoin),
1156 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1157 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1161 tlv_stream.fallbacks,
1164 version: WitnessVersion::V0.to_num(),
1165 program: Vec::from(&script.wscript_hash().into_inner()[..]),
1168 version: WitnessVersion::V0.to_num(),
1169 program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1172 version: WitnessVersion::V1.to_num(),
1173 program: Vec::from(&tweaked_pubkey.serialize()[..]),
1180 fn builds_invoice_with_allow_mpp() {
1181 let mut features = Bolt12InvoiceFeatures::empty();
1182 features.set_basic_mpp_optional();
1184 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1187 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1189 .sign(payer_sign).unwrap()
1190 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1193 .sign(recipient_sign).unwrap();
1194 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1195 assert_eq!(invoice.features(), &features);
1196 assert_eq!(tlv_stream.features, Some(&features));
1200 fn fails_signing_invoice() {
1201 match OfferBuilder::new("foo".into(), recipient_pubkey())
1204 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1206 .sign(payer_sign).unwrap()
1207 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1211 Ok(_) => panic!("expected error"),
1212 Err(e) => assert_eq!(e, SignError::Signing(())),
1215 match OfferBuilder::new("foo".into(), recipient_pubkey())
1218 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1220 .sign(payer_sign).unwrap()
1221 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1225 Ok(_) => panic!("expected error"),
1226 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1231 fn parses_invoice_with_payment_paths() {
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()
1240 .sign(recipient_sign).unwrap();
1242 let mut buffer = Vec::new();
1243 invoice.write(&mut buffer).unwrap();
1245 if let Err(e) = Invoice::try_from(buffer) {
1246 panic!("error parsing invoice: {:?}", e);
1249 let mut tlv_stream = invoice.as_tlv_stream();
1250 tlv_stream.3.paths = None;
1252 match Invoice::try_from(tlv_stream.to_bytes()) {
1253 Ok(_) => panic!("expected error"),
1254 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1257 let mut tlv_stream = invoice.as_tlv_stream();
1258 tlv_stream.3.blindedpay = None;
1260 match Invoice::try_from(tlv_stream.to_bytes()) {
1261 Ok(_) => panic!("expected error"),
1262 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1265 let empty_payment_paths = vec![];
1266 let mut tlv_stream = invoice.as_tlv_stream();
1267 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1269 match Invoice::try_from(tlv_stream.to_bytes()) {
1270 Ok(_) => panic!("expected error"),
1271 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1274 let mut payment_paths = payment_paths();
1275 payment_paths.pop();
1276 let mut tlv_stream = invoice.as_tlv_stream();
1277 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1279 match Invoice::try_from(tlv_stream.to_bytes()) {
1280 Ok(_) => panic!("expected error"),
1281 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1286 fn parses_invoice_with_created_at() {
1287 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1290 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1292 .sign(payer_sign).unwrap()
1293 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1295 .sign(recipient_sign).unwrap();
1297 let mut buffer = Vec::new();
1298 invoice.write(&mut buffer).unwrap();
1300 if let Err(e) = Invoice::try_from(buffer) {
1301 panic!("error parsing invoice: {:?}", e);
1304 let mut tlv_stream = invoice.as_tlv_stream();
1305 tlv_stream.3.created_at = None;
1307 match Invoice::try_from(tlv_stream.to_bytes()) {
1308 Ok(_) => panic!("expected error"),
1310 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1316 fn parses_invoice_with_relative_expiry() {
1317 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1320 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1322 .sign(payer_sign).unwrap()
1323 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1324 .relative_expiry(3600)
1326 .sign(recipient_sign).unwrap();
1328 let mut buffer = Vec::new();
1329 invoice.write(&mut buffer).unwrap();
1331 match Invoice::try_from(buffer) {
1332 Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1333 Err(e) => panic!("error parsing invoice: {:?}", e),
1338 fn parses_invoice_with_payment_hash() {
1339 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 .sign(payer_sign).unwrap()
1345 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1347 .sign(recipient_sign).unwrap();
1349 let mut buffer = Vec::new();
1350 invoice.write(&mut buffer).unwrap();
1352 if let Err(e) = Invoice::try_from(buffer) {
1353 panic!("error parsing invoice: {:?}", e);
1356 let mut tlv_stream = invoice.as_tlv_stream();
1357 tlv_stream.3.payment_hash = None;
1359 match Invoice::try_from(tlv_stream.to_bytes()) {
1360 Ok(_) => panic!("expected error"),
1362 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1368 fn parses_invoice_with_amount() {
1369 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1372 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1374 .sign(payer_sign).unwrap()
1375 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1377 .sign(recipient_sign).unwrap();
1379 let mut buffer = Vec::new();
1380 invoice.write(&mut buffer).unwrap();
1382 if let Err(e) = Invoice::try_from(buffer) {
1383 panic!("error parsing invoice: {:?}", e);
1386 let mut tlv_stream = invoice.as_tlv_stream();
1387 tlv_stream.3.amount = None;
1389 match Invoice::try_from(tlv_stream.to_bytes()) {
1390 Ok(_) => panic!("expected error"),
1391 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1396 fn parses_invoice_with_allow_mpp() {
1397 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1400 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1402 .sign(payer_sign).unwrap()
1403 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1406 .sign(recipient_sign).unwrap();
1408 let mut buffer = Vec::new();
1409 invoice.write(&mut buffer).unwrap();
1411 match Invoice::try_from(buffer) {
1413 let mut features = Bolt12InvoiceFeatures::empty();
1414 features.set_basic_mpp_optional();
1415 assert_eq!(invoice.features(), &features);
1417 Err(e) => panic!("error parsing invoice: {:?}", e),
1422 fn parses_invoice_with_fallback_address() {
1423 let script = Script::new();
1424 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1425 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1426 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1428 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1431 let invoice_request = offer
1432 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1434 .sign(payer_sign).unwrap();
1435 let mut unsigned_invoice = invoice_request
1436 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1437 .fallback_v0_p2wsh(&script.wscript_hash())
1438 .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1439 .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1442 // Only standard addresses will be included.
1443 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1444 // Non-standard addresses
1445 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1446 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1447 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1449 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1450 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1452 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1453 let mut buffer = Vec::new();
1454 invoice.write(&mut buffer).unwrap();
1456 match Invoice::try_from(buffer) {
1459 invoice.fallbacks(),
1461 Address::p2wsh(&script, Network::Bitcoin),
1462 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1463 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1465 payload: Payload::WitnessProgram {
1466 version: WitnessVersion::V1,
1467 program: vec![0u8; 33],
1469 network: Network::Bitcoin,
1472 payload: Payload::WitnessProgram {
1473 version: WitnessVersion::V2,
1474 program: vec![0u8; 40],
1476 network: Network::Bitcoin,
1481 Err(e) => panic!("error parsing invoice: {:?}", e),
1486 fn parses_invoice_with_node_id() {
1487 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1490 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1492 .sign(payer_sign).unwrap()
1493 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1495 .sign(recipient_sign).unwrap();
1497 let mut buffer = Vec::new();
1498 invoice.write(&mut buffer).unwrap();
1500 if let Err(e) = Invoice::try_from(buffer) {
1501 panic!("error parsing invoice: {:?}", e);
1504 let mut tlv_stream = invoice.as_tlv_stream();
1505 tlv_stream.3.node_id = None;
1507 match Invoice::try_from(tlv_stream.to_bytes()) {
1508 Ok(_) => panic!("expected error"),
1510 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1514 let invalid_pubkey = payer_pubkey();
1515 let mut tlv_stream = invoice.as_tlv_stream();
1516 tlv_stream.3.node_id = Some(&invalid_pubkey);
1518 match Invoice::try_from(tlv_stream.to_bytes()) {
1519 Ok(_) => panic!("expected error"),
1521 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1527 fn fails_parsing_invoice_without_signature() {
1528 let mut buffer = Vec::new();
1529 OfferBuilder::new("foo".into(), recipient_pubkey())
1532 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534 .sign(payer_sign).unwrap()
1535 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1538 .write(&mut buffer).unwrap();
1540 match Invoice::try_from(buffer) {
1541 Ok(_) => panic!("expected error"),
1542 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1547 fn fails_parsing_invoice_with_invalid_signature() {
1548 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1551 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1553 .sign(payer_sign).unwrap()
1554 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1556 .sign(recipient_sign).unwrap();
1557 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1558 *last_signature_byte = last_signature_byte.wrapping_add(1);
1560 let mut buffer = Vec::new();
1561 invoice.write(&mut buffer).unwrap();
1563 match Invoice::try_from(buffer) {
1564 Ok(_) => panic!("expected error"),
1566 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1572 fn fails_parsing_invoice_with_extra_tlv_records() {
1573 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1576 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1578 .sign(payer_sign).unwrap()
1579 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1581 .sign(recipient_sign).unwrap();
1583 let mut encoded_invoice = Vec::new();
1584 invoice.write(&mut encoded_invoice).unwrap();
1585 BigSize(1002).write(&mut encoded_invoice).unwrap();
1586 BigSize(32).write(&mut encoded_invoice).unwrap();
1587 [42u8; 32].write(&mut encoded_invoice).unwrap();
1589 match Invoice::try_from(encoded_invoice) {
1590 Ok(_) => panic!("expected error"),
1591 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),