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,
149 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
150 pub(super) fn deriving_payer_id<ES: Deref>(
151 offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
152 secp_ctx: &'b Secp256k1<T>, payment_id: PaymentId
153 ) -> Self where ES::Target: EntropySource {
154 let nonce = Nonce::from_entropy_source(entropy_source);
155 let payment_id = Some(payment_id);
156 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
157 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
160 invoice_request: Self::create_contents(offer, metadata),
162 payer_id_strategy: core::marker::PhantomData,
163 secp_ctx: Some(secp_ctx),
168 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
169 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
170 let offer = offer.contents.clone();
171 InvoiceRequestContentsWithoutPayerId {
172 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
173 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
177 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
178 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
181 /// Successive calls to this method will override the previous setting.
182 pub fn chain(self, network: Network) -> Result<Self, Bolt12SemanticError> {
183 self.chain_hash(ChainHash::using_genesis_block(network))
186 /// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
187 /// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
190 /// Successive calls to this method will override the previous setting.
191 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Result<Self, Bolt12SemanticError> {
192 if !self.offer.supports_chain(chain) {
193 return Err(Bolt12SemanticError::UnsupportedChain);
196 self.invoice_request.chain = Some(chain);
200 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
201 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
203 /// Successive calls to this method will override the previous setting.
205 /// [`quantity`]: Self::quantity
206 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, Bolt12SemanticError> {
207 self.invoice_request.offer.check_amount_msats_for_quantity(
208 Some(amount_msats), self.invoice_request.quantity
210 self.invoice_request.amount_msats = Some(amount_msats);
214 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
215 /// does not conform to [`Offer::is_valid_quantity`].
217 /// Successive calls to this method will override the previous setting.
218 pub fn quantity(mut self, quantity: u64) -> Result<Self, Bolt12SemanticError> {
219 self.invoice_request.offer.check_quantity(Some(quantity))?;
220 self.invoice_request.quantity = Some(quantity);
224 /// Sets the [`InvoiceRequest::payer_note`].
226 /// Successive calls to this method will override the previous setting.
227 pub fn payer_note(mut self, payer_note: String) -> Self {
228 self.invoice_request.payer_note = Some(payer_note);
232 fn build_with_checks(mut self) -> Result<
233 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
236 #[cfg(feature = "std")] {
237 if self.offer.is_expired() {
238 return Err(Bolt12SemanticError::AlreadyExpired);
242 let chain = self.invoice_request.chain();
243 if !self.offer.supports_chain(chain) {
244 return Err(Bolt12SemanticError::UnsupportedChain);
247 if chain == self.offer.implied_chain() {
248 self.invoice_request.chain = None;
251 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
252 return Err(Bolt12SemanticError::MissingAmount);
255 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
256 self.invoice_request.offer.check_amount_msats_for_quantity(
257 self.invoice_request.amount_msats, self.invoice_request.quantity
260 Ok(self.build_without_checks())
263 fn build_without_checks(mut self) ->
264 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
266 // Create the metadata for stateless verification of a Bolt12Invoice.
268 let secp_ctx = self.secp_ctx.clone();
269 if self.invoice_request.payer.0.has_derivation_material() {
270 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
272 let mut tlv_stream = self.invoice_request.as_tlv_stream();
273 debug_assert!(tlv_stream.2.payer_id.is_none());
274 tlv_stream.0.metadata = None;
275 if !metadata.derives_payer_keys() {
276 tlv_stream.2.payer_id = self.payer_id.as_ref();
279 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
280 metadata = derived_metadata;
282 if let Some(keys) = keys {
283 debug_assert!(self.payer_id.is_none());
284 self.payer_id = Some(keys.public_key());
287 self.invoice_request.payer.0 = metadata;
290 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
291 debug_assert!(self.payer_id.is_some());
292 let payer_id = self.payer_id.unwrap();
294 let invoice_request = InvoiceRequestContents {
295 inner: self.invoice_request,
298 let unsigned_invoice_request = UnsignedInvoiceRequest::new(self.offer, invoice_request);
300 (unsigned_invoice_request, keys, secp_ctx)
304 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
305 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
306 /// by [`UnsignedInvoiceRequest::sign`].
307 pub fn build(self) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
308 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
309 debug_assert!(keys.is_none());
310 Ok(unsigned_invoice_request)
314 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
315 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
316 pub fn build_and_sign(self) -> Result<InvoiceRequest, Bolt12SemanticError> {
317 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
318 debug_assert!(keys.is_some());
320 let secp_ctx = secp_ctx.unwrap();
321 let keys = keys.unwrap();
322 let invoice_request = unsigned_invoice_request
323 .sign::<_, Infallible>(
324 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
332 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
333 fn chain_unchecked(mut self, network: Network) -> Self {
334 let chain = ChainHash::using_genesis_block(network);
335 self.invoice_request.chain = Some(chain);
339 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
340 self.invoice_request.amount_msats = Some(amount_msats);
344 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
345 self.invoice_request.features = features;
349 fn quantity_unchecked(mut self, quantity: u64) -> Self {
350 self.invoice_request.quantity = Some(quantity);
354 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest {
355 self.build_without_checks().0
359 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
363 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
364 /// such, it may include unknown, odd TLV records.
365 pub struct UnsignedInvoiceRequest {
367 contents: InvoiceRequestContents,
368 tagged_hash: TaggedHash,
371 impl UnsignedInvoiceRequest {
372 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
373 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
374 // unknown TLV records, which are not stored in `OfferContents`.
375 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
376 contents.as_tlv_stream();
377 let offer_bytes = WithoutLength(&offer.bytes);
378 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
380 let mut bytes = Vec::new();
381 unsigned_tlv_stream.write(&mut bytes).unwrap();
383 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
385 Self { bytes, contents, tagged_hash }
388 /// Returns the [`TaggedHash`] of the invoice to sign.
389 pub fn tagged_hash(&self) -> &TaggedHash {
393 /// Signs the [`TaggedHash`] of the invoice request using the given function.
395 /// Note: The hash computation may have included unknown, odd TLV records.
397 /// This is not exported to bindings users as functions are not yet mapped.
398 pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
400 F: FnOnce(&Self) -> Result<Signature, E>
402 let pubkey = self.contents.payer_id;
403 let signature = merkle::sign_message(sign, &self, pubkey)?;
405 // Append the signature TLV record to the bytes.
406 let signature_tlv_stream = SignatureTlvStreamRef {
407 signature: Some(&signature),
409 signature_tlv_stream.write(&mut self.bytes).unwrap();
413 contents: self.contents,
419 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
420 fn as_ref(&self) -> &TaggedHash {
425 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
427 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
428 /// specifies these such that its recipient can send an invoice for payment.
430 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
431 /// [`Offer`]: crate::offers::offer::Offer
432 #[derive(Clone, Debug)]
433 #[cfg_attr(test, derive(PartialEq))]
434 pub struct InvoiceRequest {
435 pub(super) bytes: Vec<u8>,
436 pub(super) contents: InvoiceRequestContents,
437 signature: Signature,
440 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
441 /// ways to respond depending on whether the signing keys were derived.
442 #[derive(Clone, Debug)]
443 pub struct VerifiedInvoiceRequest {
444 /// The verified request.
445 inner: InvoiceRequest,
447 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
449 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
450 /// [`respond_with`].
452 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
453 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
454 /// [`respond_with`]: Self::respond_with
455 pub keys: Option<KeyPair>,
458 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
460 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
461 #[derive(Clone, Debug)]
462 #[cfg_attr(test, derive(PartialEq))]
463 pub(super) struct InvoiceRequestContents {
464 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
468 #[derive(Clone, Debug)]
469 #[cfg_attr(test, derive(PartialEq))]
470 pub(super) struct InvoiceRequestContentsWithoutPayerId {
471 payer: PayerContents,
472 pub(super) offer: OfferContents,
473 chain: Option<ChainHash>,
474 amount_msats: Option<u64>,
475 features: InvoiceRequestFeatures,
476 quantity: Option<u64>,
477 payer_note: Option<String>,
480 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
481 /// An unpredictable series of bytes, typically containing information about the derivation of
484 /// [`payer_id`]: Self::payer_id
485 pub fn payer_metadata(&$self) -> &[u8] {
489 /// A chain from [`Offer::chains`] that the offer is valid for.
490 pub fn chain(&$self) -> ChainHash {
494 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
495 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
497 /// [`chain`]: Self::chain
498 pub fn amount_msats(&$self) -> Option<u64> {
499 $contents.amount_msats()
502 /// Features pertaining to requesting an invoice.
503 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
504 &$contents.features()
507 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
508 pub fn quantity(&$self) -> Option<u64> {
512 /// A possibly transient pubkey used to sign the invoice request.
513 pub fn payer_id(&$self) -> PublicKey {
517 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
519 pub fn payer_note(&$self) -> Option<PrintableString> {
520 $contents.payer_note()
524 impl UnsignedInvoiceRequest {
525 offer_accessors!(self, self.contents.inner.offer);
526 invoice_request_accessors!(self, self.contents);
529 impl InvoiceRequest {
530 offer_accessors!(self, self.contents.inner.offer);
531 invoice_request_accessors!(self, self.contents);
533 /// Signature of the invoice request using [`payer_id`].
535 /// [`payer_id`]: Self::payer_id
536 pub fn signature(&self) -> Signature {
540 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
541 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
543 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
544 /// creation time is used for the `created_at` parameter.
546 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
548 /// [`Duration`]: core::time::Duration
549 #[cfg(feature = "std")]
551 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
552 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
553 let created_at = std::time::SystemTime::now()
554 .duration_since(std::time::SystemTime::UNIX_EPOCH)
555 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
557 self.respond_with_no_std(payment_paths, payment_hash, created_at)
560 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
562 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
563 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
564 /// where [`std::time::SystemTime`] is not available.
566 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
569 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
570 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
571 /// a preference. Note, however, that any privacy is lost if a public node id was used for
572 /// [`Offer::signing_pubkey`].
574 /// Errors if the request contains unknown required features.
578 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
579 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
581 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
583 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
584 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
585 pub fn respond_with_no_std(
586 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
587 created_at: core::time::Duration
588 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
589 if self.invoice_request_features().requires_unknown_bits() {
590 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
593 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
596 /// Verifies that the request was for an offer created using the given key. Returns the verified
597 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
598 /// if they could be extracted from the metadata.
600 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
601 pub fn verify<T: secp256k1::Signing>(
602 self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
603 ) -> Result<VerifiedInvoiceRequest, ()> {
604 let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
605 Ok(VerifiedInvoiceRequest {
612 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
613 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
614 self.contents.as_tlv_stream();
615 let signature_tlv_stream = SignatureTlvStreamRef {
616 signature: Some(&self.signature),
618 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
622 impl VerifiedInvoiceRequest {
623 offer_accessors!(self, self.inner.contents.inner.offer);
624 invoice_request_accessors!(self, self.inner.contents);
626 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
627 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
629 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
631 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
633 /// [`Duration`]: core::time::Duration
634 #[cfg(feature = "std")]
636 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
637 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
638 self.inner.respond_with(payment_paths, payment_hash)
641 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
643 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
645 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
646 pub fn respond_with_no_std(
647 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
648 created_at: core::time::Duration
649 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
650 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
653 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
654 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
655 /// the same [`ExpandedKey`] as the one used to create the offer.
657 /// See [`InvoiceRequest::respond_with`] for further details.
659 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
661 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
662 #[cfg(feature = "std")]
663 pub fn respond_using_derived_keys(
664 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
665 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
666 let created_at = std::time::SystemTime::now()
667 .duration_since(std::time::SystemTime::UNIX_EPOCH)
668 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
670 self.respond_using_derived_keys_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_no_std`] 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 pub fn respond_using_derived_keys_no_std(
683 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
684 created_at: core::time::Duration
685 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
686 if self.inner.invoice_request_features().requires_unknown_bits() {
687 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
690 let keys = match self.keys {
691 None => return Err(Bolt12SemanticError::InvalidMetadata),
695 InvoiceBuilder::for_offer_using_keys(
696 &self.inner, payment_paths, created_at, payment_hash, keys
701 impl InvoiceRequestContents {
702 pub(super) fn metadata(&self) -> &[u8] {
703 self.inner.metadata()
706 pub(super) fn derives_keys(&self) -> bool {
707 self.inner.payer.0.derives_payer_keys()
710 pub(super) fn chain(&self) -> ChainHash {
714 pub(super) fn amount_msats(&self) -> Option<u64> {
715 self.inner.amount_msats
718 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
722 pub(super) fn quantity(&self) -> Option<u64> {
726 pub(super) fn payer_id(&self) -> PublicKey {
730 pub(super) fn payer_note(&self) -> Option<PrintableString> {
731 self.inner.payer_note.as_ref()
732 .map(|payer_note| PrintableString(payer_note.as_str()))
735 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
736 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
737 invoice_request.payer_id = Some(&self.payer_id);
738 (payer, offer, invoice_request)
742 impl InvoiceRequestContentsWithoutPayerId {
743 pub(super) fn metadata(&self) -> &[u8] {
744 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
747 pub(super) fn chain(&self) -> ChainHash {
748 self.chain.unwrap_or_else(|| self.offer.implied_chain())
751 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
752 let payer = PayerTlvStreamRef {
753 metadata: self.payer.0.as_bytes(),
756 let offer = self.offer.as_tlv_stream();
759 if self.features == InvoiceRequestFeatures::empty() { None }
760 else { Some(&self.features) }
763 let invoice_request = InvoiceRequestTlvStreamRef {
764 chain: self.chain.as_ref(),
765 amount: self.amount_msats,
767 quantity: self.quantity,
769 payer_note: self.payer_note.as_ref(),
772 (payer, offer, invoice_request)
776 impl Writeable for UnsignedInvoiceRequest {
777 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
778 WithoutLength(&self.bytes).write(writer)
782 impl Writeable for InvoiceRequest {
783 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
784 WithoutLength(&self.bytes).write(writer)
788 impl Writeable for InvoiceRequestContents {
789 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
790 self.as_tlv_stream().write(writer)
794 /// Valid type range for invoice_request TLV records.
795 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
797 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
799 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
800 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
802 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
803 (80, chain: ChainHash),
804 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
805 (84, features: (InvoiceRequestFeatures, WithoutLength)),
806 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
807 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
808 (89, payer_note: (String, WithoutLength)),
811 type FullInvoiceRequestTlvStream =
812 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
815 type FullInvoiceRequestTlvStreamRef<'a> = (
816 PayerTlvStreamRef<'a>,
817 OfferTlvStreamRef<'a>,
818 InvoiceRequestTlvStreamRef<'a>,
819 SignatureTlvStreamRef<'a>,
822 impl SeekReadable for FullInvoiceRequestTlvStream {
823 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
824 let payer = SeekReadable::read(r)?;
825 let offer = SeekReadable::read(r)?;
826 let invoice_request = SeekReadable::read(r)?;
827 let signature = SeekReadable::read(r)?;
829 Ok((payer, offer, invoice_request, signature))
833 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
835 type PartialInvoiceRequestTlvStreamRef<'a> = (
836 PayerTlvStreamRef<'a>,
837 OfferTlvStreamRef<'a>,
838 InvoiceRequestTlvStreamRef<'a>,
841 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
842 type Error = Bolt12ParseError;
844 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
845 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
846 let ParsedMessage { bytes, tlv_stream } = invoice_request;
848 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
850 let contents = InvoiceRequestContents::try_from(
851 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
854 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
856 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
860 impl TryFrom<Vec<u8>> for InvoiceRequest {
861 type Error = Bolt12ParseError;
863 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
864 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
865 let ParsedMessage { bytes, tlv_stream } = invoice_request;
867 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
868 SignatureTlvStream { signature },
870 let contents = InvoiceRequestContents::try_from(
871 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
874 let signature = match signature {
875 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
876 Some(signature) => signature,
878 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
879 merkle::verify_signature(&signature, message, contents.payer_id)?;
881 Ok(InvoiceRequest { bytes, contents, signature })
885 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
886 type Error = Bolt12SemanticError;
888 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
890 PayerTlvStream { metadata },
892 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
895 let payer = match metadata {
896 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
897 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
899 let offer = OfferContents::try_from(offer_tlv_stream)?;
901 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
902 return Err(Bolt12SemanticError::UnsupportedChain);
905 if offer.amount().is_none() && amount.is_none() {
906 return Err(Bolt12SemanticError::MissingAmount);
909 offer.check_quantity(quantity)?;
910 offer.check_amount_msats_for_quantity(amount, quantity)?;
912 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
914 let payer_id = match payer_id {
915 None => return Err(Bolt12SemanticError::MissingPayerId),
916 Some(payer_id) => payer_id,
919 Ok(InvoiceRequestContents {
920 inner: InvoiceRequestContentsWithoutPayerId {
921 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
930 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
932 use bitcoin::blockdata::constants::ChainHash;
933 use bitcoin::network::constants::Network;
934 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
935 use core::convert::{Infallible, TryFrom};
936 use core::num::NonZeroU64;
937 #[cfg(feature = "std")]
938 use core::time::Duration;
939 use crate::sign::KeyMaterial;
940 use crate::ln::channelmanager::PaymentId;
941 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
942 use crate::ln::inbound_payment::ExpandedKey;
943 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
944 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
945 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
946 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
947 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
948 use crate::offers::payer::PayerTlvStreamRef;
949 use crate::offers::test_utils::*;
950 use crate::util::ser::{BigSize, Writeable};
951 use crate::util::string::PrintableString;
954 fn builds_invoice_request_with_defaults() {
955 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
958 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
961 let mut buffer = Vec::new();
962 unsigned_invoice_request.write(&mut buffer).unwrap();
964 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
965 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
966 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
967 assert_eq!(unsigned_invoice_request.metadata(), None);
968 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
969 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
970 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
971 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
972 assert_eq!(unsigned_invoice_request.paths(), &[]);
973 assert_eq!(unsigned_invoice_request.issuer(), None);
974 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
975 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
976 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
977 assert_eq!(unsigned_invoice_request.amount_msats(), None);
978 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
979 assert_eq!(unsigned_invoice_request.quantity(), None);
980 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
981 assert_eq!(unsigned_invoice_request.payer_note(), None);
983 match UnsignedInvoiceRequest::try_from(buffer) {
984 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
986 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
987 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
991 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
993 let mut buffer = Vec::new();
994 invoice_request.write(&mut buffer).unwrap();
996 assert_eq!(invoice_request.bytes, buffer.as_slice());
997 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
998 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
999 assert_eq!(invoice_request.metadata(), None);
1000 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1001 assert_eq!(invoice_request.description(), PrintableString("foo"));
1002 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1003 assert_eq!(invoice_request.absolute_expiry(), None);
1004 assert_eq!(invoice_request.paths(), &[]);
1005 assert_eq!(invoice_request.issuer(), None);
1006 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1007 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1008 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1009 assert_eq!(invoice_request.amount_msats(), None);
1010 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1011 assert_eq!(invoice_request.quantity(), None);
1012 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1013 assert_eq!(invoice_request.payer_note(), None);
1015 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1016 assert!(merkle::verify_signature(&invoice_request.signature, message, payer_pubkey()).is_ok());
1019 invoice_request.as_tlv_stream(),
1021 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1027 description: Some(&String::from("foo")),
1029 absolute_expiry: None,
1033 node_id: Some(&recipient_pubkey()),
1035 InvoiceRequestTlvStreamRef {
1040 payer_id: Some(&payer_pubkey()),
1043 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1047 if let Err(e) = InvoiceRequest::try_from(buffer) {
1048 panic!("error parsing invoice request: {:?}", e);
1052 #[cfg(feature = "std")]
1054 fn builds_invoice_request_from_offer_with_expiration() {
1055 let future_expiry = Duration::from_secs(u64::max_value());
1056 let past_expiry = Duration::from_secs(0);
1058 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1060 .absolute_expiry(future_expiry)
1062 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1065 panic!("error building invoice_request: {:?}", e);
1068 match OfferBuilder::new("foo".into(), recipient_pubkey())
1070 .absolute_expiry(past_expiry)
1072 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1075 Ok(_) => panic!("expected error"),
1076 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1081 fn builds_invoice_request_with_derived_metadata() {
1082 let payer_id = payer_pubkey();
1083 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1084 let entropy = FixedEntropy {};
1085 let secp_ctx = Secp256k1::new();
1086 let payment_id = PaymentId([1; 32]);
1088 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1091 let invoice_request = offer
1092 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1095 .sign(payer_sign).unwrap();
1096 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1098 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1101 .sign(recipient_sign).unwrap();
1102 match invoice.verify(&expanded_key, &secp_ctx) {
1103 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1104 Err(()) => panic!("verification failed"),
1107 // Fails verification with altered fields
1109 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1110 mut invoice_tlv_stream, mut signature_tlv_stream
1111 ) = invoice.as_tlv_stream();
1112 invoice_request_tlv_stream.amount = Some(2000);
1113 invoice_tlv_stream.amount = Some(2000);
1116 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1117 let mut bytes = Vec::new();
1118 tlv_stream.write(&mut bytes).unwrap();
1120 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1121 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1122 signature_tlv_stream.signature = Some(&signature);
1124 let mut encoded_invoice = bytes;
1125 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1127 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1128 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1130 // Fails verification with altered metadata
1132 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1133 mut signature_tlv_stream
1134 ) = invoice.as_tlv_stream();
1135 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1136 payer_tlv_stream.metadata = Some(&metadata);
1139 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1140 let mut bytes = Vec::new();
1141 tlv_stream.write(&mut bytes).unwrap();
1143 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1144 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1145 signature_tlv_stream.signature = Some(&signature);
1147 let mut encoded_invoice = bytes;
1148 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1150 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1151 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1155 fn builds_invoice_request_with_derived_payer_id() {
1156 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1157 let entropy = FixedEntropy {};
1158 let secp_ctx = Secp256k1::new();
1159 let payment_id = PaymentId([1; 32]);
1161 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1164 let invoice_request = offer
1165 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1170 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1173 .sign(recipient_sign).unwrap();
1174 match invoice.verify(&expanded_key, &secp_ctx) {
1175 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1176 Err(()) => panic!("verification failed"),
1179 // Fails verification with altered fields
1181 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1182 mut invoice_tlv_stream, mut signature_tlv_stream
1183 ) = invoice.as_tlv_stream();
1184 invoice_request_tlv_stream.amount = Some(2000);
1185 invoice_tlv_stream.amount = Some(2000);
1188 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1189 let mut bytes = Vec::new();
1190 tlv_stream.write(&mut bytes).unwrap();
1192 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1193 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1194 signature_tlv_stream.signature = Some(&signature);
1196 let mut encoded_invoice = bytes;
1197 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1199 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1200 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1202 // Fails verification with altered payer id
1204 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1205 mut signature_tlv_stream
1206 ) = invoice.as_tlv_stream();
1207 let payer_id = pubkey(1);
1208 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1211 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1212 let mut bytes = Vec::new();
1213 tlv_stream.write(&mut bytes).unwrap();
1215 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1216 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1217 signature_tlv_stream.signature = Some(&signature);
1219 let mut encoded_invoice = bytes;
1220 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1222 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1223 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1227 fn builds_invoice_request_with_chain() {
1228 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1229 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1231 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1234 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1235 .chain(Network::Bitcoin).unwrap()
1237 .sign(payer_sign).unwrap();
1238 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1239 assert_eq!(invoice_request.chain(), mainnet);
1240 assert_eq!(tlv_stream.chain, None);
1242 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1244 .chain(Network::Testnet)
1246 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1247 .chain(Network::Testnet).unwrap()
1249 .sign(payer_sign).unwrap();
1250 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1251 assert_eq!(invoice_request.chain(), testnet);
1252 assert_eq!(tlv_stream.chain, Some(&testnet));
1254 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1256 .chain(Network::Bitcoin)
1257 .chain(Network::Testnet)
1259 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1260 .chain(Network::Bitcoin).unwrap()
1262 .sign(payer_sign).unwrap();
1263 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1264 assert_eq!(invoice_request.chain(), mainnet);
1265 assert_eq!(tlv_stream.chain, None);
1267 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1269 .chain(Network::Bitcoin)
1270 .chain(Network::Testnet)
1272 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1273 .chain(Network::Bitcoin).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 match OfferBuilder::new("foo".into(), recipient_pubkey())
1283 .chain(Network::Testnet)
1285 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1286 .chain(Network::Bitcoin)
1288 Ok(_) => panic!("expected error"),
1289 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1292 match OfferBuilder::new("foo".into(), recipient_pubkey())
1294 .chain(Network::Testnet)
1296 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1299 Ok(_) => panic!("expected error"),
1300 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1305 fn builds_invoice_request_with_amount() {
1306 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1309 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1310 .amount_msats(1000).unwrap()
1312 .sign(payer_sign).unwrap();
1313 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1314 assert_eq!(invoice_request.amount_msats(), Some(1000));
1315 assert_eq!(tlv_stream.amount, Some(1000));
1317 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1320 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1321 .amount_msats(1001).unwrap()
1322 .amount_msats(1000).unwrap()
1324 .sign(payer_sign).unwrap();
1325 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1326 assert_eq!(invoice_request.amount_msats(), Some(1000));
1327 assert_eq!(tlv_stream.amount, Some(1000));
1329 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1333 .amount_msats(1001).unwrap()
1335 .sign(payer_sign).unwrap();
1336 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1337 assert_eq!(invoice_request.amount_msats(), Some(1001));
1338 assert_eq!(tlv_stream.amount, Some(1001));
1340 match OfferBuilder::new("foo".into(), recipient_pubkey())
1343 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1346 Ok(_) => panic!("expected error"),
1347 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1350 match OfferBuilder::new("foo".into(), recipient_pubkey())
1352 .supported_quantity(Quantity::Unbounded)
1354 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1355 .quantity(2).unwrap()
1358 Ok(_) => panic!("expected error"),
1359 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1362 match OfferBuilder::new("foo".into(), recipient_pubkey())
1365 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1366 .amount_msats(MAX_VALUE_MSAT + 1)
1368 Ok(_) => panic!("expected error"),
1369 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1372 match OfferBuilder::new("foo".into(), recipient_pubkey())
1374 .supported_quantity(Quantity::Unbounded)
1376 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1377 .amount_msats(1000).unwrap()
1378 .quantity(2).unwrap()
1381 Ok(_) => panic!("expected error"),
1382 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1385 match OfferBuilder::new("foo".into(), recipient_pubkey())
1387 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1390 Ok(_) => panic!("expected error"),
1391 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1394 match OfferBuilder::new("foo".into(), recipient_pubkey())
1396 .supported_quantity(Quantity::Unbounded)
1398 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1399 .quantity(u64::max_value()).unwrap()
1402 Ok(_) => panic!("expected error"),
1403 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1408 fn builds_invoice_request_with_features() {
1409 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1412 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1413 .features_unchecked(InvoiceRequestFeatures::unknown())
1415 .sign(payer_sign).unwrap();
1416 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1417 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1418 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1420 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1423 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1424 .features_unchecked(InvoiceRequestFeatures::unknown())
1425 .features_unchecked(InvoiceRequestFeatures::empty())
1427 .sign(payer_sign).unwrap();
1428 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1429 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1430 assert_eq!(tlv_stream.features, None);
1434 fn builds_invoice_request_with_quantity() {
1435 let one = NonZeroU64::new(1).unwrap();
1436 let ten = NonZeroU64::new(10).unwrap();
1438 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1440 .supported_quantity(Quantity::One)
1442 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1444 .sign(payer_sign).unwrap();
1445 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1446 assert_eq!(invoice_request.quantity(), None);
1447 assert_eq!(tlv_stream.quantity, None);
1449 match OfferBuilder::new("foo".into(), recipient_pubkey())
1451 .supported_quantity(Quantity::One)
1453 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1454 .amount_msats(2_000).unwrap()
1457 Ok(_) => panic!("expected error"),
1458 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1461 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1463 .supported_quantity(Quantity::Bounded(ten))
1465 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1466 .amount_msats(10_000).unwrap()
1467 .quantity(10).unwrap()
1469 .sign(payer_sign).unwrap();
1470 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1471 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1472 assert_eq!(tlv_stream.amount, Some(10_000));
1474 match OfferBuilder::new("foo".into(), recipient_pubkey())
1476 .supported_quantity(Quantity::Bounded(ten))
1478 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1479 .amount_msats(11_000).unwrap()
1482 Ok(_) => panic!("expected error"),
1483 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1486 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1488 .supported_quantity(Quantity::Unbounded)
1490 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1491 .amount_msats(2_000).unwrap()
1492 .quantity(2).unwrap()
1494 .sign(payer_sign).unwrap();
1495 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1496 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1497 assert_eq!(tlv_stream.amount, Some(2_000));
1499 match OfferBuilder::new("foo".into(), recipient_pubkey())
1501 .supported_quantity(Quantity::Unbounded)
1503 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506 Ok(_) => panic!("expected error"),
1507 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1510 match OfferBuilder::new("foo".into(), recipient_pubkey())
1512 .supported_quantity(Quantity::Bounded(one))
1514 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1517 Ok(_) => panic!("expected error"),
1518 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1523 fn builds_invoice_request_with_payer_note() {
1524 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1527 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1528 .payer_note("bar".into())
1530 .sign(payer_sign).unwrap();
1531 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1532 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1533 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1535 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1538 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1539 .payer_note("bar".into())
1540 .payer_note("baz".into())
1542 .sign(payer_sign).unwrap();
1543 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1544 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1545 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1549 fn fails_signing_invoice_request() {
1550 match OfferBuilder::new("foo".into(), recipient_pubkey())
1553 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1557 Ok(_) => panic!("expected error"),
1558 Err(e) => assert_eq!(e, SignError::Signing(())),
1561 match OfferBuilder::new("foo".into(), recipient_pubkey())
1564 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1566 .sign(recipient_sign)
1568 Ok(_) => panic!("expected error"),
1569 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1574 fn fails_responding_with_unknown_required_features() {
1575 match OfferBuilder::new("foo".into(), recipient_pubkey())
1578 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1579 .features_unchecked(InvoiceRequestFeatures::unknown())
1581 .sign(payer_sign).unwrap()
1582 .respond_with_no_std(payment_paths(), payment_hash(), now())
1584 Ok(_) => panic!("expected error"),
1585 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1590 fn parses_invoice_request_with_metadata() {
1591 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1594 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1596 .sign(payer_sign).unwrap();
1598 let mut buffer = Vec::new();
1599 invoice_request.write(&mut buffer).unwrap();
1601 if let Err(e) = InvoiceRequest::try_from(buffer) {
1602 panic!("error parsing invoice_request: {:?}", e);
1607 fn parses_invoice_request_with_chain() {
1608 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1611 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1612 .chain(Network::Bitcoin).unwrap()
1614 .sign(payer_sign).unwrap();
1616 let mut buffer = Vec::new();
1617 invoice_request.write(&mut buffer).unwrap();
1619 if let Err(e) = InvoiceRequest::try_from(buffer) {
1620 panic!("error parsing invoice_request: {:?}", e);
1623 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1626 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1627 .chain_unchecked(Network::Testnet)
1629 .sign(payer_sign).unwrap();
1631 let mut buffer = Vec::new();
1632 invoice_request.write(&mut buffer).unwrap();
1634 match InvoiceRequest::try_from(buffer) {
1635 Ok(_) => panic!("expected error"),
1636 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1641 fn parses_invoice_request_with_amount() {
1642 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1645 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1647 .sign(payer_sign).unwrap();
1649 let mut buffer = Vec::new();
1650 invoice_request.write(&mut buffer).unwrap();
1652 if let Err(e) = InvoiceRequest::try_from(buffer) {
1653 panic!("error parsing invoice_request: {:?}", e);
1656 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1658 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1659 .amount_msats(1000).unwrap()
1661 .sign(payer_sign).unwrap();
1663 let mut buffer = Vec::new();
1664 invoice_request.write(&mut buffer).unwrap();
1666 if let Err(e) = InvoiceRequest::try_from(buffer) {
1667 panic!("error parsing invoice_request: {:?}", e);
1670 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 match InvoiceRequest::try_from(buffer) {
1680 Ok(_) => panic!("expected error"),
1681 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1684 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1687 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1688 .amount_msats_unchecked(999)
1690 .sign(payer_sign).unwrap();
1692 let mut buffer = Vec::new();
1693 invoice_request.write(&mut buffer).unwrap();
1695 match InvoiceRequest::try_from(buffer) {
1696 Ok(_) => panic!("expected error"),
1697 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1700 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1701 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1703 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1705 .sign(payer_sign).unwrap();
1707 let mut buffer = Vec::new();
1708 invoice_request.write(&mut buffer).unwrap();
1710 match InvoiceRequest::try_from(buffer) {
1711 Ok(_) => panic!("expected error"),
1713 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1717 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1719 .supported_quantity(Quantity::Unbounded)
1721 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1722 .quantity(u64::max_value()).unwrap()
1724 .sign(payer_sign).unwrap();
1726 let mut buffer = Vec::new();
1727 invoice_request.write(&mut buffer).unwrap();
1729 match InvoiceRequest::try_from(buffer) {
1730 Ok(_) => panic!("expected error"),
1731 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1736 fn parses_invoice_request_with_quantity() {
1737 let one = NonZeroU64::new(1).unwrap();
1738 let ten = NonZeroU64::new(10).unwrap();
1740 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1742 .supported_quantity(Quantity::One)
1744 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1746 .sign(payer_sign).unwrap();
1748 let mut buffer = Vec::new();
1749 invoice_request.write(&mut buffer).unwrap();
1751 if let Err(e) = InvoiceRequest::try_from(buffer) {
1752 panic!("error parsing invoice_request: {:?}", e);
1755 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1757 .supported_quantity(Quantity::One)
1759 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1760 .amount_msats(2_000).unwrap()
1761 .quantity_unchecked(2)
1763 .sign(payer_sign).unwrap();
1765 let mut buffer = Vec::new();
1766 invoice_request.write(&mut buffer).unwrap();
1768 match InvoiceRequest::try_from(buffer) {
1769 Ok(_) => panic!("expected error"),
1771 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1775 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1777 .supported_quantity(Quantity::Bounded(ten))
1779 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1780 .amount_msats(10_000).unwrap()
1781 .quantity(10).unwrap()
1783 .sign(payer_sign).unwrap();
1785 let mut buffer = Vec::new();
1786 invoice_request.write(&mut buffer).unwrap();
1788 if let Err(e) = InvoiceRequest::try_from(buffer) {
1789 panic!("error parsing invoice_request: {:?}", e);
1792 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1794 .supported_quantity(Quantity::Bounded(ten))
1796 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1797 .amount_msats(11_000).unwrap()
1798 .quantity_unchecked(11)
1800 .sign(payer_sign).unwrap();
1802 let mut buffer = Vec::new();
1803 invoice_request.write(&mut buffer).unwrap();
1805 match InvoiceRequest::try_from(buffer) {
1806 Ok(_) => panic!("expected error"),
1807 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1810 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1812 .supported_quantity(Quantity::Unbounded)
1814 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1815 .amount_msats(2_000).unwrap()
1816 .quantity(2).unwrap()
1818 .sign(payer_sign).unwrap();
1820 let mut buffer = Vec::new();
1821 invoice_request.write(&mut buffer).unwrap();
1823 if let Err(e) = InvoiceRequest::try_from(buffer) {
1824 panic!("error parsing invoice_request: {:?}", e);
1827 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1829 .supported_quantity(Quantity::Unbounded)
1831 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1833 .sign(payer_sign).unwrap();
1835 let mut buffer = Vec::new();
1836 invoice_request.write(&mut buffer).unwrap();
1838 match InvoiceRequest::try_from(buffer) {
1839 Ok(_) => panic!("expected error"),
1840 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1843 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1845 .supported_quantity(Quantity::Bounded(one))
1847 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1849 .sign(payer_sign).unwrap();
1851 let mut buffer = Vec::new();
1852 invoice_request.write(&mut buffer).unwrap();
1854 match InvoiceRequest::try_from(buffer) {
1855 Ok(_) => panic!("expected error"),
1856 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1861 fn fails_parsing_invoice_request_without_metadata() {
1862 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1865 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1867 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1868 tlv_stream.0.metadata = None;
1870 let mut buffer = Vec::new();
1871 tlv_stream.write(&mut buffer).unwrap();
1873 match InvoiceRequest::try_from(buffer) {
1874 Ok(_) => panic!("expected error"),
1876 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1882 fn fails_parsing_invoice_request_without_payer_id() {
1883 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1886 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1888 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1889 tlv_stream.2.payer_id = None;
1891 let mut buffer = Vec::new();
1892 tlv_stream.write(&mut buffer).unwrap();
1894 match InvoiceRequest::try_from(buffer) {
1895 Ok(_) => panic!("expected error"),
1896 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1901 fn fails_parsing_invoice_request_without_node_id() {
1902 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1905 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1907 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1908 tlv_stream.1.node_id = None;
1910 let mut buffer = Vec::new();
1911 tlv_stream.write(&mut buffer).unwrap();
1913 match InvoiceRequest::try_from(buffer) {
1914 Ok(_) => panic!("expected error"),
1916 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1922 fn fails_parsing_invoice_request_without_signature() {
1923 let mut buffer = Vec::new();
1924 OfferBuilder::new("foo".into(), recipient_pubkey())
1927 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1930 .write(&mut buffer).unwrap();
1932 match InvoiceRequest::try_from(buffer) {
1933 Ok(_) => panic!("expected error"),
1934 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1939 fn fails_parsing_invoice_request_with_invalid_signature() {
1940 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1943 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1945 .sign(payer_sign).unwrap();
1946 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1947 *last_signature_byte = last_signature_byte.wrapping_add(1);
1949 let mut buffer = Vec::new();
1950 invoice_request.write(&mut buffer).unwrap();
1952 match InvoiceRequest::try_from(buffer) {
1953 Ok(_) => panic!("expected error"),
1955 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1961 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1962 let secp_ctx = Secp256k1::new();
1963 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1964 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1967 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1969 .sign::<_, Infallible>(
1970 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1974 let mut encoded_invoice_request = Vec::new();
1975 invoice_request.write(&mut encoded_invoice_request).unwrap();
1976 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1977 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1978 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1980 match InvoiceRequest::try_from(encoded_invoice_request) {
1981 Ok(_) => panic!("expected error"),
1982 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),