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 an `Invoice`.
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Refund`]: crate::offers::refund::Refund
22 //! extern crate bitcoin;
23 //! extern crate lightning;
25 //! use bitcoin::network::constants::Network;
26 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
27 //! use core::convert::Infallible;
28 //! use lightning::ln::features::OfferFeatures;
29 //! use lightning::offers::offer::Offer;
30 //! use lightning::util::ser::Writeable;
32 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
33 //! let secp_ctx = Secp256k1::new();
34 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
35 //! let pubkey = PublicKey::from(keys);
36 //! let mut buffer = Vec::new();
39 //! .parse::<Offer>()?
40 //! .request_invoice(vec![42; 64], pubkey)?
41 //! .chain(Network::Testnet)?
42 //! .amount_msats(1000)?
44 //! .payer_note("foo".to_string())
46 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
47 //! .expect("failed verifying signature")
48 //! .write(&mut buffer)
54 use bitcoin::blockdata::constants::ChainHash;
55 use bitcoin::network::constants::Network;
56 use bitcoin::secp256k1::{Message, PublicKey};
57 use bitcoin::secp256k1::schnorr::Signature;
58 use core::convert::TryFrom;
60 use crate::ln::features::InvoiceRequestFeatures;
61 use crate::ln::msgs::DecodeError;
62 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
63 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
64 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
65 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
66 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
67 use crate::util::string::PrintableString;
69 use crate::prelude::*;
71 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
73 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
75 /// See [module-level documentation] for usage.
77 /// [module-level documentation]: self
78 pub struct InvoiceRequestBuilder<'a> {
80 invoice_request: InvoiceRequestContents,
83 impl<'a> InvoiceRequestBuilder<'a> {
84 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
87 invoice_request: InvoiceRequestContents {
88 payer: PayerContents(metadata), offer: offer.contents.clone(), chain: None,
89 amount_msats: None, features: InvoiceRequestFeatures::empty(), quantity: None,
90 payer_id, payer_note: None,
95 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
96 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
99 /// Successive calls to this method will override the previous setting.
100 pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
101 let chain = ChainHash::using_genesis_block(network);
102 if !self.offer.supports_chain(chain) {
103 return Err(SemanticError::UnsupportedChain);
106 self.invoice_request.chain = Some(chain);
110 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
111 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
113 /// Successive calls to this method will override the previous setting.
115 /// [`quantity`]: Self::quantity
116 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
117 self.invoice_request.offer.check_amount_msats_for_quantity(
118 Some(amount_msats), self.invoice_request.quantity
120 self.invoice_request.amount_msats = Some(amount_msats);
124 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
125 /// does not conform to [`Offer::is_valid_quantity`].
127 /// Successive calls to this method will override the previous setting.
128 pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
129 self.invoice_request.offer.check_quantity(Some(quantity))?;
130 self.invoice_request.quantity = Some(quantity);
134 /// Sets the [`InvoiceRequest::payer_note`].
136 /// Successive calls to this method will override the previous setting.
137 pub fn payer_note(mut self, payer_note: String) -> Self {
138 self.invoice_request.payer_note = Some(payer_note);
142 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
143 /// by [`UnsignedInvoiceRequest::sign`].
144 pub fn build(mut self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
145 #[cfg(feature = "std")] {
146 if self.offer.is_expired() {
147 return Err(SemanticError::AlreadyExpired);
151 let chain = self.invoice_request.chain();
152 if !self.offer.supports_chain(chain) {
153 return Err(SemanticError::UnsupportedChain);
156 if chain == self.offer.implied_chain() {
157 self.invoice_request.chain = None;
160 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
161 return Err(SemanticError::MissingAmount);
164 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
165 self.invoice_request.offer.check_amount_msats_for_quantity(
166 self.invoice_request.amount_msats, self.invoice_request.quantity
169 let InvoiceRequestBuilder { offer, invoice_request } = self;
170 Ok(UnsignedInvoiceRequest { offer, invoice_request })
175 impl<'a> InvoiceRequestBuilder<'a> {
176 fn chain_unchecked(mut self, network: Network) -> Self {
177 let chain = ChainHash::using_genesis_block(network);
178 self.invoice_request.chain = Some(chain);
182 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
183 self.invoice_request.amount_msats = Some(amount_msats);
187 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
188 self.invoice_request.features = features;
192 fn quantity_unchecked(mut self, quantity: u64) -> Self {
193 self.invoice_request.quantity = Some(quantity);
197 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
198 let InvoiceRequestBuilder { offer, invoice_request } = self;
199 UnsignedInvoiceRequest { offer, invoice_request }
203 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
204 pub struct UnsignedInvoiceRequest<'a> {
206 invoice_request: InvoiceRequestContents,
209 impl<'a> UnsignedInvoiceRequest<'a> {
210 /// Signs the invoice request using the given function.
211 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
213 F: FnOnce(&Message) -> Result<Signature, E>
215 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
216 // unknown TLV records, which are not stored in `OfferContents`.
217 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
218 self.invoice_request.as_tlv_stream();
219 let offer_bytes = WithoutLength(&self.offer.bytes);
220 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
222 let mut bytes = Vec::new();
223 unsigned_tlv_stream.write(&mut bytes).unwrap();
225 let pubkey = self.invoice_request.payer_id;
226 let signature = Some(merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?);
228 // Append the signature TLV record to the bytes.
229 let signature_tlv_stream = SignatureTlvStreamRef {
230 signature: signature.as_ref(),
232 signature_tlv_stream.write(&mut bytes).unwrap();
236 contents: self.invoice_request,
242 /// An `InvoiceRequest` is a request for an `Invoice` formulated from an [`Offer`].
244 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
245 /// specifies these such that its recipient can send an invoice for payment.
247 /// [`Offer`]: crate::offers::offer::Offer
248 #[derive(Clone, Debug)]
249 pub struct InvoiceRequest {
250 pub(super) bytes: Vec<u8>,
251 contents: InvoiceRequestContents,
252 signature: Option<Signature>,
255 /// The contents of an [`InvoiceRequest`], which may be shared with an `Invoice`.
256 #[derive(Clone, Debug)]
257 pub(super) struct InvoiceRequestContents {
258 payer: PayerContents,
259 offer: OfferContents,
260 chain: Option<ChainHash>,
261 amount_msats: Option<u64>,
262 features: InvoiceRequestFeatures,
263 quantity: Option<u64>,
265 payer_note: Option<String>,
268 impl InvoiceRequest {
269 /// An unpredictable series of bytes, typically containing information about the derivation of
272 /// [`payer_id`]: Self::payer_id
273 pub fn metadata(&self) -> &[u8] {
274 &self.contents.payer.0[..]
277 /// A chain from [`Offer::chains`] that the offer is valid for.
278 pub fn chain(&self) -> ChainHash {
279 self.contents.chain()
282 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
283 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
285 /// [`chain`]: Self::chain
286 pub fn amount_msats(&self) -> Option<u64> {
287 self.contents.amount_msats
290 /// Features pertaining to requesting an invoice.
291 pub fn features(&self) -> &InvoiceRequestFeatures {
292 &self.contents.features
295 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
296 pub fn quantity(&self) -> Option<u64> {
297 self.contents.quantity
300 /// A possibly transient pubkey used to sign the invoice request.
301 pub fn payer_id(&self) -> PublicKey {
302 self.contents.payer_id
305 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
307 pub fn payer_note(&self) -> Option<PrintableString> {
308 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
311 /// Signature of the invoice request using [`payer_id`].
313 /// [`payer_id`]: Self::payer_id
314 pub fn signature(&self) -> Option<Signature> {
319 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
320 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
321 self.contents.as_tlv_stream();
322 let signature_tlv_stream = SignatureTlvStreamRef {
323 signature: self.signature.as_ref(),
325 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
329 impl InvoiceRequestContents {
330 fn chain(&self) -> ChainHash {
331 self.chain.unwrap_or_else(|| self.offer.implied_chain())
334 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
335 let payer = PayerTlvStreamRef {
336 metadata: Some(&self.payer.0),
339 let offer = self.offer.as_tlv_stream();
342 if self.features == InvoiceRequestFeatures::empty() { None }
343 else { Some(&self.features) }
346 let invoice_request = InvoiceRequestTlvStreamRef {
347 chain: self.chain.as_ref(),
348 amount: self.amount_msats,
350 quantity: self.quantity,
351 payer_id: Some(&self.payer_id),
352 payer_note: self.payer_note.as_ref(),
355 (payer, offer, invoice_request)
359 impl Writeable for InvoiceRequest {
360 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
361 WithoutLength(&self.bytes).write(writer)
365 impl Writeable for InvoiceRequestContents {
366 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
367 self.as_tlv_stream().write(writer)
371 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
372 (80, chain: ChainHash),
373 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
374 (84, features: InvoiceRequestFeatures),
375 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
376 (88, payer_id: PublicKey),
377 (89, payer_note: (String, WithoutLength)),
380 type FullInvoiceRequestTlvStream =
381 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
384 type FullInvoiceRequestTlvStreamRef<'a> = (
385 PayerTlvStreamRef<'a>,
386 OfferTlvStreamRef<'a>,
387 InvoiceRequestTlvStreamRef<'a>,
388 SignatureTlvStreamRef<'a>,
391 impl SeekReadable for FullInvoiceRequestTlvStream {
392 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
393 let payer = SeekReadable::read(r)?;
394 let offer = SeekReadable::read(r)?;
395 let invoice_request = SeekReadable::read(r)?;
396 let signature = SeekReadable::read(r)?;
398 Ok((payer, offer, invoice_request, signature))
402 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
404 type PartialInvoiceRequestTlvStreamRef<'a> = (
405 PayerTlvStreamRef<'a>,
406 OfferTlvStreamRef<'a>,
407 InvoiceRequestTlvStreamRef<'a>,
410 impl TryFrom<Vec<u8>> for InvoiceRequest {
411 type Error = ParseError;
413 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
414 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
415 let ParsedMessage { bytes, tlv_stream } = invoice_request;
417 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
418 SignatureTlvStream { signature },
420 let contents = InvoiceRequestContents::try_from(
421 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
424 if let Some(signature) = &signature {
425 merkle::verify_signature(signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
428 Ok(InvoiceRequest { bytes, contents, signature })
432 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
433 type Error = SemanticError;
435 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
437 PayerTlvStream { metadata },
439 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
442 let payer = match metadata {
443 None => return Err(SemanticError::MissingPayerMetadata),
444 Some(metadata) => PayerContents(metadata),
446 let offer = OfferContents::try_from(offer_tlv_stream)?;
448 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
449 return Err(SemanticError::UnsupportedChain);
452 if offer.amount().is_none() && amount.is_none() {
453 return Err(SemanticError::MissingAmount);
456 offer.check_quantity(quantity)?;
457 offer.check_amount_msats_for_quantity(amount, quantity)?;
459 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
461 let payer_id = match payer_id {
462 None => return Err(SemanticError::MissingPayerId),
463 Some(payer_id) => payer_id,
466 Ok(InvoiceRequestContents {
467 payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
474 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef};
476 use bitcoin::blockdata::constants::ChainHash;
477 use bitcoin::network::constants::Network;
478 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
479 use bitcoin::secp256k1::schnorr::Signature;
480 use core::convert::{Infallible, TryFrom};
481 use core::num::NonZeroU64;
482 #[cfg(feature = "std")]
483 use core::time::Duration;
484 use crate::ln::features::InvoiceRequestFeatures;
485 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
486 use crate::offers::merkle::{SignError, SignatureTlvStreamRef};
487 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
488 use crate::offers::parse::{ParseError, SemanticError};
489 use crate::offers::payer::PayerTlvStreamRef;
490 use crate::util::ser::{BigSize, Writeable};
491 use crate::util::string::PrintableString;
493 fn payer_keys() -> KeyPair {
494 let secp_ctx = Secp256k1::new();
495 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
498 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
499 let secp_ctx = Secp256k1::new();
500 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
501 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
504 fn payer_pubkey() -> PublicKey {
505 payer_keys().public_key()
508 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
509 let secp_ctx = Secp256k1::new();
510 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
511 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
514 fn recipient_pubkey() -> PublicKey {
515 let secp_ctx = Secp256k1::new();
516 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
520 fn builds_invoice_request_with_defaults() {
521 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
524 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
526 .sign(payer_sign).unwrap();
528 let mut buffer = Vec::new();
529 invoice_request.write(&mut buffer).unwrap();
531 assert_eq!(invoice_request.bytes, buffer.as_slice());
532 assert_eq!(invoice_request.metadata(), &[1; 32]);
533 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
534 assert_eq!(invoice_request.amount_msats(), None);
535 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
536 assert_eq!(invoice_request.quantity(), None);
537 assert_eq!(invoice_request.payer_id(), payer_pubkey());
538 assert_eq!(invoice_request.payer_note(), None);
539 assert!(invoice_request.signature().is_some());
542 invoice_request.as_tlv_stream(),
544 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
550 description: Some(&String::from("foo")),
552 absolute_expiry: None,
556 node_id: Some(&recipient_pubkey()),
558 InvoiceRequestTlvStreamRef {
563 payer_id: Some(&payer_pubkey()),
566 SignatureTlvStreamRef { signature: invoice_request.signature().as_ref() },
570 if let Err(e) = InvoiceRequest::try_from(buffer) {
571 panic!("error parsing invoice request: {:?}", e);
575 #[cfg(feature = "std")]
577 fn builds_invoice_request_from_offer_with_expiration() {
578 let future_expiry = Duration::from_secs(u64::max_value());
579 let past_expiry = Duration::from_secs(0);
581 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
583 .absolute_expiry(future_expiry)
585 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
588 panic!("error building invoice_request: {:?}", e);
591 match OfferBuilder::new("foo".into(), recipient_pubkey())
593 .absolute_expiry(past_expiry)
595 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
598 Ok(_) => panic!("expected error"),
599 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
604 fn builds_invoice_request_with_chain() {
605 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
606 let testnet = ChainHash::using_genesis_block(Network::Testnet);
608 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
611 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
612 .chain(Network::Bitcoin).unwrap()
614 .sign(payer_sign).unwrap();
615 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
616 assert_eq!(invoice_request.chain(), mainnet);
617 assert_eq!(tlv_stream.chain, None);
619 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
621 .chain(Network::Testnet)
623 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
624 .chain(Network::Testnet).unwrap()
626 .sign(payer_sign).unwrap();
627 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
628 assert_eq!(invoice_request.chain(), testnet);
629 assert_eq!(tlv_stream.chain, Some(&testnet));
631 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
633 .chain(Network::Bitcoin)
634 .chain(Network::Testnet)
636 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
637 .chain(Network::Bitcoin).unwrap()
639 .sign(payer_sign).unwrap();
640 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
641 assert_eq!(invoice_request.chain(), mainnet);
642 assert_eq!(tlv_stream.chain, None);
644 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
646 .chain(Network::Bitcoin)
647 .chain(Network::Testnet)
649 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
650 .chain(Network::Bitcoin).unwrap()
651 .chain(Network::Testnet).unwrap()
653 .sign(payer_sign).unwrap();
654 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
655 assert_eq!(invoice_request.chain(), testnet);
656 assert_eq!(tlv_stream.chain, Some(&testnet));
658 match OfferBuilder::new("foo".into(), recipient_pubkey())
660 .chain(Network::Testnet)
662 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
663 .chain(Network::Bitcoin)
665 Ok(_) => panic!("expected error"),
666 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
669 match OfferBuilder::new("foo".into(), recipient_pubkey())
671 .chain(Network::Testnet)
673 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
676 Ok(_) => panic!("expected error"),
677 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
682 fn builds_invoice_request_with_amount() {
683 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
686 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
687 .amount_msats(1000).unwrap()
689 .sign(payer_sign).unwrap();
690 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
691 assert_eq!(invoice_request.amount_msats(), Some(1000));
692 assert_eq!(tlv_stream.amount, Some(1000));
694 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
697 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
698 .amount_msats(1001).unwrap()
699 .amount_msats(1000).unwrap()
701 .sign(payer_sign).unwrap();
702 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
703 assert_eq!(invoice_request.amount_msats(), Some(1000));
704 assert_eq!(tlv_stream.amount, Some(1000));
706 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
709 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
710 .amount_msats(1001).unwrap()
712 .sign(payer_sign).unwrap();
713 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
714 assert_eq!(invoice_request.amount_msats(), Some(1001));
715 assert_eq!(tlv_stream.amount, Some(1001));
717 match OfferBuilder::new("foo".into(), recipient_pubkey())
720 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
723 Ok(_) => panic!("expected error"),
724 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
727 match OfferBuilder::new("foo".into(), recipient_pubkey())
729 .supported_quantity(Quantity::Unbounded)
731 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
732 .quantity(2).unwrap()
735 Ok(_) => panic!("expected error"),
736 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
739 match OfferBuilder::new("foo".into(), recipient_pubkey())
742 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
743 .amount_msats(MAX_VALUE_MSAT + 1)
745 Ok(_) => panic!("expected error"),
746 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
749 match OfferBuilder::new("foo".into(), recipient_pubkey())
751 .supported_quantity(Quantity::Unbounded)
753 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
754 .amount_msats(1000).unwrap()
755 .quantity(2).unwrap()
758 Ok(_) => panic!("expected error"),
759 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
762 match OfferBuilder::new("foo".into(), recipient_pubkey())
764 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
767 Ok(_) => panic!("expected error"),
768 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
773 fn builds_invoice_request_with_features() {
774 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
777 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
778 .features_unchecked(InvoiceRequestFeatures::unknown())
780 .sign(payer_sign).unwrap();
781 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
782 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
783 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
785 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
788 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
789 .features_unchecked(InvoiceRequestFeatures::unknown())
790 .features_unchecked(InvoiceRequestFeatures::empty())
792 .sign(payer_sign).unwrap();
793 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
794 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
795 assert_eq!(tlv_stream.features, None);
799 fn builds_invoice_request_with_quantity() {
800 let ten = NonZeroU64::new(10).unwrap();
802 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
804 .supported_quantity(Quantity::one())
806 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
808 .sign(payer_sign).unwrap();
809 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
810 assert_eq!(invoice_request.quantity(), None);
811 assert_eq!(tlv_stream.quantity, None);
813 match OfferBuilder::new("foo".into(), recipient_pubkey())
815 .supported_quantity(Quantity::one())
817 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
818 .amount_msats(2_000).unwrap()
821 Ok(_) => panic!("expected error"),
822 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
825 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
827 .supported_quantity(Quantity::Bounded(ten))
829 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
830 .amount_msats(10_000).unwrap()
831 .quantity(10).unwrap()
833 .sign(payer_sign).unwrap();
834 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
835 assert_eq!(invoice_request.amount_msats(), Some(10_000));
836 assert_eq!(tlv_stream.amount, Some(10_000));
838 match OfferBuilder::new("foo".into(), recipient_pubkey())
840 .supported_quantity(Quantity::Bounded(ten))
842 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
843 .amount_msats(11_000).unwrap()
846 Ok(_) => panic!("expected error"),
847 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
850 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
852 .supported_quantity(Quantity::Unbounded)
854 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
855 .amount_msats(2_000).unwrap()
856 .quantity(2).unwrap()
858 .sign(payer_sign).unwrap();
859 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
860 assert_eq!(invoice_request.amount_msats(), Some(2_000));
861 assert_eq!(tlv_stream.amount, Some(2_000));
863 match OfferBuilder::new("foo".into(), recipient_pubkey())
865 .supported_quantity(Quantity::Unbounded)
867 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
870 Ok(_) => panic!("expected error"),
871 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
876 fn builds_invoice_request_with_payer_note() {
877 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
880 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
881 .payer_note("bar".into())
883 .sign(payer_sign).unwrap();
884 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
885 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
886 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
888 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
891 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
892 .payer_note("bar".into())
893 .payer_note("baz".into())
895 .sign(payer_sign).unwrap();
896 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
897 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
898 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
902 fn fails_signing_invoice_request() {
903 match OfferBuilder::new("foo".into(), recipient_pubkey())
906 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
910 Ok(_) => panic!("expected error"),
911 Err(e) => assert_eq!(e, SignError::Signing(())),
914 match OfferBuilder::new("foo".into(), recipient_pubkey())
917 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
919 .sign(recipient_sign)
921 Ok(_) => panic!("expected error"),
922 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
927 fn parses_invoice_request_with_metadata() {
928 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
931 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
933 .sign(payer_sign).unwrap();
935 let mut buffer = Vec::new();
936 invoice_request.write(&mut buffer).unwrap();
938 if let Err(e) = InvoiceRequest::try_from(buffer) {
939 panic!("error parsing invoice_request: {:?}", e);
944 fn parses_invoice_request_with_chain() {
945 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
948 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
949 .chain(Network::Bitcoin).unwrap()
951 .sign(payer_sign).unwrap();
953 let mut buffer = Vec::new();
954 invoice_request.write(&mut buffer).unwrap();
956 if let Err(e) = InvoiceRequest::try_from(buffer) {
957 panic!("error parsing invoice_request: {:?}", e);
960 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
963 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
964 .chain_unchecked(Network::Testnet)
966 .sign(payer_sign).unwrap();
968 let mut buffer = Vec::new();
969 invoice_request.write(&mut buffer).unwrap();
971 match InvoiceRequest::try_from(buffer) {
972 Ok(_) => panic!("expected error"),
973 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
978 fn parses_invoice_request_with_amount() {
979 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
982 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
984 .sign(payer_sign).unwrap();
986 let mut buffer = Vec::new();
987 invoice_request.write(&mut buffer).unwrap();
989 if let Err(e) = InvoiceRequest::try_from(buffer) {
990 panic!("error parsing invoice_request: {:?}", e);
993 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
995 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
996 .amount_msats(1000).unwrap()
998 .sign(payer_sign).unwrap();
1000 let mut buffer = Vec::new();
1001 invoice_request.write(&mut buffer).unwrap();
1003 if let Err(e) = InvoiceRequest::try_from(buffer) {
1004 panic!("error parsing invoice_request: {:?}", e);
1007 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1009 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1011 .sign(payer_sign).unwrap();
1013 let mut buffer = Vec::new();
1014 invoice_request.write(&mut buffer).unwrap();
1016 match InvoiceRequest::try_from(buffer) {
1017 Ok(_) => panic!("expected error"),
1018 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1021 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1024 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1025 .amount_msats_unchecked(999)
1027 .sign(payer_sign).unwrap();
1029 let mut buffer = Vec::new();
1030 invoice_request.write(&mut buffer).unwrap();
1032 match InvoiceRequest::try_from(buffer) {
1033 Ok(_) => panic!("expected error"),
1034 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1037 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1038 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1040 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1042 .sign(payer_sign).unwrap();
1044 let mut buffer = Vec::new();
1045 invoice_request.write(&mut buffer).unwrap();
1047 match InvoiceRequest::try_from(buffer) {
1048 Ok(_) => panic!("expected error"),
1050 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1056 fn parses_invoice_request_with_quantity() {
1057 let ten = NonZeroU64::new(10).unwrap();
1059 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1061 .supported_quantity(Quantity::one())
1063 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1065 .sign(payer_sign).unwrap();
1067 let mut buffer = Vec::new();
1068 invoice_request.write(&mut buffer).unwrap();
1070 if let Err(e) = InvoiceRequest::try_from(buffer) {
1071 panic!("error parsing invoice_request: {:?}", e);
1074 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1076 .supported_quantity(Quantity::one())
1078 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1079 .amount_msats(2_000).unwrap()
1080 .quantity_unchecked(2)
1082 .sign(payer_sign).unwrap();
1084 let mut buffer = Vec::new();
1085 invoice_request.write(&mut buffer).unwrap();
1087 match InvoiceRequest::try_from(buffer) {
1088 Ok(_) => panic!("expected error"),
1090 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1094 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1096 .supported_quantity(Quantity::Bounded(ten))
1098 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1099 .amount_msats(10_000).unwrap()
1100 .quantity(10).unwrap()
1102 .sign(payer_sign).unwrap();
1104 let mut buffer = Vec::new();
1105 invoice_request.write(&mut buffer).unwrap();
1107 if let Err(e) = InvoiceRequest::try_from(buffer) {
1108 panic!("error parsing invoice_request: {:?}", e);
1111 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1113 .supported_quantity(Quantity::Bounded(ten))
1115 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1116 .amount_msats(11_000).unwrap()
1117 .quantity_unchecked(11)
1119 .sign(payer_sign).unwrap();
1121 let mut buffer = Vec::new();
1122 invoice_request.write(&mut buffer).unwrap();
1124 match InvoiceRequest::try_from(buffer) {
1125 Ok(_) => panic!("expected error"),
1126 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1129 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1131 .supported_quantity(Quantity::Unbounded)
1133 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1134 .amount_msats(2_000).unwrap()
1135 .quantity(2).unwrap()
1137 .sign(payer_sign).unwrap();
1139 let mut buffer = Vec::new();
1140 invoice_request.write(&mut buffer).unwrap();
1142 if let Err(e) = InvoiceRequest::try_from(buffer) {
1143 panic!("error parsing invoice_request: {:?}", e);
1146 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1148 .supported_quantity(Quantity::Unbounded)
1150 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1152 .sign(payer_sign).unwrap();
1154 let mut buffer = Vec::new();
1155 invoice_request.write(&mut buffer).unwrap();
1157 match InvoiceRequest::try_from(buffer) {
1158 Ok(_) => panic!("expected error"),
1159 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1164 fn fails_parsing_invoice_request_without_metadata() {
1165 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1168 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1170 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1171 tlv_stream.0.metadata = None;
1173 let mut buffer = Vec::new();
1174 tlv_stream.write(&mut buffer).unwrap();
1176 match InvoiceRequest::try_from(buffer) {
1177 Ok(_) => panic!("expected error"),
1179 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1185 fn fails_parsing_invoice_request_without_payer_id() {
1186 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1189 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1191 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1192 tlv_stream.2.payer_id = None;
1194 let mut buffer = Vec::new();
1195 tlv_stream.write(&mut buffer).unwrap();
1197 match InvoiceRequest::try_from(buffer) {
1198 Ok(_) => panic!("expected error"),
1199 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1204 fn fails_parsing_invoice_request_without_node_id() {
1205 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1208 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1210 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1211 tlv_stream.1.node_id = None;
1213 let mut buffer = Vec::new();
1214 tlv_stream.write(&mut buffer).unwrap();
1216 match InvoiceRequest::try_from(buffer) {
1217 Ok(_) => panic!("expected error"),
1219 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1225 fn parses_invoice_request_without_signature() {
1226 let mut buffer = Vec::new();
1227 OfferBuilder::new("foo".into(), recipient_pubkey())
1230 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1233 .write(&mut buffer).unwrap();
1235 if let Err(e) = InvoiceRequest::try_from(buffer) {
1236 panic!("error parsing invoice_request: {:?}", e);
1241 fn fails_parsing_invoice_request_with_invalid_signature() {
1242 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1245 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1247 .sign(payer_sign).unwrap();
1248 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1249 *last_signature_byte = last_signature_byte.wrapping_add(1);
1251 let mut buffer = Vec::new();
1252 invoice_request.write(&mut buffer).unwrap();
1254 match InvoiceRequest::try_from(buffer) {
1255 Ok(_) => panic!("expected error"),
1257 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1263 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1264 let secp_ctx = Secp256k1::new();
1265 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1266 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1269 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1271 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1274 let mut encoded_invoice_request = Vec::new();
1275 invoice_request.write(&mut encoded_invoice_request).unwrap();
1276 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1277 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1278 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1280 match InvoiceRequest::try_from(encoded_invoice_request) {
1281 Ok(_) => panic!("expected error"),
1282 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),