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, OfferBuilder, OfferTlvStreamRef, Quantity};
945 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
946 use crate::offers::payer::PayerTlvStreamRef;
947 use crate::offers::test_utils::*;
948 use crate::util::ser::{BigSize, Writeable};
949 use crate::util::string::PrintableString;
952 fn builds_invoice_request_with_defaults() {
953 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
956 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
959 let mut buffer = Vec::new();
960 unsigned_invoice_request.write(&mut buffer).unwrap();
962 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
963 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
964 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
965 assert_eq!(unsigned_invoice_request.metadata(), None);
966 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
967 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
968 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
969 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
970 assert_eq!(unsigned_invoice_request.paths(), &[]);
971 assert_eq!(unsigned_invoice_request.issuer(), None);
972 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
973 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
974 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
975 assert_eq!(unsigned_invoice_request.amount_msats(), None);
976 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
977 assert_eq!(unsigned_invoice_request.quantity(), None);
978 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
979 assert_eq!(unsigned_invoice_request.payer_note(), None);
981 match UnsignedInvoiceRequest::try_from(buffer) {
982 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
984 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
985 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
989 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
991 let mut buffer = Vec::new();
992 invoice_request.write(&mut buffer).unwrap();
994 assert_eq!(invoice_request.bytes, buffer.as_slice());
995 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
996 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
997 assert_eq!(invoice_request.metadata(), None);
998 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
999 assert_eq!(invoice_request.description(), PrintableString("foo"));
1000 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1001 assert_eq!(invoice_request.absolute_expiry(), None);
1002 assert_eq!(invoice_request.paths(), &[]);
1003 assert_eq!(invoice_request.issuer(), None);
1004 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1005 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1006 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1007 assert_eq!(invoice_request.amount_msats(), None);
1008 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1009 assert_eq!(invoice_request.quantity(), None);
1010 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1011 assert_eq!(invoice_request.payer_note(), None);
1013 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1014 assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());
1017 invoice_request.as_tlv_stream(),
1019 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1025 description: Some(&String::from("foo")),
1027 absolute_expiry: None,
1031 node_id: Some(&recipient_pubkey()),
1033 InvoiceRequestTlvStreamRef {
1038 payer_id: Some(&payer_pubkey()),
1041 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1045 if let Err(e) = InvoiceRequest::try_from(buffer) {
1046 panic!("error parsing invoice request: {:?}", e);
1050 #[cfg(feature = "std")]
1052 fn builds_invoice_request_from_offer_with_expiration() {
1053 let future_expiry = Duration::from_secs(u64::max_value());
1054 let past_expiry = Duration::from_secs(0);
1056 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1058 .absolute_expiry(future_expiry)
1060 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1063 panic!("error building invoice_request: {:?}", e);
1066 match OfferBuilder::new("foo".into(), recipient_pubkey())
1068 .absolute_expiry(past_expiry)
1070 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 Ok(_) => panic!("expected error"),
1074 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1079 fn builds_invoice_request_with_derived_metadata() {
1080 let payer_id = payer_pubkey();
1081 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1082 let entropy = FixedEntropy {};
1083 let secp_ctx = Secp256k1::new();
1084 let payment_id = PaymentId([1; 32]);
1086 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1089 let invoice_request = offer
1090 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1093 .sign(payer_sign).unwrap();
1094 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1096 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1099 .sign(recipient_sign).unwrap();
1100 match invoice.verify(&expanded_key, &secp_ctx) {
1101 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1102 Err(()) => panic!("verification failed"),
1105 // Fails verification with altered fields
1107 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1108 mut invoice_tlv_stream, mut signature_tlv_stream
1109 ) = invoice.as_tlv_stream();
1110 invoice_request_tlv_stream.amount = Some(2000);
1111 invoice_tlv_stream.amount = Some(2000);
1114 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1115 let mut bytes = Vec::new();
1116 tlv_stream.write(&mut bytes).unwrap();
1118 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1119 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1120 signature_tlv_stream.signature = Some(&signature);
1122 let mut encoded_invoice = bytes;
1123 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1125 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1126 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1128 // Fails verification with altered metadata
1130 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1131 mut signature_tlv_stream
1132 ) = invoice.as_tlv_stream();
1133 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1134 payer_tlv_stream.metadata = Some(&metadata);
1137 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1138 let mut bytes = Vec::new();
1139 tlv_stream.write(&mut bytes).unwrap();
1141 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1142 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1143 signature_tlv_stream.signature = Some(&signature);
1145 let mut encoded_invoice = bytes;
1146 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1148 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1149 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1153 fn builds_invoice_request_with_derived_payer_id() {
1154 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1155 let entropy = FixedEntropy {};
1156 let secp_ctx = Secp256k1::new();
1157 let payment_id = PaymentId([1; 32]);
1159 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1162 let invoice_request = offer
1163 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1168 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1171 .sign(recipient_sign).unwrap();
1172 match invoice.verify(&expanded_key, &secp_ctx) {
1173 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1174 Err(()) => panic!("verification failed"),
1177 // Fails verification with altered fields
1179 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1180 mut invoice_tlv_stream, mut signature_tlv_stream
1181 ) = invoice.as_tlv_stream();
1182 invoice_request_tlv_stream.amount = Some(2000);
1183 invoice_tlv_stream.amount = Some(2000);
1186 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1187 let mut bytes = Vec::new();
1188 tlv_stream.write(&mut bytes).unwrap();
1190 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1191 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1192 signature_tlv_stream.signature = Some(&signature);
1194 let mut encoded_invoice = bytes;
1195 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1197 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1198 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1200 // Fails verification with altered payer id
1202 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1203 mut signature_tlv_stream
1204 ) = invoice.as_tlv_stream();
1205 let payer_id = pubkey(1);
1206 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1209 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1210 let mut bytes = Vec::new();
1211 tlv_stream.write(&mut bytes).unwrap();
1213 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1214 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1215 signature_tlv_stream.signature = Some(&signature);
1217 let mut encoded_invoice = bytes;
1218 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1220 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1221 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1225 fn builds_invoice_request_with_chain() {
1226 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1227 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1229 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1232 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1233 .chain(Network::Bitcoin).unwrap()
1235 .sign(payer_sign).unwrap();
1236 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1237 assert_eq!(invoice_request.chain(), mainnet);
1238 assert_eq!(tlv_stream.chain, None);
1240 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1242 .chain(Network::Testnet)
1244 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1245 .chain(Network::Testnet).unwrap()
1247 .sign(payer_sign).unwrap();
1248 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1249 assert_eq!(invoice_request.chain(), testnet);
1250 assert_eq!(tlv_stream.chain, Some(&testnet));
1252 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1254 .chain(Network::Bitcoin)
1255 .chain(Network::Testnet)
1257 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258 .chain(Network::Bitcoin).unwrap()
1260 .sign(payer_sign).unwrap();
1261 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1262 assert_eq!(invoice_request.chain(), mainnet);
1263 assert_eq!(tlv_stream.chain, None);
1265 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1267 .chain(Network::Bitcoin)
1268 .chain(Network::Testnet)
1270 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271 .chain(Network::Bitcoin).unwrap()
1272 .chain(Network::Testnet).unwrap()
1274 .sign(payer_sign).unwrap();
1275 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1276 assert_eq!(invoice_request.chain(), testnet);
1277 assert_eq!(tlv_stream.chain, Some(&testnet));
1279 match OfferBuilder::new("foo".into(), recipient_pubkey())
1281 .chain(Network::Testnet)
1283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1284 .chain(Network::Bitcoin)
1286 Ok(_) => panic!("expected error"),
1287 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1290 match OfferBuilder::new("foo".into(), recipient_pubkey())
1292 .chain(Network::Testnet)
1294 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1297 Ok(_) => panic!("expected error"),
1298 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1303 fn builds_invoice_request_with_amount() {
1304 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1307 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1308 .amount_msats(1000).unwrap()
1310 .sign(payer_sign).unwrap();
1311 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1312 assert_eq!(invoice_request.amount_msats(), Some(1000));
1313 assert_eq!(tlv_stream.amount, Some(1000));
1315 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1318 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1319 .amount_msats(1001).unwrap()
1320 .amount_msats(1000).unwrap()
1322 .sign(payer_sign).unwrap();
1323 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1324 assert_eq!(invoice_request.amount_msats(), Some(1000));
1325 assert_eq!(tlv_stream.amount, Some(1000));
1327 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1330 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1331 .amount_msats(1001).unwrap()
1333 .sign(payer_sign).unwrap();
1334 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1335 assert_eq!(invoice_request.amount_msats(), Some(1001));
1336 assert_eq!(tlv_stream.amount, Some(1001));
1338 match OfferBuilder::new("foo".into(), recipient_pubkey())
1341 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344 Ok(_) => panic!("expected error"),
1345 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1348 match OfferBuilder::new("foo".into(), recipient_pubkey())
1350 .supported_quantity(Quantity::Unbounded)
1352 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1353 .quantity(2).unwrap()
1356 Ok(_) => panic!("expected error"),
1357 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1360 match OfferBuilder::new("foo".into(), recipient_pubkey())
1363 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1364 .amount_msats(MAX_VALUE_MSAT + 1)
1366 Ok(_) => panic!("expected error"),
1367 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1370 match OfferBuilder::new("foo".into(), recipient_pubkey())
1372 .supported_quantity(Quantity::Unbounded)
1374 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1375 .amount_msats(1000).unwrap()
1376 .quantity(2).unwrap()
1379 Ok(_) => panic!("expected error"),
1380 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1383 match OfferBuilder::new("foo".into(), recipient_pubkey())
1385 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1388 Ok(_) => panic!("expected error"),
1389 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1392 match OfferBuilder::new("foo".into(), recipient_pubkey())
1394 .supported_quantity(Quantity::Unbounded)
1396 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1397 .quantity(u64::max_value()).unwrap()
1400 Ok(_) => panic!("expected error"),
1401 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1406 fn builds_invoice_request_with_features() {
1407 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1410 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1411 .features_unchecked(InvoiceRequestFeatures::unknown())
1413 .sign(payer_sign).unwrap();
1414 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1415 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1416 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1418 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1421 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1422 .features_unchecked(InvoiceRequestFeatures::unknown())
1423 .features_unchecked(InvoiceRequestFeatures::empty())
1425 .sign(payer_sign).unwrap();
1426 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1427 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1428 assert_eq!(tlv_stream.features, None);
1432 fn builds_invoice_request_with_quantity() {
1433 let one = NonZeroU64::new(1).unwrap();
1434 let ten = NonZeroU64::new(10).unwrap();
1436 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1438 .supported_quantity(Quantity::One)
1440 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1442 .sign(payer_sign).unwrap();
1443 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1444 assert_eq!(invoice_request.quantity(), None);
1445 assert_eq!(tlv_stream.quantity, None);
1447 match OfferBuilder::new("foo".into(), recipient_pubkey())
1449 .supported_quantity(Quantity::One)
1451 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1452 .amount_msats(2_000).unwrap()
1455 Ok(_) => panic!("expected error"),
1456 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1459 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1461 .supported_quantity(Quantity::Bounded(ten))
1463 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1464 .amount_msats(10_000).unwrap()
1465 .quantity(10).unwrap()
1467 .sign(payer_sign).unwrap();
1468 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1469 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1470 assert_eq!(tlv_stream.amount, Some(10_000));
1472 match OfferBuilder::new("foo".into(), recipient_pubkey())
1474 .supported_quantity(Quantity::Bounded(ten))
1476 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1477 .amount_msats(11_000).unwrap()
1480 Ok(_) => panic!("expected error"),
1481 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1484 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1486 .supported_quantity(Quantity::Unbounded)
1488 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1489 .amount_msats(2_000).unwrap()
1490 .quantity(2).unwrap()
1492 .sign(payer_sign).unwrap();
1493 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1494 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1495 assert_eq!(tlv_stream.amount, Some(2_000));
1497 match OfferBuilder::new("foo".into(), recipient_pubkey())
1499 .supported_quantity(Quantity::Unbounded)
1501 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1504 Ok(_) => panic!("expected error"),
1505 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1508 match OfferBuilder::new("foo".into(), recipient_pubkey())
1510 .supported_quantity(Quantity::Bounded(one))
1512 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1515 Ok(_) => panic!("expected error"),
1516 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1521 fn builds_invoice_request_with_payer_note() {
1522 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1525 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1526 .payer_note("bar".into())
1528 .sign(payer_sign).unwrap();
1529 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1530 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1531 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1533 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1536 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1537 .payer_note("bar".into())
1538 .payer_note("baz".into())
1540 .sign(payer_sign).unwrap();
1541 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1542 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1543 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1547 fn fails_signing_invoice_request() {
1548 match OfferBuilder::new("foo".into(), recipient_pubkey())
1551 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555 Ok(_) => panic!("expected error"),
1556 Err(e) => assert_eq!(e, SignError::Signing(())),
1559 match OfferBuilder::new("foo".into(), recipient_pubkey())
1562 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1564 .sign(recipient_sign)
1566 Ok(_) => panic!("expected error"),
1567 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1572 fn fails_responding_with_unknown_required_features() {
1573 match OfferBuilder::new("foo".into(), recipient_pubkey())
1576 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1577 .features_unchecked(InvoiceRequestFeatures::unknown())
1579 .sign(payer_sign).unwrap()
1580 .respond_with_no_std(payment_paths(), payment_hash(), now())
1582 Ok(_) => panic!("expected error"),
1583 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1588 fn parses_invoice_request_with_metadata() {
1589 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1592 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1594 .sign(payer_sign).unwrap();
1596 let mut buffer = Vec::new();
1597 invoice_request.write(&mut buffer).unwrap();
1599 if let Err(e) = InvoiceRequest::try_from(buffer) {
1600 panic!("error parsing invoice_request: {:?}", e);
1605 fn parses_invoice_request_with_chain() {
1606 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1609 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1610 .chain(Network::Bitcoin).unwrap()
1612 .sign(payer_sign).unwrap();
1614 let mut buffer = Vec::new();
1615 invoice_request.write(&mut buffer).unwrap();
1617 if let Err(e) = InvoiceRequest::try_from(buffer) {
1618 panic!("error parsing invoice_request: {:?}", e);
1621 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1624 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1625 .chain_unchecked(Network::Testnet)
1627 .sign(payer_sign).unwrap();
1629 let mut buffer = Vec::new();
1630 invoice_request.write(&mut buffer).unwrap();
1632 match InvoiceRequest::try_from(buffer) {
1633 Ok(_) => panic!("expected error"),
1634 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1639 fn parses_invoice_request_with_amount() {
1640 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1643 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1645 .sign(payer_sign).unwrap();
1647 let mut buffer = Vec::new();
1648 invoice_request.write(&mut buffer).unwrap();
1650 if let Err(e) = InvoiceRequest::try_from(buffer) {
1651 panic!("error parsing invoice_request: {:?}", e);
1654 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1656 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1657 .amount_msats(1000).unwrap()
1659 .sign(payer_sign).unwrap();
1661 let mut buffer = Vec::new();
1662 invoice_request.write(&mut buffer).unwrap();
1664 if let Err(e) = InvoiceRequest::try_from(buffer) {
1665 panic!("error parsing invoice_request: {:?}", e);
1668 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1670 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1672 .sign(payer_sign).unwrap();
1674 let mut buffer = Vec::new();
1675 invoice_request.write(&mut buffer).unwrap();
1677 match InvoiceRequest::try_from(buffer) {
1678 Ok(_) => panic!("expected error"),
1679 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1682 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1685 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1686 .amount_msats_unchecked(999)
1688 .sign(payer_sign).unwrap();
1690 let mut buffer = Vec::new();
1691 invoice_request.write(&mut buffer).unwrap();
1693 match InvoiceRequest::try_from(buffer) {
1694 Ok(_) => panic!("expected error"),
1695 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1698 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1699 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1701 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1703 .sign(payer_sign).unwrap();
1705 let mut buffer = Vec::new();
1706 invoice_request.write(&mut buffer).unwrap();
1708 match InvoiceRequest::try_from(buffer) {
1709 Ok(_) => panic!("expected error"),
1711 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1715 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1717 .supported_quantity(Quantity::Unbounded)
1719 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1720 .quantity(u64::max_value()).unwrap()
1722 .sign(payer_sign).unwrap();
1724 let mut buffer = Vec::new();
1725 invoice_request.write(&mut buffer).unwrap();
1727 match InvoiceRequest::try_from(buffer) {
1728 Ok(_) => panic!("expected error"),
1729 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1734 fn parses_invoice_request_with_quantity() {
1735 let one = NonZeroU64::new(1).unwrap();
1736 let ten = NonZeroU64::new(10).unwrap();
1738 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1740 .supported_quantity(Quantity::One)
1742 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1744 .sign(payer_sign).unwrap();
1746 let mut buffer = Vec::new();
1747 invoice_request.write(&mut buffer).unwrap();
1749 if let Err(e) = InvoiceRequest::try_from(buffer) {
1750 panic!("error parsing invoice_request: {:?}", e);
1753 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1755 .supported_quantity(Quantity::One)
1757 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1758 .amount_msats(2_000).unwrap()
1759 .quantity_unchecked(2)
1761 .sign(payer_sign).unwrap();
1763 let mut buffer = Vec::new();
1764 invoice_request.write(&mut buffer).unwrap();
1766 match InvoiceRequest::try_from(buffer) {
1767 Ok(_) => panic!("expected error"),
1769 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1773 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1775 .supported_quantity(Quantity::Bounded(ten))
1777 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1778 .amount_msats(10_000).unwrap()
1779 .quantity(10).unwrap()
1781 .sign(payer_sign).unwrap();
1783 let mut buffer = Vec::new();
1784 invoice_request.write(&mut buffer).unwrap();
1786 if let Err(e) = InvoiceRequest::try_from(buffer) {
1787 panic!("error parsing invoice_request: {:?}", e);
1790 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1792 .supported_quantity(Quantity::Bounded(ten))
1794 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1795 .amount_msats(11_000).unwrap()
1796 .quantity_unchecked(11)
1798 .sign(payer_sign).unwrap();
1800 let mut buffer = Vec::new();
1801 invoice_request.write(&mut buffer).unwrap();
1803 match InvoiceRequest::try_from(buffer) {
1804 Ok(_) => panic!("expected error"),
1805 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1808 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1810 .supported_quantity(Quantity::Unbounded)
1812 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1813 .amount_msats(2_000).unwrap()
1814 .quantity(2).unwrap()
1816 .sign(payer_sign).unwrap();
1818 let mut buffer = Vec::new();
1819 invoice_request.write(&mut buffer).unwrap();
1821 if let Err(e) = InvoiceRequest::try_from(buffer) {
1822 panic!("error parsing invoice_request: {:?}", e);
1825 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1827 .supported_quantity(Quantity::Unbounded)
1829 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1831 .sign(payer_sign).unwrap();
1833 let mut buffer = Vec::new();
1834 invoice_request.write(&mut buffer).unwrap();
1836 match InvoiceRequest::try_from(buffer) {
1837 Ok(_) => panic!("expected error"),
1838 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1841 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1843 .supported_quantity(Quantity::Bounded(one))
1845 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1847 .sign(payer_sign).unwrap();
1849 let mut buffer = Vec::new();
1850 invoice_request.write(&mut buffer).unwrap();
1852 match InvoiceRequest::try_from(buffer) {
1853 Ok(_) => panic!("expected error"),
1854 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1859 fn fails_parsing_invoice_request_without_metadata() {
1860 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1863 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1865 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1866 tlv_stream.0.metadata = None;
1868 let mut buffer = Vec::new();
1869 tlv_stream.write(&mut buffer).unwrap();
1871 match InvoiceRequest::try_from(buffer) {
1872 Ok(_) => panic!("expected error"),
1874 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1880 fn fails_parsing_invoice_request_without_payer_id() {
1881 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1884 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1886 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1887 tlv_stream.2.payer_id = None;
1889 let mut buffer = Vec::new();
1890 tlv_stream.write(&mut buffer).unwrap();
1892 match InvoiceRequest::try_from(buffer) {
1893 Ok(_) => panic!("expected error"),
1894 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1899 fn fails_parsing_invoice_request_without_node_id() {
1900 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1903 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1905 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1906 tlv_stream.1.node_id = None;
1908 let mut buffer = Vec::new();
1909 tlv_stream.write(&mut buffer).unwrap();
1911 match InvoiceRequest::try_from(buffer) {
1912 Ok(_) => panic!("expected error"),
1914 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1920 fn fails_parsing_invoice_request_without_signature() {
1921 let mut buffer = Vec::new();
1922 OfferBuilder::new("foo".into(), recipient_pubkey())
1925 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1928 .write(&mut buffer).unwrap();
1930 match InvoiceRequest::try_from(buffer) {
1931 Ok(_) => panic!("expected error"),
1932 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1937 fn fails_parsing_invoice_request_with_invalid_signature() {
1938 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1941 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1943 .sign(payer_sign).unwrap();
1944 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1945 *last_signature_byte = last_signature_byte.wrapping_add(1);
1947 let mut buffer = Vec::new();
1948 invoice_request.write(&mut buffer).unwrap();
1950 match InvoiceRequest::try_from(buffer) {
1951 Ok(_) => panic!("expected error"),
1953 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1959 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1960 let secp_ctx = Secp256k1::new();
1961 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1962 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1965 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1967 .sign::<_, Infallible>(
1968 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1972 let mut encoded_invoice_request = Vec::new();
1973 invoice_request.write(&mut encoded_invoice_request).unwrap();
1974 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1975 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1976 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1978 match InvoiceRequest::try_from(encoded_invoice_request) {
1979 Ok(_) => panic!("expected error"),
1980 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),