1use bitcoin::constants::ChainHash;
69use bitcoin::network::Network;
70use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, self};
71use bitcoin::secp256k1::schnorr::Signature;
72use crate::io;
73use crate::blinded_path::message::BlindedMessagePath;
74use crate::blinded_path::payment::BlindedPaymentPath;
75use crate::types::payment::PaymentHash;
76use crate::ln::channelmanager::PaymentId;
77use crate::types::features::InvoiceRequestFeatures;
78use crate::ln::inbound_payment::{ExpandedKey, IV_LEN};
79use crate::ln::msgs::DecodeError;
80use crate::offers::merkle::{SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, self, SIGNATURE_TLV_RECORD_SIZE};
81use crate::offers::nonce::Nonce;
82use crate::offers::offer::{Amount, EXPERIMENTAL_OFFER_TYPES, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OFFER_TYPES, Offer, OfferContents, OfferId, OfferTlvStream, OfferTlvStreamRef};
83use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
84use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
85use crate::offers::signer::{Metadata, MetadataMaterial};
86use crate::onion_message::dns_resolution::HumanReadableName;
87use crate::util::ser::{CursorReadable, HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
88use crate::util::string::{PrintableString, UntrustedString};
89
90#[cfg(not(c_bindings))]
91use {
92 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
93};
94#[cfg(c_bindings)]
95use {
96 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
97};
98
99#[allow(unused_imports)]
100use crate::prelude::*;
101
102pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
104
105pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";
106
107pub struct InvoiceRequestBuilder<'a, 'b, T: secp256k1::Signing> {
115 offer: &'a Offer,
116 invoice_request: InvoiceRequestContentsWithoutPayerSigningPubkey,
117 payer_signing_pubkey: Option<PublicKey>,
118 secp_ctx: Option<&'b Secp256k1<T>>,
119}
120
121#[cfg(c_bindings)]
127pub struct InvoiceRequestWithDerivedPayerSigningPubkeyBuilder<'a, 'b> {
128 offer: &'a Offer,
129 invoice_request: InvoiceRequestContentsWithoutPayerSigningPubkey,
130 payer_signing_pubkey: Option<PublicKey>,
131 secp_ctx: Option<&'b Secp256k1<secp256k1::All>>,
132}
133
134macro_rules! invoice_request_derived_payer_signing_pubkey_builder_methods { (
135 $self: ident, $self_type: ty, $secp_context: ty
136) => {
137 #[cfg_attr(c_bindings, allow(dead_code))]
138 pub(super) fn deriving_signing_pubkey(
139 offer: &'a Offer, expanded_key: &ExpandedKey, nonce: Nonce,
140 secp_ctx: &'b Secp256k1<$secp_context>, payment_id: PaymentId
141 ) -> Self {
142 let payment_id = Some(payment_id);
143 let derivation_material = MetadataMaterial::new(nonce, expanded_key, payment_id);
144 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
145 Self {
146 offer,
147 invoice_request: Self::create_contents(offer, metadata),
148 payer_signing_pubkey: None,
149 secp_ctx: Some(secp_ctx),
150 }
151 }
152
153 pub fn build_and_sign($self: $self_type) -> Result<InvoiceRequest, Bolt12SemanticError> {
155 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_with_checks()?;
156 #[cfg(c_bindings)]
157 let mut unsigned_invoice_request = unsigned_invoice_request;
158 debug_assert!(keys.is_some());
159
160 let secp_ctx = secp_ctx.unwrap();
161 let keys = keys.unwrap();
162 let invoice_request = unsigned_invoice_request
163 .sign(|message: &UnsignedInvoiceRequest|
164 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
165 )
166 .unwrap();
167 Ok(invoice_request)
168 }
169} }
170
171macro_rules! invoice_request_builder_methods { (
172 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
173) => {
174 #[cfg_attr(c_bindings, allow(dead_code))]
175 fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerSigningPubkey {
176 let offer = offer.contents.clone();
177 InvoiceRequestContentsWithoutPayerSigningPubkey {
178 payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
179 features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
180 offer_from_hrn: None,
181 #[cfg(test)]
182 experimental_bar: None,
183 }
184 }
185
186 pub fn chain($self: $self_type, network: Network) -> Result<$return_type, Bolt12SemanticError> {
192 $self.chain_hash(ChainHash::using_genesis_block(network))
193 }
194
195 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> Result<$return_type, Bolt12SemanticError> {
201 if !$self.offer.supports_chain(chain) {
202 return Err(Bolt12SemanticError::UnsupportedChain);
203 }
204
205 $self.invoice_request.chain = Some(chain);
206 Ok($return_value)
207 }
208
209 pub fn amount_msats($($self_mut)* $self: $self_type, amount_msats: u64) -> Result<$return_type, Bolt12SemanticError> {
216 $self.invoice_request.offer.check_amount_msats_for_quantity(
217 Some(amount_msats), $self.invoice_request.quantity
218 )?;
219 $self.invoice_request.amount_msats = Some(amount_msats);
220 Ok($return_value)
221 }
222
223 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> Result<$return_type, Bolt12SemanticError> {
228 $self.invoice_request.offer.check_quantity(Some(quantity))?;
229 $self.invoice_request.quantity = Some(quantity);
230 Ok($return_value)
231 }
232
233 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
237 $self.invoice_request.payer_note = Some(payer_note);
238 $return_value
239 }
240
241 pub fn sourced_from_human_readable_name($($self_mut)* $self: $self_type, hrn: HumanReadableName) -> $return_type {
245 $self.invoice_request.offer_from_hrn = Some(hrn);
246 $return_value
247 }
248
249 fn build_with_checks($($self_mut)* $self: $self_type) -> Result<
250 (UnsignedInvoiceRequest, Option<Keypair>, Option<&'b Secp256k1<$secp_context>>),
251 Bolt12SemanticError
252 > {
253 #[cfg(feature = "std")] {
254 if $self.offer.is_expired() {
255 return Err(Bolt12SemanticError::AlreadyExpired);
256 }
257 }
258
259 let chain = $self.invoice_request.chain();
260 if !$self.offer.supports_chain(chain) {
261 return Err(Bolt12SemanticError::UnsupportedChain);
262 }
263
264 if chain == $self.offer.implied_chain() {
265 $self.invoice_request.chain = None;
266 }
267
268 if $self.offer.amount().is_none() && $self.invoice_request.amount_msats.is_none() {
269 return Err(Bolt12SemanticError::MissingAmount);
270 }
271
272 $self.invoice_request.offer.check_quantity($self.invoice_request.quantity)?;
273 $self.invoice_request.offer.check_amount_msats_for_quantity(
274 $self.invoice_request.amount_msats, $self.invoice_request.quantity
275 )?;
276
277 Ok($self.build_without_checks())
278 }
279
280 fn build_without_checks($($self_mut)* $self: $self_type) ->
281 (UnsignedInvoiceRequest, Option<Keypair>, Option<&'b Secp256k1<$secp_context>>)
282 {
283 let mut keys = None;
285 let secp_ctx = $self.secp_ctx.clone();
286 if $self.invoice_request.payer.0.has_derivation_material() {
287 let mut metadata = core::mem::take(&mut $self.invoice_request.payer.0);
288
289 let mut tlv_stream = $self.invoice_request.as_tlv_stream();
290 debug_assert!(tlv_stream.2.payer_id.is_none());
291 tlv_stream.0.metadata = None;
292 if !metadata.derives_payer_keys() {
293 tlv_stream.2.payer_id = $self.payer_signing_pubkey.as_ref();
294 }
295
296 let (derived_metadata, derived_keys) =
297 metadata.derive_from(IV_BYTES, tlv_stream, $self.secp_ctx);
298 metadata = derived_metadata;
299 keys = derived_keys;
300 if let Some(keys) = keys {
301 debug_assert!($self.payer_signing_pubkey.is_none());
302 $self.payer_signing_pubkey = Some(keys.public_key());
303 }
304
305 $self.invoice_request.payer.0 = metadata;
306 }
307
308 debug_assert!($self.invoice_request.payer.0.as_bytes().is_some());
309 debug_assert!($self.payer_signing_pubkey.is_some());
310 let payer_signing_pubkey = $self.payer_signing_pubkey.unwrap();
311
312 let invoice_request = InvoiceRequestContents {
313 #[cfg(not(c_bindings))]
314 inner: $self.invoice_request,
315 #[cfg(c_bindings)]
316 inner: $self.invoice_request.clone(),
317 payer_signing_pubkey,
318 };
319 let unsigned_invoice_request = UnsignedInvoiceRequest::new($self.offer, invoice_request);
320
321 (unsigned_invoice_request, keys, secp_ctx)
322 }
323} }
324
325#[cfg(test)]
326macro_rules! invoice_request_builder_test_methods { (
327 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
328) => {
329 #[cfg_attr(c_bindings, allow(dead_code))]
330 pub(super) fn payer_metadata($($self_mut)* $self: $self_type, metadata: Metadata) -> $return_type {
331 $self.invoice_request.payer = PayerContents(metadata);
332 $return_value
333 }
334
335 #[cfg_attr(c_bindings, allow(dead_code))]
336 fn chain_unchecked($($self_mut)* $self: $self_type, network: Network) -> $return_type {
337 let chain = ChainHash::using_genesis_block(network);
338 $self.invoice_request.chain = Some(chain);
339 $return_value
340 }
341
342 #[cfg_attr(c_bindings, allow(dead_code))]
343 fn amount_msats_unchecked($($self_mut)* $self: $self_type, amount_msats: u64) -> $return_type {
344 $self.invoice_request.amount_msats = Some(amount_msats);
345 $return_value
346 }
347
348 #[cfg_attr(c_bindings, allow(dead_code))]
349 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
350 $self.invoice_request.features = features;
351 $return_value
352 }
353
354 #[cfg_attr(c_bindings, allow(dead_code))]
355 fn quantity_unchecked($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
356 $self.invoice_request.quantity = Some(quantity);
357 $return_value
358 }
359
360 #[cfg_attr(c_bindings, allow(dead_code))]
361 pub(super) fn payer_signing_pubkey($($self_mut)* $self: $self_type, signing_pubkey: PublicKey) -> $return_type {
362 $self.payer_signing_pubkey = Some(signing_pubkey);
363 $return_value
364 }
365
366 #[cfg_attr(c_bindings, allow(dead_code))]
367 pub(super) fn experimental_bar($($self_mut)* $self: $self_type, experimental_bar: u64) -> $return_type {
368 $self.invoice_request.experimental_bar = Some(experimental_bar);
369 $return_value
370 }
371
372 #[cfg_attr(c_bindings, allow(dead_code))]
373 pub(super) fn build_unchecked($self: $self_type) -> UnsignedInvoiceRequest {
374 $self.build_without_checks().0
375 }
376
377 #[cfg_attr(c_bindings, allow(dead_code))]
378 pub(super) fn build_unchecked_and_sign($self: $self_type) -> InvoiceRequest {
379 let (unsigned_invoice_request, keys, secp_ctx) = $self.build_without_checks();
380 #[cfg(c_bindings)]
381 let mut unsigned_invoice_request = unsigned_invoice_request;
382 debug_assert!(keys.is_some());
383
384 let secp_ctx = secp_ctx.unwrap();
385 let keys = keys.unwrap();
386 unsigned_invoice_request
387 .sign(|message: &UnsignedInvoiceRequest|
388 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
389 )
390 .unwrap()
391 }
392} }
393
394impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, T> {
395 invoice_request_derived_payer_signing_pubkey_builder_methods!(self, Self, T);
396 invoice_request_builder_methods!(self, Self, Self, self, T, mut);
397
398 #[cfg(test)]
399 invoice_request_builder_test_methods!(self, Self, Self, self, mut);
400}
401
402#[cfg(all(c_bindings, not(test)))]
403impl<'a, 'b> InvoiceRequestWithDerivedPayerSigningPubkeyBuilder<'a, 'b> {
404 invoice_request_derived_payer_signing_pubkey_builder_methods!(self, &mut Self, secp256k1::All);
405 invoice_request_builder_methods!(self, &mut Self, (), (), secp256k1::All);
406}
407
408#[cfg(all(c_bindings, test))]
409impl<'a, 'b> InvoiceRequestWithDerivedPayerSigningPubkeyBuilder<'a, 'b> {
410 invoice_request_derived_payer_signing_pubkey_builder_methods!(self, &mut Self, secp256k1::All);
411 invoice_request_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
412 invoice_request_builder_test_methods!(self, &mut Self, &mut Self, self);
413}
414
415#[cfg(c_bindings)]
416impl<'a, 'b> From<InvoiceRequestWithDerivedPayerSigningPubkeyBuilder<'a, 'b>>
417for InvoiceRequestBuilder<'a, 'b, secp256k1::All> {
418 fn from(builder: InvoiceRequestWithDerivedPayerSigningPubkeyBuilder<'a, 'b>) -> Self {
419 let InvoiceRequestWithDerivedPayerSigningPubkeyBuilder {
420 offer, invoice_request, payer_signing_pubkey, secp_ctx,
421 } = builder;
422
423 Self {
424 offer, invoice_request, payer_signing_pubkey, secp_ctx,
425 }
426 }
427}
428
429#[derive(Clone)]
436pub struct UnsignedInvoiceRequest {
437 bytes: Vec<u8>,
438 experimental_bytes: Vec<u8>,
439 contents: InvoiceRequestContents,
440 tagged_hash: TaggedHash,
441}
442
443pub trait SignInvoiceRequestFn {
445 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()>;
447}
448
449impl<F> SignInvoiceRequestFn for F
450where
451 F: Fn(&UnsignedInvoiceRequest) -> Result<Signature, ()>,
452{
453 fn sign_invoice_request(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
454 self(message)
455 }
456}
457
458impl<F> SignFn<UnsignedInvoiceRequest> for F
459where
460 F: SignInvoiceRequestFn,
461{
462 fn sign(&self, message: &UnsignedInvoiceRequest) -> Result<Signature, ()> {
463 self.sign_invoice_request(message)
464 }
465}
466
467impl UnsignedInvoiceRequest {
468 fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
469 let (
472 payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream,
473 _experimental_offer_tlv_stream, experimental_invoice_request_tlv_stream,
474 ) = contents.as_tlv_stream();
475
476 let mut bytes = Vec::with_capacity(
481 offer.bytes.len()
482 + payer_tlv_stream.serialized_length()
483 + invoice_request_tlv_stream.serialized_length()
484 + SIGNATURE_TLV_RECORD_SIZE
485 + experimental_invoice_request_tlv_stream.serialized_length(),
486 );
487
488 payer_tlv_stream.write(&mut bytes).unwrap();
489
490 for record in TlvStream::new(&offer.bytes).range(OFFER_TYPES) {
491 record.write(&mut bytes).unwrap();
492 }
493
494 let remaining_bytes = &offer.bytes[bytes.len() - payer_tlv_stream.serialized_length()..];
495
496 invoice_request_tlv_stream.write(&mut bytes).unwrap();
497
498 let mut experimental_tlv_stream = TlvStream::new(remaining_bytes)
499 .range(EXPERIMENTAL_OFFER_TYPES)
500 .peekable();
501 let mut experimental_bytes = Vec::with_capacity(
502 remaining_bytes.len()
503 - experimental_tlv_stream
504 .peek()
505 .map_or(remaining_bytes.len(), |first_record| first_record.start)
506 + experimental_invoice_request_tlv_stream.serialized_length(),
507 );
508
509 for record in experimental_tlv_stream {
510 record.write(&mut experimental_bytes).unwrap();
511 }
512
513 experimental_invoice_request_tlv_stream.write(&mut experimental_bytes).unwrap();
514 debug_assert_eq!(experimental_bytes.len(), experimental_bytes.capacity());
515
516 let tlv_stream = TlvStream::new(&bytes).chain(TlvStream::new(&experimental_bytes));
517 let tagged_hash = TaggedHash::from_tlv_stream(SIGNATURE_TAG, tlv_stream);
518
519 Self { bytes, experimental_bytes, contents, tagged_hash }
520 }
521
522 pub fn tagged_hash(&self) -> &TaggedHash {
524 &self.tagged_hash
525 }
526}
527
528macro_rules! unsigned_invoice_request_sign_method { (
529 $self: ident, $self_type: ty $(, $self_mut: tt)?
530) => {
531 pub fn sign<F: SignInvoiceRequestFn>(
535 $($self_mut)* $self: $self_type, sign: F
536 ) -> Result<InvoiceRequest, SignError> {
537 let pubkey = $self.contents.payer_signing_pubkey;
538 let signature = merkle::sign_message(sign, &$self, pubkey)?;
539
540 let signature_tlv_stream = SignatureTlvStreamRef {
542 signature: Some(&signature),
543 };
544 signature_tlv_stream.write(&mut $self.bytes).unwrap();
545
546 debug_assert_eq!(
548 $self.bytes.len() + $self.experimental_bytes.len() + 2,
551 $self.bytes.capacity(),
552 );
553 $self.bytes.extend_from_slice(&$self.experimental_bytes);
554
555 Ok(InvoiceRequest {
556 #[cfg(not(c_bindings))]
557 bytes: $self.bytes,
558 #[cfg(c_bindings)]
559 bytes: $self.bytes.clone(),
560 #[cfg(not(c_bindings))]
561 contents: $self.contents,
562 #[cfg(c_bindings)]
563 contents: $self.contents.clone(),
564 signature,
565 })
566 }
567} }
568
569#[cfg(not(c_bindings))]
570impl UnsignedInvoiceRequest {
571 unsigned_invoice_request_sign_method!(self, Self, mut);
572}
573
574#[cfg(c_bindings)]
575impl UnsignedInvoiceRequest {
576 unsigned_invoice_request_sign_method!(self, &mut Self);
577}
578
579impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
580 fn as_ref(&self) -> &TaggedHash {
581 &self.tagged_hash
582 }
583}
584
585#[derive(Clone, Debug)]
593#[cfg_attr(test, derive(PartialEq))]
594pub struct InvoiceRequest {
595 pub(super) bytes: Vec<u8>,
596 pub(super) contents: InvoiceRequestContents,
597 signature: Signature,
598}
599
600#[derive(Clone, Debug)]
604pub struct VerifiedInvoiceRequest {
605 pub offer_id: OfferId,
607
608 pub(crate) inner: InvoiceRequest,
610
611 #[cfg_attr(feature = "std", doc = "If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call [`respond_with`].")]
614 #[cfg_attr(feature = "std", doc = "")]
615 #[cfg_attr(feature = "std", doc = "[`respond_using_derived_keys`]: Self::respond_using_derived_keys")]
617 #[cfg_attr(feature = "std", doc = "[`respond_with`]: Self::respond_with")]
618 pub keys: Option<Keypair>,
619}
620
621#[derive(Clone, Debug)]
625#[cfg_attr(test, derive(PartialEq))]
626pub(super) struct InvoiceRequestContents {
627 pub(super) inner: InvoiceRequestContentsWithoutPayerSigningPubkey,
628 payer_signing_pubkey: PublicKey,
629}
630
631#[derive(Clone, Debug)]
632#[cfg_attr(test, derive(PartialEq))]
633pub(super) struct InvoiceRequestContentsWithoutPayerSigningPubkey {
634 pub(super) payer: PayerContents,
635 pub(super) offer: OfferContents,
636 chain: Option<ChainHash>,
637 amount_msats: Option<u64>,
638 features: InvoiceRequestFeatures,
639 quantity: Option<u64>,
640 payer_note: Option<String>,
641 offer_from_hrn: Option<HumanReadableName>,
642 #[cfg(test)]
643 experimental_bar: Option<u64>,
644}
645
646macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
647 pub fn payer_metadata(&$self) -> &[u8] {
652 $contents.metadata()
653 }
654
655 pub fn chain(&$self) -> ChainHash {
657 $contents.chain()
658 }
659
660 pub fn amount_msats(&$self) -> Option<u64> {
665 $contents.amount_msats()
666 }
667
668 pub fn has_amount_msats(&$self) -> bool {
674 $contents.has_amount_msats()
675 }
676
677 pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
679 &$contents.features()
680 }
681
682 pub fn quantity(&$self) -> Option<u64> {
684 $contents.quantity()
685 }
686
687 pub fn payer_signing_pubkey(&$self) -> PublicKey {
689 $contents.payer_signing_pubkey()
690 }
691
692 pub fn payer_note(&$self) -> Option<PrintableString> {
695 $contents.payer_note()
696 }
697
698 pub fn offer_from_hrn(&$self) -> &Option<HumanReadableName> {
701 $contents.offer_from_hrn()
702 }
703} }
704
705impl UnsignedInvoiceRequest {
706 offer_accessors!(self, self.contents.inner.offer);
707 invoice_request_accessors!(self, self.contents);
708}
709
710macro_rules! invoice_request_respond_with_explicit_signing_pubkey_methods { (
711 $self: ident, $contents: expr, $builder: ty
712) => {
713 #[cfg(feature = "std")]
721 pub fn respond_with(
722 &$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash
723 ) -> Result<$builder, Bolt12SemanticError> {
724 let created_at = std::time::SystemTime::now()
725 .duration_since(std::time::SystemTime::UNIX_EPOCH)
726 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
727
728 $contents.respond_with_no_std(payment_paths, payment_hash, created_at)
729 }
730
731 #[cfg_attr(feature = "std", doc = "Useful for non-`std` builds where [`std::time::SystemTime`] is not available.")]
736 pub fn respond_with_no_std(
757 &$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
758 created_at: core::time::Duration
759 ) -> Result<$builder, Bolt12SemanticError> {
760 if $contents.invoice_request_features().requires_unknown_bits() {
761 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
762 }
763
764 let signing_pubkey = match $contents.contents.inner.offer.issuer_signing_pubkey() {
765 Some(signing_pubkey) => signing_pubkey,
766 None => return Err(Bolt12SemanticError::MissingIssuerSigningPubkey),
767 };
768
769 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
770 }
771
772 #[cfg(test)]
773 #[allow(dead_code)]
774 pub(super) fn respond_with_no_std_using_signing_pubkey(
775 &$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
776 created_at: core::time::Duration, signing_pubkey: PublicKey
777 ) -> Result<$builder, Bolt12SemanticError> {
778 debug_assert!($contents.contents.inner.offer.issuer_signing_pubkey().is_none());
779
780 if $contents.invoice_request_features().requires_unknown_bits() {
781 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
782 }
783
784 <$builder>::for_offer(&$contents, payment_paths, created_at, payment_hash, signing_pubkey)
785 }
786} }
787
788macro_rules! invoice_request_verify_method { ($self: ident, $self_type: ty) => {
789 pub fn verify_using_metadata<
797 #[cfg(not(c_bindings))]
798 T: secp256k1::Signing
799 >(
800 $self: $self_type, key: &ExpandedKey,
801 #[cfg(not(c_bindings))]
802 secp_ctx: &Secp256k1<T>,
803 #[cfg(c_bindings)]
804 secp_ctx: &Secp256k1<secp256k1::All>,
805 ) -> Result<VerifiedInvoiceRequest, ()> {
806 let (offer_id, keys) =
807 $self.contents.inner.offer.verify_using_metadata(&$self.bytes, key, secp_ctx)?;
808 Ok(VerifiedInvoiceRequest {
809 offer_id,
810 #[cfg(not(c_bindings))]
811 inner: $self,
812 #[cfg(c_bindings)]
813 inner: $self.clone(),
814 keys,
815 })
816 }
817
818 pub fn verify_using_recipient_data<
826 #[cfg(not(c_bindings))]
827 T: secp256k1::Signing
828 >(
829 $self: $self_type, nonce: Nonce, key: &ExpandedKey,
830 #[cfg(not(c_bindings))]
831 secp_ctx: &Secp256k1<T>,
832 #[cfg(c_bindings)]
833 secp_ctx: &Secp256k1<secp256k1::All>,
834 ) -> Result<VerifiedInvoiceRequest, ()> {
835 let (offer_id, keys) = $self.contents.inner.offer.verify_using_recipient_data(
836 &$self.bytes, nonce, key, secp_ctx
837 )?;
838 Ok(VerifiedInvoiceRequest {
839 offer_id,
840 #[cfg(not(c_bindings))]
841 inner: $self,
842 #[cfg(c_bindings)]
843 inner: $self.clone(),
844 keys,
845 })
846 }
847} }
848
849#[cfg(not(c_bindings))]
850impl InvoiceRequest {
851 offer_accessors!(self, self.contents.inner.offer);
852 invoice_request_accessors!(self, self.contents);
853 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceBuilder<ExplicitSigningPubkey>);
854 invoice_request_verify_method!(self, Self);
855
856 #[cfg(async_payments)]
857 pub(super) fn bytes(&self) -> &Vec<u8> {
858 &self.bytes
859 }
860}
861
862#[cfg(c_bindings)]
863impl InvoiceRequest {
864 offer_accessors!(self, self.contents.inner.offer);
865 invoice_request_accessors!(self, self.contents);
866 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self, InvoiceWithExplicitSigningPubkeyBuilder);
867 invoice_request_verify_method!(self, &Self);
868}
869
870impl InvoiceRequest {
871 pub fn signature(&self) -> Signature {
875 self.signature
876 }
877
878 pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
879 let (
880 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
881 experimental_offer_tlv_stream, experimental_invoice_request_tlv_stream,
882 ) = self.contents.as_tlv_stream();
883 let signature_tlv_stream = SignatureTlvStreamRef {
884 signature: Some(&self.signature),
885 };
886 (
887 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
888 signature_tlv_stream, experimental_offer_tlv_stream,
889 experimental_invoice_request_tlv_stream,
890 )
891 }
892}
893
894macro_rules! invoice_request_respond_with_derived_signing_pubkey_methods { (
895 $self: ident, $contents: expr, $builder: ty
896) => {
897 #[cfg(feature = "std")]
905 pub fn respond_using_derived_keys(
906 &$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash
907 ) -> Result<$builder, Bolt12SemanticError> {
908 let created_at = std::time::SystemTime::now()
909 .duration_since(std::time::SystemTime::UNIX_EPOCH)
910 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
911
912 $self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
913 }
914
915 pub fn respond_using_derived_keys_no_std(
923 &$self, payment_paths: Vec<BlindedPaymentPath>, payment_hash: PaymentHash,
924 created_at: core::time::Duration
925 ) -> Result<$builder, Bolt12SemanticError> {
926 if $self.inner.invoice_request_features().requires_unknown_bits() {
927 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
928 }
929
930 let keys = match $self.keys {
931 None => return Err(Bolt12SemanticError::InvalidMetadata),
932 Some(keys) => keys,
933 };
934
935 match $contents.contents.inner.offer.issuer_signing_pubkey() {
936 Some(signing_pubkey) => debug_assert_eq!(signing_pubkey, keys.public_key()),
937 None => return Err(Bolt12SemanticError::MissingIssuerSigningPubkey),
938 }
939
940 <$builder>::for_offer_using_keys(
941 &$self.inner, payment_paths, created_at, payment_hash, keys
942 )
943 }
944} }
945
946impl VerifiedInvoiceRequest {
947 offer_accessors!(self, self.inner.contents.inner.offer);
948 invoice_request_accessors!(self, self.inner.contents);
949 #[cfg(not(c_bindings))]
950 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<ExplicitSigningPubkey>);
951 #[cfg(c_bindings)]
952 invoice_request_respond_with_explicit_signing_pubkey_methods!(self, self.inner, InvoiceWithExplicitSigningPubkeyBuilder);
953 #[cfg(not(c_bindings))]
954 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceBuilder<DerivedSigningPubkey>);
955 #[cfg(c_bindings)]
956 invoice_request_respond_with_derived_signing_pubkey_methods!(self, self.inner, InvoiceWithDerivedSigningPubkeyBuilder);
957
958 pub(crate) fn fields(&self) -> InvoiceRequestFields {
959 let InvoiceRequestContents {
960 payer_signing_pubkey,
961 inner: InvoiceRequestContentsWithoutPayerSigningPubkey {
962 quantity, payer_note, ..
963 },
964 } = &self.inner.contents;
965
966 InvoiceRequestFields {
967 payer_signing_pubkey: *payer_signing_pubkey,
968 quantity: *quantity,
969 payer_note_truncated: payer_note.clone()
970 .map(|mut s| { s.truncate(PAYER_NOTE_LIMIT); UntrustedString(s) }),
971 human_readable_name: self.offer_from_hrn().clone(),
972 }
973 }
974}
975
976impl InvoiceRequestContents {
977 pub(super) fn metadata(&self) -> &[u8] {
978 self.inner.metadata()
979 }
980
981 pub(super) fn chain(&self) -> ChainHash {
982 self.inner.chain()
983 }
984
985 pub(super) fn amount_msats(&self) -> Option<u64> {
986 self.inner
987 .amount_msats()
988 .or_else(|| match self.inner.offer.amount() {
989 Some(Amount::Bitcoin { amount_msats }) => {
990 Some(amount_msats.saturating_mul(self.quantity().unwrap_or(1)))
991 },
992 Some(Amount::Currency { .. }) => None,
993 None => { debug_assert!(false); None},
994 })
995 }
996
997 pub(super) fn has_amount_msats(&self) -> bool {
998 self.inner.amount_msats().is_some()
999 }
1000
1001 pub(super) fn features(&self) -> &InvoiceRequestFeatures {
1002 &self.inner.features
1003 }
1004
1005 pub(super) fn quantity(&self) -> Option<u64> {
1006 self.inner.quantity
1007 }
1008
1009 pub(super) fn payer_signing_pubkey(&self) -> PublicKey {
1010 self.payer_signing_pubkey
1011 }
1012
1013 pub(super) fn payer_note(&self) -> Option<PrintableString> {
1014 self.inner.payer_note.as_ref()
1015 .map(|payer_note| PrintableString(payer_note.as_str()))
1016 }
1017
1018 pub(super) fn offer_from_hrn(&self) -> &Option<HumanReadableName> {
1019 &self.inner.offer_from_hrn
1020 }
1021
1022 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
1023 let (payer, offer, mut invoice_request, experimental_offer, experimental_invoice_request) =
1024 self.inner.as_tlv_stream();
1025 invoice_request.payer_id = Some(&self.payer_signing_pubkey);
1026 (payer, offer, invoice_request, experimental_offer, experimental_invoice_request)
1027 }
1028}
1029
1030impl InvoiceRequestContentsWithoutPayerSigningPubkey {
1031 pub(super) fn metadata(&self) -> &[u8] {
1032 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
1033 }
1034
1035 pub(super) fn chain(&self) -> ChainHash {
1036 self.chain.unwrap_or_else(|| self.offer.implied_chain())
1037 }
1038
1039 pub(super) fn amount_msats(&self) -> Option<u64> {
1040 self.amount_msats
1041 }
1042
1043 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
1044 let payer = PayerTlvStreamRef {
1045 metadata: self.payer.0.as_bytes(),
1046 };
1047
1048 let (offer, experimental_offer) = self.offer.as_tlv_stream();
1049
1050 let features = {
1051 if self.features == InvoiceRequestFeatures::empty() { None }
1052 else { Some(&self.features) }
1053 };
1054
1055 let invoice_request = InvoiceRequestTlvStreamRef {
1056 chain: self.chain.as_ref(),
1057 amount: self.amount_msats,
1058 features,
1059 quantity: self.quantity,
1060 payer_id: None,
1061 payer_note: self.payer_note.as_ref(),
1062 offer_from_hrn: self.offer_from_hrn.as_ref(),
1063 paths: None,
1064 };
1065
1066 let experimental_invoice_request = ExperimentalInvoiceRequestTlvStreamRef {
1067 #[cfg(test)]
1068 experimental_bar: self.experimental_bar,
1069 };
1070
1071 (payer, offer, invoice_request, experimental_offer, experimental_invoice_request)
1072 }
1073}
1074
1075impl Writeable for UnsignedInvoiceRequest {
1076 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1077 WithoutLength(&self.bytes).write(writer)
1078 }
1079}
1080
1081impl Writeable for InvoiceRequest {
1082 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1083 WithoutLength(&self.bytes).write(writer)
1084 }
1085}
1086
1087impl Writeable for InvoiceRequestContents {
1088 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1089 self.as_tlv_stream().write(writer)
1090 }
1091}
1092
1093impl Readable for InvoiceRequest {
1094 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1095 let bytes: WithoutLength<Vec<u8>> = Readable::read(reader)?;
1096 Self::try_from(bytes.0).map_err(|_| DecodeError::InvalidValue)
1097 }
1098}
1099
1100pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;
1102
1103pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;
1108
1109tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef<'a>, INVOICE_REQUEST_TYPES, {
1112 (80, chain: ChainHash),
1113 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
1114 (84, features: (InvoiceRequestFeatures, WithoutLength)),
1115 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
1116 (INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
1117 (89, payer_note: (String, WithoutLength)),
1118 (90, paths: (Vec<BlindedMessagePath>, WithoutLength)),
1120 (91, offer_from_hrn: HumanReadableName),
1121});
1122
1123pub(super) const EXPERIMENTAL_INVOICE_REQUEST_TYPES: core::ops::Range<u64> =
1125 2_000_000_000..3_000_000_000;
1126
1127#[cfg(not(test))]
1128tlv_stream!(
1129 ExperimentalInvoiceRequestTlvStream, ExperimentalInvoiceRequestTlvStreamRef,
1130 EXPERIMENTAL_INVOICE_REQUEST_TYPES, {}
1131);
1132
1133#[cfg(test)]
1134tlv_stream!(
1135 ExperimentalInvoiceRequestTlvStream, ExperimentalInvoiceRequestTlvStreamRef,
1136 EXPERIMENTAL_INVOICE_REQUEST_TYPES, {
1137 (2_999_999_999, experimental_bar: (u64, HighZeroBytesDroppedBigSize)),
1138 }
1139);
1140
1141type FullInvoiceRequestTlvStream = (
1142 PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream,
1143 ExperimentalOfferTlvStream, ExperimentalInvoiceRequestTlvStream,
1144);
1145
1146type FullInvoiceRequestTlvStreamRef<'a> = (
1147 PayerTlvStreamRef<'a>,
1148 OfferTlvStreamRef<'a>,
1149 InvoiceRequestTlvStreamRef<'a>,
1150 SignatureTlvStreamRef<'a>,
1151 ExperimentalOfferTlvStreamRef,
1152 ExperimentalInvoiceRequestTlvStreamRef,
1153);
1154
1155impl CursorReadable for FullInvoiceRequestTlvStream {
1156 fn read<R: AsRef<[u8]>>(r: &mut io::Cursor<R>) -> Result<Self, DecodeError> {
1157 let payer = CursorReadable::read(r)?;
1158 let offer = CursorReadable::read(r)?;
1159 let invoice_request = CursorReadable::read(r)?;
1160 let signature = CursorReadable::read(r)?;
1161 let experimental_offer = CursorReadable::read(r)?;
1162 let experimental_invoice_request = CursorReadable::read(r)?;
1163
1164 Ok(
1165 (
1166 payer, offer, invoice_request, signature, experimental_offer,
1167 experimental_invoice_request,
1168 )
1169 )
1170 }
1171}
1172
1173type PartialInvoiceRequestTlvStream = (
1174 PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, ExperimentalOfferTlvStream,
1175 ExperimentalInvoiceRequestTlvStream,
1176);
1177
1178type PartialInvoiceRequestTlvStreamRef<'a> = (
1179 PayerTlvStreamRef<'a>,
1180 OfferTlvStreamRef<'a>,
1181 InvoiceRequestTlvStreamRef<'a>,
1182 ExperimentalOfferTlvStreamRef,
1183 ExperimentalInvoiceRequestTlvStreamRef,
1184);
1185
1186impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
1187 type Error = Bolt12ParseError;
1188
1189 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1190 let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
1191 let ParsedMessage { mut bytes, tlv_stream } = invoice_request;
1192
1193 let contents = InvoiceRequestContents::try_from(tlv_stream)?;
1194 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1195
1196 let offset = TlvStream::new(&bytes)
1197 .range(0..INVOICE_REQUEST_TYPES.end)
1198 .last()
1199 .map_or(0, |last_record| last_record.end);
1200 let experimental_bytes = bytes.split_off(offset);
1201
1202 Ok(UnsignedInvoiceRequest { bytes, experimental_bytes, contents, tagged_hash })
1203 }
1204}
1205
1206impl TryFrom<Vec<u8>> for InvoiceRequest {
1207 type Error = Bolt12ParseError;
1208
1209 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1210 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
1211 let ParsedMessage { bytes, tlv_stream } = invoice_request;
1212 let (
1213 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1214 SignatureTlvStream { signature },
1215 experimental_offer_tlv_stream,
1216 experimental_invoice_request_tlv_stream,
1217 ) = tlv_stream;
1218 let contents = InvoiceRequestContents::try_from(
1219 (
1220 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
1221 experimental_offer_tlv_stream, experimental_invoice_request_tlv_stream,
1222 )
1223 )?;
1224
1225 let signature = match signature {
1226 None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1227 Some(signature) => signature,
1228 };
1229 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
1230 merkle::verify_signature(&signature, &message, contents.payer_signing_pubkey)?;
1231
1232 Ok(InvoiceRequest { bytes, contents, signature })
1233 }
1234}
1235
1236impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
1237 type Error = Bolt12SemanticError;
1238
1239 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
1240 let (
1241 PayerTlvStream { metadata },
1242 offer_tlv_stream,
1243 InvoiceRequestTlvStream {
1244 chain, amount, features, quantity, payer_id, payer_note, paths,
1245 offer_from_hrn,
1246 },
1247 experimental_offer_tlv_stream,
1248 ExperimentalInvoiceRequestTlvStream {
1249 #[cfg(test)]
1250 experimental_bar,
1251 },
1252 ) = tlv_stream;
1253
1254 let payer = match metadata {
1255 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
1256 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
1257 };
1258 let offer = OfferContents::try_from((offer_tlv_stream, experimental_offer_tlv_stream))?;
1259
1260 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
1261 return Err(Bolt12SemanticError::UnsupportedChain);
1262 }
1263
1264 if offer.amount().is_none() && amount.is_none() {
1265 return Err(Bolt12SemanticError::MissingAmount);
1266 }
1267
1268 offer.check_quantity(quantity)?;
1269 offer.check_amount_msats_for_quantity(amount, quantity)?;
1270
1271 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
1272
1273 let payer_signing_pubkey = match payer_id {
1274 None => return Err(Bolt12SemanticError::MissingPayerSigningPubkey),
1275 Some(payer_id) => payer_id,
1276 };
1277
1278 if paths.is_some() {
1279 return Err(Bolt12SemanticError::UnexpectedPaths);
1280 }
1281
1282 Ok(InvoiceRequestContents {
1283 inner: InvoiceRequestContentsWithoutPayerSigningPubkey {
1284 payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
1285 offer_from_hrn,
1286 #[cfg(test)]
1287 experimental_bar,
1288 },
1289 payer_signing_pubkey,
1290 })
1291 }
1292}
1293
1294#[derive(Clone, Debug, Eq, PartialEq)]
1298pub struct InvoiceRequestFields {
1299 pub payer_signing_pubkey: PublicKey,
1301
1302 pub quantity: Option<u64>,
1304
1305 pub payer_note_truncated: Option<UntrustedString>,
1308
1309 pub human_readable_name: Option<HumanReadableName>,
1311}
1312
1313pub const PAYER_NOTE_LIMIT: usize = 512;
1315
1316impl Writeable for InvoiceRequestFields {
1317 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1318 write_tlv_fields!(writer, {
1319 (0, self.payer_signing_pubkey, required),
1320 (1, self.human_readable_name, option),
1321 (2, self.quantity.map(|v| HighZeroBytesDroppedBigSize(v)), option),
1322 (4, self.payer_note_truncated.as_ref().map(|s| WithoutLength(&s.0)), option),
1323 });
1324 Ok(())
1325 }
1326}
1327
1328impl Readable for InvoiceRequestFields {
1329 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1330 _init_and_read_len_prefixed_tlv_fields!(reader, {
1331 (0, payer_signing_pubkey, required),
1332 (1, human_readable_name, option),
1333 (2, quantity, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1334 (4, payer_note_truncated, (option, encoding: (String, WithoutLength))),
1335 });
1336
1337 Ok(InvoiceRequestFields {
1338 payer_signing_pubkey: payer_signing_pubkey.0.unwrap(),
1339 quantity,
1340 payer_note_truncated: payer_note_truncated.map(|s| UntrustedString(s)),
1341 human_readable_name,
1342 })
1343 }
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348 use super::{EXPERIMENTAL_INVOICE_REQUEST_TYPES, ExperimentalInvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, InvoiceRequest, InvoiceRequestFields, InvoiceRequestTlvStreamRef, PAYER_NOTE_LIMIT, SIGNATURE_TAG, UnsignedInvoiceRequest};
1349
1350 use bitcoin::constants::ChainHash;
1351 use bitcoin::network::Network;
1352 use bitcoin::secp256k1::{Keypair, Secp256k1, SecretKey, self};
1353 use core::num::NonZeroU64;
1354 #[cfg(feature = "std")]
1355 use core::time::Duration;
1356 use crate::ln::channelmanager::PaymentId;
1357 use crate::types::features::{InvoiceRequestFeatures, OfferFeatures};
1358 use crate::ln::inbound_payment::ExpandedKey;
1359 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1360 use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
1361 use crate::offers::merkle::{SignatureTlvStreamRef, TaggedHash, TlvStream, self};
1362 use crate::offers::nonce::Nonce;
1363 use crate::offers::offer::{Amount, ExperimentalOfferTlvStreamRef, OfferTlvStreamRef, Quantity};
1364 #[cfg(not(c_bindings))]
1365 use {
1366 crate::offers::offer::OfferBuilder,
1367 };
1368 #[cfg(c_bindings)]
1369 use {
1370 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1371 };
1372 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1373 use crate::offers::payer::PayerTlvStreamRef;
1374 use crate::offers::test_utils::*;
1375 use crate::util::ser::{BigSize, Readable, Writeable};
1376 use crate::util::string::{PrintableString, UntrustedString};
1377
1378 #[test]
1379 fn builds_invoice_request_with_defaults() {
1380 let expanded_key = ExpandedKey::new([42; 32]);
1381 let entropy = FixedEntropy {};
1382 let nonce = Nonce::from_entropy_source(&entropy);
1383 let secp_ctx = Secp256k1::new();
1384 let payment_id = PaymentId([1; 32]);
1385 let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
1386
1387 let invoice_request = OfferBuilder::new(recipient_pubkey())
1388 .amount_msats(1000)
1389 .build().unwrap()
1390 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1391 .build_and_sign().unwrap();
1392
1393 let mut buffer = Vec::new();
1394 invoice_request.write(&mut buffer).unwrap();
1395
1396 assert_eq!(invoice_request.bytes, buffer.as_slice());
1397 assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
1398 assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1399 assert_eq!(invoice_request.metadata(), None);
1400 assert_eq!(invoice_request.amount(), Some(Amount::Bitcoin { amount_msats: 1000 }));
1401 assert_eq!(invoice_request.description(), Some(PrintableString("")));
1402 assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
1403 assert_eq!(invoice_request.absolute_expiry(), None);
1404 assert_eq!(invoice_request.paths(), &[]);
1405 assert_eq!(invoice_request.issuer(), None);
1406 assert_eq!(invoice_request.supported_quantity(), Quantity::One);
1407 assert_eq!(invoice_request.issuer_signing_pubkey(), Some(recipient_pubkey()));
1408 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1409 assert_eq!(invoice_request.amount_msats(), Some(1000));
1410 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1411 assert_eq!(invoice_request.quantity(), None);
1412 assert_eq!(invoice_request.payer_note(), None);
1413
1414 let message = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &invoice_request.bytes);
1415 assert!(
1416 merkle::verify_signature(
1417 &invoice_request.signature, &message, invoice_request.payer_signing_pubkey(),
1418 ).is_ok()
1419 );
1420
1421 assert_eq!(
1422 invoice_request.as_tlv_stream(),
1423 (
1424 PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
1425 OfferTlvStreamRef {
1426 chains: None,
1427 metadata: None,
1428 currency: None,
1429 amount: Some(1000),
1430 description: Some(&String::from("")),
1431 features: None,
1432 absolute_expiry: None,
1433 paths: None,
1434 issuer: None,
1435 quantity_max: None,
1436 issuer_id: Some(&recipient_pubkey()),
1437 },
1438 InvoiceRequestTlvStreamRef {
1439 chain: None,
1440 amount: None,
1441 features: None,
1442 quantity: None,
1443 payer_id: Some(&invoice_request.payer_signing_pubkey()),
1444 payer_note: None,
1445 paths: None,
1446 offer_from_hrn: None,
1447 },
1448 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
1449 ExperimentalOfferTlvStreamRef {
1450 experimental_foo: None,
1451 },
1452 ExperimentalInvoiceRequestTlvStreamRef {
1453 experimental_bar: None,
1454 },
1455 ),
1456 );
1457
1458 if let Err(e) = InvoiceRequest::try_from(buffer) {
1459 panic!("error parsing invoice request: {:?}", e);
1460 }
1461 }
1462
1463 #[cfg(feature = "std")]
1464 #[test]
1465 fn builds_invoice_request_from_offer_with_expiration() {
1466 let expanded_key = ExpandedKey::new([42; 32]);
1467 let entropy = FixedEntropy {};
1468 let nonce = Nonce::from_entropy_source(&entropy);
1469 let secp_ctx = Secp256k1::new();
1470 let payment_id = PaymentId([1; 32]);
1471
1472 let future_expiry = Duration::from_secs(u64::max_value());
1473 let past_expiry = Duration::from_secs(0);
1474
1475 if let Err(e) = OfferBuilder::new(recipient_pubkey())
1476 .amount_msats(1000)
1477 .absolute_expiry(future_expiry)
1478 .build().unwrap()
1479 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1480 .build_and_sign()
1481 {
1482 panic!("error building invoice_request: {:?}", e);
1483 }
1484
1485 match OfferBuilder::new(recipient_pubkey())
1486 .amount_msats(1000)
1487 .absolute_expiry(past_expiry)
1488 .build().unwrap()
1489 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1490 .build_and_sign()
1491 {
1492 Ok(_) => panic!("expected error"),
1493 Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1494 }
1495 }
1496
1497 #[test]
1498 fn builds_invoice_request_with_derived_payer_signing_pubkey() {
1499 let expanded_key = ExpandedKey::new([42; 32]);
1500 let entropy = FixedEntropy {};
1501 let nonce = Nonce::from_entropy_source(&entropy);
1502 let secp_ctx = Secp256k1::new();
1503 let payment_id = PaymentId([1; 32]);
1504
1505 let offer = OfferBuilder::new(recipient_pubkey())
1506 .amount_msats(1000)
1507 .experimental_foo(42)
1508 .build().unwrap();
1509 let invoice_request = offer
1510 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1511 .experimental_bar(42)
1512 .build_and_sign()
1513 .unwrap();
1514
1515 let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
1516 .unwrap()
1517 .experimental_baz(42)
1518 .build().unwrap()
1519 .sign(recipient_sign).unwrap();
1520 assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
1521 assert!(
1522 invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_ok()
1523 );
1524
1525 let (
1527 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
1528 mut invoice_tlv_stream, mut signature_tlv_stream, experimental_offer_tlv_stream,
1529 experimental_invoice_request_tlv_stream, experimental_invoice_tlv_stream,
1530 ) = invoice.as_tlv_stream();
1531 invoice_request_tlv_stream.amount = Some(2000);
1532 invoice_tlv_stream.amount = Some(2000);
1533
1534 let tlv_stream =
1535 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1536 let experimental_tlv_stream = (
1537 experimental_offer_tlv_stream, experimental_invoice_request_tlv_stream,
1538 experimental_invoice_tlv_stream,
1539 );
1540 let mut bytes = Vec::new();
1541 (&tlv_stream, &experimental_tlv_stream).write(&mut bytes).unwrap();
1542
1543 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1544 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1545 signature_tlv_stream.signature = Some(&signature);
1546
1547 let mut encoded_invoice = Vec::new();
1548 (tlv_stream, signature_tlv_stream, experimental_tlv_stream)
1549 .write(&mut encoded_invoice)
1550 .unwrap();
1551
1552 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1553 assert!(
1554 invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err()
1555 );
1556
1557 let (
1559 payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
1560 mut signature_tlv_stream, experimental_offer_tlv_stream,
1561 experimental_invoice_request_tlv_stream, experimental_invoice_tlv_stream,
1562 ) = invoice.as_tlv_stream();
1563 let payer_id = pubkey(1);
1564 invoice_request_tlv_stream.payer_id = Some(&payer_id);
1565
1566 let tlv_stream =
1567 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
1568 let experimental_tlv_stream = (
1569 experimental_offer_tlv_stream, experimental_invoice_request_tlv_stream,
1570 experimental_invoice_tlv_stream,
1571 );
1572 let mut bytes = Vec::new();
1573 (&tlv_stream, &experimental_tlv_stream).write(&mut bytes).unwrap();
1574
1575 let message = TaggedHash::from_valid_tlv_stream_bytes(INVOICE_SIGNATURE_TAG, &bytes);
1576 let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
1577 signature_tlv_stream.signature = Some(&signature);
1578
1579 let mut encoded_invoice = Vec::new();
1580 (tlv_stream, signature_tlv_stream, experimental_tlv_stream)
1581 .write(&mut encoded_invoice)
1582 .unwrap();
1583
1584 let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
1585 assert!(
1586 invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx).is_err()
1587 );
1588 }
1589
1590 #[test]
1591 fn builds_invoice_request_with_chain() {
1592 let expanded_key = ExpandedKey::new([42; 32]);
1593 let entropy = FixedEntropy {};
1594 let nonce = Nonce::from_entropy_source(&entropy);
1595 let secp_ctx = Secp256k1::new();
1596 let payment_id = PaymentId([1; 32]);
1597
1598 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1599 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1600
1601 let invoice_request = OfferBuilder::new(recipient_pubkey())
1602 .amount_msats(1000)
1603 .build().unwrap()
1604 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1605 .chain(Network::Bitcoin).unwrap()
1606 .build_and_sign().unwrap();
1607 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1608 assert_eq!(invoice_request.chain(), mainnet);
1609 assert_eq!(tlv_stream.chain, None);
1610
1611 let invoice_request = OfferBuilder::new(recipient_pubkey())
1612 .amount_msats(1000)
1613 .chain(Network::Testnet)
1614 .build().unwrap()
1615 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1616 .chain(Network::Testnet).unwrap()
1617 .build_and_sign().unwrap();
1618 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1619 assert_eq!(invoice_request.chain(), testnet);
1620 assert_eq!(tlv_stream.chain, Some(&testnet));
1621
1622 let invoice_request = OfferBuilder::new(recipient_pubkey())
1623 .amount_msats(1000)
1624 .chain(Network::Bitcoin)
1625 .chain(Network::Testnet)
1626 .build().unwrap()
1627 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1628 .chain(Network::Bitcoin).unwrap()
1629 .build_and_sign().unwrap();
1630 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1631 assert_eq!(invoice_request.chain(), mainnet);
1632 assert_eq!(tlv_stream.chain, None);
1633
1634 let invoice_request = OfferBuilder::new(recipient_pubkey())
1635 .amount_msats(1000)
1636 .chain(Network::Bitcoin)
1637 .chain(Network::Testnet)
1638 .build().unwrap()
1639 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1640 .chain(Network::Bitcoin).unwrap()
1641 .chain(Network::Testnet).unwrap()
1642 .build_and_sign().unwrap();
1643 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1644 assert_eq!(invoice_request.chain(), testnet);
1645 assert_eq!(tlv_stream.chain, Some(&testnet));
1646
1647 match OfferBuilder::new(recipient_pubkey())
1648 .amount_msats(1000)
1649 .chain(Network::Testnet)
1650 .build().unwrap()
1651 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1652 .chain(Network::Bitcoin)
1653 {
1654 Ok(_) => panic!("expected error"),
1655 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1656 }
1657
1658 match OfferBuilder::new(recipient_pubkey())
1659 .amount_msats(1000)
1660 .chain(Network::Testnet)
1661 .build().unwrap()
1662 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1663 .build_and_sign()
1664 {
1665 Ok(_) => panic!("expected error"),
1666 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1667 }
1668 }
1669
1670 #[test]
1671 fn builds_invoice_request_with_amount() {
1672 let expanded_key = ExpandedKey::new([42; 32]);
1673 let entropy = FixedEntropy {};
1674 let nonce = Nonce::from_entropy_source(&entropy);
1675 let secp_ctx = Secp256k1::new();
1676 let payment_id = PaymentId([1; 32]);
1677
1678 let invoice_request = OfferBuilder::new(recipient_pubkey())
1679 .amount_msats(1000)
1680 .build().unwrap()
1681 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1682 .amount_msats(1000).unwrap()
1683 .build_and_sign().unwrap();
1684 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1685 assert!(invoice_request.has_amount_msats());
1686 assert_eq!(invoice_request.amount_msats(), Some(1000));
1687 assert_eq!(tlv_stream.amount, Some(1000));
1688
1689 let invoice_request = OfferBuilder::new(recipient_pubkey())
1690 .amount_msats(1000)
1691 .build().unwrap()
1692 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1693 .amount_msats(1001).unwrap()
1694 .amount_msats(1000).unwrap()
1695 .build_and_sign().unwrap();
1696 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1697 assert!(invoice_request.has_amount_msats());
1698 assert_eq!(invoice_request.amount_msats(), Some(1000));
1699 assert_eq!(tlv_stream.amount, Some(1000));
1700
1701 let invoice_request = OfferBuilder::new(recipient_pubkey())
1702 .amount_msats(1000)
1703 .build().unwrap()
1704 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1705 .amount_msats(1001).unwrap()
1706 .build_and_sign().unwrap();
1707 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1708 assert!(invoice_request.has_amount_msats());
1709 assert_eq!(invoice_request.amount_msats(), Some(1001));
1710 assert_eq!(tlv_stream.amount, Some(1001));
1711
1712 match OfferBuilder::new(recipient_pubkey())
1713 .amount_msats(1000)
1714 .build().unwrap()
1715 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1716 .amount_msats(999)
1717 {
1718 Ok(_) => panic!("expected error"),
1719 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1720 }
1721
1722 match OfferBuilder::new(recipient_pubkey())
1723 .amount_msats(1000)
1724 .supported_quantity(Quantity::Unbounded)
1725 .build().unwrap()
1726 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1727 .quantity(2).unwrap()
1728 .amount_msats(1000)
1729 {
1730 Ok(_) => panic!("expected error"),
1731 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1732 }
1733
1734 match OfferBuilder::new(recipient_pubkey())
1735 .amount_msats(1000)
1736 .build().unwrap()
1737 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1738 .amount_msats(MAX_VALUE_MSAT + 1)
1739 {
1740 Ok(_) => panic!("expected error"),
1741 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1742 }
1743
1744 match OfferBuilder::new(recipient_pubkey())
1745 .amount_msats(1000)
1746 .supported_quantity(Quantity::Unbounded)
1747 .build().unwrap()
1748 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1749 .amount_msats(1000).unwrap()
1750 .quantity(2).unwrap()
1751 .build_and_sign()
1752 {
1753 Ok(_) => panic!("expected error"),
1754 Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
1755 }
1756
1757 match OfferBuilder::new(recipient_pubkey())
1758 .build().unwrap()
1759 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1760 .build_and_sign()
1761 {
1762 Ok(_) => panic!("expected error"),
1763 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
1764 }
1765
1766 match OfferBuilder::new(recipient_pubkey())
1767 .amount_msats(1000)
1768 .supported_quantity(Quantity::Unbounded)
1769 .build().unwrap()
1770 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1771 .quantity(u64::max_value()).unwrap()
1772 .build_and_sign()
1773 {
1774 Ok(_) => panic!("expected error"),
1775 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1776 }
1777 }
1778
1779 #[test]
1780 fn builds_invoice_request_without_amount() {
1781 let expanded_key = ExpandedKey::new([42; 32]);
1782 let entropy = FixedEntropy {};
1783 let nonce = Nonce::from_entropy_source(&entropy);
1784 let secp_ctx = Secp256k1::new();
1785 let payment_id = PaymentId([1; 32]);
1786
1787 let invoice_request = OfferBuilder::new(recipient_pubkey())
1788 .amount_msats(1000)
1789 .build().unwrap()
1790 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1791 .build_and_sign().unwrap();
1792 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1793 assert!(!invoice_request.has_amount_msats());
1794 assert_eq!(invoice_request.amount_msats(), Some(1000));
1795 assert_eq!(tlv_stream.amount, None);
1796
1797 let invoice_request = OfferBuilder::new(recipient_pubkey())
1798 .amount_msats(1000)
1799 .supported_quantity(Quantity::Unbounded)
1800 .build().unwrap()
1801 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1802 .quantity(2).unwrap()
1803 .build_and_sign().unwrap();
1804 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1805 assert!(!invoice_request.has_amount_msats());
1806 assert_eq!(invoice_request.amount_msats(), Some(2000));
1807 assert_eq!(tlv_stream.amount, None);
1808
1809 let invoice_request = OfferBuilder::new(recipient_pubkey())
1810 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 10 })
1811 .build_unchecked()
1812 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1813 .build_unchecked_and_sign();
1814 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1815 assert!(!invoice_request.has_amount_msats());
1816 assert_eq!(invoice_request.amount_msats(), None);
1817 assert_eq!(tlv_stream.amount, None);
1818 }
1819
1820 #[test]
1821 fn builds_invoice_request_with_features() {
1822 let expanded_key = ExpandedKey::new([42; 32]);
1823 let entropy = FixedEntropy {};
1824 let nonce = Nonce::from_entropy_source(&entropy);
1825 let secp_ctx = Secp256k1::new();
1826 let payment_id = PaymentId([1; 32]);
1827
1828 let invoice_request = OfferBuilder::new(recipient_pubkey())
1829 .amount_msats(1000)
1830 .build().unwrap()
1831 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1832 .features_unchecked(InvoiceRequestFeatures::unknown())
1833 .build_and_sign().unwrap();
1834 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1835 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
1836 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
1837
1838 let invoice_request = OfferBuilder::new(recipient_pubkey())
1839 .amount_msats(1000)
1840 .build().unwrap()
1841 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1842 .features_unchecked(InvoiceRequestFeatures::unknown())
1843 .features_unchecked(InvoiceRequestFeatures::empty())
1844 .build_and_sign().unwrap();
1845 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1846 assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
1847 assert_eq!(tlv_stream.features, None);
1848 }
1849
1850 #[test]
1851 fn builds_invoice_request_with_quantity() {
1852 let expanded_key = ExpandedKey::new([42; 32]);
1853 let entropy = FixedEntropy {};
1854 let nonce = Nonce::from_entropy_source(&entropy);
1855 let secp_ctx = Secp256k1::new();
1856 let payment_id = PaymentId([1; 32]);
1857
1858 let one = NonZeroU64::new(1).unwrap();
1859 let ten = NonZeroU64::new(10).unwrap();
1860
1861 let invoice_request = OfferBuilder::new(recipient_pubkey())
1862 .amount_msats(1000)
1863 .supported_quantity(Quantity::One)
1864 .build().unwrap()
1865 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1866 .build_and_sign().unwrap();
1867 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1868 assert_eq!(invoice_request.quantity(), None);
1869 assert_eq!(tlv_stream.quantity, None);
1870
1871 match OfferBuilder::new(recipient_pubkey())
1872 .amount_msats(1000)
1873 .supported_quantity(Quantity::One)
1874 .build().unwrap()
1875 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1876 .amount_msats(2_000).unwrap()
1877 .quantity(2)
1878 {
1879 Ok(_) => panic!("expected error"),
1880 Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
1881 }
1882
1883 let invoice_request = OfferBuilder::new(recipient_pubkey())
1884 .amount_msats(1000)
1885 .supported_quantity(Quantity::Bounded(ten))
1886 .build().unwrap()
1887 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1888 .amount_msats(10_000).unwrap()
1889 .quantity(10).unwrap()
1890 .build_and_sign().unwrap();
1891 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1892 assert_eq!(invoice_request.amount_msats(), Some(10_000));
1893 assert_eq!(tlv_stream.amount, Some(10_000));
1894
1895 match OfferBuilder::new(recipient_pubkey())
1896 .amount_msats(1000)
1897 .supported_quantity(Quantity::Bounded(ten))
1898 .build().unwrap()
1899 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1900 .amount_msats(11_000).unwrap()
1901 .quantity(11)
1902 {
1903 Ok(_) => panic!("expected error"),
1904 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
1905 }
1906
1907 let invoice_request = OfferBuilder::new(recipient_pubkey())
1908 .amount_msats(1000)
1909 .supported_quantity(Quantity::Unbounded)
1910 .build().unwrap()
1911 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1912 .amount_msats(2_000).unwrap()
1913 .quantity(2).unwrap()
1914 .build_and_sign().unwrap();
1915 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1916 assert_eq!(invoice_request.amount_msats(), Some(2_000));
1917 assert_eq!(tlv_stream.amount, Some(2_000));
1918
1919 match OfferBuilder::new(recipient_pubkey())
1920 .amount_msats(1000)
1921 .supported_quantity(Quantity::Unbounded)
1922 .build().unwrap()
1923 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1924 .build_and_sign()
1925 {
1926 Ok(_) => panic!("expected error"),
1927 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1928 }
1929
1930 match OfferBuilder::new(recipient_pubkey())
1931 .amount_msats(1000)
1932 .supported_quantity(Quantity::Bounded(one))
1933 .build().unwrap()
1934 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1935 .build_and_sign()
1936 {
1937 Ok(_) => panic!("expected error"),
1938 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
1939 }
1940 }
1941
1942 #[test]
1943 fn builds_invoice_request_with_payer_note() {
1944 let expanded_key = ExpandedKey::new([42; 32]);
1945 let entropy = FixedEntropy {};
1946 let nonce = Nonce::from_entropy_source(&entropy);
1947 let secp_ctx = Secp256k1::new();
1948 let payment_id = PaymentId([1; 32]);
1949
1950 let invoice_request = OfferBuilder::new(recipient_pubkey())
1951 .amount_msats(1000)
1952 .build().unwrap()
1953 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1954 .payer_note("bar".into())
1955 .build_and_sign().unwrap();
1956 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1957 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
1958 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1959
1960 let invoice_request = OfferBuilder::new(recipient_pubkey())
1961 .amount_msats(1000)
1962 .build().unwrap()
1963 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1964 .payer_note("bar".into())
1965 .payer_note("baz".into())
1966 .build_and_sign().unwrap();
1967 let (_, _, tlv_stream, _, _, _) = invoice_request.as_tlv_stream();
1968 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
1969 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1970 }
1971
1972 #[test]
1973 fn fails_responding_with_unknown_required_features() {
1974 let expanded_key = ExpandedKey::new([42; 32]);
1975 let entropy = FixedEntropy {};
1976 let nonce = Nonce::from_entropy_source(&entropy);
1977 let secp_ctx = Secp256k1::new();
1978 let payment_id = PaymentId([1; 32]);
1979
1980 match OfferBuilder::new(recipient_pubkey())
1981 .amount_msats(1000)
1982 .build().unwrap()
1983 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
1984 .features_unchecked(InvoiceRequestFeatures::unknown())
1985 .build_and_sign().unwrap()
1986 .respond_with_no_std(payment_paths(), payment_hash(), now())
1987 {
1988 Ok(_) => panic!("expected error"),
1989 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1990 }
1991 }
1992
1993 #[test]
1994 fn parses_invoice_request_with_metadata() {
1995 let expanded_key = ExpandedKey::new([42; 32]);
1996 let entropy = FixedEntropy {};
1997 let nonce = Nonce::from_entropy_source(&entropy);
1998 let secp_ctx = Secp256k1::new();
1999 let payment_id = PaymentId([1; 32]);
2000
2001 let invoice_request = OfferBuilder::new(recipient_pubkey())
2002 .amount_msats(1000)
2003 .build().unwrap()
2004 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2005 .build_and_sign().unwrap();
2006
2007 let mut buffer = Vec::new();
2008 invoice_request.write(&mut buffer).unwrap();
2009
2010 if let Err(e) = InvoiceRequest::try_from(buffer) {
2011 panic!("error parsing invoice_request: {:?}", e);
2012 }
2013 }
2014
2015 #[test]
2016 fn parses_invoice_request_with_chain() {
2017 let expanded_key = ExpandedKey::new([42; 32]);
2018 let entropy = FixedEntropy {};
2019 let nonce = Nonce::from_entropy_source(&entropy);
2020 let secp_ctx = Secp256k1::new();
2021 let payment_id = PaymentId([1; 32]);
2022
2023 let invoice_request = OfferBuilder::new(recipient_pubkey())
2024 .amount_msats(1000)
2025 .build().unwrap()
2026 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2027 .chain(Network::Bitcoin).unwrap()
2028 .build_and_sign().unwrap();
2029
2030 let mut buffer = Vec::new();
2031 invoice_request.write(&mut buffer).unwrap();
2032
2033 if let Err(e) = InvoiceRequest::try_from(buffer) {
2034 panic!("error parsing invoice_request: {:?}", e);
2035 }
2036
2037 let invoice_request = OfferBuilder::new(recipient_pubkey())
2038 .amount_msats(1000)
2039 .build().unwrap()
2040 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2041 .chain_unchecked(Network::Testnet)
2042 .build_unchecked_and_sign();
2043
2044 let mut buffer = Vec::new();
2045 invoice_request.write(&mut buffer).unwrap();
2046
2047 match InvoiceRequest::try_from(buffer) {
2048 Ok(_) => panic!("expected error"),
2049 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
2050 }
2051 }
2052
2053 #[test]
2054 fn parses_invoice_request_with_amount() {
2055 let expanded_key = ExpandedKey::new([42; 32]);
2056 let entropy = FixedEntropy {};
2057 let nonce = Nonce::from_entropy_source(&entropy);
2058 let secp_ctx = Secp256k1::new();
2059 let payment_id = PaymentId([1; 32]);
2060
2061 let invoice_request = OfferBuilder::new(recipient_pubkey())
2062 .amount_msats(1000)
2063 .build().unwrap()
2064 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2065 .build_and_sign().unwrap();
2066
2067 let mut buffer = Vec::new();
2068 invoice_request.write(&mut buffer).unwrap();
2069
2070 if let Err(e) = InvoiceRequest::try_from(buffer) {
2071 panic!("error parsing invoice_request: {:?}", e);
2072 }
2073
2074 let invoice_request = OfferBuilder::new(recipient_pubkey())
2075 .build().unwrap()
2076 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2077 .amount_msats(1000).unwrap()
2078 .build_and_sign().unwrap();
2079
2080 let mut buffer = Vec::new();
2081 invoice_request.write(&mut buffer).unwrap();
2082
2083 if let Err(e) = InvoiceRequest::try_from(buffer) {
2084 panic!("error parsing invoice_request: {:?}", e);
2085 }
2086
2087 let invoice_request = OfferBuilder::new(recipient_pubkey())
2088 .build().unwrap()
2089 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2090 .build_unchecked_and_sign();
2091
2092 let mut buffer = Vec::new();
2093 invoice_request.write(&mut buffer).unwrap();
2094
2095 match InvoiceRequest::try_from(buffer) {
2096 Ok(_) => panic!("expected error"),
2097 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2098 }
2099
2100 let invoice_request = OfferBuilder::new(recipient_pubkey())
2101 .amount_msats(1000)
2102 .build().unwrap()
2103 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2104 .amount_msats_unchecked(999)
2105 .build_unchecked_and_sign();
2106
2107 let mut buffer = Vec::new();
2108 invoice_request.write(&mut buffer).unwrap();
2109
2110 match InvoiceRequest::try_from(buffer) {
2111 Ok(_) => panic!("expected error"),
2112 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
2113 }
2114
2115 let invoice_request = OfferBuilder::new(recipient_pubkey())
2116 .description("foo".to_string())
2117 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
2118 .build_unchecked()
2119 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2120 .build_unchecked_and_sign();
2121
2122 let mut buffer = Vec::new();
2123 invoice_request.write(&mut buffer).unwrap();
2124
2125 match InvoiceRequest::try_from(buffer) {
2126 Ok(_) => panic!("expected error"),
2127 Err(e) => {
2128 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
2129 },
2130 }
2131
2132 let invoice_request = OfferBuilder::new(recipient_pubkey())
2133 .amount_msats(1000)
2134 .supported_quantity(Quantity::Unbounded)
2135 .build().unwrap()
2136 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2137 .quantity(u64::max_value()).unwrap()
2138 .build_unchecked_and_sign();
2139
2140 let mut buffer = Vec::new();
2141 invoice_request.write(&mut buffer).unwrap();
2142
2143 match InvoiceRequest::try_from(buffer) {
2144 Ok(_) => panic!("expected error"),
2145 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
2146 }
2147 }
2148
2149 #[test]
2150 fn parses_invoice_request_with_quantity() {
2151 let expanded_key = ExpandedKey::new([42; 32]);
2152 let entropy = FixedEntropy {};
2153 let nonce = Nonce::from_entropy_source(&entropy);
2154 let secp_ctx = Secp256k1::new();
2155 let payment_id = PaymentId([1; 32]);
2156
2157 let one = NonZeroU64::new(1).unwrap();
2158 let ten = NonZeroU64::new(10).unwrap();
2159
2160 let invoice_request = OfferBuilder::new(recipient_pubkey())
2161 .amount_msats(1000)
2162 .supported_quantity(Quantity::One)
2163 .build().unwrap()
2164 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2165 .build_and_sign().unwrap();
2166
2167 let mut buffer = Vec::new();
2168 invoice_request.write(&mut buffer).unwrap();
2169
2170 if let Err(e) = InvoiceRequest::try_from(buffer) {
2171 panic!("error parsing invoice_request: {:?}", e);
2172 }
2173
2174 let invoice_request = OfferBuilder::new(recipient_pubkey())
2175 .amount_msats(1000)
2176 .supported_quantity(Quantity::One)
2177 .build().unwrap()
2178 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2179 .amount_msats(2_000).unwrap()
2180 .quantity_unchecked(2)
2181 .build_unchecked_and_sign();
2182
2183 let mut buffer = Vec::new();
2184 invoice_request.write(&mut buffer).unwrap();
2185
2186 match InvoiceRequest::try_from(buffer) {
2187 Ok(_) => panic!("expected error"),
2188 Err(e) => {
2189 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
2190 },
2191 }
2192
2193 let invoice_request = OfferBuilder::new(recipient_pubkey())
2194 .amount_msats(1000)
2195 .supported_quantity(Quantity::Bounded(ten))
2196 .build().unwrap()
2197 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2198 .amount_msats(10_000).unwrap()
2199 .quantity(10).unwrap()
2200 .build_and_sign().unwrap();
2201
2202 let mut buffer = Vec::new();
2203 invoice_request.write(&mut buffer).unwrap();
2204
2205 if let Err(e) = InvoiceRequest::try_from(buffer) {
2206 panic!("error parsing invoice_request: {:?}", e);
2207 }
2208
2209 let invoice_request = OfferBuilder::new(recipient_pubkey())
2210 .amount_msats(1000)
2211 .supported_quantity(Quantity::Bounded(ten))
2212 .build().unwrap()
2213 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2214 .amount_msats(11_000).unwrap()
2215 .quantity_unchecked(11)
2216 .build_unchecked_and_sign();
2217
2218 let mut buffer = Vec::new();
2219 invoice_request.write(&mut buffer).unwrap();
2220
2221 match InvoiceRequest::try_from(buffer) {
2222 Ok(_) => panic!("expected error"),
2223 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
2224 }
2225
2226 let invoice_request = OfferBuilder::new(recipient_pubkey())
2227 .amount_msats(1000)
2228 .supported_quantity(Quantity::Unbounded)
2229 .build().unwrap()
2230 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2231 .amount_msats(2_000).unwrap()
2232 .quantity(2).unwrap()
2233 .build_and_sign().unwrap();
2234
2235 let mut buffer = Vec::new();
2236 invoice_request.write(&mut buffer).unwrap();
2237
2238 if let Err(e) = InvoiceRequest::try_from(buffer) {
2239 panic!("error parsing invoice_request: {:?}", e);
2240 }
2241
2242 let invoice_request = OfferBuilder::new(recipient_pubkey())
2243 .amount_msats(1000)
2244 .supported_quantity(Quantity::Unbounded)
2245 .build().unwrap()
2246 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2247 .build_unchecked_and_sign();
2248
2249 let mut buffer = Vec::new();
2250 invoice_request.write(&mut buffer).unwrap();
2251
2252 match InvoiceRequest::try_from(buffer) {
2253 Ok(_) => panic!("expected error"),
2254 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2255 }
2256
2257 let invoice_request = OfferBuilder::new(recipient_pubkey())
2258 .amount_msats(1000)
2259 .supported_quantity(Quantity::Bounded(one))
2260 .build().unwrap()
2261 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2262 .build_unchecked_and_sign();
2263
2264 let mut buffer = Vec::new();
2265 invoice_request.write(&mut buffer).unwrap();
2266
2267 match InvoiceRequest::try_from(buffer) {
2268 Ok(_) => panic!("expected error"),
2269 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
2270 }
2271 }
2272
2273 #[test]
2274 fn fails_parsing_invoice_request_without_metadata() {
2275 let expanded_key = ExpandedKey::new([42; 32]);
2276 let entropy = FixedEntropy {};
2277 let nonce = Nonce::from_entropy_source(&entropy);
2278 let secp_ctx = Secp256k1::new();
2279 let payment_id = PaymentId([1; 32]);
2280
2281 let unsigned_invoice_request = OfferBuilder::new(recipient_pubkey())
2282 .amount_msats(1000)
2283 .build().unwrap()
2284 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2285 .build_unchecked();
2286 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2287 tlv_stream.0.metadata = None;
2288
2289 let mut buffer = Vec::new();
2290 tlv_stream.write(&mut buffer).unwrap();
2291
2292 match InvoiceRequest::try_from(buffer) {
2293 Ok(_) => panic!("expected error"),
2294 Err(e) => {
2295 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
2296 },
2297 }
2298 }
2299
2300 #[test]
2301 fn fails_parsing_invoice_request_without_payer_signing_pubkey() {
2302 let expanded_key = ExpandedKey::new([42; 32]);
2303 let entropy = FixedEntropy {};
2304 let nonce = Nonce::from_entropy_source(&entropy);
2305 let secp_ctx = Secp256k1::new();
2306 let payment_id = PaymentId([1; 32]);
2307
2308 let unsigned_invoice_request = OfferBuilder::new(recipient_pubkey())
2309 .amount_msats(1000)
2310 .build().unwrap()
2311 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2312 .build_unchecked();
2313 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2314 tlv_stream.2.payer_id = None;
2315
2316 let mut buffer = Vec::new();
2317 tlv_stream.write(&mut buffer).unwrap();
2318
2319 match InvoiceRequest::try_from(buffer) {
2320 Ok(_) => panic!("expected error"),
2321 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerSigningPubkey)),
2322 }
2323 }
2324
2325 #[test]
2326 fn fails_parsing_invoice_request_without_issuer_id() {
2327 let expanded_key = ExpandedKey::new([42; 32]);
2328 let entropy = FixedEntropy {};
2329 let nonce = Nonce::from_entropy_source(&entropy);
2330 let secp_ctx = Secp256k1::new();
2331 let payment_id = PaymentId([1; 32]);
2332
2333 let unsigned_invoice_request = OfferBuilder::new(recipient_pubkey())
2334 .amount_msats(1000)
2335 .build().unwrap()
2336 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2337 .build_unchecked();
2338 let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
2339 tlv_stream.1.issuer_id = None;
2340
2341 let mut buffer = Vec::new();
2342 tlv_stream.write(&mut buffer).unwrap();
2343
2344 match InvoiceRequest::try_from(buffer) {
2345 Ok(_) => panic!("expected error"),
2346 Err(e) => {
2347 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingIssuerSigningPubkey));
2348 },
2349 }
2350 }
2351
2352 #[test]
2353 fn fails_parsing_invoice_request_without_signature() {
2354 let expanded_key = ExpandedKey::new([42; 32]);
2355 let entropy = FixedEntropy {};
2356 let nonce = Nonce::from_entropy_source(&entropy);
2357 let secp_ctx = Secp256k1::new();
2358 let payment_id = PaymentId([1; 32]);
2359
2360 let mut buffer = Vec::new();
2361 OfferBuilder::new(recipient_pubkey())
2362 .amount_msats(1000)
2363 .build().unwrap()
2364 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2365 .build_unchecked()
2366 .contents
2367 .write(&mut buffer).unwrap();
2368
2369 match InvoiceRequest::try_from(buffer) {
2370 Ok(_) => panic!("expected error"),
2371 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2372 }
2373 }
2374
2375 #[test]
2376 fn fails_parsing_invoice_request_with_invalid_signature() {
2377 let expanded_key = ExpandedKey::new([42; 32]);
2378 let entropy = FixedEntropy {};
2379 let nonce = Nonce::from_entropy_source(&entropy);
2380 let secp_ctx = Secp256k1::new();
2381 let payment_id = PaymentId([1; 32]);
2382
2383 let mut invoice_request = OfferBuilder::new(recipient_pubkey())
2384 .amount_msats(1000)
2385 .build().unwrap()
2386 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2387 .build_and_sign().unwrap();
2388 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
2389 *last_signature_byte = last_signature_byte.wrapping_add(1);
2390
2391 let mut buffer = Vec::new();
2392 invoice_request.write(&mut buffer).unwrap();
2393
2394 match InvoiceRequest::try_from(buffer) {
2395 Ok(_) => panic!("expected error"),
2396 Err(e) => {
2397 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::IncorrectSignature));
2398 },
2399 }
2400 }
2401
2402 #[test]
2403 fn parses_invoice_request_with_unknown_tlv_records() {
2404 let expanded_key = ExpandedKey::new([42; 32]);
2405 let entropy = FixedEntropy {};
2406 let nonce = Nonce::from_entropy_source(&entropy);
2407 let payment_id = PaymentId([1; 32]);
2408
2409 const UNKNOWN_ODD_TYPE: u64 = INVOICE_REQUEST_TYPES.end - 1;
2410 assert!(UNKNOWN_ODD_TYPE % 2 == 1);
2411
2412 let secp_ctx = Secp256k1::new();
2413 let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2414 let (mut unsigned_invoice_request, payer_keys, _) = OfferBuilder::new(keys.public_key())
2415 .amount_msats(1000)
2416 .build().unwrap()
2417 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2418 .build_without_checks();
2419
2420 let mut unknown_bytes = Vec::new();
2421 BigSize(UNKNOWN_ODD_TYPE).write(&mut unknown_bytes).unwrap();
2422 BigSize(32).write(&mut unknown_bytes).unwrap();
2423 [42u8; 32].write(&mut unknown_bytes).unwrap();
2424
2425 unsigned_invoice_request.bytes.reserve_exact(
2426 unsigned_invoice_request.bytes.capacity()
2427 - unsigned_invoice_request.bytes.len()
2428 + unknown_bytes.len(),
2429 );
2430 unsigned_invoice_request.bytes.extend_from_slice(&unknown_bytes);
2431 unsigned_invoice_request.tagged_hash =
2432 TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &unsigned_invoice_request.bytes);
2433
2434 let keys = payer_keys.unwrap();
2435 let invoice_request = unsigned_invoice_request
2436 .sign(|message: &UnsignedInvoiceRequest|
2437 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2438 )
2439 .unwrap();
2440
2441 let mut encoded_invoice_request = Vec::new();
2442 invoice_request.write(&mut encoded_invoice_request).unwrap();
2443
2444 match InvoiceRequest::try_from(encoded_invoice_request.clone()) {
2445 Ok(invoice_request) => assert_eq!(invoice_request.bytes, encoded_invoice_request),
2446 Err(e) => panic!("error parsing invoice_request: {:?}", e),
2447 }
2448
2449 const UNKNOWN_EVEN_TYPE: u64 = INVOICE_REQUEST_TYPES.end - 2;
2450 assert!(UNKNOWN_EVEN_TYPE % 2 == 0);
2451
2452 let (mut unsigned_invoice_request, payer_keys, _) = OfferBuilder::new(keys.public_key())
2453 .amount_msats(1000)
2454 .build().unwrap()
2455 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2456 .build_without_checks();
2457
2458 let mut unknown_bytes = Vec::new();
2459 BigSize(UNKNOWN_EVEN_TYPE).write(&mut unknown_bytes).unwrap();
2460 BigSize(32).write(&mut unknown_bytes).unwrap();
2461 [42u8; 32].write(&mut unknown_bytes).unwrap();
2462
2463 unsigned_invoice_request.bytes.reserve_exact(
2464 unsigned_invoice_request.bytes.capacity()
2465 - unsigned_invoice_request.bytes.len()
2466 + unknown_bytes.len(),
2467 );
2468 unsigned_invoice_request.bytes.extend_from_slice(&unknown_bytes);
2469 unsigned_invoice_request.tagged_hash =
2470 TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &unsigned_invoice_request.bytes);
2471
2472 let keys = payer_keys.unwrap();
2473 let invoice_request = unsigned_invoice_request
2474 .sign(|message: &UnsignedInvoiceRequest|
2475 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2476 )
2477 .unwrap();
2478
2479 let mut encoded_invoice_request = Vec::new();
2480 invoice_request.write(&mut encoded_invoice_request).unwrap();
2481
2482 match InvoiceRequest::try_from(encoded_invoice_request) {
2483 Ok(_) => panic!("expected error"),
2484 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
2485 }
2486 }
2487
2488 #[test]
2489 fn parses_invoice_request_with_experimental_tlv_records() {
2490 let expanded_key = ExpandedKey::new([42; 32]);
2491 let entropy = FixedEntropy {};
2492 let nonce = Nonce::from_entropy_source(&entropy);
2493 let payment_id = PaymentId([1; 32]);
2494
2495 const UNKNOWN_ODD_TYPE: u64 = EXPERIMENTAL_INVOICE_REQUEST_TYPES.start + 1;
2496 assert!(UNKNOWN_ODD_TYPE % 2 == 1);
2497
2498 let secp_ctx = Secp256k1::new();
2499 let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2500 let (mut unsigned_invoice_request, payer_keys, _) = OfferBuilder::new(keys.public_key())
2501 .amount_msats(1000)
2502 .build().unwrap()
2503 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2504 .build_without_checks();
2505
2506 let mut unknown_bytes = Vec::new();
2507 BigSize(UNKNOWN_ODD_TYPE).write(&mut unknown_bytes).unwrap();
2508 BigSize(32).write(&mut unknown_bytes).unwrap();
2509 [42u8; 32].write(&mut unknown_bytes).unwrap();
2510
2511 unsigned_invoice_request.bytes.reserve_exact(
2512 unsigned_invoice_request.bytes.capacity()
2513 - unsigned_invoice_request.bytes.len()
2514 + unknown_bytes.len(),
2515 );
2516 unsigned_invoice_request.experimental_bytes.extend_from_slice(&unknown_bytes);
2517
2518 let tlv_stream = TlvStream::new(&unsigned_invoice_request.bytes)
2519 .chain(TlvStream::new(&unsigned_invoice_request.experimental_bytes));
2520 unsigned_invoice_request.tagged_hash =
2521 TaggedHash::from_tlv_stream(SIGNATURE_TAG, tlv_stream);
2522
2523 let keys = payer_keys.unwrap();
2524 let invoice_request = unsigned_invoice_request
2525 .sign(|message: &UnsignedInvoiceRequest|
2526 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2527 )
2528 .unwrap();
2529
2530 let mut encoded_invoice_request = Vec::new();
2531 invoice_request.write(&mut encoded_invoice_request).unwrap();
2532
2533 match InvoiceRequest::try_from(encoded_invoice_request.clone()) {
2534 Ok(invoice_request) => assert_eq!(invoice_request.bytes, encoded_invoice_request),
2535 Err(e) => panic!("error parsing invoice_request: {:?}", e),
2536 }
2537
2538 const UNKNOWN_EVEN_TYPE: u64 = EXPERIMENTAL_INVOICE_REQUEST_TYPES.start;
2539 assert!(UNKNOWN_EVEN_TYPE % 2 == 0);
2540
2541 let (mut unsigned_invoice_request, payer_keys, _) = OfferBuilder::new(keys.public_key())
2542 .amount_msats(1000)
2543 .build().unwrap()
2544 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2545 .build_without_checks();
2546
2547 let mut unknown_bytes = Vec::new();
2548 BigSize(UNKNOWN_EVEN_TYPE).write(&mut unknown_bytes).unwrap();
2549 BigSize(32).write(&mut unknown_bytes).unwrap();
2550 [42u8; 32].write(&mut unknown_bytes).unwrap();
2551
2552 unsigned_invoice_request.bytes.reserve_exact(
2553 unsigned_invoice_request.bytes.capacity()
2554 - unsigned_invoice_request.bytes.len()
2555 + unknown_bytes.len(),
2556 );
2557 unsigned_invoice_request.experimental_bytes.extend_from_slice(&unknown_bytes);
2558
2559 let tlv_stream = TlvStream::new(&unsigned_invoice_request.bytes)
2560 .chain(TlvStream::new(&unsigned_invoice_request.experimental_bytes));
2561 unsigned_invoice_request.tagged_hash =
2562 TaggedHash::from_tlv_stream(SIGNATURE_TAG, tlv_stream);
2563
2564 let keys = payer_keys.unwrap();
2565 let invoice_request = unsigned_invoice_request
2566 .sign(|message: &UnsignedInvoiceRequest|
2567 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
2568 )
2569 .unwrap();
2570
2571 let mut encoded_invoice_request = Vec::new();
2572 invoice_request.write(&mut encoded_invoice_request).unwrap();
2573
2574 match InvoiceRequest::try_from(encoded_invoice_request) {
2575 Ok(_) => panic!("expected error"),
2576 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
2577 }
2578
2579 let invoice_request = OfferBuilder::new(keys.public_key())
2580 .amount_msats(1000)
2581 .build().unwrap()
2582 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2583 .build_and_sign().unwrap();
2584
2585 let mut encoded_invoice_request = Vec::new();
2586 invoice_request.write(&mut encoded_invoice_request).unwrap();
2587
2588 BigSize(UNKNOWN_ODD_TYPE).write(&mut encoded_invoice_request).unwrap();
2589 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2590 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2591
2592 match InvoiceRequest::try_from(encoded_invoice_request) {
2593 Ok(_) => panic!("expected error"),
2594 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::IncorrectSignature)),
2595 }
2596 }
2597
2598 #[test]
2599 fn fails_parsing_invoice_request_with_out_of_range_tlv_records() {
2600 let expanded_key = ExpandedKey::new([42; 32]);
2601 let entropy = FixedEntropy {};
2602 let nonce = Nonce::from_entropy_source(&entropy);
2603 let secp_ctx = Secp256k1::new();
2604 let payment_id = PaymentId([1; 32]);
2605
2606 let invoice_request = OfferBuilder::new(recipient_pubkey())
2607 .amount_msats(1000)
2608 .build().unwrap()
2609 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2610 .build_and_sign().unwrap();
2611
2612 let mut encoded_invoice_request = Vec::new();
2613 invoice_request.write(&mut encoded_invoice_request).unwrap();
2614 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
2615 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2616 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2617
2618 match InvoiceRequest::try_from(encoded_invoice_request) {
2619 Ok(_) => panic!("expected error"),
2620 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2621 }
2622
2623 let mut encoded_invoice_request = Vec::new();
2624 invoice_request.write(&mut encoded_invoice_request).unwrap();
2625 BigSize(EXPERIMENTAL_INVOICE_REQUEST_TYPES.end).write(&mut encoded_invoice_request).unwrap();
2626 BigSize(32).write(&mut encoded_invoice_request).unwrap();
2627 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
2628
2629 match InvoiceRequest::try_from(encoded_invoice_request) {
2630 Ok(_) => panic!("expected error"),
2631 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2632 }
2633 }
2634
2635 #[test]
2636 fn copies_verified_invoice_request_fields() {
2637 let node_id = recipient_pubkey();
2638 let expanded_key = ExpandedKey::new([42; 32]);
2639 let entropy = FixedEntropy {};
2640 let nonce = Nonce::from_entropy_source(&entropy);
2641 let secp_ctx = Secp256k1::new();
2642 let payment_id = PaymentId([1; 32]);
2643
2644 #[cfg(c_bindings)]
2645 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
2646 let offer = OfferBuilder::deriving_signing_pubkey(node_id, &expanded_key, nonce, &secp_ctx)
2647 .chain(Network::Testnet)
2648 .amount_msats(1000)
2649 .supported_quantity(Quantity::Unbounded)
2650 .build().unwrap();
2651 assert_eq!(offer.issuer_signing_pubkey(), Some(node_id));
2652
2653 let invoice_request = offer
2654 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2655 .chain(Network::Testnet).unwrap()
2656 .quantity(1).unwrap()
2657 .payer_note("0".repeat(PAYER_NOTE_LIMIT * 2))
2658 .build_and_sign().unwrap();
2659 match invoice_request.verify_using_metadata(&expanded_key, &secp_ctx) {
2660 Ok(invoice_request) => {
2661 let fields = invoice_request.fields();
2662 assert_eq!(invoice_request.offer_id, offer.id());
2663 assert_eq!(
2664 fields,
2665 InvoiceRequestFields {
2666 payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
2667 quantity: Some(1),
2668 payer_note_truncated: Some(UntrustedString("0".repeat(PAYER_NOTE_LIMIT))),
2669 human_readable_name: None,
2670 }
2671 );
2672
2673 let mut buffer = Vec::new();
2674 fields.write(&mut buffer).unwrap();
2675
2676 let deserialized_fields: InvoiceRequestFields =
2677 Readable::read(&mut buffer.as_slice()).unwrap();
2678 assert_eq!(deserialized_fields, fields);
2679 },
2680 Err(_) => panic!("unexpected error"),
2681 }
2682 }
2683}