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 macro_rules! invoice_request_explicit_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
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: $self_type) -> 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 macro_rules! invoice_request_derived_payer_id_builder_methods { ($self: ident, $self_type: ty) => {
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: $self_type) -> 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 macro_rules! invoice_request_builder_methods { (
192 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
194 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
195 let offer = offer.contents.clone();
196 InvoiceRequestContentsWithoutPayerId {
197 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
198 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
202 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
203 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
206 /// Successive calls to this method will override the previous setting.
207 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
208 $self.chain_hash(ChainHash::using_genesis_block(network))
211 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
212 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
215 /// Successive calls to this method will override the previous setting.
216 pub(crate) fn chain_hash(mut $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
217 if !$self.offer.supports_chain(chain) {
218 return Err(Bolt12SemanticError::UnsupportedChain);
221 $self.invoice_request.chain = Some(chain);
225 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
226 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
228 /// Successive calls to this method will override the previous setting.
230 /// [`quantity`]: Self::quantity
231 pub fn amount_msats(mut $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
232 $self.invoice_request.offer.check_amount_msats_for_quantity(
233 Some(amount_msats), $self.invoice_request.quantity
235 $self.invoice_request.amount_msats = Some(amount_msats);
239 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
240 /// does not conform to [`Offer::is_valid_quantity`].
242 /// Successive calls to this method will override the previous setting.
243 pub fn quantity(mut $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
244 $self.invoice_request.offer.check_quantity(Some(quantity))?;
245 $self.invoice_request.quantity = Some(quantity);
249 /// Sets the [`InvoiceRequest::payer_note`].
251 /// Successive calls to this method will override the previous setting.
252 pub fn payer_note(mut $self: $self_type, payer_note: String) -> $return_type {
253 $self.invoice_request.payer_note = Some(payer_note);
257 fn build_with_checks(mut $self: $self_type) -> Result<
258 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
261 #[cfg(feature = "std")] {
262 if $self.offer.is_expired() {
263 return Err(Bolt12SemanticError::AlreadyExpired);
267 let chain = $self.invoice_request.chain();
268 if !$self.offer.supports_chain(chain) {
269 return Err(Bolt12SemanticError::UnsupportedChain);
272 if chain == $self.offer.implied_chain() {
273 $self.invoice_request.chain = None;
276 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
277 return Err(Bolt12SemanticError::MissingAmount);
280 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
281 $self.invoice_request.offer.check_amount_msats_for_quantity(
282 $self.invoice_request.amount_msats, $self.invoice_request.quantity
285 Ok($self.build_without_checks())
288 fn build_without_checks(mut $self: $self_type) ->
289 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
291 // Create the metadata for stateless verification of a Bolt12Invoice.
293 let secp_ctx = $self.secp_ctx.clone();
294 if $self.invoice_request.payer.0.has_derivation_material() {
295 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
297 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
298 debug_assert!(tlv_stream.2.payer_id.is_none());
299 tlv_stream.0.metadata = None;
300 if !metadata.derives_payer_keys() {
301 tlv_stream.2.payer_id = $self.payer_id.as_ref();
304 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
305 metadata = derived_metadata;
307 if let Some(keys) = keys {
308 debug_assert!($self.payer_id.is_none());
309 $self.payer_id = Some(keys.public_key());
312 $self.invoice_request.payer.0 = metadata;
315 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
316 debug_assert!($self.payer_id.is_some());
317 let payer_id = $self.payer_id.unwrap();
319 let invoice_request = InvoiceRequestContents {
320 inner: $self.invoice_request,
323 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
325 (unsigned_invoice_request, keys, secp_ctx)
330 macro_rules! invoice_request_builder_test_methods { (
331 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
333 fn chain_unchecked(mut $self: $self_type, network: Network) -> $return_type {
334 let chain = ChainHash::using_genesis_block(network);
335 $self.invoice_request.chain = Some(chain);
339 fn amount_msats_unchecked(mut $self: $self_type, amount_msats: u64) -> $return_type {
340 $self.invoice_request.amount_msats = Some(amount_msats);
344 fn features_unchecked(mut $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
345 $self.invoice_request.features = features;
349 fn quantity_unchecked(mut $self: $self_type, quantity: u64) -> $return_type {
350 $self.invoice_request.quantity = Some(quantity);
354 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
355 $self.build_without_checks().0
359 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
360 invoice_request_explicit_payer_id_builder_methods!(self, Self);
363 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
364 invoice_request_derived_payer_id_builder_methods!(self, Self);
367 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
368 invoice_request_builder_methods!(self, Self, Self, self);
371 invoice_request_builder_test_methods!(self, Self, Self, self);
374 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
378 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
379 /// such, it may include unknown, odd TLV records.
380 pub struct UnsignedInvoiceRequest {
382 contents: InvoiceRequestContents,
383 tagged_hash: TaggedHash,
386 impl UnsignedInvoiceRequest {
387 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
388 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
389 // unknown TLV records, which are not stored in `OfferContents`.
390 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
391 contents.as_tlv_stream();
392 let offer_bytes = WithoutLength(&offer.bytes);
393 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
395 let mut bytes = Vec::new();
396 unsigned_tlv_stream.write(&mut bytes).unwrap();
398 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
400 Self { bytes, contents, tagged_hash }
403 /// Returns the [`TaggedHash`] of the invoice to sign.
404 pub fn tagged_hash(&self) -> &TaggedHash {
409 macro_rules! unsigned_invoice_request_sign_method { ($self: ident, $self_type: ty) => {
410 /// Signs the [`TaggedHash`] of the invoice request using the given function.
412 /// Note: The hash computation may have included unknown, odd TLV records.
414 /// This is not exported to bindings users as functions are not yet mapped.
415 pub fn sign<F, E>(mut $self: $self_type, sign: F) -> Result<InvoiceRequest, SignError<E>>
417 F: FnOnce(&Self) -> Result<Signature, E>
419 let pubkey = $self.contents.payer_id;
420 let signature = merkle::sign_message(sign, &$self, pubkey)?;
422 // Append the signature TLV record to the bytes.
423 let signature_tlv_stream = SignatureTlvStreamRef {
424 signature: Some(&signature),
426 signature_tlv_stream.write(&mut $self.bytes).unwrap();
430 contents: $self.contents,
436 impl UnsignedInvoiceRequest {
437 unsigned_invoice_request_sign_method!(self, Self);
440 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
441 fn as_ref(&self) -> &TaggedHash {
446 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
448 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
449 /// specifies these such that its recipient can send an invoice for payment.
451 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
452 /// [`Offer`]: crate::offers::offer::Offer
453 #[derive(Clone, Debug)]
454 #[cfg_attr(test, derive(PartialEq))]
455 pub struct InvoiceRequest {
456 pub(super) bytes: Vec<u8>,
457 pub(super) contents: InvoiceRequestContents,
458 signature: Signature,
461 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
462 /// ways to respond depending on whether the signing keys were derived.
463 #[derive(Clone, Debug)]
464 pub struct VerifiedInvoiceRequest {
465 /// The verified request.
466 inner: InvoiceRequest,
468 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
470 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
471 /// [`respond_with`].
473 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
474 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
475 /// [`respond_with`]: Self::respond_with
476 pub keys: Option<KeyPair>,
479 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
481 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
482 #[derive(Clone, Debug)]
483 #[cfg_attr(test, derive(PartialEq))]
484 pub(super) struct InvoiceRequestContents {
485 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
489 #[derive(Clone, Debug)]
490 #[cfg_attr(test, derive(PartialEq))]
491 pub(super) struct InvoiceRequestContentsWithoutPayerId {
492 payer: PayerContents,
493 pub(super) offer: OfferContents,
494 chain: Option<ChainHash>,
495 amount_msats: Option<u64>,
496 features: InvoiceRequestFeatures,
497 quantity: Option<u64>,
498 payer_note: Option<String>,
501 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
502 /// An unpredictable series of bytes, typically containing information about the derivation of
505 /// [`payer_id`]: Self::payer_id
506 pub fn payer_metadata(&$self) -> &[u8] {
510 /// A chain from [`Offer::chains`] that the offer is valid for.
511 pub fn chain(&$self) -> ChainHash {
515 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
516 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
518 /// [`chain`]: Self::chain
519 pub fn amount_msats(&$self) -> Option<u64> {
520 $contents.amount_msats()
523 /// Features pertaining to requesting an invoice.
524 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
525 &$contents.features()
528 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
529 pub fn quantity(&$self) -> Option<u64> {
533 /// A possibly transient pubkey used to sign the invoice request.
534 pub fn payer_id(&$self) -> PublicKey {
538 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
540 pub fn payer_note(&$self) -> Option<PrintableString> {
541 $contents.payer_note()
545 impl UnsignedInvoiceRequest {
546 offer_accessors!(self, self.contents.inner.offer);
547 invoice_request_accessors!(self, self.contents);
550 impl InvoiceRequest {
551 offer_accessors!(self, self.contents.inner.offer);
552 invoice_request_accessors!(self, self.contents);
554 /// Signature of the invoice request using [`payer_id`].
556 /// [`payer_id`]: Self::payer_id
557 pub fn signature(&self) -> Signature {
561 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
562 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
564 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
565 /// creation time is used for the `created_at` parameter.
567 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
569 /// [`Duration`]: core::time::Duration
570 #[cfg(feature = "std")]
572 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
573 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
574 let created_at = std::time::SystemTime::now()
575 .duration_since(std::time::SystemTime::UNIX_EPOCH)
576 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
578 self.respond_with_no_std(payment_paths, payment_hash, created_at)
581 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
583 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
584 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
585 /// where [`std::time::SystemTime`] is not available.
587 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
590 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
591 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
592 /// a preference. Note, however, that any privacy is lost if a public node id was used for
593 /// [`Offer::signing_pubkey`].
595 /// Errors if the request contains unknown required features.
599 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
600 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
602 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
604 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
605 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
606 pub fn respond_with_no_std(
607 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
608 created_at: core::time::Duration
609 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
610 if self.invoice_request_features().requires_unknown_bits() {
611 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
614 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
617 /// Verifies that the request was for an offer created using the given key. Returns the verified
618 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
619 /// if they could be extracted from the metadata.
621 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
622 pub fn verify<T: secp256k1::Signing>(
623 self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
624 ) -> Result<VerifiedInvoiceRequest, ()> {
625 let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
626 Ok(VerifiedInvoiceRequest {
632 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
633 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
634 self.contents.as_tlv_stream();
635 let signature_tlv_stream = SignatureTlvStreamRef {
636 signature: Some(&self.signature),
638 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
642 impl VerifiedInvoiceRequest {
643 offer_accessors!(self, self.inner.contents.inner.offer);
644 invoice_request_accessors!(self, self.inner.contents);
646 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
647 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
649 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
651 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
653 /// [`Duration`]: core::time::Duration
654 #[cfg(feature = "std")]
656 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
657 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
658 self.inner.respond_with(payment_paths, payment_hash)
661 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
663 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
665 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
666 pub fn respond_with_no_std(
667 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
668 created_at: core::time::Duration
669 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
670 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
673 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
674 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
675 /// the same [`ExpandedKey`] as the one used to create the offer.
677 /// See [`InvoiceRequest::respond_with`] for further details.
679 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
681 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
682 #[cfg(feature = "std")]
683 pub fn respond_using_derived_keys(
684 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
685 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
686 let created_at = std::time::SystemTime::now()
687 .duration_since(std::time::SystemTime::UNIX_EPOCH)
688 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
690 self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
693 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
694 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
695 /// the same [`ExpandedKey`] as the one used to create the offer.
697 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
699 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
701 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
702 pub fn respond_using_derived_keys_no_std(
703 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
704 created_at: core::time::Duration
705 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
706 if self.inner.invoice_request_features().requires_unknown_bits() {
707 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
710 let keys = match self.keys {
711 None => return Err(Bolt12SemanticError::InvalidMetadata),
715 InvoiceBuilder::for_offer_using_keys(
716 &self.inner, payment_paths, created_at, payment_hash, keys
721 impl InvoiceRequestContents {
722 pub(super) fn metadata(&self) -> &[u8] {
723 self.inner.metadata()
726 pub(super) fn derives_keys(&self) -> bool {
727 self.inner.payer.0.derives_payer_keys()
730 pub(super) fn chain(&self) -> ChainHash {
734 pub(super) fn amount_msats(&self) -> Option<u64> {
735 self.inner.amount_msats
738 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
742 pub(super) fn quantity(&self) -> Option<u64> {
746 pub(super) fn payer_id(&self) -> PublicKey {
750 pub(super) fn payer_note(&self) -> Option<PrintableString> {
751 self.inner.payer_note.as_ref()
752 .map(|payer_note| PrintableString(payer_note.as_str()))
755 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
756 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
757 invoice_request.payer_id = Some(&self.payer_id);
758 (payer, offer, invoice_request)
762 impl InvoiceRequestContentsWithoutPayerId {
763 pub(super) fn metadata(&self) -> &[u8] {
764 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
767 pub(super) fn chain(&self) -> ChainHash {
768 self.chain.unwrap_or_else(|| self.offer.implied_chain())
771 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
772 let payer = PayerTlvStreamRef {
773 metadata: self.payer.0.as_bytes(),
776 let offer = self.offer.as_tlv_stream();
779 if self.features == InvoiceRequestFeatures::empty() { None }
780 else { Some(&self.features) }
783 let invoice_request = InvoiceRequestTlvStreamRef {
784 chain: self.chain.as_ref(),
785 amount: self.amount_msats,
787 quantity: self.quantity,
789 payer_note: self.payer_note.as_ref(),
792 (payer, offer, invoice_request)
796 impl Writeable for UnsignedInvoiceRequest {
797 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
798 WithoutLength(&self.bytes).write(writer)
802 impl Writeable for InvoiceRequest {
803 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
804 WithoutLength(&self.bytes).write(writer)
808 impl Writeable for InvoiceRequestContents {
809 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
810 self.as_tlv_stream().write(writer)
814 /// Valid type range for invoice_request TLV records.
815 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
817 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
819 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
820 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
822 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
823 (80, chain: ChainHash),
824 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
825 (84, features: (InvoiceRequestFeatures, WithoutLength)),
826 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
827 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
828 (89, payer_note: (String, WithoutLength)),
831 type FullInvoiceRequestTlvStream =
832 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
834 type FullInvoiceRequestTlvStreamRef<'a> = (
835 PayerTlvStreamRef<'a>,
836 OfferTlvStreamRef<'a>,
837 InvoiceRequestTlvStreamRef<'a>,
838 SignatureTlvStreamRef<'a>,
841 impl SeekReadable for FullInvoiceRequestTlvStream {
842 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
843 let payer = SeekReadable::read(r)?;
844 let offer = SeekReadable::read(r)?;
845 let invoice_request = SeekReadable::read(r)?;
846 let signature = SeekReadable::read(r)?;
848 Ok((payer, offer, invoice_request, signature))
852 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
854 type PartialInvoiceRequestTlvStreamRef<'a> = (
855 PayerTlvStreamRef<'a>,
856 OfferTlvStreamRef<'a>,
857 InvoiceRequestTlvStreamRef<'a>,
860 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
861 type Error = Bolt12ParseError;
863 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
864 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
865 let ParsedMessage { bytes, tlv_stream } = invoice_request;
867 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
869 let contents = InvoiceRequestContents::try_from(
870 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
873 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
875 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
879 impl TryFrom<Vec<u8>> for InvoiceRequest {
880 type Error = Bolt12ParseError;
882 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
883 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
884 let ParsedMessage { bytes, tlv_stream } = invoice_request;
886 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
887 SignatureTlvStream { signature },
889 let contents = InvoiceRequestContents::try_from(
890 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
893 let signature = match signature {
894 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
895 Some(signature) => signature,
897 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
898 merkle::verify_signature(&signature, &message, contents.payer_id)?;
900 Ok(InvoiceRequest { bytes, contents, signature })
904 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
905 type Error = Bolt12SemanticError;
907 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
909 PayerTlvStream { metadata },
911 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
914 let payer = match metadata {
915 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
916 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
918 let offer = OfferContents::try_from(offer_tlv_stream)?;
920 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
921 return Err(Bolt12SemanticError::UnsupportedChain);
924 if offer.amount().is_none() && amount.is_none() {
925 return Err(Bolt12SemanticError::MissingAmount);
928 offer.check_quantity(quantity)?;
929 offer.check_amount_msats_for_quantity(amount, quantity)?;
931 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
933 let payer_id = match payer_id {
934 None => return Err(Bolt12SemanticError::MissingPayerId),
935 Some(payer_id) => payer_id,
938 Ok(InvoiceRequestContents {
939 inner: InvoiceRequestContentsWithoutPayerId {
940 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
949 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
951 use bitcoin::blockdata::constants::ChainHash;
952 use bitcoin::network::constants::Network;
953 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
954 use core::convert::{Infallible, TryFrom};
955 use core::num::NonZeroU64;
956 #[cfg(feature = "std")]
957 use core::time::Duration;
958 use crate::sign::KeyMaterial;
959 use crate::ln::channelmanager::PaymentId;
960 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
961 use crate::ln::inbound_payment::ExpandedKey;
962 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
963 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
964 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
965 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
966 #[cfg(not(c_bindings))]
968 crate::offers::offer::OfferBuilder,
972 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
974 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
975 use crate::offers::payer::PayerTlvStreamRef;
976 use crate::offers::test_utils::*;
977 use crate::util::ser::{BigSize, Writeable};
978 use crate::util::string::PrintableString;
981 fn builds_invoice_request_with_defaults() {
982 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
985 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
988 let mut buffer = Vec::new();
989 unsigned_invoice_request.write(&mut buffer).unwrap();
991 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
992 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
993 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
994 assert_eq!(unsigned_invoice_request.metadata(), None);
995 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
996 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
997 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
998 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
999 assert_eq!(unsigned_invoice_request.paths(), &[]);
1000 assert_eq!(unsigned_invoice_request.issuer(), None);
1001 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
1002 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
1003 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1004 assert_eq!(unsigned_invoice_request.amount_msats(), None);
1005 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1006 assert_eq!(unsigned_invoice_request.quantity(), None);
1007 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
1008 assert_eq!(unsigned_invoice_request.payer_note(), None);
1010 match UnsignedInvoiceRequest::try_from(buffer) {
1011 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
1013 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
1014 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
1018 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
1020 let mut buffer = Vec::new();
1021 invoice_request.write(&mut buffer).unwrap();
1023 assert_eq!(invoice_request.bytes, buffer.as_slice());
1024 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1025 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1026 assert_eq!(invoice_request.metadata(), None);
1027 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1028 assert_eq!(invoice_request.description(), PrintableString("foo"));
1029 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1030 assert_eq!(invoice_request.absolute_expiry(), None);
1031 assert_eq!(invoice_request.paths(), &[]);
1032 assert_eq!(invoice_request.issuer(), None);
1033 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1034 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1035 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1036 assert_eq!(invoice_request.amount_msats(), None);
1037 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1038 assert_eq!(invoice_request.quantity(), None);
1039 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1040 assert_eq!(invoice_request.payer_note(), None);
1042 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1043 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1046 invoice_request.as_tlv_stream(),
1048 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1054 description: Some(&String::from("foo")),
1056 absolute_expiry: None,
1060 node_id: Some(&recipient_pubkey()),
1062 InvoiceRequestTlvStreamRef {
1067 payer_id: Some(&payer_pubkey()),
1070 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1074 if let Err(e) = InvoiceRequest::try_from(buffer) {
1075 panic!("error parsing invoice request: {:?}", e);
1079 #[cfg(feature = "std")]
1081 fn builds_invoice_request_from_offer_with_expiration() {
1082 let future_expiry = Duration::from_secs(u64::max_value());
1083 let past_expiry = Duration::from_secs(0);
1085 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1087 .absolute_expiry(future_expiry)
1089 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1092 panic!("error building invoice_request: {:?}", e);
1095 match OfferBuilder::new("foo".into(), recipient_pubkey())
1097 .absolute_expiry(past_expiry)
1099 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1102 Ok(_) => panic!("expected error"),
1103 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1108 fn builds_invoice_request_with_derived_metadata() {
1109 let payer_id = payer_pubkey();
1110 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1111 let entropy = FixedEntropy {};
1112 let secp_ctx = Secp256k1::new();
1113 let payment_id = PaymentId([1; 32]);
1115 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1118 let invoice_request = offer
1119 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1122 .sign(payer_sign).unwrap();
1123 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1125 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1128 .sign(recipient_sign).unwrap();
1129 match invoice.verify(&expanded_key, &secp_ctx) {
1130 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1131 Err(()) => panic!("verification failed"),
1134 // Fails verification with altered fields
1136 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1137 mut invoice_tlv_stream, mut signature_tlv_stream
1138 ) = invoice.as_tlv_stream();
1139 invoice_request_tlv_stream.amount = Some(2000);
1140 invoice_tlv_stream.amount = Some(2000);
1143 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1144 let mut bytes = Vec::new();
1145 tlv_stream.write(&mut bytes).unwrap();
1147 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1148 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1149 signature_tlv_stream.signature = Some(&signature);
1151 let mut encoded_invoice = bytes;
1152 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1154 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1155 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1157 // Fails verification with altered metadata
1159 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1160 mut signature_tlv_stream
1161 ) = invoice.as_tlv_stream();
1162 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1163 payer_tlv_stream.metadata = Some(&metadata);
1166 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1167 let mut bytes = Vec::new();
1168 tlv_stream.write(&mut bytes).unwrap();
1170 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1171 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1172 signature_tlv_stream.signature = Some(&signature);
1174 let mut encoded_invoice = bytes;
1175 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1177 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1178 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1182 fn builds_invoice_request_with_derived_payer_id() {
1183 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1184 let entropy = FixedEntropy {};
1185 let secp_ctx = Secp256k1::new();
1186 let payment_id = PaymentId([1; 32]);
1188 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1191 let invoice_request = offer
1192 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1197 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1200 .sign(recipient_sign).unwrap();
1201 match invoice.verify(&expanded_key, &secp_ctx) {
1202 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1203 Err(()) => panic!("verification failed"),
1206 // Fails verification with altered fields
1208 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1209 mut invoice_tlv_stream, mut signature_tlv_stream
1210 ) = invoice.as_tlv_stream();
1211 invoice_request_tlv_stream.amount = Some(2000);
1212 invoice_tlv_stream.amount = Some(2000);
1215 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1216 let mut bytes = Vec::new();
1217 tlv_stream.write(&mut bytes).unwrap();
1219 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1220 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1221 signature_tlv_stream.signature = Some(&signature);
1223 let mut encoded_invoice = bytes;
1224 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1226 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1227 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1229 // Fails verification with altered payer id
1231 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1232 mut signature_tlv_stream
1233 ) = invoice.as_tlv_stream();
1234 let payer_id = pubkey(1);
1235 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1238 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1239 let mut bytes = Vec::new();
1240 tlv_stream.write(&mut bytes).unwrap();
1242 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1243 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1244 signature_tlv_stream.signature = Some(&signature);
1246 let mut encoded_invoice = bytes;
1247 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1249 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1250 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1254 fn builds_invoice_request_with_chain() {
1255 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1256 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1258 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
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::Testnet)
1273 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1274 .chain(Network::Testnet).unwrap()
1276 .sign(payer_sign).unwrap();
1277 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1278 assert_eq!(invoice_request.chain(), testnet);
1279 assert_eq!(tlv_stream.chain, Some(&testnet));
1281 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1283 .chain(Network::Bitcoin)
1284 .chain(Network::Testnet)
1286 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1287 .chain(Network::Bitcoin).unwrap()
1289 .sign(payer_sign).unwrap();
1290 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1291 assert_eq!(invoice_request.chain(), mainnet);
1292 assert_eq!(tlv_stream.chain, None);
1294 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1296 .chain(Network::Bitcoin)
1297 .chain(Network::Testnet)
1299 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1300 .chain(Network::Bitcoin).unwrap()
1301 .chain(Network::Testnet).unwrap()
1303 .sign(payer_sign).unwrap();
1304 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1305 assert_eq!(invoice_request.chain(), testnet);
1306 assert_eq!(tlv_stream.chain, Some(&testnet));
1308 match OfferBuilder::new("foo".into(), recipient_pubkey())
1310 .chain(Network::Testnet)
1312 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1313 .chain(Network::Bitcoin)
1315 Ok(_) => panic!("expected error"),
1316 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1319 match OfferBuilder::new("foo".into(), recipient_pubkey())
1321 .chain(Network::Testnet)
1323 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1326 Ok(_) => panic!("expected error"),
1327 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1332 fn builds_invoice_request_with_amount() {
1333 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1336 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1337 .amount_msats(1000).unwrap()
1339 .sign(payer_sign).unwrap();
1340 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1341 assert_eq!(invoice_request.amount_msats(), Some(1000));
1342 assert_eq!(tlv_stream.amount, Some(1000));
1344 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1347 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1348 .amount_msats(1001).unwrap()
1349 .amount_msats(1000).unwrap()
1351 .sign(payer_sign).unwrap();
1352 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1353 assert_eq!(invoice_request.amount_msats(), Some(1000));
1354 assert_eq!(tlv_stream.amount, Some(1000));
1356 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1359 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1360 .amount_msats(1001).unwrap()
1362 .sign(payer_sign).unwrap();
1363 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1364 assert_eq!(invoice_request.amount_msats(), Some(1001));
1365 assert_eq!(tlv_stream.amount, Some(1001));
1367 match OfferBuilder::new("foo".into(), recipient_pubkey())
1370 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1373 Ok(_) => panic!("expected error"),
1374 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1377 match OfferBuilder::new("foo".into(), recipient_pubkey())
1379 .supported_quantity(Quantity::Unbounded)
1381 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1382 .quantity(2).unwrap()
1385 Ok(_) => panic!("expected error"),
1386 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1389 match OfferBuilder::new("foo".into(), recipient_pubkey())
1392 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1393 .amount_msats(MAX_VALUE_MSAT + 1)
1395 Ok(_) => panic!("expected error"),
1396 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1399 match OfferBuilder::new("foo".into(), recipient_pubkey())
1401 .supported_quantity(Quantity::Unbounded)
1403 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1404 .amount_msats(1000).unwrap()
1405 .quantity(2).unwrap()
1408 Ok(_) => panic!("expected error"),
1409 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1412 match OfferBuilder::new("foo".into(), recipient_pubkey())
1414 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1417 Ok(_) => panic!("expected error"),
1418 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1421 match OfferBuilder::new("foo".into(), recipient_pubkey())
1423 .supported_quantity(Quantity::Unbounded)
1425 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1426 .quantity(u64::max_value()).unwrap()
1429 Ok(_) => panic!("expected error"),
1430 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1435 fn builds_invoice_request_with_features() {
1436 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1439 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1440 .features_unchecked(InvoiceRequestFeatures::unknown())
1442 .sign(payer_sign).unwrap();
1443 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1444 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1445 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1447 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1450 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1451 .features_unchecked(InvoiceRequestFeatures::unknown())
1452 .features_unchecked(InvoiceRequestFeatures::empty())
1454 .sign(payer_sign).unwrap();
1455 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1456 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1457 assert_eq!(tlv_stream.features, None);
1461 fn builds_invoice_request_with_quantity() {
1462 let one = NonZeroU64::new(1).unwrap();
1463 let ten = NonZeroU64::new(10).unwrap();
1465 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1467 .supported_quantity(Quantity::One)
1469 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1471 .sign(payer_sign).unwrap();
1472 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1473 assert_eq!(invoice_request.quantity(), None);
1474 assert_eq!(tlv_stream.quantity, None);
1476 match OfferBuilder::new("foo".into(), recipient_pubkey())
1478 .supported_quantity(Quantity::One)
1480 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1481 .amount_msats(2_000).unwrap()
1484 Ok(_) => panic!("expected error"),
1485 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1488 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1490 .supported_quantity(Quantity::Bounded(ten))
1492 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1493 .amount_msats(10_000).unwrap()
1494 .quantity(10).unwrap()
1496 .sign(payer_sign).unwrap();
1497 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1498 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1499 assert_eq!(tlv_stream.amount, Some(10_000));
1501 match OfferBuilder::new("foo".into(), recipient_pubkey())
1503 .supported_quantity(Quantity::Bounded(ten))
1505 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 .amount_msats(11_000).unwrap()
1509 Ok(_) => panic!("expected error"),
1510 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1513 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1515 .supported_quantity(Quantity::Unbounded)
1517 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1518 .amount_msats(2_000).unwrap()
1519 .quantity(2).unwrap()
1521 .sign(payer_sign).unwrap();
1522 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1523 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1524 assert_eq!(tlv_stream.amount, Some(2_000));
1526 match OfferBuilder::new("foo".into(), recipient_pubkey())
1528 .supported_quantity(Quantity::Unbounded)
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1533 Ok(_) => panic!("expected error"),
1534 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1537 match OfferBuilder::new("foo".into(), recipient_pubkey())
1539 .supported_quantity(Quantity::Bounded(one))
1541 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1544 Ok(_) => panic!("expected error"),
1545 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1550 fn builds_invoice_request_with_payer_note() {
1551 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1554 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555 .payer_note("bar".into())
1557 .sign(payer_sign).unwrap();
1558 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1559 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1560 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1562 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1565 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1566 .payer_note("bar".into())
1567 .payer_note("baz".into())
1569 .sign(payer_sign).unwrap();
1570 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1571 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1572 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1576 fn fails_signing_invoice_request() {
1577 match OfferBuilder::new("foo".into(), recipient_pubkey())
1580 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1584 Ok(_) => panic!("expected error"),
1585 Err(e) => assert_eq!(e, SignError::Signing(())),
1588 match OfferBuilder::new("foo".into(), recipient_pubkey())
1591 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1593 .sign(recipient_sign)
1595 Ok(_) => panic!("expected error"),
1596 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1601 fn fails_responding_with_unknown_required_features() {
1602 match OfferBuilder::new("foo".into(), recipient_pubkey())
1605 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1606 .features_unchecked(InvoiceRequestFeatures::unknown())
1608 .sign(payer_sign).unwrap()
1609 .respond_with_no_std(payment_paths(), payment_hash(), now())
1611 Ok(_) => panic!("expected error"),
1612 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1617 fn parses_invoice_request_with_metadata() {
1618 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1621 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1623 .sign(payer_sign).unwrap();
1625 let mut buffer = Vec::new();
1626 invoice_request.write(&mut buffer).unwrap();
1628 if let Err(e) = InvoiceRequest::try_from(buffer) {
1629 panic!("error parsing invoice_request: {:?}", e);
1634 fn parses_invoice_request_with_chain() {
1635 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1638 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1639 .chain(Network::Bitcoin).unwrap()
1641 .sign(payer_sign).unwrap();
1643 let mut buffer = Vec::new();
1644 invoice_request.write(&mut buffer).unwrap();
1646 if let Err(e) = InvoiceRequest::try_from(buffer) {
1647 panic!("error parsing invoice_request: {:?}", e);
1650 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1653 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1654 .chain_unchecked(Network::Testnet)
1656 .sign(payer_sign).unwrap();
1658 let mut buffer = Vec::new();
1659 invoice_request.write(&mut buffer).unwrap();
1661 match InvoiceRequest::try_from(buffer) {
1662 Ok(_) => panic!("expected error"),
1663 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1668 fn parses_invoice_request_with_amount() {
1669 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1672 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1674 .sign(payer_sign).unwrap();
1676 let mut buffer = Vec::new();
1677 invoice_request.write(&mut buffer).unwrap();
1679 if let Err(e) = InvoiceRequest::try_from(buffer) {
1680 panic!("error parsing invoice_request: {:?}", e);
1683 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1685 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1686 .amount_msats(1000).unwrap()
1688 .sign(payer_sign).unwrap();
1690 let mut buffer = Vec::new();
1691 invoice_request.write(&mut buffer).unwrap();
1693 if let Err(e) = InvoiceRequest::try_from(buffer) {
1694 panic!("error parsing invoice_request: {:?}", e);
1697 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1699 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1701 .sign(payer_sign).unwrap();
1703 let mut buffer = Vec::new();
1704 invoice_request.write(&mut buffer).unwrap();
1706 match InvoiceRequest::try_from(buffer) {
1707 Ok(_) => panic!("expected error"),
1708 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1711 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1714 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1715 .amount_msats_unchecked(999)
1717 .sign(payer_sign).unwrap();
1719 let mut buffer = Vec::new();
1720 invoice_request.write(&mut buffer).unwrap();
1722 match InvoiceRequest::try_from(buffer) {
1723 Ok(_) => panic!("expected error"),
1724 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1727 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1728 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1730 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1732 .sign(payer_sign).unwrap();
1734 let mut buffer = Vec::new();
1735 invoice_request.write(&mut buffer).unwrap();
1737 match InvoiceRequest::try_from(buffer) {
1738 Ok(_) => panic!("expected error"),
1740 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1744 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1746 .supported_quantity(Quantity::Unbounded)
1748 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1749 .quantity(u64::max_value()).unwrap()
1751 .sign(payer_sign).unwrap();
1753 let mut buffer = Vec::new();
1754 invoice_request.write(&mut buffer).unwrap();
1756 match InvoiceRequest::try_from(buffer) {
1757 Ok(_) => panic!("expected error"),
1758 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1763 fn parses_invoice_request_with_quantity() {
1764 let one = NonZeroU64::new(1).unwrap();
1765 let ten = NonZeroU64::new(10).unwrap();
1767 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1769 .supported_quantity(Quantity::One)
1771 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1773 .sign(payer_sign).unwrap();
1775 let mut buffer = Vec::new();
1776 invoice_request.write(&mut buffer).unwrap();
1778 if let Err(e) = InvoiceRequest::try_from(buffer) {
1779 panic!("error parsing invoice_request: {:?}", e);
1782 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1784 .supported_quantity(Quantity::One)
1786 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1787 .amount_msats(2_000).unwrap()
1788 .quantity_unchecked(2)
1790 .sign(payer_sign).unwrap();
1792 let mut buffer = Vec::new();
1793 invoice_request.write(&mut buffer).unwrap();
1795 match InvoiceRequest::try_from(buffer) {
1796 Ok(_) => panic!("expected error"),
1798 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1802 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1804 .supported_quantity(Quantity::Bounded(ten))
1806 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .amount_msats(10_000).unwrap()
1808 .quantity(10).unwrap()
1810 .sign(payer_sign).unwrap();
1812 let mut buffer = Vec::new();
1813 invoice_request.write(&mut buffer).unwrap();
1815 if let Err(e) = InvoiceRequest::try_from(buffer) {
1816 panic!("error parsing invoice_request: {:?}", e);
1819 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1821 .supported_quantity(Quantity::Bounded(ten))
1823 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1824 .amount_msats(11_000).unwrap()
1825 .quantity_unchecked(11)
1827 .sign(payer_sign).unwrap();
1829 let mut buffer = Vec::new();
1830 invoice_request.write(&mut buffer).unwrap();
1832 match InvoiceRequest::try_from(buffer) {
1833 Ok(_) => panic!("expected error"),
1834 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1837 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1839 .supported_quantity(Quantity::Unbounded)
1841 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1842 .amount_msats(2_000).unwrap()
1843 .quantity(2).unwrap()
1845 .sign(payer_sign).unwrap();
1847 let mut buffer = Vec::new();
1848 invoice_request.write(&mut buffer).unwrap();
1850 if let Err(e) = InvoiceRequest::try_from(buffer) {
1851 panic!("error parsing invoice_request: {:?}", e);
1854 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1856 .supported_quantity(Quantity::Unbounded)
1858 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1860 .sign(payer_sign).unwrap();
1862 let mut buffer = Vec::new();
1863 invoice_request.write(&mut buffer).unwrap();
1865 match InvoiceRequest::try_from(buffer) {
1866 Ok(_) => panic!("expected error"),
1867 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1870 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1872 .supported_quantity(Quantity::Bounded(one))
1874 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1876 .sign(payer_sign).unwrap();
1878 let mut buffer = Vec::new();
1879 invoice_request.write(&mut buffer).unwrap();
1881 match InvoiceRequest::try_from(buffer) {
1882 Ok(_) => panic!("expected error"),
1883 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1888 fn fails_parsing_invoice_request_without_metadata() {
1889 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1892 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1894 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1895 tlv_stream.0.metadata = None;
1897 let mut buffer = Vec::new();
1898 tlv_stream.write(&mut buffer).unwrap();
1900 match InvoiceRequest::try_from(buffer) {
1901 Ok(_) => panic!("expected error"),
1903 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1909 fn fails_parsing_invoice_request_without_payer_id() {
1910 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1913 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1915 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1916 tlv_stream.2.payer_id = None;
1918 let mut buffer = Vec::new();
1919 tlv_stream.write(&mut buffer).unwrap();
1921 match InvoiceRequest::try_from(buffer) {
1922 Ok(_) => panic!("expected error"),
1923 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1928 fn fails_parsing_invoice_request_without_node_id() {
1929 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1932 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1934 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1935 tlv_stream.1.node_id = None;
1937 let mut buffer = Vec::new();
1938 tlv_stream.write(&mut buffer).unwrap();
1940 match InvoiceRequest::try_from(buffer) {
1941 Ok(_) => panic!("expected error"),
1943 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1949 fn fails_parsing_invoice_request_without_signature() {
1950 let mut buffer = Vec::new();
1951 OfferBuilder::new("foo".into(), recipient_pubkey())
1954 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1957 .write(&mut buffer).unwrap();
1959 match InvoiceRequest::try_from(buffer) {
1960 Ok(_) => panic!("expected error"),
1961 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1966 fn fails_parsing_invoice_request_with_invalid_signature() {
1967 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1970 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1972 .sign(payer_sign).unwrap();
1973 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1974 *last_signature_byte = last_signature_byte.wrapping_add(1);
1976 let mut buffer = Vec::new();
1977 invoice_request.write(&mut buffer).unwrap();
1979 match InvoiceRequest::try_from(buffer) {
1980 Ok(_) => panic!("expected error"),
1982 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1988 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1989 let secp_ctx = Secp256k1::new();
1990 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1991 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1994 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1996 .sign::<_, Infallible>(
1997 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2001 let mut encoded_invoice_request = Vec::new();
2002 invoice_request.write(&mut encoded_invoice_request).unwrap();
2003 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2004 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2005 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2007 match InvoiceRequest::try_from(encoded_invoice_request) {
2008 Ok(_) => panic!("expected error"),
2009 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),