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_request` messages.
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with a [`Bolt12Invoice`].
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
23 //! extern crate bitcoin;
24 //! extern crate lightning;
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
33 //! # fn parse() -> Result<(), lightning::offers::parse::Bolt12ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
40 //! .parse::<Offer>()?
41 //! .request_invoice(vec![42; 64], pubkey)?
42 //! .chain(Network::Testnet)?
43 //! .amount_msats(1000)?
45 //! .payer_note("foo".to_string())
47 //! .sign::<_, Infallible>(
48 //! |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
50 //! .expect("failed verifying signature")
51 //! .write(&mut buffer)
57 use bitcoin::blockdata::constants::ChainHash;
58 use bitcoin::network::constants::Network;
59 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
60 use bitcoin::secp256k1::schnorr::Signature;
61 use core::convert::{AsRef, Infallible, TryFrom};
63 use crate::sign::EntropySource;
65 use crate::blinded_path::BlindedPath;
66 use crate::ln::PaymentHash;
67 use crate::ln::channelmanager::PaymentId;
68 use crate::ln::features::InvoiceRequestFeatures;
69 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
70 use crate::ln::msgs::DecodeError;
71 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
72 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
73 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
74 use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
75 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
76 use crate::offers::signer::{Metadata, MetadataMaterial};
77 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
78 use crate::util::string::PrintableString;
80 use crate::prelude::*;
82 /// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
83 pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
85 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
87 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
89 /// See [module-level documentation] for usage.
91 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
93 /// [module-level documentation]: self
94 pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
96 invoice_request: InvoiceRequestContentsWithoutPayerId,
97 payer_id: Option<PublicKey>,
98 payer_id_strategy: core::marker::PhantomData<P>,
99 secp_ctx: Option<&'b Secp256k1<T>>,
102 /// Indicates how [`InvoiceRequest::payer_id`] will be set.
104 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
105 pub trait PayerIdStrategy {}
107 /// [`InvoiceRequest::payer_id`] will be explicitly set.
109 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
110 pub struct ExplicitPayerId {}
112 /// [`InvoiceRequest::payer_id`] will be derived.
114 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
115 pub struct DerivedPayerId {}
117 impl PayerIdStrategy for ExplicitPayerId {}
118 impl PayerIdStrategy for DerivedPayerId {}
120 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
121 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
124 invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
125 payer_id: Some(payer_id),
126 payer_id_strategy: core::marker::PhantomData,
131 pub(super) fn deriving_metadata<ES: Deref>(
132 offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
133 payment_id: PaymentId,
134 ) -> Self where ES::Target: EntropySource {
135 let nonce = Nonce::from_entropy_source(entropy_source);
136 let payment_id = Some(payment_id);
137 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
138 let metadata = Metadata::Derived(derivation_material);
141 invoice_request: Self::create_contents(offer, metadata),
142 payer_id: Some(payer_id),
143 payer_id_strategy: core::marker::PhantomData,
148 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
149 /// by [`UnsignedInvoiceRequest::sign`].
150 pub fn build(self) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
151 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
152 debug_assert!(keys.is_none());
153 Ok(unsigned_invoice_request)
157 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
158 pub(super) fn deriving_payer_id<ES: Deref>(
159 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
160 secp_ctx: &'b Secp256k1<T>, payment_id: PaymentId
161 ) -> Self where ES::Target: EntropySource {
162 let nonce = Nonce::from_entropy_source(entropy_source);
163 let payment_id = Some(payment_id);
164 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
165 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
168 invoice_request: Self::create_contents(offer, metadata),
170 payer_id_strategy: core::marker::PhantomData,
171 secp_ctx: Some(secp_ctx),
175 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
176 pub fn build_and_sign(self) -> Result<InvoiceRequest, Bolt12SemanticError> {
177 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
178 debug_assert!(keys.is_some());
180 let secp_ctx = secp_ctx.unwrap();
181 let keys = keys.unwrap();
182 let invoice_request = unsigned_invoice_request
183 .sign::<_, Infallible>(
184 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
191 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
192 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
193 let offer = offer.contents.clone();
194 InvoiceRequestContentsWithoutPayerId {
195 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
196 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
200 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
201 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
204 /// Successive calls to this method will override the previous setting.
205 pub fn chain(self, network: Network) -> Result<Self, Bolt12SemanticError> {
206 self.chain_hash(ChainHash::using_genesis_block(network))
209 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
210 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
213 /// Successive calls to this method will override the previous setting.
214 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Result<Self, Bolt12SemanticError> {
215 if !self.offer.supports_chain(chain) {
216 return Err(Bolt12SemanticError::UnsupportedChain);
219 self.invoice_request.chain = Some(chain);
223 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
224 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
226 /// Successive calls to this method will override the previous setting.
228 /// [`quantity`]: Self::quantity
229 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, Bolt12SemanticError> {
230 self.invoice_request.offer.check_amount_msats_for_quantity(
231 Some(amount_msats), self.invoice_request.quantity
233 self.invoice_request.amount_msats = Some(amount_msats);
237 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
238 /// does not conform to [`Offer::is_valid_quantity`].
240 /// Successive calls to this method will override the previous setting.
241 pub fn quantity(mut self, quantity: u64) -> Result<Self, Bolt12SemanticError> {
242 self.invoice_request.offer.check_quantity(Some(quantity))?;
243 self.invoice_request.quantity = Some(quantity);
247 /// Sets the [`InvoiceRequest::payer_note`].
249 /// Successive calls to this method will override the previous setting.
250 pub fn payer_note(mut self, payer_note: String) -> Self {
251 self.invoice_request.payer_note = Some(payer_note);
255 fn build_with_checks(mut self) -> Result<
256 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
259 #[cfg(feature = "std")] {
260 if self.offer.is_expired() {
261 return Err(Bolt12SemanticError::AlreadyExpired);
265 let chain = self.invoice_request.chain();
266 if !self.offer.supports_chain(chain) {
267 return Err(Bolt12SemanticError::UnsupportedChain);
270 if chain == self.offer.implied_chain() {
271 self.invoice_request.chain = None;
274 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
275 return Err(Bolt12SemanticError::MissingAmount);
278 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
279 self.invoice_request.offer.check_amount_msats_for_quantity(
280 self.invoice_request.amount_msats, self.invoice_request.quantity
283 Ok(self.build_without_checks())
286 fn build_without_checks(mut self) ->
287 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
289 // Create the metadata for stateless verification of a Bolt12Invoice.
291 let secp_ctx = self.secp_ctx.clone();
292 if self.invoice_request.payer.0.has_derivation_material() {
293 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
295 let mut tlv_stream = self.invoice_request.as_tlv_stream();
296 debug_assert!(tlv_stream.2.payer_id.is_none());
297 tlv_stream.0.metadata = None;
298 if !metadata.derives_payer_keys() {
299 tlv_stream.2.payer_id = self.payer_id.as_ref();
302 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
303 metadata = derived_metadata;
305 if let Some(keys) = keys {
306 debug_assert!(self.payer_id.is_none());
307 self.payer_id = Some(keys.public_key());
310 self.invoice_request.payer.0 = metadata;
313 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
314 debug_assert!(self.payer_id.is_some());
315 let payer_id = self.payer_id.unwrap();
317 let invoice_request = InvoiceRequestContents {
318 inner: self.invoice_request,
321 let unsigned_invoice_request = UnsignedInvoiceRequest::new(self.offer, invoice_request);
323 (unsigned_invoice_request, keys, secp_ctx)
328 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
329 fn chain_unchecked(mut self, network: Network) -> Self {
330 let chain = ChainHash::using_genesis_block(network);
331 self.invoice_request.chain = Some(chain);
335 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
336 self.invoice_request.amount_msats = Some(amount_msats);
340 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
341 self.invoice_request.features = features;
345 fn quantity_unchecked(mut self, quantity: u64) -> Self {
346 self.invoice_request.quantity = Some(quantity);
350 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest {
351 self.build_without_checks().0
355 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
359 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
360 /// such, it may include unknown, odd TLV records.
361 pub struct UnsignedInvoiceRequest {
363 contents: InvoiceRequestContents,
364 tagged_hash: TaggedHash,
367 impl UnsignedInvoiceRequest {
368 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
369 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
370 // unknown TLV records, which are not stored in `OfferContents`.
371 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
372 contents.as_tlv_stream();
373 let offer_bytes = WithoutLength(&offer.bytes);
374 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
376 let mut bytes = Vec::new();
377 unsigned_tlv_stream.write(&mut bytes).unwrap();
379 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
381 Self { bytes, contents, tagged_hash }
384 /// Returns the [`TaggedHash`] of the invoice to sign.
385 pub fn tagged_hash(&self) -> &TaggedHash {
389 /// Signs the [`TaggedHash`] of the invoice request using the given function.
391 /// Note: The hash computation may have included unknown, odd TLV records.
393 /// This is not exported to bindings users as functions are not yet mapped.
394 pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
396 F: FnOnce(&Self) -> Result<Signature, E>
398 let pubkey = self.contents.payer_id;
399 let signature = merkle::sign_message(sign, &self, pubkey)?;
401 // Append the signature TLV record to the bytes.
402 let signature_tlv_stream = SignatureTlvStreamRef {
403 signature: Some(&signature),
405 signature_tlv_stream.write(&mut self.bytes).unwrap();
409 contents: self.contents,
415 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
416 fn as_ref(&self) -> &TaggedHash {
421 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
423 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
424 /// specifies these such that its recipient can send an invoice for payment.
426 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
427 /// [`Offer`]: crate::offers::offer::Offer
428 #[derive(Clone, Debug)]
429 #[cfg_attr(test, derive(PartialEq))]
430 pub struct InvoiceRequest {
431 pub(super) bytes: Vec<u8>,
432 pub(super) contents: InvoiceRequestContents,
433 signature: Signature,
436 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
437 /// ways to respond depending on whether the signing keys were derived.
438 #[derive(Clone, Debug)]
439 pub struct VerifiedInvoiceRequest {
440 /// The verified request.
441 inner: InvoiceRequest,
443 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
445 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
446 /// [`respond_with`].
448 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
449 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
450 /// [`respond_with`]: Self::respond_with
451 pub keys: Option<KeyPair>,
454 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
456 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
457 #[derive(Clone, Debug)]
458 #[cfg_attr(test, derive(PartialEq))]
459 pub(super) struct InvoiceRequestContents {
460 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
464 #[derive(Clone, Debug)]
465 #[cfg_attr(test, derive(PartialEq))]
466 pub(super) struct InvoiceRequestContentsWithoutPayerId {
467 payer: PayerContents,
468 pub(super) offer: OfferContents,
469 chain: Option<ChainHash>,
470 amount_msats: Option<u64>,
471 features: InvoiceRequestFeatures,
472 quantity: Option<u64>,
473 payer_note: Option<String>,
476 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
477 /// An unpredictable series of bytes, typically containing information about the derivation of
480 /// [`payer_id`]: Self::payer_id
481 pub fn payer_metadata(&$self) -> &[u8] {
485 /// A chain from [`Offer::chains`] that the offer is valid for.
486 pub fn chain(&$self) -> ChainHash {
490 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
491 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
493 /// [`chain`]: Self::chain
494 pub fn amount_msats(&$self) -> Option<u64> {
495 $contents.amount_msats()
498 /// Features pertaining to requesting an invoice.
499 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
500 &$contents.features()
503 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
504 pub fn quantity(&$self) -> Option<u64> {
508 /// A possibly transient pubkey used to sign the invoice request.
509 pub fn payer_id(&$self) -> PublicKey {
513 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
515 pub fn payer_note(&$self) -> Option<PrintableString> {
516 $contents.payer_note()
520 impl UnsignedInvoiceRequest {
521 offer_accessors!(self, self.contents.inner.offer);
522 invoice_request_accessors!(self, self.contents);
525 impl InvoiceRequest {
526 offer_accessors!(self, self.contents.inner.offer);
527 invoice_request_accessors!(self, self.contents);
529 /// Signature of the invoice request using [`payer_id`].
531 /// [`payer_id`]: Self::payer_id
532 pub fn signature(&self) -> Signature {
536 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
537 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
539 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
540 /// creation time is used for the `created_at` parameter.
542 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
544 /// [`Duration`]: core::time::Duration
545 #[cfg(feature = "std")]
547 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
548 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
549 let created_at = std::time::SystemTime::now()
550 .duration_since(std::time::SystemTime::UNIX_EPOCH)
551 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
553 self.respond_with_no_std(payment_paths, payment_hash, created_at)
556 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
558 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
559 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
560 /// where [`std::time::SystemTime`] is not available.
562 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
565 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
566 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
567 /// a preference. Note, however, that any privacy is lost if a public node id was used for
568 /// [`Offer::signing_pubkey`].
570 /// Errors if the request contains unknown required features.
574 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
575 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
577 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
579 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
580 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
581 pub fn respond_with_no_std(
582 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
583 created_at: core::time::Duration
584 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
585 if self.invoice_request_features().requires_unknown_bits() {
586 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
589 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
592 /// Verifies that the request was for an offer created using the given key. Returns the verified
593 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
594 /// if they could be extracted from the metadata.
596 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
597 pub fn verify<T: secp256k1::Signing>(
598 self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
599 ) -> Result<VerifiedInvoiceRequest, ()> {
600 let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
601 Ok(VerifiedInvoiceRequest {
607 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
608 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
609 self.contents.as_tlv_stream();
610 let signature_tlv_stream = SignatureTlvStreamRef {
611 signature: Some(&self.signature),
613 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
617 impl VerifiedInvoiceRequest {
618 offer_accessors!(self, self.inner.contents.inner.offer);
619 invoice_request_accessors!(self, self.inner.contents);
621 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
622 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
624 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
626 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
628 /// [`Duration`]: core::time::Duration
629 #[cfg(feature = "std")]
631 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
632 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
633 self.inner.respond_with(payment_paths, payment_hash)
636 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
638 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
640 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
641 pub fn respond_with_no_std(
642 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
643 created_at: core::time::Duration
644 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
645 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
648 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
649 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
650 /// the same [`ExpandedKey`] as the one used to create the offer.
652 /// See [`InvoiceRequest::respond_with`] for further details.
654 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
656 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
657 #[cfg(feature = "std")]
658 pub fn respond_using_derived_keys(
659 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
660 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
661 let created_at = std::time::SystemTime::now()
662 .duration_since(std::time::SystemTime::UNIX_EPOCH)
663 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
665 self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
668 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
669 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
670 /// the same [`ExpandedKey`] as the one used to create the offer.
672 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
674 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
676 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
677 pub fn respond_using_derived_keys_no_std(
678 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
679 created_at: core::time::Duration
680 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
681 if self.inner.invoice_request_features().requires_unknown_bits() {
682 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
685 let keys = match self.keys {
686 None => return Err(Bolt12SemanticError::InvalidMetadata),
690 InvoiceBuilder::for_offer_using_keys(
691 &self.inner, payment_paths, created_at, payment_hash, keys
696 impl InvoiceRequestContents {
697 pub(super) fn metadata(&self) -> &[u8] {
698 self.inner.metadata()
701 pub(super) fn derives_keys(&self) -> bool {
702 self.inner.payer.0.derives_payer_keys()
705 pub(super) fn chain(&self) -> ChainHash {
709 pub(super) fn amount_msats(&self) -> Option<u64> {
710 self.inner.amount_msats
713 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
717 pub(super) fn quantity(&self) -> Option<u64> {
721 pub(super) fn payer_id(&self) -> PublicKey {
725 pub(super) fn payer_note(&self) -> Option<PrintableString> {
726 self.inner.payer_note.as_ref()
727 .map(|payer_note| PrintableString(payer_note.as_str()))
730 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
731 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
732 invoice_request.payer_id = Some(&self.payer_id);
733 (payer, offer, invoice_request)
737 impl InvoiceRequestContentsWithoutPayerId {
738 pub(super) fn metadata(&self) -> &[u8] {
739 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
742 pub(super) fn chain(&self) -> ChainHash {
743 self.chain.unwrap_or_else(|| self.offer.implied_chain())
746 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
747 let payer = PayerTlvStreamRef {
748 metadata: self.payer.0.as_bytes(),
751 let offer = self.offer.as_tlv_stream();
754 if self.features == InvoiceRequestFeatures::empty() { None }
755 else { Some(&self.features) }
758 let invoice_request = InvoiceRequestTlvStreamRef {
759 chain: self.chain.as_ref(),
760 amount: self.amount_msats,
762 quantity: self.quantity,
764 payer_note: self.payer_note.as_ref(),
767 (payer, offer, invoice_request)
771 impl Writeable for UnsignedInvoiceRequest {
772 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
773 WithoutLength(&self.bytes).write(writer)
777 impl Writeable for InvoiceRequest {
778 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
779 WithoutLength(&self.bytes).write(writer)
783 impl Writeable for InvoiceRequestContents {
784 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
785 self.as_tlv_stream().write(writer)
789 /// Valid type range for invoice_request TLV records.
790 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
792 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
794 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
795 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
797 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
798 (80, chain: ChainHash),
799 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
800 (84, features: (InvoiceRequestFeatures, WithoutLength)),
801 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
802 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
803 (89, payer_note: (String, WithoutLength)),
806 type FullInvoiceRequestTlvStream =
807 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
809 type FullInvoiceRequestTlvStreamRef<'a> = (
810 PayerTlvStreamRef<'a>,
811 OfferTlvStreamRef<'a>,
812 InvoiceRequestTlvStreamRef<'a>,
813 SignatureTlvStreamRef<'a>,
816 impl SeekReadable for FullInvoiceRequestTlvStream {
817 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
818 let payer = SeekReadable::read(r)?;
819 let offer = SeekReadable::read(r)?;
820 let invoice_request = SeekReadable::read(r)?;
821 let signature = SeekReadable::read(r)?;
823 Ok((payer, offer, invoice_request, signature))
827 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
829 type PartialInvoiceRequestTlvStreamRef<'a> = (
830 PayerTlvStreamRef<'a>,
831 OfferTlvStreamRef<'a>,
832 InvoiceRequestTlvStreamRef<'a>,
835 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
836 type Error = Bolt12ParseError;
838 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
839 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
840 let ParsedMessage { bytes, tlv_stream } = invoice_request;
842 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
844 let contents = InvoiceRequestContents::try_from(
845 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
848 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
850 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
854 impl TryFrom<Vec<u8>> for InvoiceRequest {
855 type Error = Bolt12ParseError;
857 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
858 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
859 let ParsedMessage { bytes, tlv_stream } = invoice_request;
861 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
862 SignatureTlvStream { signature },
864 let contents = InvoiceRequestContents::try_from(
865 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
868 let signature = match signature {
869 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
870 Some(signature) => signature,
872 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
873 merkle::verify_signature(&signature, &message, contents.payer_id)?;
875 Ok(InvoiceRequest { bytes, contents, signature })
879 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
880 type Error = Bolt12SemanticError;
882 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
884 PayerTlvStream { metadata },
886 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
889 let payer = match metadata {
890 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
891 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
893 let offer = OfferContents::try_from(offer_tlv_stream)?;
895 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
896 return Err(Bolt12SemanticError::UnsupportedChain);
899 if offer.amount().is_none() && amount.is_none() {
900 return Err(Bolt12SemanticError::MissingAmount);
903 offer.check_quantity(quantity)?;
904 offer.check_amount_msats_for_quantity(amount, quantity)?;
906 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
908 let payer_id = match payer_id {
909 None => return Err(Bolt12SemanticError::MissingPayerId),
910 Some(payer_id) => payer_id,
913 Ok(InvoiceRequestContents {
914 inner: InvoiceRequestContentsWithoutPayerId {
915 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
924 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
926 use bitcoin::blockdata::constants::ChainHash;
927 use bitcoin::network::constants::Network;
928 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
929 use core::convert::{Infallible, TryFrom};
930 use core::num::NonZeroU64;
931 #[cfg(feature = "std")]
932 use core::time::Duration;
933 use crate::sign::KeyMaterial;
934 use crate::ln::channelmanager::PaymentId;
935 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
936 use crate::ln::inbound_payment::ExpandedKey;
937 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
938 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
939 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
940 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
941 #[cfg(not(c_bindings))]
943 crate::offers::offer::OfferBuilder,
947 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
949 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
950 use crate::offers::payer::PayerTlvStreamRef;
951 use crate::offers::test_utils::*;
952 use crate::util::ser::{BigSize, Writeable};
953 use crate::util::string::PrintableString;
956 fn builds_invoice_request_with_defaults() {
957 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
960 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
963 let mut buffer = Vec::new();
964 unsigned_invoice_request.write(&mut buffer).unwrap();
966 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
967 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
968 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
969 assert_eq!(unsigned_invoice_request.metadata(), None);
970 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
971 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
972 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
973 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
974 assert_eq!(unsigned_invoice_request.paths(), &[]);
975 assert_eq!(unsigned_invoice_request.issuer(), None);
976 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
977 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
978 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
979 assert_eq!(unsigned_invoice_request.amount_msats(), None);
980 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
981 assert_eq!(unsigned_invoice_request.quantity(), None);
982 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
983 assert_eq!(unsigned_invoice_request.payer_note(), None);
985 match UnsignedInvoiceRequest::try_from(buffer) {
986 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
988 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
989 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
993 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
995 let mut buffer = Vec::new();
996 invoice_request.write(&mut buffer).unwrap();
998 assert_eq!(invoice_request.bytes, buffer.as_slice());
999 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1000 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1001 assert_eq!(invoice_request.metadata(), None);
1002 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1003 assert_eq!(invoice_request.description(), PrintableString("foo"));
1004 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1005 assert_eq!(invoice_request.absolute_expiry(), None);
1006 assert_eq!(invoice_request.paths(), &[]);
1007 assert_eq!(invoice_request.issuer(), None);
1008 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1009 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1010 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1011 assert_eq!(invoice_request.amount_msats(), None);
1012 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1013 assert_eq!(invoice_request.quantity(), None);
1014 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1015 assert_eq!(invoice_request.payer_note(), None);
1017 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1018 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1021 invoice_request.as_tlv_stream(),
1023 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1029 description: Some(&String::from("foo")),
1031 absolute_expiry: None,
1035 node_id: Some(&recipient_pubkey()),
1037 InvoiceRequestTlvStreamRef {
1042 payer_id: Some(&payer_pubkey()),
1045 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1049 if let Err(e) = InvoiceRequest::try_from(buffer) {
1050 panic!("error parsing invoice request: {:?}", e);
1054 #[cfg(feature = "std")]
1056 fn builds_invoice_request_from_offer_with_expiration() {
1057 let future_expiry = Duration::from_secs(u64::max_value());
1058 let past_expiry = Duration::from_secs(0);
1060 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1062 .absolute_expiry(future_expiry)
1064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1067 panic!("error building invoice_request: {:?}", e);
1070 match OfferBuilder::new("foo".into(), recipient_pubkey())
1072 .absolute_expiry(past_expiry)
1074 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1077 Ok(_) => panic!("expected error"),
1078 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1083 fn builds_invoice_request_with_derived_metadata() {
1084 let payer_id = payer_pubkey();
1085 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1086 let entropy = FixedEntropy {};
1087 let secp_ctx = Secp256k1::new();
1088 let payment_id = PaymentId([1; 32]);
1090 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1093 let invoice_request = offer
1094 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1097 .sign(payer_sign).unwrap();
1098 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1100 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1103 .sign(recipient_sign).unwrap();
1104 match invoice.verify(&expanded_key, &secp_ctx) {
1105 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1106 Err(()) => panic!("verification failed"),
1109 // Fails verification with altered fields
1111 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1112 mut invoice_tlv_stream, mut signature_tlv_stream
1113 ) = invoice.as_tlv_stream();
1114 invoice_request_tlv_stream.amount = Some(2000);
1115 invoice_tlv_stream.amount = Some(2000);
1118 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1119 let mut bytes = Vec::new();
1120 tlv_stream.write(&mut bytes).unwrap();
1122 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1123 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1124 signature_tlv_stream.signature = Some(&signature);
1126 let mut encoded_invoice = bytes;
1127 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1129 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1130 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1132 // Fails verification with altered metadata
1134 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1135 mut signature_tlv_stream
1136 ) = invoice.as_tlv_stream();
1137 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1138 payer_tlv_stream.metadata = Some(&metadata);
1141 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1142 let mut bytes = Vec::new();
1143 tlv_stream.write(&mut bytes).unwrap();
1145 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1146 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1147 signature_tlv_stream.signature = Some(&signature);
1149 let mut encoded_invoice = bytes;
1150 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1152 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1153 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1157 fn builds_invoice_request_with_derived_payer_id() {
1158 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1159 let entropy = FixedEntropy {};
1160 let secp_ctx = Secp256k1::new();
1161 let payment_id = PaymentId([1; 32]);
1163 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1166 let invoice_request = offer
1167 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1172 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1175 .sign(recipient_sign).unwrap();
1176 match invoice.verify(&expanded_key, &secp_ctx) {
1177 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1178 Err(()) => panic!("verification failed"),
1181 // Fails verification with altered fields
1183 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1184 mut invoice_tlv_stream, mut signature_tlv_stream
1185 ) = invoice.as_tlv_stream();
1186 invoice_request_tlv_stream.amount = Some(2000);
1187 invoice_tlv_stream.amount = Some(2000);
1190 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1191 let mut bytes = Vec::new();
1192 tlv_stream.write(&mut bytes).unwrap();
1194 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1195 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1196 signature_tlv_stream.signature = Some(&signature);
1198 let mut encoded_invoice = bytes;
1199 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1201 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1202 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1204 // Fails verification with altered payer id
1206 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1207 mut signature_tlv_stream
1208 ) = invoice.as_tlv_stream();
1209 let payer_id = pubkey(1);
1210 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1213 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1214 let mut bytes = Vec::new();
1215 tlv_stream.write(&mut bytes).unwrap();
1217 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1218 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1219 signature_tlv_stream.signature = Some(&signature);
1221 let mut encoded_invoice = bytes;
1222 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1224 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1225 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1229 fn builds_invoice_request_with_chain() {
1230 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1231 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1233 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1237 .chain(Network::Bitcoin).unwrap()
1239 .sign(payer_sign).unwrap();
1240 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1241 assert_eq!(invoice_request.chain(), mainnet);
1242 assert_eq!(tlv_stream.chain, None);
1244 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1246 .chain(Network::Testnet)
1248 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 .chain(Network::Testnet).unwrap()
1251 .sign(payer_sign).unwrap();
1252 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1253 assert_eq!(invoice_request.chain(), testnet);
1254 assert_eq!(tlv_stream.chain, Some(&testnet));
1256 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1258 .chain(Network::Bitcoin)
1259 .chain(Network::Testnet)
1261 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1262 .chain(Network::Bitcoin).unwrap()
1264 .sign(payer_sign).unwrap();
1265 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1266 assert_eq!(invoice_request.chain(), mainnet);
1267 assert_eq!(tlv_stream.chain, None);
1269 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1271 .chain(Network::Bitcoin)
1272 .chain(Network::Testnet)
1274 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275 .chain(Network::Bitcoin).unwrap()
1276 .chain(Network::Testnet).unwrap()
1278 .sign(payer_sign).unwrap();
1279 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1280 assert_eq!(invoice_request.chain(), testnet);
1281 assert_eq!(tlv_stream.chain, Some(&testnet));
1283 match OfferBuilder::new("foo".into(), recipient_pubkey())
1285 .chain(Network::Testnet)
1287 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288 .chain(Network::Bitcoin)
1290 Ok(_) => panic!("expected error"),
1291 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1294 match OfferBuilder::new("foo".into(), recipient_pubkey())
1296 .chain(Network::Testnet)
1298 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1301 Ok(_) => panic!("expected error"),
1302 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1307 fn builds_invoice_request_with_amount() {
1308 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1311 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1312 .amount_msats(1000).unwrap()
1314 .sign(payer_sign).unwrap();
1315 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1316 assert_eq!(invoice_request.amount_msats(), Some(1000));
1317 assert_eq!(tlv_stream.amount, Some(1000));
1319 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1322 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1323 .amount_msats(1001).unwrap()
1324 .amount_msats(1000).unwrap()
1326 .sign(payer_sign).unwrap();
1327 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1328 assert_eq!(invoice_request.amount_msats(), Some(1000));
1329 assert_eq!(tlv_stream.amount, Some(1000));
1331 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1334 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1335 .amount_msats(1001).unwrap()
1337 .sign(payer_sign).unwrap();
1338 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1339 assert_eq!(invoice_request.amount_msats(), Some(1001));
1340 assert_eq!(tlv_stream.amount, Some(1001));
1342 match OfferBuilder::new("foo".into(), recipient_pubkey())
1345 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1348 Ok(_) => panic!("expected error"),
1349 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1352 match OfferBuilder::new("foo".into(), recipient_pubkey())
1354 .supported_quantity(Quantity::Unbounded)
1356 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1357 .quantity(2).unwrap()
1360 Ok(_) => panic!("expected error"),
1361 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1364 match OfferBuilder::new("foo".into(), recipient_pubkey())
1367 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1368 .amount_msats(MAX_VALUE_MSAT + 1)
1370 Ok(_) => panic!("expected error"),
1371 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1374 match OfferBuilder::new("foo".into(), recipient_pubkey())
1376 .supported_quantity(Quantity::Unbounded)
1378 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1379 .amount_msats(1000).unwrap()
1380 .quantity(2).unwrap()
1383 Ok(_) => panic!("expected error"),
1384 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1387 match OfferBuilder::new("foo".into(), recipient_pubkey())
1389 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1392 Ok(_) => panic!("expected error"),
1393 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1396 match OfferBuilder::new("foo".into(), recipient_pubkey())
1398 .supported_quantity(Quantity::Unbounded)
1400 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1401 .quantity(u64::max_value()).unwrap()
1404 Ok(_) => panic!("expected error"),
1405 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1410 fn builds_invoice_request_with_features() {
1411 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1414 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1415 .features_unchecked(InvoiceRequestFeatures::unknown())
1417 .sign(payer_sign).unwrap();
1418 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1419 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1420 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1422 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1425 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1426 .features_unchecked(InvoiceRequestFeatures::unknown())
1427 .features_unchecked(InvoiceRequestFeatures::empty())
1429 .sign(payer_sign).unwrap();
1430 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1431 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1432 assert_eq!(tlv_stream.features, None);
1436 fn builds_invoice_request_with_quantity() {
1437 let one = NonZeroU64::new(1).unwrap();
1438 let ten = NonZeroU64::new(10).unwrap();
1440 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1442 .supported_quantity(Quantity::One)
1444 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446 .sign(payer_sign).unwrap();
1447 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1448 assert_eq!(invoice_request.quantity(), None);
1449 assert_eq!(tlv_stream.quantity, None);
1451 match OfferBuilder::new("foo".into(), recipient_pubkey())
1453 .supported_quantity(Quantity::One)
1455 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1456 .amount_msats(2_000).unwrap()
1459 Ok(_) => panic!("expected error"),
1460 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1463 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1465 .supported_quantity(Quantity::Bounded(ten))
1467 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1468 .amount_msats(10_000).unwrap()
1469 .quantity(10).unwrap()
1471 .sign(payer_sign).unwrap();
1472 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1473 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1474 assert_eq!(tlv_stream.amount, Some(10_000));
1476 match OfferBuilder::new("foo".into(), recipient_pubkey())
1478 .supported_quantity(Quantity::Bounded(ten))
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1481 .amount_msats(11_000).unwrap()
1484 Ok(_) => panic!("expected error"),
1485 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1488 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1490 .supported_quantity(Quantity::Unbounded)
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .amount_msats(2_000).unwrap()
1494 .quantity(2).unwrap()
1496 .sign(payer_sign).unwrap();
1497 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1498 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1499 assert_eq!(tlv_stream.amount, Some(2_000));
1501 match OfferBuilder::new("foo".into(), recipient_pubkey())
1503 .supported_quantity(Quantity::Unbounded)
1505 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1508 Ok(_) => panic!("expected error"),
1509 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1512 match OfferBuilder::new("foo".into(), recipient_pubkey())
1514 .supported_quantity(Quantity::Bounded(one))
1516 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1519 Ok(_) => panic!("expected error"),
1520 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1525 fn builds_invoice_request_with_payer_note() {
1526 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1529 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1530 .payer_note("bar".into())
1532 .sign(payer_sign).unwrap();
1533 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1534 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1535 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1537 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1540 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1541 .payer_note("bar".into())
1542 .payer_note("baz".into())
1544 .sign(payer_sign).unwrap();
1545 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1546 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1547 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1551 fn fails_signing_invoice_request() {
1552 match OfferBuilder::new("foo".into(), recipient_pubkey())
1555 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1559 Ok(_) => panic!("expected error"),
1560 Err(e) => assert_eq!(e, SignError::Signing(())),
1563 match OfferBuilder::new("foo".into(), recipient_pubkey())
1566 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1568 .sign(recipient_sign)
1570 Ok(_) => panic!("expected error"),
1571 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1576 fn fails_responding_with_unknown_required_features() {
1577 match OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1581 .features_unchecked(InvoiceRequestFeatures::unknown())
1583 .sign(payer_sign).unwrap()
1584 .respond_with_no_std(payment_paths(), payment_hash(), now())
1586 Ok(_) => panic!("expected error"),
1587 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1592 fn parses_invoice_request_with_metadata() {
1593 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1596 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1598 .sign(payer_sign).unwrap();
1600 let mut buffer = Vec::new();
1601 invoice_request.write(&mut buffer).unwrap();
1603 if let Err(e) = InvoiceRequest::try_from(buffer) {
1604 panic!("error parsing invoice_request: {:?}", e);
1609 fn parses_invoice_request_with_chain() {
1610 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1613 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1614 .chain(Network::Bitcoin).unwrap()
1616 .sign(payer_sign).unwrap();
1618 let mut buffer = Vec::new();
1619 invoice_request.write(&mut buffer).unwrap();
1621 if let Err(e) = InvoiceRequest::try_from(buffer) {
1622 panic!("error parsing invoice_request: {:?}", e);
1625 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1628 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1629 .chain_unchecked(Network::Testnet)
1631 .sign(payer_sign).unwrap();
1633 let mut buffer = Vec::new();
1634 invoice_request.write(&mut buffer).unwrap();
1636 match InvoiceRequest::try_from(buffer) {
1637 Ok(_) => panic!("expected error"),
1638 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1643 fn parses_invoice_request_with_amount() {
1644 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1647 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1649 .sign(payer_sign).unwrap();
1651 let mut buffer = Vec::new();
1652 invoice_request.write(&mut buffer).unwrap();
1654 if let Err(e) = InvoiceRequest::try_from(buffer) {
1655 panic!("error parsing invoice_request: {:?}", e);
1658 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1660 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1661 .amount_msats(1000).unwrap()
1663 .sign(payer_sign).unwrap();
1665 let mut buffer = Vec::new();
1666 invoice_request.write(&mut buffer).unwrap();
1668 if let Err(e) = InvoiceRequest::try_from(buffer) {
1669 panic!("error parsing invoice_request: {:?}", e);
1672 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1674 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1676 .sign(payer_sign).unwrap();
1678 let mut buffer = Vec::new();
1679 invoice_request.write(&mut buffer).unwrap();
1681 match InvoiceRequest::try_from(buffer) {
1682 Ok(_) => panic!("expected error"),
1683 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1686 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1689 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1690 .amount_msats_unchecked(999)
1692 .sign(payer_sign).unwrap();
1694 let mut buffer = Vec::new();
1695 invoice_request.write(&mut buffer).unwrap();
1697 match InvoiceRequest::try_from(buffer) {
1698 Ok(_) => panic!("expected error"),
1699 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1702 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1703 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1705 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1707 .sign(payer_sign).unwrap();
1709 let mut buffer = Vec::new();
1710 invoice_request.write(&mut buffer).unwrap();
1712 match InvoiceRequest::try_from(buffer) {
1713 Ok(_) => panic!("expected error"),
1715 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1719 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1721 .supported_quantity(Quantity::Unbounded)
1723 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1724 .quantity(u64::max_value()).unwrap()
1726 .sign(payer_sign).unwrap();
1728 let mut buffer = Vec::new();
1729 invoice_request.write(&mut buffer).unwrap();
1731 match InvoiceRequest::try_from(buffer) {
1732 Ok(_) => panic!("expected error"),
1733 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1738 fn parses_invoice_request_with_quantity() {
1739 let one = NonZeroU64::new(1).unwrap();
1740 let ten = NonZeroU64::new(10).unwrap();
1742 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1744 .supported_quantity(Quantity::One)
1746 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1748 .sign(payer_sign).unwrap();
1750 let mut buffer = Vec::new();
1751 invoice_request.write(&mut buffer).unwrap();
1753 if let Err(e) = InvoiceRequest::try_from(buffer) {
1754 panic!("error parsing invoice_request: {:?}", e);
1757 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1759 .supported_quantity(Quantity::One)
1761 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1762 .amount_msats(2_000).unwrap()
1763 .quantity_unchecked(2)
1765 .sign(payer_sign).unwrap();
1767 let mut buffer = Vec::new();
1768 invoice_request.write(&mut buffer).unwrap();
1770 match InvoiceRequest::try_from(buffer) {
1771 Ok(_) => panic!("expected error"),
1773 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1777 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1779 .supported_quantity(Quantity::Bounded(ten))
1781 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1782 .amount_msats(10_000).unwrap()
1783 .quantity(10).unwrap()
1785 .sign(payer_sign).unwrap();
1787 let mut buffer = Vec::new();
1788 invoice_request.write(&mut buffer).unwrap();
1790 if let Err(e) = InvoiceRequest::try_from(buffer) {
1791 panic!("error parsing invoice_request: {:?}", e);
1794 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1796 .supported_quantity(Quantity::Bounded(ten))
1798 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1799 .amount_msats(11_000).unwrap()
1800 .quantity_unchecked(11)
1802 .sign(payer_sign).unwrap();
1804 let mut buffer = Vec::new();
1805 invoice_request.write(&mut buffer).unwrap();
1807 match InvoiceRequest::try_from(buffer) {
1808 Ok(_) => panic!("expected error"),
1809 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1812 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1814 .supported_quantity(Quantity::Unbounded)
1816 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1817 .amount_msats(2_000).unwrap()
1818 .quantity(2).unwrap()
1820 .sign(payer_sign).unwrap();
1822 let mut buffer = Vec::new();
1823 invoice_request.write(&mut buffer).unwrap();
1825 if let Err(e) = InvoiceRequest::try_from(buffer) {
1826 panic!("error parsing invoice_request: {:?}", e);
1829 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1831 .supported_quantity(Quantity::Unbounded)
1833 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1835 .sign(payer_sign).unwrap();
1837 let mut buffer = Vec::new();
1838 invoice_request.write(&mut buffer).unwrap();
1840 match InvoiceRequest::try_from(buffer) {
1841 Ok(_) => panic!("expected error"),
1842 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1845 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1847 .supported_quantity(Quantity::Bounded(one))
1849 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1851 .sign(payer_sign).unwrap();
1853 let mut buffer = Vec::new();
1854 invoice_request.write(&mut buffer).unwrap();
1856 match InvoiceRequest::try_from(buffer) {
1857 Ok(_) => panic!("expected error"),
1858 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1863 fn fails_parsing_invoice_request_without_metadata() {
1864 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1867 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1869 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1870 tlv_stream.0.metadata = None;
1872 let mut buffer = Vec::new();
1873 tlv_stream.write(&mut buffer).unwrap();
1875 match InvoiceRequest::try_from(buffer) {
1876 Ok(_) => panic!("expected error"),
1878 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1884 fn fails_parsing_invoice_request_without_payer_id() {
1885 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1888 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1890 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1891 tlv_stream.2.payer_id = None;
1893 let mut buffer = Vec::new();
1894 tlv_stream.write(&mut buffer).unwrap();
1896 match InvoiceRequest::try_from(buffer) {
1897 Ok(_) => panic!("expected error"),
1898 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1903 fn fails_parsing_invoice_request_without_node_id() {
1904 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1907 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1909 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1910 tlv_stream.1.node_id = None;
1912 let mut buffer = Vec::new();
1913 tlv_stream.write(&mut buffer).unwrap();
1915 match InvoiceRequest::try_from(buffer) {
1916 Ok(_) => panic!("expected error"),
1918 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1924 fn fails_parsing_invoice_request_without_signature() {
1925 let mut buffer = Vec::new();
1926 OfferBuilder::new("foo".into(), recipient_pubkey())
1929 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1932 .write(&mut buffer).unwrap();
1934 match InvoiceRequest::try_from(buffer) {
1935 Ok(_) => panic!("expected error"),
1936 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1941 fn fails_parsing_invoice_request_with_invalid_signature() {
1942 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1945 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1947 .sign(payer_sign).unwrap();
1948 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1949 *last_signature_byte = last_signature_byte.wrapping_add(1);
1951 let mut buffer = Vec::new();
1952 invoice_request.write(&mut buffer).unwrap();
1954 match InvoiceRequest::try_from(buffer) {
1955 Ok(_) => panic!("expected error"),
1957 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1963 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1964 let secp_ctx = Secp256k1::new();
1965 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1966 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1969 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1971 .sign::<_, Infallible>(
1972 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1976 let mut encoded_invoice_request = Vec::new();
1977 invoice_request.write(&mut encoded_invoice_request).unwrap();
1978 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1979 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1980 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1982 match InvoiceRequest::try_from(encoded_invoice_request) {
1983 Ok(_) => panic!("expected error"),
1984 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),