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 {
611 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
612 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
613 self.contents.as_tlv_stream();
614 let signature_tlv_stream = SignatureTlvStreamRef {
615 signature: Some(&self.signature),
617 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
621 impl VerifiedInvoiceRequest {
622 offer_accessors!(self, self.inner.contents.inner.offer);
623 invoice_request_accessors!(self, self.inner.contents);
625 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
626 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
628 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
630 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
632 /// [`Duration`]: core::time::Duration
633 #[cfg(feature = "std")]
635 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
636 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
637 self.inner.respond_with(payment_paths, payment_hash)
640 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
642 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
644 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
645 pub fn respond_with_no_std(
646 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
647 created_at: core::time::Duration
648 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
649 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
652 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
653 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
654 /// the same [`ExpandedKey`] as the one used to create the offer.
656 /// See [`InvoiceRequest::respond_with`] for further details.
658 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
660 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
661 #[cfg(feature = "std")]
662 pub fn respond_using_derived_keys(
663 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
664 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
665 let created_at = std::time::SystemTime::now()
666 .duration_since(std::time::SystemTime::UNIX_EPOCH)
667 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
669 self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
672 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
673 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
674 /// the same [`ExpandedKey`] as the one used to create the offer.
676 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
678 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
680 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
681 pub fn respond_using_derived_keys_no_std(
682 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
683 created_at: core::time::Duration
684 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
685 if self.inner.invoice_request_features().requires_unknown_bits() {
686 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
689 let keys = match self.keys {
690 None => return Err(Bolt12SemanticError::InvalidMetadata),
694 InvoiceBuilder::for_offer_using_keys(
695 &self.inner, payment_paths, created_at, payment_hash, keys
700 impl InvoiceRequestContents {
701 pub(super) fn metadata(&self) -> &[u8] {
702 self.inner.metadata()
705 pub(super) fn derives_keys(&self) -> bool {
706 self.inner.payer.0.derives_payer_keys()
709 pub(super) fn chain(&self) -> ChainHash {
713 pub(super) fn amount_msats(&self) -> Option<u64> {
714 self.inner.amount_msats
717 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
721 pub(super) fn quantity(&self) -> Option<u64> {
725 pub(super) fn payer_id(&self) -> PublicKey {
729 pub(super) fn payer_note(&self) -> Option<PrintableString> {
730 self.inner.payer_note.as_ref()
731 .map(|payer_note| PrintableString(payer_note.as_str()))
734 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
735 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
736 invoice_request.payer_id = Some(&self.payer_id);
737 (payer, offer, invoice_request)
741 impl InvoiceRequestContentsWithoutPayerId {
742 pub(super) fn metadata(&self) -> &[u8] {
743 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
746 pub(super) fn chain(&self) -> ChainHash {
747 self.chain.unwrap_or_else(|| self.offer.implied_chain())
750 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
751 let payer = PayerTlvStreamRef {
752 metadata: self.payer.0.as_bytes(),
755 let offer = self.offer.as_tlv_stream();
758 if self.features == InvoiceRequestFeatures::empty() { None }
759 else { Some(&self.features) }
762 let invoice_request = InvoiceRequestTlvStreamRef {
763 chain: self.chain.as_ref(),
764 amount: self.amount_msats,
766 quantity: self.quantity,
768 payer_note: self.payer_note.as_ref(),
771 (payer, offer, invoice_request)
775 impl Writeable for UnsignedInvoiceRequest {
776 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
777 WithoutLength(&self.bytes).write(writer)
781 impl Writeable for InvoiceRequest {
782 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
783 WithoutLength(&self.bytes).write(writer)
787 impl Writeable for InvoiceRequestContents {
788 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
789 self.as_tlv_stream().write(writer)
793 /// Valid type range for invoice_request TLV records.
794 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
796 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
798 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
799 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
801 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
802 (80, chain: ChainHash),
803 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
804 (84, features: (InvoiceRequestFeatures, WithoutLength)),
805 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
806 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
807 (89, payer_note: (String, WithoutLength)),
810 type FullInvoiceRequestTlvStream =
811 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
813 type FullInvoiceRequestTlvStreamRef<'a> = (
814 PayerTlvStreamRef<'a>,
815 OfferTlvStreamRef<'a>,
816 InvoiceRequestTlvStreamRef<'a>,
817 SignatureTlvStreamRef<'a>,
820 impl SeekReadable for FullInvoiceRequestTlvStream {
821 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
822 let payer = SeekReadable::read(r)?;
823 let offer = SeekReadable::read(r)?;
824 let invoice_request = SeekReadable::read(r)?;
825 let signature = SeekReadable::read(r)?;
827 Ok((payer, offer, invoice_request, signature))
831 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
833 type PartialInvoiceRequestTlvStreamRef<'a> = (
834 PayerTlvStreamRef<'a>,
835 OfferTlvStreamRef<'a>,
836 InvoiceRequestTlvStreamRef<'a>,
839 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
840 type Error = Bolt12ParseError;
842 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
843 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
844 let ParsedMessage { bytes, tlv_stream } = invoice_request;
846 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
848 let contents = InvoiceRequestContents::try_from(
849 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
852 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
854 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
858 impl TryFrom<Vec<u8>> for InvoiceRequest {
859 type Error = Bolt12ParseError;
861 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
862 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
863 let ParsedMessage { bytes, tlv_stream } = invoice_request;
865 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
866 SignatureTlvStream { signature },
868 let contents = InvoiceRequestContents::try_from(
869 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
872 let signature = match signature {
873 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
874 Some(signature) => signature,
876 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
877 merkle::verify_signature(&signature, &message, contents.payer_id)?;
879 Ok(InvoiceRequest { bytes, contents, signature })
883 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
884 type Error = Bolt12SemanticError;
886 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
888 PayerTlvStream { metadata },
890 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
893 let payer = match metadata {
894 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
895 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
897 let offer = OfferContents::try_from(offer_tlv_stream)?;
899 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
900 return Err(Bolt12SemanticError::UnsupportedChain);
903 if offer.amount().is_none() && amount.is_none() {
904 return Err(Bolt12SemanticError::MissingAmount);
907 offer.check_quantity(quantity)?;
908 offer.check_amount_msats_for_quantity(amount, quantity)?;
910 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
912 let payer_id = match payer_id {
913 None => return Err(Bolt12SemanticError::MissingPayerId),
914 Some(payer_id) => payer_id,
917 Ok(InvoiceRequestContents {
918 inner: InvoiceRequestContentsWithoutPayerId {
919 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
928 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
930 use bitcoin::blockdata::constants::ChainHash;
931 use bitcoin::network::constants::Network;
932 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
933 use core::convert::{Infallible, TryFrom};
934 use core::num::NonZeroU64;
935 #[cfg(feature = "std")]
936 use core::time::Duration;
937 use crate::sign::KeyMaterial;
938 use crate::ln::channelmanager::PaymentId;
939 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
940 use crate::ln::inbound_payment::ExpandedKey;
941 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
942 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
943 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
944 use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
945 #[cfg(not(c_bindings))]
947 crate::offers::offer::OfferBuilder,
951 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
953 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
954 use crate::offers::payer::PayerTlvStreamRef;
955 use crate::offers::test_utils::*;
956 use crate::util::ser::{BigSize, Writeable};
957 use crate::util::string::PrintableString;
960 fn builds_invoice_request_with_defaults() {
961 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
964 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
967 let mut buffer = Vec::new();
968 unsigned_invoice_request.write(&mut buffer).unwrap();
970 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
971 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
972 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
973 assert_eq!(unsigned_invoice_request.metadata(), None);
974 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
975 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
976 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
977 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
978 assert_eq!(unsigned_invoice_request.paths(), &[]);
979 assert_eq!(unsigned_invoice_request.issuer(), None);
980 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
981 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
982 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
983 assert_eq!(unsigned_invoice_request.amount_msats(), None);
984 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
985 assert_eq!(unsigned_invoice_request.quantity(), None);
986 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
987 assert_eq!(unsigned_invoice_request.payer_note(), None);
989 match UnsignedInvoiceRequest::try_from(buffer) {
990 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
992 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
993 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
997 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
999 let mut buffer = Vec::new();
1000 invoice_request.write(&mut buffer).unwrap();
1002 assert_eq!(invoice_request.bytes, buffer.as_slice());
1003 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
1004 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1005 assert_eq!(invoice_request.metadata(), None);
1006 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1007 assert_eq!(invoice_request.description(), PrintableString("foo"));
1008 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1009 assert_eq!(invoice_request.absolute_expiry(), None);
1010 assert_eq!(invoice_request.paths(), &[]);
1011 assert_eq!(invoice_request.issuer(), None);
1012 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1013 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1014 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1015 assert_eq!(invoice_request.amount_msats(), None);
1016 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1017 assert_eq!(invoice_request.quantity(), None);
1018 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1019 assert_eq!(invoice_request.payer_note(), None);
1021 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1022 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1025 invoice_request.as_tlv_stream(),
1027 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1033 description: Some(&String::from("foo")),
1035 absolute_expiry: None,
1039 node_id: Some(&recipient_pubkey()),
1041 InvoiceRequestTlvStreamRef {
1046 payer_id: Some(&payer_pubkey()),
1049 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1053 if let Err(e) = InvoiceRequest::try_from(buffer) {
1054 panic!("error parsing invoice request: {:?}", e);
1058 #[cfg(feature = "std")]
1060 fn builds_invoice_request_from_offer_with_expiration() {
1061 let future_expiry = Duration::from_secs(u64::max_value());
1062 let past_expiry = Duration::from_secs(0);
1064 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1066 .absolute_expiry(future_expiry)
1068 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 panic!("error building invoice_request: {:?}", e);
1074 match OfferBuilder::new("foo".into(), recipient_pubkey())
1076 .absolute_expiry(past_expiry)
1078 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1081 Ok(_) => panic!("expected error"),
1082 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1087 fn builds_invoice_request_with_derived_metadata() {
1088 let payer_id = payer_pubkey();
1089 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1090 let entropy = FixedEntropy {};
1091 let secp_ctx = Secp256k1::new();
1092 let payment_id = PaymentId([1; 32]);
1094 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1097 let invoice_request = offer
1098 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1101 .sign(payer_sign).unwrap();
1102 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1104 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1107 .sign(recipient_sign).unwrap();
1108 match invoice.verify(&expanded_key, &secp_ctx) {
1109 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1110 Err(()) => panic!("verification failed"),
1113 // Fails verification with altered fields
1115 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1116 mut invoice_tlv_stream, mut signature_tlv_stream
1117 ) = invoice.as_tlv_stream();
1118 invoice_request_tlv_stream.amount = Some(2000);
1119 invoice_tlv_stream.amount = Some(2000);
1122 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1123 let mut bytes = Vec::new();
1124 tlv_stream.write(&mut bytes).unwrap();
1126 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1127 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1128 signature_tlv_stream.signature = Some(&signature);
1130 let mut encoded_invoice = bytes;
1131 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1133 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1134 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1136 // Fails verification with altered metadata
1138 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1139 mut signature_tlv_stream
1140 ) = invoice.as_tlv_stream();
1141 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1142 payer_tlv_stream.metadata = Some(&metadata);
1145 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1146 let mut bytes = Vec::new();
1147 tlv_stream.write(&mut bytes).unwrap();
1149 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1150 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1151 signature_tlv_stream.signature = Some(&signature);
1153 let mut encoded_invoice = bytes;
1154 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1156 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1157 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1161 fn builds_invoice_request_with_derived_payer_id() {
1162 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1163 let entropy = FixedEntropy {};
1164 let secp_ctx = Secp256k1::new();
1165 let payment_id = PaymentId([1; 32]);
1167 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1170 let invoice_request = offer
1171 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1176 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1179 .sign(recipient_sign).unwrap();
1180 match invoice.verify(&expanded_key, &secp_ctx) {
1181 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1182 Err(()) => panic!("verification failed"),
1185 // Fails verification with altered fields
1187 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1188 mut invoice_tlv_stream, mut signature_tlv_stream
1189 ) = invoice.as_tlv_stream();
1190 invoice_request_tlv_stream.amount = Some(2000);
1191 invoice_tlv_stream.amount = Some(2000);
1194 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1195 let mut bytes = Vec::new();
1196 tlv_stream.write(&mut bytes).unwrap();
1198 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1199 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1200 signature_tlv_stream.signature = Some(&signature);
1202 let mut encoded_invoice = bytes;
1203 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1205 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1206 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1208 // Fails verification with altered payer id
1210 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1211 mut signature_tlv_stream
1212 ) = invoice.as_tlv_stream();
1213 let payer_id = pubkey(1);
1214 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1217 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1218 let mut bytes = Vec::new();
1219 tlv_stream.write(&mut bytes).unwrap();
1221 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1222 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1223 signature_tlv_stream.signature = Some(&signature);
1225 let mut encoded_invoice = bytes;
1226 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1228 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1229 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1233 fn builds_invoice_request_with_chain() {
1234 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1235 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1237 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1240 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1241 .chain(Network::Bitcoin).unwrap()
1243 .sign(payer_sign).unwrap();
1244 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1245 assert_eq!(invoice_request.chain(), mainnet);
1246 assert_eq!(tlv_stream.chain, None);
1248 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1250 .chain(Network::Testnet)
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1253 .chain(Network::Testnet).unwrap()
1255 .sign(payer_sign).unwrap();
1256 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1257 assert_eq!(invoice_request.chain(), testnet);
1258 assert_eq!(tlv_stream.chain, Some(&testnet));
1260 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1262 .chain(Network::Bitcoin)
1263 .chain(Network::Testnet)
1265 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1266 .chain(Network::Bitcoin).unwrap()
1268 .sign(payer_sign).unwrap();
1269 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1270 assert_eq!(invoice_request.chain(), mainnet);
1271 assert_eq!(tlv_stream.chain, None);
1273 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1275 .chain(Network::Bitcoin)
1276 .chain(Network::Testnet)
1278 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1279 .chain(Network::Bitcoin).unwrap()
1280 .chain(Network::Testnet).unwrap()
1282 .sign(payer_sign).unwrap();
1283 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1284 assert_eq!(invoice_request.chain(), testnet);
1285 assert_eq!(tlv_stream.chain, Some(&testnet));
1287 match OfferBuilder::new("foo".into(), recipient_pubkey())
1289 .chain(Network::Testnet)
1291 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1292 .chain(Network::Bitcoin)
1294 Ok(_) => panic!("expected error"),
1295 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1298 match OfferBuilder::new("foo".into(), recipient_pubkey())
1300 .chain(Network::Testnet)
1302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1305 Ok(_) => panic!("expected error"),
1306 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1311 fn builds_invoice_request_with_amount() {
1312 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1315 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1316 .amount_msats(1000).unwrap()
1318 .sign(payer_sign).unwrap();
1319 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1320 assert_eq!(invoice_request.amount_msats(), Some(1000));
1321 assert_eq!(tlv_stream.amount, Some(1000));
1323 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1326 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1327 .amount_msats(1001).unwrap()
1328 .amount_msats(1000).unwrap()
1330 .sign(payer_sign).unwrap();
1331 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1332 assert_eq!(invoice_request.amount_msats(), Some(1000));
1333 assert_eq!(tlv_stream.amount, Some(1000));
1335 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1338 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1339 .amount_msats(1001).unwrap()
1341 .sign(payer_sign).unwrap();
1342 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1343 assert_eq!(invoice_request.amount_msats(), Some(1001));
1344 assert_eq!(tlv_stream.amount, Some(1001));
1346 match OfferBuilder::new("foo".into(), recipient_pubkey())
1349 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1352 Ok(_) => panic!("expected error"),
1353 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1356 match OfferBuilder::new("foo".into(), recipient_pubkey())
1358 .supported_quantity(Quantity::Unbounded)
1360 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1361 .quantity(2).unwrap()
1364 Ok(_) => panic!("expected error"),
1365 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1368 match OfferBuilder::new("foo".into(), recipient_pubkey())
1371 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1372 .amount_msats(MAX_VALUE_MSAT + 1)
1374 Ok(_) => panic!("expected error"),
1375 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1378 match OfferBuilder::new("foo".into(), recipient_pubkey())
1380 .supported_quantity(Quantity::Unbounded)
1382 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1383 .amount_msats(1000).unwrap()
1384 .quantity(2).unwrap()
1387 Ok(_) => panic!("expected error"),
1388 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1391 match OfferBuilder::new("foo".into(), recipient_pubkey())
1393 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1396 Ok(_) => panic!("expected error"),
1397 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1400 match OfferBuilder::new("foo".into(), recipient_pubkey())
1402 .supported_quantity(Quantity::Unbounded)
1404 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .quantity(u64::max_value()).unwrap()
1408 Ok(_) => panic!("expected error"),
1409 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1414 fn builds_invoice_request_with_features() {
1415 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1418 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1419 .features_unchecked(InvoiceRequestFeatures::unknown())
1421 .sign(payer_sign).unwrap();
1422 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1423 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1424 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1426 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1429 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1430 .features_unchecked(InvoiceRequestFeatures::unknown())
1431 .features_unchecked(InvoiceRequestFeatures::empty())
1433 .sign(payer_sign).unwrap();
1434 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1435 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1436 assert_eq!(tlv_stream.features, None);
1440 fn builds_invoice_request_with_quantity() {
1441 let one = NonZeroU64::new(1).unwrap();
1442 let ten = NonZeroU64::new(10).unwrap();
1444 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1446 .supported_quantity(Quantity::One)
1448 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1450 .sign(payer_sign).unwrap();
1451 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1452 assert_eq!(invoice_request.quantity(), None);
1453 assert_eq!(tlv_stream.quantity, None);
1455 match OfferBuilder::new("foo".into(), recipient_pubkey())
1457 .supported_quantity(Quantity::One)
1459 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1460 .amount_msats(2_000).unwrap()
1463 Ok(_) => panic!("expected error"),
1464 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1467 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1469 .supported_quantity(Quantity::Bounded(ten))
1471 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1472 .amount_msats(10_000).unwrap()
1473 .quantity(10).unwrap()
1475 .sign(payer_sign).unwrap();
1476 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1477 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1478 assert_eq!(tlv_stream.amount, Some(10_000));
1480 match OfferBuilder::new("foo".into(), recipient_pubkey())
1482 .supported_quantity(Quantity::Bounded(ten))
1484 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1485 .amount_msats(11_000).unwrap()
1488 Ok(_) => panic!("expected error"),
1489 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1492 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1494 .supported_quantity(Quantity::Unbounded)
1496 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1497 .amount_msats(2_000).unwrap()
1498 .quantity(2).unwrap()
1500 .sign(payer_sign).unwrap();
1501 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1502 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1503 assert_eq!(tlv_stream.amount, Some(2_000));
1505 match OfferBuilder::new("foo".into(), recipient_pubkey())
1507 .supported_quantity(Quantity::Unbounded)
1509 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1516 match OfferBuilder::new("foo".into(), recipient_pubkey())
1518 .supported_quantity(Quantity::Bounded(one))
1520 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1523 Ok(_) => panic!("expected error"),
1524 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1529 fn builds_invoice_request_with_payer_note() {
1530 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1533 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534 .payer_note("bar".into())
1536 .sign(payer_sign).unwrap();
1537 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1538 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1539 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1541 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1544 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1545 .payer_note("bar".into())
1546 .payer_note("baz".into())
1548 .sign(payer_sign).unwrap();
1549 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1550 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1551 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1555 fn fails_signing_invoice_request() {
1556 match OfferBuilder::new("foo".into(), recipient_pubkey())
1559 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1563 Ok(_) => panic!("expected error"),
1564 Err(e) => assert_eq!(e, SignError::Signing(())),
1567 match OfferBuilder::new("foo".into(), recipient_pubkey())
1570 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1572 .sign(recipient_sign)
1574 Ok(_) => panic!("expected error"),
1575 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1580 fn fails_responding_with_unknown_required_features() {
1581 match OfferBuilder::new("foo".into(), recipient_pubkey())
1584 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1585 .features_unchecked(InvoiceRequestFeatures::unknown())
1587 .sign(payer_sign).unwrap()
1588 .respond_with_no_std(payment_paths(), payment_hash(), now())
1590 Ok(_) => panic!("expected error"),
1591 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1596 fn parses_invoice_request_with_metadata() {
1597 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1600 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1602 .sign(payer_sign).unwrap();
1604 let mut buffer = Vec::new();
1605 invoice_request.write(&mut buffer).unwrap();
1607 if let Err(e) = InvoiceRequest::try_from(buffer) {
1608 panic!("error parsing invoice_request: {:?}", e);
1613 fn parses_invoice_request_with_chain() {
1614 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1617 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1618 .chain(Network::Bitcoin).unwrap()
1620 .sign(payer_sign).unwrap();
1622 let mut buffer = Vec::new();
1623 invoice_request.write(&mut buffer).unwrap();
1625 if let Err(e) = InvoiceRequest::try_from(buffer) {
1626 panic!("error parsing invoice_request: {:?}", e);
1629 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1632 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1633 .chain_unchecked(Network::Testnet)
1635 .sign(payer_sign).unwrap();
1637 let mut buffer = Vec::new();
1638 invoice_request.write(&mut buffer).unwrap();
1640 match InvoiceRequest::try_from(buffer) {
1641 Ok(_) => panic!("expected error"),
1642 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1647 fn parses_invoice_request_with_amount() {
1648 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1651 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1653 .sign(payer_sign).unwrap();
1655 let mut buffer = Vec::new();
1656 invoice_request.write(&mut buffer).unwrap();
1658 if let Err(e) = InvoiceRequest::try_from(buffer) {
1659 panic!("error parsing invoice_request: {:?}", e);
1662 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1664 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1665 .amount_msats(1000).unwrap()
1667 .sign(payer_sign).unwrap();
1669 let mut buffer = Vec::new();
1670 invoice_request.write(&mut buffer).unwrap();
1672 if let Err(e) = InvoiceRequest::try_from(buffer) {
1673 panic!("error parsing invoice_request: {:?}", e);
1676 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1678 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1680 .sign(payer_sign).unwrap();
1682 let mut buffer = Vec::new();
1683 invoice_request.write(&mut buffer).unwrap();
1685 match InvoiceRequest::try_from(buffer) {
1686 Ok(_) => panic!("expected error"),
1687 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1690 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1693 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1694 .amount_msats_unchecked(999)
1696 .sign(payer_sign).unwrap();
1698 let mut buffer = Vec::new();
1699 invoice_request.write(&mut buffer).unwrap();
1701 match InvoiceRequest::try_from(buffer) {
1702 Ok(_) => panic!("expected error"),
1703 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1706 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1707 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1709 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1711 .sign(payer_sign).unwrap();
1713 let mut buffer = Vec::new();
1714 invoice_request.write(&mut buffer).unwrap();
1716 match InvoiceRequest::try_from(buffer) {
1717 Ok(_) => panic!("expected error"),
1719 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1723 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1725 .supported_quantity(Quantity::Unbounded)
1727 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1728 .quantity(u64::max_value()).unwrap()
1730 .sign(payer_sign).unwrap();
1732 let mut buffer = Vec::new();
1733 invoice_request.write(&mut buffer).unwrap();
1735 match InvoiceRequest::try_from(buffer) {
1736 Ok(_) => panic!("expected error"),
1737 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1742 fn parses_invoice_request_with_quantity() {
1743 let one = NonZeroU64::new(1).unwrap();
1744 let ten = NonZeroU64::new(10).unwrap();
1746 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1748 .supported_quantity(Quantity::One)
1750 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1752 .sign(payer_sign).unwrap();
1754 let mut buffer = Vec::new();
1755 invoice_request.write(&mut buffer).unwrap();
1757 if let Err(e) = InvoiceRequest::try_from(buffer) {
1758 panic!("error parsing invoice_request: {:?}", e);
1761 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1763 .supported_quantity(Quantity::One)
1765 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1766 .amount_msats(2_000).unwrap()
1767 .quantity_unchecked(2)
1769 .sign(payer_sign).unwrap();
1771 let mut buffer = Vec::new();
1772 invoice_request.write(&mut buffer).unwrap();
1774 match InvoiceRequest::try_from(buffer) {
1775 Ok(_) => panic!("expected error"),
1777 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1781 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1783 .supported_quantity(Quantity::Bounded(ten))
1785 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1786 .amount_msats(10_000).unwrap()
1787 .quantity(10).unwrap()
1789 .sign(payer_sign).unwrap();
1791 let mut buffer = Vec::new();
1792 invoice_request.write(&mut buffer).unwrap();
1794 if let Err(e) = InvoiceRequest::try_from(buffer) {
1795 panic!("error parsing invoice_request: {:?}", e);
1798 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1800 .supported_quantity(Quantity::Bounded(ten))
1802 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1803 .amount_msats(11_000).unwrap()
1804 .quantity_unchecked(11)
1806 .sign(payer_sign).unwrap();
1808 let mut buffer = Vec::new();
1809 invoice_request.write(&mut buffer).unwrap();
1811 match InvoiceRequest::try_from(buffer) {
1812 Ok(_) => panic!("expected error"),
1813 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1816 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1818 .supported_quantity(Quantity::Unbounded)
1820 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1821 .amount_msats(2_000).unwrap()
1822 .quantity(2).unwrap()
1824 .sign(payer_sign).unwrap();
1826 let mut buffer = Vec::new();
1827 invoice_request.write(&mut buffer).unwrap();
1829 if let Err(e) = InvoiceRequest::try_from(buffer) {
1830 panic!("error parsing invoice_request: {:?}", e);
1833 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1835 .supported_quantity(Quantity::Unbounded)
1837 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1839 .sign(payer_sign).unwrap();
1841 let mut buffer = Vec::new();
1842 invoice_request.write(&mut buffer).unwrap();
1844 match InvoiceRequest::try_from(buffer) {
1845 Ok(_) => panic!("expected error"),
1846 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1849 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1851 .supported_quantity(Quantity::Bounded(one))
1853 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1855 .sign(payer_sign).unwrap();
1857 let mut buffer = Vec::new();
1858 invoice_request.write(&mut buffer).unwrap();
1860 match InvoiceRequest::try_from(buffer) {
1861 Ok(_) => panic!("expected error"),
1862 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1867 fn fails_parsing_invoice_request_without_metadata() {
1868 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1871 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1873 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1874 tlv_stream.0.metadata = None;
1876 let mut buffer = Vec::new();
1877 tlv_stream.write(&mut buffer).unwrap();
1879 match InvoiceRequest::try_from(buffer) {
1880 Ok(_) => panic!("expected error"),
1882 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1888 fn fails_parsing_invoice_request_without_payer_id() {
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.2.payer_id = 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"),
1902 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1907 fn fails_parsing_invoice_request_without_node_id() {
1908 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1911 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1913 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1914 tlv_stream.1.node_id = None;
1916 let mut buffer = Vec::new();
1917 tlv_stream.write(&mut buffer).unwrap();
1919 match InvoiceRequest::try_from(buffer) {
1920 Ok(_) => panic!("expected error"),
1922 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1928 fn fails_parsing_invoice_request_without_signature() {
1929 let mut buffer = Vec::new();
1930 OfferBuilder::new("foo".into(), recipient_pubkey())
1933 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1936 .write(&mut buffer).unwrap();
1938 match InvoiceRequest::try_from(buffer) {
1939 Ok(_) => panic!("expected error"),
1940 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1945 fn fails_parsing_invoice_request_with_invalid_signature() {
1946 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1949 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1951 .sign(payer_sign).unwrap();
1952 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1953 *last_signature_byte = last_signature_byte.wrapping_add(1);
1955 let mut buffer = Vec::new();
1956 invoice_request.write(&mut buffer).unwrap();
1958 match InvoiceRequest::try_from(buffer) {
1959 Ok(_) => panic!("expected error"),
1961 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1967 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1968 let secp_ctx = Secp256k1::new();
1969 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1970 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1973 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1975 .sign::<_, Infallible>(
1976 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1980 let mut encoded_invoice_request = Vec::new();
1981 invoice_request.write(&mut encoded_invoice_request).unwrap();
1982 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1983 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1984 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1986 match InvoiceRequest::try_from(encoded_invoice_request) {
1987 Ok(_) => panic!("expected error"),
1988 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),