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 //! [`Invoice`]: crate::offers::invoice::Invoice
20 //! [`Refund`]: crate::offers::refund::Refund
23 //! extern crate bitcoin;
24 //! extern crate lightning;
26 //! use bitcoin::network::constants::Network;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use core::convert::Infallible;
29 //! use lightning::ln::features::OfferFeatures;
30 //! use lightning::offers::offer::Offer;
31 //! use lightning::util::ser::Writeable;
33 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
34 //! let secp_ctx = Secp256k1::new();
35 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
36 //! let pubkey = PublicKey::from(keys);
37 //! let mut buffer = Vec::new();
40 //! .parse::<Offer>()?
41 //! .request_invoice(vec![42; 64], pubkey)?
42 //! .chain(Network::Testnet)?
43 //! .amount_msats(1000)?
45 //! .payer_note("foo".to_string())
47 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
48 //! .expect("failed verifying signature")
49 //! .write(&mut buffer)
55 use bitcoin::blockdata::constants::ChainHash;
56 use bitcoin::network::constants::Network;
57 use bitcoin::secp256k1::{Message, PublicKey};
58 use bitcoin::secp256k1::schnorr::Signature;
59 use core::convert::TryFrom;
61 use crate::ln::PaymentHash;
62 use crate::ln::features::InvoiceRequestFeatures;
63 use crate::ln::msgs::DecodeError;
64 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
65 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
66 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
67 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
68 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
69 use crate::onion_message::BlindedPath;
70 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
71 use crate::util::string::PrintableString;
73 use crate::prelude::*;
75 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
77 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
79 /// See [module-level documentation] for usage.
81 /// [module-level documentation]: self
82 pub struct InvoiceRequestBuilder<'a> {
84 invoice_request: InvoiceRequestContents,
87 impl<'a> InvoiceRequestBuilder<'a> {
88 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
91 invoice_request: InvoiceRequestContents {
92 payer: PayerContents(metadata), offer: offer.contents.clone(), chain: None,
93 amount_msats: None, features: InvoiceRequestFeatures::empty(), quantity: None,
94 payer_id, payer_note: None,
99 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
100 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
103 /// Successive calls to this method will override the previous setting.
104 pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
105 let chain = ChainHash::using_genesis_block(network);
106 if !self.offer.supports_chain(chain) {
107 return Err(SemanticError::UnsupportedChain);
110 self.invoice_request.chain = Some(chain);
114 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
115 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
117 /// Successive calls to this method will override the previous setting.
119 /// [`quantity`]: Self::quantity
120 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
121 self.invoice_request.offer.check_amount_msats_for_quantity(
122 Some(amount_msats), self.invoice_request.quantity
124 self.invoice_request.amount_msats = Some(amount_msats);
128 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
129 /// does not conform to [`Offer::is_valid_quantity`].
131 /// Successive calls to this method will override the previous setting.
132 pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
133 self.invoice_request.offer.check_quantity(Some(quantity))?;
134 self.invoice_request.quantity = Some(quantity);
138 /// Sets the [`InvoiceRequest::payer_note`].
140 /// Successive calls to this method will override the previous setting.
141 pub fn payer_note(mut self, payer_note: String) -> Self {
142 self.invoice_request.payer_note = Some(payer_note);
146 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
147 /// by [`UnsignedInvoiceRequest::sign`].
148 pub fn build(mut self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
149 #[cfg(feature = "std")] {
150 if self.offer.is_expired() {
151 return Err(SemanticError::AlreadyExpired);
155 let chain = self.invoice_request.chain();
156 if !self.offer.supports_chain(chain) {
157 return Err(SemanticError::UnsupportedChain);
160 if chain == self.offer.implied_chain() {
161 self.invoice_request.chain = None;
164 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
165 return Err(SemanticError::MissingAmount);
168 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
169 self.invoice_request.offer.check_amount_msats_for_quantity(
170 self.invoice_request.amount_msats, self.invoice_request.quantity
173 let InvoiceRequestBuilder { offer, invoice_request } = self;
174 Ok(UnsignedInvoiceRequest { offer, invoice_request })
179 impl<'a> InvoiceRequestBuilder<'a> {
180 fn chain_unchecked(mut self, network: Network) -> Self {
181 let chain = ChainHash::using_genesis_block(network);
182 self.invoice_request.chain = Some(chain);
186 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
187 self.invoice_request.amount_msats = Some(amount_msats);
191 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
192 self.invoice_request.features = features;
196 fn quantity_unchecked(mut self, quantity: u64) -> Self {
197 self.invoice_request.quantity = Some(quantity);
201 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
202 let InvoiceRequestBuilder { offer, invoice_request } = self;
203 UnsignedInvoiceRequest { offer, invoice_request }
207 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
208 pub struct UnsignedInvoiceRequest<'a> {
210 invoice_request: InvoiceRequestContents,
213 impl<'a> UnsignedInvoiceRequest<'a> {
214 /// Signs the invoice request using the given function.
215 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
217 F: FnOnce(&Message) -> Result<Signature, E>
219 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
220 // unknown TLV records, which are not stored in `OfferContents`.
221 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
222 self.invoice_request.as_tlv_stream();
223 let offer_bytes = WithoutLength(&self.offer.bytes);
224 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
226 let mut bytes = Vec::new();
227 unsigned_tlv_stream.write(&mut bytes).unwrap();
229 let pubkey = self.invoice_request.payer_id;
230 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
232 // Append the signature TLV record to the bytes.
233 let signature_tlv_stream = SignatureTlvStreamRef {
234 signature: Some(&signature),
236 signature_tlv_stream.write(&mut bytes).unwrap();
240 contents: self.invoice_request,
246 /// An `InvoiceRequest` is a request for an [`Invoice`] formulated from an [`Offer`].
248 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
249 /// specifies these such that its recipient can send an invoice for payment.
251 /// [`Invoice`]: crate::offers::invoice::Invoice
252 /// [`Offer`]: crate::offers::offer::Offer
253 #[derive(Clone, Debug)]
254 pub struct InvoiceRequest {
255 pub(super) bytes: Vec<u8>,
256 pub(super) contents: InvoiceRequestContents,
257 signature: Signature,
260 /// The contents of an [`InvoiceRequest`], which may be shared with an [`Invoice`].
262 /// [`Invoice`]: crate::offers::invoice::Invoice
263 #[derive(Clone, Debug)]
264 pub(super) struct InvoiceRequestContents {
265 payer: PayerContents,
266 pub(super) offer: OfferContents,
267 chain: Option<ChainHash>,
268 amount_msats: Option<u64>,
269 features: InvoiceRequestFeatures,
270 quantity: Option<u64>,
272 payer_note: Option<String>,
275 impl InvoiceRequest {
276 /// An unpredictable series of bytes, typically containing information about the derivation of
279 /// [`payer_id`]: Self::payer_id
280 pub fn metadata(&self) -> &[u8] {
281 &self.contents.payer.0[..]
284 /// A chain from [`Offer::chains`] that the offer is valid for.
285 pub fn chain(&self) -> ChainHash {
286 self.contents.chain()
289 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
290 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
292 /// [`chain`]: Self::chain
293 pub fn amount_msats(&self) -> Option<u64> {
294 self.contents.amount_msats
297 /// Features pertaining to requesting an invoice.
298 pub fn features(&self) -> &InvoiceRequestFeatures {
299 &self.contents.features
302 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
303 pub fn quantity(&self) -> Option<u64> {
304 self.contents.quantity
307 /// A possibly transient pubkey used to sign the invoice request.
308 pub fn payer_id(&self) -> PublicKey {
309 self.contents.payer_id
312 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
314 pub fn payer_note(&self) -> Option<PrintableString> {
315 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
318 /// Signature of the invoice request using [`payer_id`].
320 /// [`payer_id`]: Self::payer_id
321 pub fn signature(&self) -> Signature {
325 /// Creates an [`Invoice`] for the request with the given required fields.
327 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
328 /// calling this method in `std` builds. For `no-std` builds, a final [`Duration`] parameter
329 /// must be given, which is used to set [`Invoice::created_at`] since [`std::time::SystemTime`]
330 /// is not available.
332 /// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
335 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
336 /// must contain one or more elements.
338 /// Errors if the request contains unknown required features.
340 /// [`Duration`]: core::time::Duration
341 /// [`Invoice`]: crate::offers::invoice::Invoice
342 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
344 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
345 #[cfg(not(feature = "std"))]
346 created_at: core::time::Duration
347 ) -> Result<InvoiceBuilder, SemanticError> {
348 if self.features().requires_unknown_bits() {
349 return Err(SemanticError::UnknownRequiredFeatures);
352 #[cfg(feature = "std")]
353 let created_at = std::time::SystemTime::now()
354 .duration_since(std::time::SystemTime::UNIX_EPOCH)
355 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
357 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
361 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
362 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
363 self.contents.as_tlv_stream();
364 let signature_tlv_stream = SignatureTlvStreamRef {
365 signature: Some(&self.signature),
367 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
371 impl InvoiceRequestContents {
372 pub(super) fn chain(&self) -> ChainHash {
373 self.chain.unwrap_or_else(|| self.offer.implied_chain())
376 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
377 let payer = PayerTlvStreamRef {
378 metadata: Some(&self.payer.0),
381 let offer = self.offer.as_tlv_stream();
384 if self.features == InvoiceRequestFeatures::empty() { None }
385 else { Some(&self.features) }
388 let invoice_request = InvoiceRequestTlvStreamRef {
389 chain: self.chain.as_ref(),
390 amount: self.amount_msats,
392 quantity: self.quantity,
393 payer_id: Some(&self.payer_id),
394 payer_note: self.payer_note.as_ref(),
397 (payer, offer, invoice_request)
401 impl Writeable for InvoiceRequest {
402 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
403 WithoutLength(&self.bytes).write(writer)
407 impl Writeable for InvoiceRequestContents {
408 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
409 self.as_tlv_stream().write(writer)
413 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
414 (80, chain: ChainHash),
415 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
416 (84, features: (InvoiceRequestFeatures, WithoutLength)),
417 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
418 (88, payer_id: PublicKey),
419 (89, payer_note: (String, WithoutLength)),
422 type FullInvoiceRequestTlvStream =
423 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
426 type FullInvoiceRequestTlvStreamRef<'a> = (
427 PayerTlvStreamRef<'a>,
428 OfferTlvStreamRef<'a>,
429 InvoiceRequestTlvStreamRef<'a>,
430 SignatureTlvStreamRef<'a>,
433 impl SeekReadable for FullInvoiceRequestTlvStream {
434 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
435 let payer = SeekReadable::read(r)?;
436 let offer = SeekReadable::read(r)?;
437 let invoice_request = SeekReadable::read(r)?;
438 let signature = SeekReadable::read(r)?;
440 Ok((payer, offer, invoice_request, signature))
444 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
446 type PartialInvoiceRequestTlvStreamRef<'a> = (
447 PayerTlvStreamRef<'a>,
448 OfferTlvStreamRef<'a>,
449 InvoiceRequestTlvStreamRef<'a>,
452 impl TryFrom<Vec<u8>> for InvoiceRequest {
453 type Error = ParseError;
455 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
456 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
457 let ParsedMessage { bytes, tlv_stream } = invoice_request;
459 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
460 SignatureTlvStream { signature },
462 let contents = InvoiceRequestContents::try_from(
463 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
466 let signature = match signature {
467 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
468 Some(signature) => signature,
470 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
472 Ok(InvoiceRequest { bytes, contents, signature })
476 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
477 type Error = SemanticError;
479 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
481 PayerTlvStream { metadata },
483 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
486 let payer = match metadata {
487 None => return Err(SemanticError::MissingPayerMetadata),
488 Some(metadata) => PayerContents(metadata),
490 let offer = OfferContents::try_from(offer_tlv_stream)?;
492 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
493 return Err(SemanticError::UnsupportedChain);
496 if offer.amount().is_none() && amount.is_none() {
497 return Err(SemanticError::MissingAmount);
500 offer.check_quantity(quantity)?;
501 offer.check_amount_msats_for_quantity(amount, quantity)?;
503 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
505 let payer_id = match payer_id {
506 None => return Err(SemanticError::MissingPayerId),
507 Some(payer_id) => payer_id,
510 Ok(InvoiceRequestContents {
511 payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
518 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
520 use bitcoin::blockdata::constants::ChainHash;
521 use bitcoin::network::constants::Network;
522 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
523 use bitcoin::secp256k1::schnorr::Signature;
524 use core::convert::{Infallible, TryFrom};
525 use core::num::NonZeroU64;
526 #[cfg(feature = "std")]
527 use core::time::Duration;
528 use crate::ln::features::InvoiceRequestFeatures;
529 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
530 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
531 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
532 use crate::offers::parse::{ParseError, SemanticError};
533 use crate::offers::payer::PayerTlvStreamRef;
534 use crate::util::ser::{BigSize, Writeable};
535 use crate::util::string::PrintableString;
537 fn payer_keys() -> KeyPair {
538 let secp_ctx = Secp256k1::new();
539 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
542 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
543 let secp_ctx = Secp256k1::new();
544 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
545 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
548 fn payer_pubkey() -> PublicKey {
549 payer_keys().public_key()
552 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
553 let secp_ctx = Secp256k1::new();
554 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
555 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
558 fn recipient_pubkey() -> PublicKey {
559 let secp_ctx = Secp256k1::new();
560 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
564 fn builds_invoice_request_with_defaults() {
565 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
568 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
570 .sign(payer_sign).unwrap();
572 let mut buffer = Vec::new();
573 invoice_request.write(&mut buffer).unwrap();
575 assert_eq!(invoice_request.bytes, buffer.as_slice());
576 assert_eq!(invoice_request.metadata(), &[1; 32]);
577 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
578 assert_eq!(invoice_request.amount_msats(), None);
579 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
580 assert_eq!(invoice_request.quantity(), None);
581 assert_eq!(invoice_request.payer_id(), payer_pubkey());
582 assert_eq!(invoice_request.payer_note(), None);
584 merkle::verify_signature(
585 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
590 invoice_request.as_tlv_stream(),
592 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
598 description: Some(&String::from("foo")),
600 absolute_expiry: None,
604 node_id: Some(&recipient_pubkey()),
606 InvoiceRequestTlvStreamRef {
611 payer_id: Some(&payer_pubkey()),
614 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
618 if let Err(e) = InvoiceRequest::try_from(buffer) {
619 panic!("error parsing invoice request: {:?}", e);
623 #[cfg(feature = "std")]
625 fn builds_invoice_request_from_offer_with_expiration() {
626 let future_expiry = Duration::from_secs(u64::max_value());
627 let past_expiry = Duration::from_secs(0);
629 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
631 .absolute_expiry(future_expiry)
633 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
636 panic!("error building invoice_request: {:?}", e);
639 match OfferBuilder::new("foo".into(), recipient_pubkey())
641 .absolute_expiry(past_expiry)
643 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
646 Ok(_) => panic!("expected error"),
647 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
652 fn builds_invoice_request_with_chain() {
653 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
654 let testnet = ChainHash::using_genesis_block(Network::Testnet);
656 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
659 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
660 .chain(Network::Bitcoin).unwrap()
662 .sign(payer_sign).unwrap();
663 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
664 assert_eq!(invoice_request.chain(), mainnet);
665 assert_eq!(tlv_stream.chain, None);
667 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
669 .chain(Network::Testnet)
671 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
672 .chain(Network::Testnet).unwrap()
674 .sign(payer_sign).unwrap();
675 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
676 assert_eq!(invoice_request.chain(), testnet);
677 assert_eq!(tlv_stream.chain, Some(&testnet));
679 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
681 .chain(Network::Bitcoin)
682 .chain(Network::Testnet)
684 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
685 .chain(Network::Bitcoin).unwrap()
687 .sign(payer_sign).unwrap();
688 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
689 assert_eq!(invoice_request.chain(), mainnet);
690 assert_eq!(tlv_stream.chain, None);
692 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
694 .chain(Network::Bitcoin)
695 .chain(Network::Testnet)
697 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
698 .chain(Network::Bitcoin).unwrap()
699 .chain(Network::Testnet).unwrap()
701 .sign(payer_sign).unwrap();
702 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
703 assert_eq!(invoice_request.chain(), testnet);
704 assert_eq!(tlv_stream.chain, Some(&testnet));
706 match OfferBuilder::new("foo".into(), recipient_pubkey())
708 .chain(Network::Testnet)
710 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
711 .chain(Network::Bitcoin)
713 Ok(_) => panic!("expected error"),
714 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
717 match OfferBuilder::new("foo".into(), recipient_pubkey())
719 .chain(Network::Testnet)
721 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
724 Ok(_) => panic!("expected error"),
725 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
730 fn builds_invoice_request_with_amount() {
731 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
734 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
735 .amount_msats(1000).unwrap()
737 .sign(payer_sign).unwrap();
738 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
739 assert_eq!(invoice_request.amount_msats(), Some(1000));
740 assert_eq!(tlv_stream.amount, Some(1000));
742 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
745 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
746 .amount_msats(1001).unwrap()
747 .amount_msats(1000).unwrap()
749 .sign(payer_sign).unwrap();
750 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
751 assert_eq!(invoice_request.amount_msats(), Some(1000));
752 assert_eq!(tlv_stream.amount, Some(1000));
754 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
757 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
758 .amount_msats(1001).unwrap()
760 .sign(payer_sign).unwrap();
761 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
762 assert_eq!(invoice_request.amount_msats(), Some(1001));
763 assert_eq!(tlv_stream.amount, Some(1001));
765 match OfferBuilder::new("foo".into(), recipient_pubkey())
768 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
771 Ok(_) => panic!("expected error"),
772 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
775 match OfferBuilder::new("foo".into(), recipient_pubkey())
777 .supported_quantity(Quantity::Unbounded)
779 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
780 .quantity(2).unwrap()
783 Ok(_) => panic!("expected error"),
784 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
787 match OfferBuilder::new("foo".into(), recipient_pubkey())
790 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
791 .amount_msats(MAX_VALUE_MSAT + 1)
793 Ok(_) => panic!("expected error"),
794 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
797 match OfferBuilder::new("foo".into(), recipient_pubkey())
799 .supported_quantity(Quantity::Unbounded)
801 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
802 .amount_msats(1000).unwrap()
803 .quantity(2).unwrap()
806 Ok(_) => panic!("expected error"),
807 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
810 match OfferBuilder::new("foo".into(), recipient_pubkey())
812 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
815 Ok(_) => panic!("expected error"),
816 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
821 fn builds_invoice_request_with_features() {
822 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
825 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
826 .features_unchecked(InvoiceRequestFeatures::unknown())
828 .sign(payer_sign).unwrap();
829 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
830 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
831 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
833 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
836 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
837 .features_unchecked(InvoiceRequestFeatures::unknown())
838 .features_unchecked(InvoiceRequestFeatures::empty())
840 .sign(payer_sign).unwrap();
841 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
842 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
843 assert_eq!(tlv_stream.features, None);
847 fn builds_invoice_request_with_quantity() {
848 let ten = NonZeroU64::new(10).unwrap();
850 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
852 .supported_quantity(Quantity::one())
854 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
856 .sign(payer_sign).unwrap();
857 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
858 assert_eq!(invoice_request.quantity(), None);
859 assert_eq!(tlv_stream.quantity, None);
861 match OfferBuilder::new("foo".into(), recipient_pubkey())
863 .supported_quantity(Quantity::one())
865 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
866 .amount_msats(2_000).unwrap()
869 Ok(_) => panic!("expected error"),
870 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
873 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
875 .supported_quantity(Quantity::Bounded(ten))
877 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
878 .amount_msats(10_000).unwrap()
879 .quantity(10).unwrap()
881 .sign(payer_sign).unwrap();
882 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
883 assert_eq!(invoice_request.amount_msats(), Some(10_000));
884 assert_eq!(tlv_stream.amount, Some(10_000));
886 match OfferBuilder::new("foo".into(), recipient_pubkey())
888 .supported_quantity(Quantity::Bounded(ten))
890 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
891 .amount_msats(11_000).unwrap()
894 Ok(_) => panic!("expected error"),
895 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
898 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
900 .supported_quantity(Quantity::Unbounded)
902 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
903 .amount_msats(2_000).unwrap()
904 .quantity(2).unwrap()
906 .sign(payer_sign).unwrap();
907 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
908 assert_eq!(invoice_request.amount_msats(), Some(2_000));
909 assert_eq!(tlv_stream.amount, Some(2_000));
911 match OfferBuilder::new("foo".into(), recipient_pubkey())
913 .supported_quantity(Quantity::Unbounded)
915 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
918 Ok(_) => panic!("expected error"),
919 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
924 fn builds_invoice_request_with_payer_note() {
925 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
928 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
929 .payer_note("bar".into())
931 .sign(payer_sign).unwrap();
932 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
933 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
934 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
936 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
939 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
940 .payer_note("bar".into())
941 .payer_note("baz".into())
943 .sign(payer_sign).unwrap();
944 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
945 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
946 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
950 fn fails_signing_invoice_request() {
951 match OfferBuilder::new("foo".into(), recipient_pubkey())
954 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
958 Ok(_) => panic!("expected error"),
959 Err(e) => assert_eq!(e, SignError::Signing(())),
962 match OfferBuilder::new("foo".into(), recipient_pubkey())
965 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
967 .sign(recipient_sign)
969 Ok(_) => panic!("expected error"),
970 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
975 fn parses_invoice_request_with_metadata() {
976 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
979 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
981 .sign(payer_sign).unwrap();
983 let mut buffer = Vec::new();
984 invoice_request.write(&mut buffer).unwrap();
986 if let Err(e) = InvoiceRequest::try_from(buffer) {
987 panic!("error parsing invoice_request: {:?}", e);
992 fn parses_invoice_request_with_chain() {
993 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
996 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
997 .chain(Network::Bitcoin).unwrap()
999 .sign(payer_sign).unwrap();
1001 let mut buffer = Vec::new();
1002 invoice_request.write(&mut buffer).unwrap();
1004 if let Err(e) = InvoiceRequest::try_from(buffer) {
1005 panic!("error parsing invoice_request: {:?}", e);
1008 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1011 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1012 .chain_unchecked(Network::Testnet)
1014 .sign(payer_sign).unwrap();
1016 let mut buffer = Vec::new();
1017 invoice_request.write(&mut buffer).unwrap();
1019 match InvoiceRequest::try_from(buffer) {
1020 Ok(_) => panic!("expected error"),
1021 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1026 fn parses_invoice_request_with_amount() {
1027 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1030 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1032 .sign(payer_sign).unwrap();
1034 let mut buffer = Vec::new();
1035 invoice_request.write(&mut buffer).unwrap();
1037 if let Err(e) = InvoiceRequest::try_from(buffer) {
1038 panic!("error parsing invoice_request: {:?}", e);
1041 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1043 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1044 .amount_msats(1000).unwrap()
1046 .sign(payer_sign).unwrap();
1048 let mut buffer = Vec::new();
1049 invoice_request.write(&mut buffer).unwrap();
1051 if let Err(e) = InvoiceRequest::try_from(buffer) {
1052 panic!("error parsing invoice_request: {:?}", e);
1055 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1057 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1059 .sign(payer_sign).unwrap();
1061 let mut buffer = Vec::new();
1062 invoice_request.write(&mut buffer).unwrap();
1064 match InvoiceRequest::try_from(buffer) {
1065 Ok(_) => panic!("expected error"),
1066 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1069 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1072 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 .amount_msats_unchecked(999)
1075 .sign(payer_sign).unwrap();
1077 let mut buffer = Vec::new();
1078 invoice_request.write(&mut buffer).unwrap();
1080 match InvoiceRequest::try_from(buffer) {
1081 Ok(_) => panic!("expected error"),
1082 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1085 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1086 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1088 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1090 .sign(payer_sign).unwrap();
1092 let mut buffer = Vec::new();
1093 invoice_request.write(&mut buffer).unwrap();
1095 match InvoiceRequest::try_from(buffer) {
1096 Ok(_) => panic!("expected error"),
1098 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1104 fn parses_invoice_request_with_quantity() {
1105 let ten = NonZeroU64::new(10).unwrap();
1107 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1109 .supported_quantity(Quantity::one())
1111 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1113 .sign(payer_sign).unwrap();
1115 let mut buffer = Vec::new();
1116 invoice_request.write(&mut buffer).unwrap();
1118 if let Err(e) = InvoiceRequest::try_from(buffer) {
1119 panic!("error parsing invoice_request: {:?}", e);
1122 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1124 .supported_quantity(Quantity::one())
1126 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1127 .amount_msats(2_000).unwrap()
1128 .quantity_unchecked(2)
1130 .sign(payer_sign).unwrap();
1132 let mut buffer = Vec::new();
1133 invoice_request.write(&mut buffer).unwrap();
1135 match InvoiceRequest::try_from(buffer) {
1136 Ok(_) => panic!("expected error"),
1138 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1142 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1144 .supported_quantity(Quantity::Bounded(ten))
1146 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1147 .amount_msats(10_000).unwrap()
1148 .quantity(10).unwrap()
1150 .sign(payer_sign).unwrap();
1152 let mut buffer = Vec::new();
1153 invoice_request.write(&mut buffer).unwrap();
1155 if let Err(e) = InvoiceRequest::try_from(buffer) {
1156 panic!("error parsing invoice_request: {:?}", e);
1159 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1161 .supported_quantity(Quantity::Bounded(ten))
1163 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164 .amount_msats(11_000).unwrap()
1165 .quantity_unchecked(11)
1167 .sign(payer_sign).unwrap();
1169 let mut buffer = Vec::new();
1170 invoice_request.write(&mut buffer).unwrap();
1172 match InvoiceRequest::try_from(buffer) {
1173 Ok(_) => panic!("expected error"),
1174 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1177 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1179 .supported_quantity(Quantity::Unbounded)
1181 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1182 .amount_msats(2_000).unwrap()
1183 .quantity(2).unwrap()
1185 .sign(payer_sign).unwrap();
1187 let mut buffer = Vec::new();
1188 invoice_request.write(&mut buffer).unwrap();
1190 if let Err(e) = InvoiceRequest::try_from(buffer) {
1191 panic!("error parsing invoice_request: {:?}", e);
1194 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1196 .supported_quantity(Quantity::Unbounded)
1198 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1200 .sign(payer_sign).unwrap();
1202 let mut buffer = Vec::new();
1203 invoice_request.write(&mut buffer).unwrap();
1205 match InvoiceRequest::try_from(buffer) {
1206 Ok(_) => panic!("expected error"),
1207 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1212 fn fails_parsing_invoice_request_without_metadata() {
1213 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1216 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1218 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1219 tlv_stream.0.metadata = None;
1221 let mut buffer = Vec::new();
1222 tlv_stream.write(&mut buffer).unwrap();
1224 match InvoiceRequest::try_from(buffer) {
1225 Ok(_) => panic!("expected error"),
1227 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1233 fn fails_parsing_invoice_request_without_payer_id() {
1234 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1237 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1239 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1240 tlv_stream.2.payer_id = None;
1242 let mut buffer = Vec::new();
1243 tlv_stream.write(&mut buffer).unwrap();
1245 match InvoiceRequest::try_from(buffer) {
1246 Ok(_) => panic!("expected error"),
1247 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1252 fn fails_parsing_invoice_request_without_node_id() {
1253 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1256 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1259 tlv_stream.1.node_id = None;
1261 let mut buffer = Vec::new();
1262 tlv_stream.write(&mut buffer).unwrap();
1264 match InvoiceRequest::try_from(buffer) {
1265 Ok(_) => panic!("expected error"),
1267 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1273 fn fails_parsing_invoice_request_without_signature() {
1274 let mut buffer = Vec::new();
1275 OfferBuilder::new("foo".into(), recipient_pubkey())
1278 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1281 .write(&mut buffer).unwrap();
1283 match InvoiceRequest::try_from(buffer) {
1284 Ok(_) => panic!("expected error"),
1285 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1290 fn fails_parsing_invoice_request_with_invalid_signature() {
1291 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1294 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1296 .sign(payer_sign).unwrap();
1297 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1298 *last_signature_byte = last_signature_byte.wrapping_add(1);
1300 let mut buffer = Vec::new();
1301 invoice_request.write(&mut buffer).unwrap();
1303 match InvoiceRequest::try_from(buffer) {
1304 Ok(_) => panic!("expected error"),
1306 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1312 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1313 let secp_ctx = Secp256k1::new();
1314 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1315 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1318 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1320 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1323 let mut encoded_invoice_request = Vec::new();
1324 invoice_request.write(&mut encoded_invoice_request).unwrap();
1325 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1326 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1327 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1329 match InvoiceRequest::try_from(encoded_invoice_request) {
1330 Ok(_) => panic!("expected error"),
1331 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),