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(mut self, network: Network) -> Result<Self, Bolt12SemanticError> {
183 let chain = ChainHash::using_genesis_block(network);
184 if !self.offer.supports_chain(chain) {
185 return Err(Bolt12SemanticError::UnsupportedChain);
188 self.invoice_request.chain = Some(chain);
192 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
193 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
195 /// Successive calls to this method will override the previous setting.
197 /// [`quantity`]: Self::quantity
198 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, Bolt12SemanticError> {
199 self.invoice_request.offer.check_amount_msats_for_quantity(
200 Some(amount_msats), self.invoice_request.quantity
202 self.invoice_request.amount_msats = Some(amount_msats);
206 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
207 /// does not conform to [`Offer::is_valid_quantity`].
209 /// Successive calls to this method will override the previous setting.
210 pub fn quantity(mut self, quantity: u64) -> Result<Self, Bolt12SemanticError> {
211 self.invoice_request.offer.check_quantity(Some(quantity))?;
212 self.invoice_request.quantity = Some(quantity);
216 /// Sets the [`InvoiceRequest::payer_note`].
218 /// Successive calls to this method will override the previous setting.
219 pub fn payer_note(mut self, payer_note: String) -> Self {
220 self.invoice_request.payer_note = Some(payer_note);
224 fn build_with_checks(mut self) -> Result<
225 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
228 #[cfg(feature = "std")] {
229 if self.offer.is_expired() {
230 return Err(Bolt12SemanticError::AlreadyExpired);
234 let chain = self.invoice_request.chain();
235 if !self.offer.supports_chain(chain) {
236 return Err(Bolt12SemanticError::UnsupportedChain);
239 if chain == self.offer.implied_chain() {
240 self.invoice_request.chain = None;
243 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
244 return Err(Bolt12SemanticError::MissingAmount);
247 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
248 self.invoice_request.offer.check_amount_msats_for_quantity(
249 self.invoice_request.amount_msats, self.invoice_request.quantity
252 Ok(self.build_without_checks())
255 fn build_without_checks(mut self) ->
256 (UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
258 // Create the metadata for stateless verification of a Bolt12Invoice.
260 let secp_ctx = self.secp_ctx.clone();
261 if self.invoice_request.payer.0.has_derivation_material() {
262 let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);
264 let mut tlv_stream = self.invoice_request.as_tlv_stream();
265 debug_assert!(tlv_stream.2.payer_id.is_none());
266 tlv_stream.0.metadata = None;
267 if !metadata.derives_payer_keys() {
268 tlv_stream.2.payer_id = self.payer_id.as_ref();
271 let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
272 metadata = derived_metadata;
274 if let Some(keys) = keys {
275 debug_assert!(self.payer_id.is_none());
276 self.payer_id = Some(keys.public_key());
279 self.invoice_request.payer.0 = metadata;
282 debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
283 debug_assert!(self.payer_id.is_some());
284 let payer_id = self.payer_id.unwrap();
286 let invoice_request = InvoiceRequestContents {
287 inner: self.invoice_request,
290 let unsigned_invoice_request = UnsignedInvoiceRequest::new(self.offer, invoice_request);
292 (unsigned_invoice_request, keys, secp_ctx)
296 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
297 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
298 /// by [`UnsignedInvoiceRequest::sign`].
299 pub fn build(self) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
300 let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
301 debug_assert!(keys.is_none());
302 Ok(unsigned_invoice_request)
306 impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
307 /// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
308 pub fn build_and_sign(self) -> Result<InvoiceRequest, Bolt12SemanticError> {
309 let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
310 debug_assert!(keys.is_some());
312 let secp_ctx = secp_ctx.unwrap();
313 let keys = keys.unwrap();
314 let invoice_request = unsigned_invoice_request
315 .sign::<_, Infallible>(
316 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
324 impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
325 fn chain_unchecked(mut self, network: Network) -> Self {
326 let chain = ChainHash::using_genesis_block(network);
327 self.invoice_request.chain = Some(chain);
331 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
332 self.invoice_request.amount_msats = Some(amount_msats);
336 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
337 self.invoice_request.features = features;
341 fn quantity_unchecked(mut self, quantity: u64) -> Self {
342 self.invoice_request.quantity = Some(quantity);
346 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest {
347 self.build_without_checks().0
351 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
355 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
356 /// such, it may include unknown, odd TLV records.
357 pub struct UnsignedInvoiceRequest {
359 contents: InvoiceRequestContents,
360 tagged_hash: TaggedHash,
363 impl UnsignedInvoiceRequest {
364 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
365 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
366 // unknown TLV records, which are not stored in `OfferContents`.
367 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
368 contents.as_tlv_stream();
369 let offer_bytes = WithoutLength(&offer.bytes);
370 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
372 let mut bytes = Vec::new();
373 unsigned_tlv_stream.write(&mut bytes).unwrap();
375 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
377 Self { bytes, contents, tagged_hash }
380 /// Returns the [`TaggedHash`] of the invoice to sign.
381 pub fn tagged_hash(&self) -> &TaggedHash {
385 /// Signs the [`TaggedHash`] of the invoice request using the given function.
387 /// Note: The hash computation may have included unknown, odd TLV records.
389 /// This is not exported to bindings users as functions are not yet mapped.
390 pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
392 F: FnOnce(&Self) -> Result<Signature, E>
394 let pubkey = self.contents.payer_id;
395 let signature = merkle::sign_message(sign, &self, pubkey)?;
397 // Append the signature TLV record to the bytes.
398 let signature_tlv_stream = SignatureTlvStreamRef {
399 signature: Some(&signature),
401 signature_tlv_stream.write(&mut self.bytes).unwrap();
405 contents: self.contents,
411 impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
412 fn as_ref(&self) -> &TaggedHash {
417 /// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
419 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
420 /// specifies these such that its recipient can send an invoice for payment.
422 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
423 /// [`Offer`]: crate::offers::offer::Offer
424 #[derive(Clone, Debug)]
425 #[cfg_attr(test, derive(PartialEq))]
426 pub struct InvoiceRequest {
427 pub(super) bytes: Vec<u8>,
428 pub(super) contents: InvoiceRequestContents,
429 signature: Signature,
432 /// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
433 /// ways to respond depending on whether the signing keys were derived.
434 #[derive(Clone, Debug)]
435 pub struct VerifiedInvoiceRequest {
436 /// The verified request.
437 inner: InvoiceRequest,
439 /// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
441 /// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
442 /// [`respond_with`].
444 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
445 /// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
446 /// [`respond_with`]: Self::respond_with
447 pub keys: Option<KeyPair>,
450 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
452 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
453 #[derive(Clone, Debug)]
454 #[cfg_attr(test, derive(PartialEq))]
455 pub(super) struct InvoiceRequestContents {
456 pub(super) inner: InvoiceRequestContentsWithoutPayerId,
460 #[derive(Clone, Debug)]
461 #[cfg_attr(test, derive(PartialEq))]
462 pub(super) struct InvoiceRequestContentsWithoutPayerId {
463 payer: PayerContents,
464 pub(super) offer: OfferContents,
465 chain: Option<ChainHash>,
466 amount_msats: Option<u64>,
467 features: InvoiceRequestFeatures,
468 quantity: Option<u64>,
469 payer_note: Option<String>,
472 macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
473 /// An unpredictable series of bytes, typically containing information about the derivation of
476 /// [`payer_id`]: Self::payer_id
477 pub fn payer_metadata(&$self) -> &[u8] {
481 /// A chain from [`Offer::chains`] that the offer is valid for.
482 pub fn chain(&$self) -> ChainHash {
486 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
487 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
489 /// [`chain`]: Self::chain
490 pub fn amount_msats(&$self) -> Option<u64> {
491 $contents.amount_msats()
494 /// Features pertaining to requesting an invoice.
495 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
496 &$contents.features()
499 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
500 pub fn quantity(&$self) -> Option<u64> {
504 /// A possibly transient pubkey used to sign the invoice request.
505 pub fn payer_id(&$self) -> PublicKey {
509 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
511 pub fn payer_note(&$self) -> Option<PrintableString> {
512 $contents.payer_note()
516 impl UnsignedInvoiceRequest {
517 offer_accessors!(self, self.contents.inner.offer);
518 invoice_request_accessors!(self, self.contents);
521 impl InvoiceRequest {
522 offer_accessors!(self, self.contents.inner.offer);
523 invoice_request_accessors!(self, self.contents);
525 /// Signature of the invoice request using [`payer_id`].
527 /// [`payer_id`]: Self::payer_id
528 pub fn signature(&self) -> Signature {
532 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
533 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
535 /// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
536 /// creation time is used for the `created_at` parameter.
538 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
540 /// [`Duration`]: core::time::Duration
541 #[cfg(feature = "std")]
543 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
544 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
545 let created_at = std::time::SystemTime::now()
546 .duration_since(std::time::SystemTime::UNIX_EPOCH)
547 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
549 self.respond_with_no_std(payment_paths, payment_hash, created_at)
552 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
554 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
555 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
556 /// where [`std::time::SystemTime`] is not available.
558 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
561 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
562 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
563 /// a preference. Note, however, that any privacy is lost if a public node id was used for
564 /// [`Offer::signing_pubkey`].
566 /// Errors if the request contains unknown required features.
570 /// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
571 /// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
573 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
575 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
576 /// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
577 pub fn respond_with_no_std(
578 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
579 created_at: core::time::Duration
580 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
581 if self.invoice_request_features().requires_unknown_bits() {
582 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
585 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
588 /// Verifies that the request was for an offer created using the given key. Returns the verified
589 /// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
590 /// if they could be extracted from the metadata.
592 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
593 pub fn verify<T: secp256k1::Signing>(
594 self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
595 ) -> Result<VerifiedInvoiceRequest, ()> {
596 let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
597 Ok(VerifiedInvoiceRequest {
604 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
605 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
606 self.contents.as_tlv_stream();
607 let signature_tlv_stream = SignatureTlvStreamRef {
608 signature: Some(&self.signature),
610 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
614 impl VerifiedInvoiceRequest {
615 offer_accessors!(self, self.inner.contents.inner.offer);
616 invoice_request_accessors!(self, self.inner.contents);
618 /// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
619 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
621 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
623 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
625 /// [`Duration`]: core::time::Duration
626 #[cfg(feature = "std")]
628 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
629 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
630 self.inner.respond_with(payment_paths, payment_hash)
633 /// Creates an [`InvoiceBuilder`] for the request with the given required fields.
635 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
637 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
638 pub fn respond_with_no_std(
639 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
640 created_at: core::time::Duration
641 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
642 self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
645 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
646 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
647 /// the same [`ExpandedKey`] as the one used to create the offer.
649 /// See [`InvoiceRequest::respond_with`] for further details.
651 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
653 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
654 #[cfg(feature = "std")]
655 pub fn respond_using_derived_keys(
656 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
657 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
658 let created_at = std::time::SystemTime::now()
659 .duration_since(std::time::SystemTime::UNIX_EPOCH)
660 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
662 self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
665 /// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
666 /// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
667 /// the same [`ExpandedKey`] as the one used to create the offer.
669 /// See [`InvoiceRequest::respond_with_no_std`] for further details.
671 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
673 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
674 pub fn respond_using_derived_keys_no_std(
675 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
676 created_at: core::time::Duration
677 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
678 if self.inner.invoice_request_features().requires_unknown_bits() {
679 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
682 let keys = match self.keys {
683 None => return Err(Bolt12SemanticError::InvalidMetadata),
687 InvoiceBuilder::for_offer_using_keys(
688 &self.inner, payment_paths, created_at, payment_hash, keys
693 impl InvoiceRequestContents {
694 pub(super) fn metadata(&self) -> &[u8] {
695 self.inner.metadata()
698 pub(super) fn derives_keys(&self) -> bool {
699 self.inner.payer.0.derives_payer_keys()
702 pub(super) fn chain(&self) -> ChainHash {
706 pub(super) fn amount_msats(&self) -> Option<u64> {
707 self.inner.amount_msats
710 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
714 pub(super) fn quantity(&self) -> Option<u64> {
718 pub(super) fn payer_id(&self) -> PublicKey {
722 pub(super) fn payer_note(&self) -> Option<PrintableString> {
723 self.inner.payer_note.as_ref()
724 .map(|payer_note| PrintableString(payer_note.as_str()))
727 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
728 let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
729 invoice_request.payer_id = Some(&self.payer_id);
730 (payer, offer, invoice_request)
734 impl InvoiceRequestContentsWithoutPayerId {
735 pub(super) fn metadata(&self) -> &[u8] {
736 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
739 pub(super) fn chain(&self) -> ChainHash {
740 self.chain.unwrap_or_else(|| self.offer.implied_chain())
743 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
744 let payer = PayerTlvStreamRef {
745 metadata: self.payer.0.as_bytes(),
748 let offer = self.offer.as_tlv_stream();
751 if self.features == InvoiceRequestFeatures::empty() { None }
752 else { Some(&self.features) }
755 let invoice_request = InvoiceRequestTlvStreamRef {
756 chain: self.chain.as_ref(),
757 amount: self.amount_msats,
759 quantity: self.quantity,
761 payer_note: self.payer_note.as_ref(),
764 (payer, offer, invoice_request)
768 impl Writeable for UnsignedInvoiceRequest {
769 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
770 WithoutLength(&self.bytes).write(writer)
774 impl Writeable for InvoiceRequest {
775 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
776 WithoutLength(&self.bytes).write(writer)
780 impl Writeable for InvoiceRequestContents {
781 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
782 self.as_tlv_stream().write(writer)
786 /// Valid type range for invoice_request TLV records.
787 pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
789 /// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
791 /// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
792 pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
794 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
795 (80, chain: ChainHash),
796 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
797 (84, features: (InvoiceRequestFeatures, WithoutLength)),
798 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
799 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
800 (89, payer_note: (String, WithoutLength)),
803 type FullInvoiceRequestTlvStream =
804 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
807 type FullInvoiceRequestTlvStreamRef<'a> = (
808 PayerTlvStreamRef<'a>,
809 OfferTlvStreamRef<'a>,
810 InvoiceRequestTlvStreamRef<'a>,
811 SignatureTlvStreamRef<'a>,
814 impl SeekReadable for FullInvoiceRequestTlvStream {
815 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
816 let payer = SeekReadable::read(r)?;
817 let offer = SeekReadable::read(r)?;
818 let invoice_request = SeekReadable::read(r)?;
819 let signature = SeekReadable::read(r)?;
821 Ok((payer, offer, invoice_request, signature))
825 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
827 type PartialInvoiceRequestTlvStreamRef<'a> = (
828 PayerTlvStreamRef<'a>,
829 OfferTlvStreamRef<'a>,
830 InvoiceRequestTlvStreamRef<'a>,
833 impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
834 type Error = Bolt12ParseError;
836 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
837 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
838 let ParsedMessage { bytes, tlv_stream } = invoice_request;
840 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
842 let contents = InvoiceRequestContents::try_from(
843 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
846 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
848 Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
852 impl TryFrom<Vec<u8>> for InvoiceRequest {
853 type Error = Bolt12ParseError;
855 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
856 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
857 let ParsedMessage { bytes, tlv_stream } = invoice_request;
859 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
860 SignatureTlvStream { signature },
862 let contents = InvoiceRequestContents::try_from(
863 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
866 let signature = match signature {
867 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
868 Some(signature) => signature,
870 let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
871 merkle::verify_signature(&signature, message, contents.payer_id)?;
873 Ok(InvoiceRequest { bytes, contents, signature })
877 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
878 type Error = Bolt12SemanticError;
880 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
882 PayerTlvStream { metadata },
884 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
887 let payer = match metadata {
888 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
889 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
891 let offer = OfferContents::try_from(offer_tlv_stream)?;
893 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
894 return Err(Bolt12SemanticError::UnsupportedChain);
897 if offer.amount().is_none() && amount.is_none() {
898 return Err(Bolt12SemanticError::MissingAmount);
901 offer.check_quantity(quantity)?;
902 offer.check_amount_msats_for_quantity(amount, quantity)?;
904 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
906 let payer_id = match payer_id {
907 None => return Err(Bolt12SemanticError::MissingPayerId),
908 Some(payer_id) => payer_id,
911 Ok(InvoiceRequestContents {
912 inner: InvoiceRequestContentsWithoutPayerId {
913 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
922 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};
924 use bitcoin::blockdata::constants::ChainHash;
925 use bitcoin::network::constants::Network;
926 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
927 use core::convert::{Infallible, TryFrom};
928 use core::num::NonZeroU64;
929 #[cfg(feature = "std")]
930 use core::time::Duration;
931 use crate::sign::KeyMaterial;
932 use crate::ln::channelmanager::PaymentId;
933 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
934 use crate::ln::inbound_payment::ExpandedKey;
935 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
936 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
937 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
938 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
939 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
940 use crate::offers::payer::PayerTlvStreamRef;
941 use crate::offers::test_utils::*;
942 use crate::util::ser::{BigSize, Writeable};
943 use crate::util::string::PrintableString;
946 fn builds_invoice_request_with_defaults() {
947 let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
950 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
953 let mut buffer = Vec::new();
954 unsigned_invoice_request.write(&mut buffer).unwrap();
956 assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
957 assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
958 assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
959 assert_eq!(unsigned_invoice_request.metadata(), None);
960 assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
961 assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
962 assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
963 assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
964 assert_eq!(unsigned_invoice_request.paths(), &[]);
965 assert_eq!(unsigned_invoice_request.issuer(), None);
966 assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
967 assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
968 assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
969 assert_eq!(unsigned_invoice_request.amount_msats(), None);
970 assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
971 assert_eq!(unsigned_invoice_request.quantity(), None);
972 assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
973 assert_eq!(unsigned_invoice_request.payer_note(), None);
975 match UnsignedInvoiceRequest::try_from(buffer) {
976 Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
978 assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
979 assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
983 let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();
985 let mut buffer = Vec::new();
986 invoice_request.write(&mut buffer).unwrap();
988 assert_eq!(invoice_request.bytes, buffer.as_slice());
989 assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
990 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
991 assert_eq!(invoice_request.metadata(), None);
992 assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
993 assert_eq!(invoice_request.description(), PrintableString("foo"));
994 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
995 assert_eq!(invoice_request.absolute_expiry(), None);
996 assert_eq!(invoice_request.paths(), &[]);
997 assert_eq!(invoice_request.issuer(), None);
998 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
999 assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
1000 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1001 assert_eq!(invoice_request.amount_msats(), None);
1002 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1003 assert_eq!(invoice_request.quantity(), None);
1004 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1005 assert_eq!(invoice_request.payer_note(), None);
1007 let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
1008 assert!(merkle::verify_signature(&invoice_request.signature, message, payer_pubkey()).is_ok());
1011 invoice_request.as_tlv_stream(),
1013 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1019 description: Some(&String::from("foo")),
1021 absolute_expiry: None,
1025 node_id: Some(&recipient_pubkey()),
1027 InvoiceRequestTlvStreamRef {
1032 payer_id: Some(&payer_pubkey()),
1035 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1039 if let Err(e) = InvoiceRequest::try_from(buffer) {
1040 panic!("error parsing invoice request: {:?}", e);
1044 #[cfg(feature = "std")]
1046 fn builds_invoice_request_from_offer_with_expiration() {
1047 let future_expiry = Duration::from_secs(u64::max_value());
1048 let past_expiry = Duration::from_secs(0);
1050 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1052 .absolute_expiry(future_expiry)
1054 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1057 panic!("error building invoice_request: {:?}", e);
1060 match OfferBuilder::new("foo".into(), recipient_pubkey())
1062 .absolute_expiry(past_expiry)
1064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1067 Ok(_) => panic!("expected error"),
1068 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1073 fn builds_invoice_request_with_derived_metadata() {
1074 let payer_id = payer_pubkey();
1075 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1076 let entropy = FixedEntropy {};
1077 let secp_ctx = Secp256k1::new();
1078 let payment_id = PaymentId([1; 32]);
1080 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1083 let invoice_request = offer
1084 .request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
1087 .sign(payer_sign).unwrap();
1088 assert_eq!(invoice_request.payer_id(), payer_pubkey());
1090 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1093 .sign(recipient_sign).unwrap();
1094 match invoice.verify(&expanded_key, &secp_ctx) {
1095 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1096 Err(()) => panic!("verification failed"),
1099 // Fails verification with altered fields
1101 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1102 mut invoice_tlv_stream, mut signature_tlv_stream
1103 ) = invoice.as_tlv_stream();
1104 invoice_request_tlv_stream.amount = Some(2000);
1105 invoice_tlv_stream.amount = Some(2000);
1108 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1109 let mut bytes = Vec::new();
1110 tlv_stream.write(&mut bytes).unwrap();
1112 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1113 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1114 signature_tlv_stream.signature = Some(&signature);
1116 let mut encoded_invoice = bytes;
1117 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1119 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1120 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1122 // Fails verification with altered metadata
1124 mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1125 mut signature_tlv_stream
1126 ) = invoice.as_tlv_stream();
1127 let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1128 payer_tlv_stream.metadata = Some(&metadata);
1131 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1132 let mut bytes = Vec::new();
1133 tlv_stream.write(&mut bytes).unwrap();
1135 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1136 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1137 signature_tlv_stream.signature = Some(&signature);
1139 let mut encoded_invoice = bytes;
1140 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1142 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1143 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1147 fn builds_invoice_request_with_derived_payer_id() {
1148 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1149 let entropy = FixedEntropy {};
1150 let secp_ctx = Secp256k1::new();
1151 let payment_id = PaymentId([1; 32]);
1153 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1156 let invoice_request = offer
1157 .request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
1162 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1165 .sign(recipient_sign).unwrap();
1166 match invoice.verify(&expanded_key, &secp_ctx) {
1167 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1168 Err(()) => panic!("verification failed"),
1171 // Fails verification with altered fields
1173 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1174 mut invoice_tlv_stream, mut signature_tlv_stream
1175 ) = invoice.as_tlv_stream();
1176 invoice_request_tlv_stream.amount = Some(2000);
1177 invoice_tlv_stream.amount = Some(2000);
1180 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1181 let mut bytes = Vec::new();
1182 tlv_stream.write(&mut bytes).unwrap();
1184 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1185 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1186 signature_tlv_stream.signature = Some(&signature);
1188 let mut encoded_invoice = bytes;
1189 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1191 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1192 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1194 // Fails verification with altered payer id
1196 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1197 mut signature_tlv_stream
1198 ) = invoice.as_tlv_stream();
1199 let payer_id = pubkey(1);
1200 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1203 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1204 let mut bytes = Vec::new();
1205 tlv_stream.write(&mut bytes).unwrap();
1207 let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
1208 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1209 signature_tlv_stream.signature = Some(&signature);
1211 let mut encoded_invoice = bytes;
1212 signature_tlv_stream.write(&mut encoded_invoice).unwrap();
1214 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1215 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1219 fn builds_invoice_request_with_chain() {
1220 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1221 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1223 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1226 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1227 .chain(Network::Bitcoin).unwrap()
1229 .sign(payer_sign).unwrap();
1230 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1231 assert_eq!(invoice_request.chain(), mainnet);
1232 assert_eq!(tlv_stream.chain, None);
1234 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .chain(Network::Testnet)
1238 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1239 .chain(Network::Testnet).unwrap()
1241 .sign(payer_sign).unwrap();
1242 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1243 assert_eq!(invoice_request.chain(), testnet);
1244 assert_eq!(tlv_stream.chain, Some(&testnet));
1246 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1248 .chain(Network::Bitcoin)
1249 .chain(Network::Testnet)
1251 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1252 .chain(Network::Bitcoin).unwrap()
1254 .sign(payer_sign).unwrap();
1255 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1256 assert_eq!(invoice_request.chain(), mainnet);
1257 assert_eq!(tlv_stream.chain, None);
1259 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1261 .chain(Network::Bitcoin)
1262 .chain(Network::Testnet)
1264 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1265 .chain(Network::Bitcoin).unwrap()
1266 .chain(Network::Testnet).unwrap()
1268 .sign(payer_sign).unwrap();
1269 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1270 assert_eq!(invoice_request.chain(), testnet);
1271 assert_eq!(tlv_stream.chain, Some(&testnet));
1273 match OfferBuilder::new("foo".into(), recipient_pubkey())
1275 .chain(Network::Testnet)
1277 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1278 .chain(Network::Bitcoin)
1280 Ok(_) => panic!("expected error"),
1281 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1284 match OfferBuilder::new("foo".into(), recipient_pubkey())
1286 .chain(Network::Testnet)
1288 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1291 Ok(_) => panic!("expected error"),
1292 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1297 fn builds_invoice_request_with_amount() {
1298 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1301 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1302 .amount_msats(1000).unwrap()
1304 .sign(payer_sign).unwrap();
1305 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1306 assert_eq!(invoice_request.amount_msats(), Some(1000));
1307 assert_eq!(tlv_stream.amount, Some(1000));
1309 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1312 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1313 .amount_msats(1001).unwrap()
1314 .amount_msats(1000).unwrap()
1316 .sign(payer_sign).unwrap();
1317 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1318 assert_eq!(invoice_request.amount_msats(), Some(1000));
1319 assert_eq!(tlv_stream.amount, Some(1000));
1321 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1324 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1325 .amount_msats(1001).unwrap()
1327 .sign(payer_sign).unwrap();
1328 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1329 assert_eq!(invoice_request.amount_msats(), Some(1001));
1330 assert_eq!(tlv_stream.amount, Some(1001));
1332 match OfferBuilder::new("foo".into(), recipient_pubkey())
1335 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1338 Ok(_) => panic!("expected error"),
1339 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1342 match OfferBuilder::new("foo".into(), recipient_pubkey())
1344 .supported_quantity(Quantity::Unbounded)
1346 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .quantity(2).unwrap()
1350 Ok(_) => panic!("expected error"),
1351 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1354 match OfferBuilder::new("foo".into(), recipient_pubkey())
1357 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1358 .amount_msats(MAX_VALUE_MSAT + 1)
1360 Ok(_) => panic!("expected error"),
1361 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1364 match OfferBuilder::new("foo".into(), recipient_pubkey())
1366 .supported_quantity(Quantity::Unbounded)
1368 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1369 .amount_msats(1000).unwrap()
1370 .quantity(2).unwrap()
1373 Ok(_) => panic!("expected error"),
1374 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1377 match OfferBuilder::new("foo".into(), recipient_pubkey())
1379 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1382 Ok(_) => panic!("expected error"),
1383 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1386 match OfferBuilder::new("foo".into(), recipient_pubkey())
1388 .supported_quantity(Quantity::Unbounded)
1390 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1391 .quantity(u64::max_value()).unwrap()
1394 Ok(_) => panic!("expected error"),
1395 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1400 fn builds_invoice_request_with_features() {
1401 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1404 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1405 .features_unchecked(InvoiceRequestFeatures::unknown())
1407 .sign(payer_sign).unwrap();
1408 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1409 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1410 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1412 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1415 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1416 .features_unchecked(InvoiceRequestFeatures::unknown())
1417 .features_unchecked(InvoiceRequestFeatures::empty())
1419 .sign(payer_sign).unwrap();
1420 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1421 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1422 assert_eq!(tlv_stream.features, None);
1426 fn builds_invoice_request_with_quantity() {
1427 let one = NonZeroU64::new(1).unwrap();
1428 let ten = NonZeroU64::new(10).unwrap();
1430 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1432 .supported_quantity(Quantity::One)
1434 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1436 .sign(payer_sign).unwrap();
1437 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1438 assert_eq!(invoice_request.quantity(), None);
1439 assert_eq!(tlv_stream.quantity, None);
1441 match OfferBuilder::new("foo".into(), recipient_pubkey())
1443 .supported_quantity(Quantity::One)
1445 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1446 .amount_msats(2_000).unwrap()
1449 Ok(_) => panic!("expected error"),
1450 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1453 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1455 .supported_quantity(Quantity::Bounded(ten))
1457 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1458 .amount_msats(10_000).unwrap()
1459 .quantity(10).unwrap()
1461 .sign(payer_sign).unwrap();
1462 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1463 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1464 assert_eq!(tlv_stream.amount, Some(10_000));
1466 match OfferBuilder::new("foo".into(), recipient_pubkey())
1468 .supported_quantity(Quantity::Bounded(ten))
1470 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1471 .amount_msats(11_000).unwrap()
1474 Ok(_) => panic!("expected error"),
1475 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1478 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1480 .supported_quantity(Quantity::Unbounded)
1482 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1483 .amount_msats(2_000).unwrap()
1484 .quantity(2).unwrap()
1486 .sign(payer_sign).unwrap();
1487 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1488 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1489 assert_eq!(tlv_stream.amount, Some(2_000));
1491 match OfferBuilder::new("foo".into(), recipient_pubkey())
1493 .supported_quantity(Quantity::Unbounded)
1495 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1498 Ok(_) => panic!("expected error"),
1499 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1502 match OfferBuilder::new("foo".into(), recipient_pubkey())
1504 .supported_quantity(Quantity::Bounded(one))
1506 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1509 Ok(_) => panic!("expected error"),
1510 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1515 fn builds_invoice_request_with_payer_note() {
1516 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1519 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1520 .payer_note("bar".into())
1522 .sign(payer_sign).unwrap();
1523 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1524 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1525 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1527 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1530 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1531 .payer_note("bar".into())
1532 .payer_note("baz".into())
1534 .sign(payer_sign).unwrap();
1535 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
1536 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1537 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1541 fn fails_signing_invoice_request() {
1542 match OfferBuilder::new("foo".into(), recipient_pubkey())
1545 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1549 Ok(_) => panic!("expected error"),
1550 Err(e) => assert_eq!(e, SignError::Signing(())),
1553 match OfferBuilder::new("foo".into(), recipient_pubkey())
1556 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1558 .sign(recipient_sign)
1560 Ok(_) => panic!("expected error"),
1561 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1566 fn fails_responding_with_unknown_required_features() {
1567 match OfferBuilder::new("foo".into(), recipient_pubkey())
1570 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
1571 .features_unchecked(InvoiceRequestFeatures::unknown())
1573 .sign(payer_sign).unwrap()
1574 .respond_with_no_std(payment_paths(), payment_hash(), now())
1576 Ok(_) => panic!("expected error"),
1577 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1582 fn parses_invoice_request_with_metadata() {
1583 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1586 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1588 .sign(payer_sign).unwrap();
1590 let mut buffer = Vec::new();
1591 invoice_request.write(&mut buffer).unwrap();
1593 if let Err(e) = InvoiceRequest::try_from(buffer) {
1594 panic!("error parsing invoice_request: {:?}", e);
1599 fn parses_invoice_request_with_chain() {
1600 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1603 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1604 .chain(Network::Bitcoin).unwrap()
1606 .sign(payer_sign).unwrap();
1608 let mut buffer = Vec::new();
1609 invoice_request.write(&mut buffer).unwrap();
1611 if let Err(e) = InvoiceRequest::try_from(buffer) {
1612 panic!("error parsing invoice_request: {:?}", e);
1615 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1618 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1619 .chain_unchecked(Network::Testnet)
1621 .sign(payer_sign).unwrap();
1623 let mut buffer = Vec::new();
1624 invoice_request.write(&mut buffer).unwrap();
1626 match InvoiceRequest::try_from(buffer) {
1627 Ok(_) => panic!("expected error"),
1628 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
1633 fn parses_invoice_request_with_amount() {
1634 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1637 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1639 .sign(payer_sign).unwrap();
1641 let mut buffer = Vec::new();
1642 invoice_request.write(&mut buffer).unwrap();
1644 if let Err(e) = InvoiceRequest::try_from(buffer) {
1645 panic!("error parsing invoice_request: {:?}", e);
1648 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1650 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1651 .amount_msats(1000).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()
1666 .sign(payer_sign).unwrap();
1668 let mut buffer = Vec::new();
1669 invoice_request.write(&mut buffer).unwrap();
1671 match InvoiceRequest::try_from(buffer) {
1672 Ok(_) => panic!("expected error"),
1673 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1676 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1679 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1680 .amount_msats_unchecked(999)
1682 .sign(payer_sign).unwrap();
1684 let mut buffer = Vec::new();
1685 invoice_request.write(&mut buffer).unwrap();
1687 match InvoiceRequest::try_from(buffer) {
1688 Ok(_) => panic!("expected error"),
1689 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
1692 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1693 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1695 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1697 .sign(payer_sign).unwrap();
1699 let mut buffer = Vec::new();
1700 invoice_request.write(&mut buffer).unwrap();
1702 match InvoiceRequest::try_from(buffer) {
1703 Ok(_) => panic!("expected error"),
1705 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
1709 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1711 .supported_quantity(Quantity::Unbounded)
1713 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1714 .quantity(u64::max_value()).unwrap()
1716 .sign(payer_sign).unwrap();
1718 let mut buffer = Vec::new();
1719 invoice_request.write(&mut buffer).unwrap();
1721 match InvoiceRequest::try_from(buffer) {
1722 Ok(_) => panic!("expected error"),
1723 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1728 fn parses_invoice_request_with_quantity() {
1729 let one = NonZeroU64::new(1).unwrap();
1730 let ten = NonZeroU64::new(10).unwrap();
1732 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1734 .supported_quantity(Quantity::One)
1736 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1738 .sign(payer_sign).unwrap();
1740 let mut buffer = Vec::new();
1741 invoice_request.write(&mut buffer).unwrap();
1743 if let Err(e) = InvoiceRequest::try_from(buffer) {
1744 panic!("error parsing invoice_request: {:?}", e);
1747 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1749 .supported_quantity(Quantity::One)
1751 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1752 .amount_msats(2_000).unwrap()
1753 .quantity_unchecked(2)
1755 .sign(payer_sign).unwrap();
1757 let mut buffer = Vec::new();
1758 invoice_request.write(&mut buffer).unwrap();
1760 match InvoiceRequest::try_from(buffer) {
1761 Ok(_) => panic!("expected error"),
1763 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1767 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1769 .supported_quantity(Quantity::Bounded(ten))
1771 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1772 .amount_msats(10_000).unwrap()
1773 .quantity(10).unwrap()
1775 .sign(payer_sign).unwrap();
1777 let mut buffer = Vec::new();
1778 invoice_request.write(&mut buffer).unwrap();
1780 if let Err(e) = InvoiceRequest::try_from(buffer) {
1781 panic!("error parsing invoice_request: {:?}", e);
1784 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1786 .supported_quantity(Quantity::Bounded(ten))
1788 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1789 .amount_msats(11_000).unwrap()
1790 .quantity_unchecked(11)
1792 .sign(payer_sign).unwrap();
1794 let mut buffer = Vec::new();
1795 invoice_request.write(&mut buffer).unwrap();
1797 match InvoiceRequest::try_from(buffer) {
1798 Ok(_) => panic!("expected error"),
1799 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
1802 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1804 .supported_quantity(Quantity::Unbounded)
1806 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1807 .amount_msats(2_000).unwrap()
1808 .quantity(2).unwrap()
1810 .sign(payer_sign).unwrap();
1812 let mut buffer = Vec::new();
1813 invoice_request.write(&mut buffer).unwrap();
1815 if let Err(e) = InvoiceRequest::try_from(buffer) {
1816 panic!("error parsing invoice_request: {:?}", e);
1819 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1821 .supported_quantity(Quantity::Unbounded)
1823 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1825 .sign(payer_sign).unwrap();
1827 let mut buffer = Vec::new();
1828 invoice_request.write(&mut buffer).unwrap();
1830 match InvoiceRequest::try_from(buffer) {
1831 Ok(_) => panic!("expected error"),
1832 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1835 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1837 .supported_quantity(Quantity::Bounded(one))
1839 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1841 .sign(payer_sign).unwrap();
1843 let mut buffer = Vec::new();
1844 invoice_request.write(&mut buffer).unwrap();
1846 match InvoiceRequest::try_from(buffer) {
1847 Ok(_) => panic!("expected error"),
1848 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
1853 fn fails_parsing_invoice_request_without_metadata() {
1854 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1857 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1859 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1860 tlv_stream.0.metadata = None;
1862 let mut buffer = Vec::new();
1863 tlv_stream.write(&mut buffer).unwrap();
1865 match InvoiceRequest::try_from(buffer) {
1866 Ok(_) => panic!("expected error"),
1868 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1874 fn fails_parsing_invoice_request_without_payer_id() {
1875 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1878 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1880 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1881 tlv_stream.2.payer_id = None;
1883 let mut buffer = Vec::new();
1884 tlv_stream.write(&mut buffer).unwrap();
1886 match InvoiceRequest::try_from(buffer) {
1887 Ok(_) => panic!("expected error"),
1888 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
1893 fn fails_parsing_invoice_request_without_node_id() {
1894 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1897 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1899 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
1900 tlv_stream.1.node_id = None;
1902 let mut buffer = Vec::new();
1903 tlv_stream.write(&mut buffer).unwrap();
1905 match InvoiceRequest::try_from(buffer) {
1906 Ok(_) => panic!("expected error"),
1908 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1914 fn fails_parsing_invoice_request_without_signature() {
1915 let mut buffer = Vec::new();
1916 OfferBuilder::new("foo".into(), recipient_pubkey())
1919 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1922 .write(&mut buffer).unwrap();
1924 match InvoiceRequest::try_from(buffer) {
1925 Ok(_) => panic!("expected error"),
1926 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1931 fn fails_parsing_invoice_request_with_invalid_signature() {
1932 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1935 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1937 .sign(payer_sign).unwrap();
1938 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1939 *last_signature_byte = last_signature_byte.wrapping_add(1);
1941 let mut buffer = Vec::new();
1942 invoice_request.write(&mut buffer).unwrap();
1944 match InvoiceRequest::try_from(buffer) {
1945 Ok(_) => panic!("expected error"),
1947 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1953 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1954 let secp_ctx = Secp256k1::new();
1955 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1956 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1959 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1961 .sign::<_, Infallible>(
1962 |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
1966 let mut encoded_invoice_request = Vec::new();
1967 invoice_request.write(&mut encoded_invoice_request).unwrap();
1968 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1969 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1970 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1972 match InvoiceRequest::try_from(encoded_invoice_request) {
1973 Ok(_) => panic!("expected error"),
1974 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),