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 ordered from most-preferred to least-preferred, if there's
337 /// a preference. Note, however, that any privacy is lost if a public node id was used for
338 /// [`Offer::signing_pubkey`].
340 /// Errors if the request contains unknown required features.
342 /// [`Duration`]: core::time::Duration
343 /// [`Invoice`]: crate::offers::invoice::Invoice
344 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
346 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
347 #[cfg(any(test, not(feature = "std")))]
348 created_at: core::time::Duration
349 ) -> Result<InvoiceBuilder, SemanticError> {
350 if self.features().requires_unknown_bits() {
351 return Err(SemanticError::UnknownRequiredFeatures);
354 #[cfg(all(not(test), feature = "std"))]
355 let created_at = std::time::SystemTime::now()
356 .duration_since(std::time::SystemTime::UNIX_EPOCH)
357 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
359 InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
363 fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
364 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
365 self.contents.as_tlv_stream();
366 let signature_tlv_stream = SignatureTlvStreamRef {
367 signature: Some(&self.signature),
369 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
373 impl InvoiceRequestContents {
374 pub(super) fn chain(&self) -> ChainHash {
375 self.chain.unwrap_or_else(|| self.offer.implied_chain())
378 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
379 let payer = PayerTlvStreamRef {
380 metadata: Some(&self.payer.0),
383 let offer = self.offer.as_tlv_stream();
386 if self.features == InvoiceRequestFeatures::empty() { None }
387 else { Some(&self.features) }
390 let invoice_request = InvoiceRequestTlvStreamRef {
391 chain: self.chain.as_ref(),
392 amount: self.amount_msats,
394 quantity: self.quantity,
395 payer_id: Some(&self.payer_id),
396 payer_note: self.payer_note.as_ref(),
399 (payer, offer, invoice_request)
403 impl Writeable for InvoiceRequest {
404 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
405 WithoutLength(&self.bytes).write(writer)
409 impl Writeable for InvoiceRequestContents {
410 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
411 self.as_tlv_stream().write(writer)
415 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
416 (80, chain: ChainHash),
417 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
418 (84, features: (InvoiceRequestFeatures, WithoutLength)),
419 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
420 (88, payer_id: PublicKey),
421 (89, payer_note: (String, WithoutLength)),
424 type FullInvoiceRequestTlvStream =
425 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
428 type FullInvoiceRequestTlvStreamRef<'a> = (
429 PayerTlvStreamRef<'a>,
430 OfferTlvStreamRef<'a>,
431 InvoiceRequestTlvStreamRef<'a>,
432 SignatureTlvStreamRef<'a>,
435 impl SeekReadable for FullInvoiceRequestTlvStream {
436 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
437 let payer = SeekReadable::read(r)?;
438 let offer = SeekReadable::read(r)?;
439 let invoice_request = SeekReadable::read(r)?;
440 let signature = SeekReadable::read(r)?;
442 Ok((payer, offer, invoice_request, signature))
446 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
448 type PartialInvoiceRequestTlvStreamRef<'a> = (
449 PayerTlvStreamRef<'a>,
450 OfferTlvStreamRef<'a>,
451 InvoiceRequestTlvStreamRef<'a>,
454 impl TryFrom<Vec<u8>> for InvoiceRequest {
455 type Error = ParseError;
457 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
458 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
459 let ParsedMessage { bytes, tlv_stream } = invoice_request;
461 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
462 SignatureTlvStream { signature },
464 let contents = InvoiceRequestContents::try_from(
465 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
468 let signature = match signature {
469 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
470 Some(signature) => signature,
472 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
474 Ok(InvoiceRequest { bytes, contents, signature })
478 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
479 type Error = SemanticError;
481 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
483 PayerTlvStream { metadata },
485 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
488 let payer = match metadata {
489 None => return Err(SemanticError::MissingPayerMetadata),
490 Some(metadata) => PayerContents(metadata),
492 let offer = OfferContents::try_from(offer_tlv_stream)?;
494 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
495 return Err(SemanticError::UnsupportedChain);
498 if offer.amount().is_none() && amount.is_none() {
499 return Err(SemanticError::MissingAmount);
502 offer.check_quantity(quantity)?;
503 offer.check_amount_msats_for_quantity(amount, quantity)?;
505 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
507 let payer_id = match payer_id {
508 None => return Err(SemanticError::MissingPayerId),
509 Some(payer_id) => payer_id,
512 Ok(InvoiceRequestContents {
513 payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
520 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
522 use bitcoin::blockdata::constants::ChainHash;
523 use bitcoin::network::constants::Network;
524 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
525 use bitcoin::secp256k1::schnorr::Signature;
526 use core::convert::{Infallible, TryFrom};
527 use core::num::NonZeroU64;
528 #[cfg(feature = "std")]
529 use core::time::Duration;
530 use crate::ln::features::InvoiceRequestFeatures;
531 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
532 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
533 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
534 use crate::offers::parse::{ParseError, SemanticError};
535 use crate::offers::payer::PayerTlvStreamRef;
536 use crate::util::ser::{BigSize, Writeable};
537 use crate::util::string::PrintableString;
539 fn payer_keys() -> KeyPair {
540 let secp_ctx = Secp256k1::new();
541 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
544 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
545 let secp_ctx = Secp256k1::new();
546 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
547 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
550 fn payer_pubkey() -> PublicKey {
551 payer_keys().public_key()
554 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
555 let secp_ctx = Secp256k1::new();
556 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
557 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
560 fn recipient_pubkey() -> PublicKey {
561 let secp_ctx = Secp256k1::new();
562 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
566 fn builds_invoice_request_with_defaults() {
567 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
570 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
572 .sign(payer_sign).unwrap();
574 let mut buffer = Vec::new();
575 invoice_request.write(&mut buffer).unwrap();
577 assert_eq!(invoice_request.bytes, buffer.as_slice());
578 assert_eq!(invoice_request.metadata(), &[1; 32]);
579 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
580 assert_eq!(invoice_request.amount_msats(), None);
581 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
582 assert_eq!(invoice_request.quantity(), None);
583 assert_eq!(invoice_request.payer_id(), payer_pubkey());
584 assert_eq!(invoice_request.payer_note(), None);
586 merkle::verify_signature(
587 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
592 invoice_request.as_tlv_stream(),
594 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
600 description: Some(&String::from("foo")),
602 absolute_expiry: None,
606 node_id: Some(&recipient_pubkey()),
608 InvoiceRequestTlvStreamRef {
613 payer_id: Some(&payer_pubkey()),
616 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
620 if let Err(e) = InvoiceRequest::try_from(buffer) {
621 panic!("error parsing invoice request: {:?}", e);
625 #[cfg(feature = "std")]
627 fn builds_invoice_request_from_offer_with_expiration() {
628 let future_expiry = Duration::from_secs(u64::max_value());
629 let past_expiry = Duration::from_secs(0);
631 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
633 .absolute_expiry(future_expiry)
635 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
638 panic!("error building invoice_request: {:?}", e);
641 match OfferBuilder::new("foo".into(), recipient_pubkey())
643 .absolute_expiry(past_expiry)
645 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
648 Ok(_) => panic!("expected error"),
649 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
654 fn builds_invoice_request_with_chain() {
655 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
656 let testnet = ChainHash::using_genesis_block(Network::Testnet);
658 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
661 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
662 .chain(Network::Bitcoin).unwrap()
664 .sign(payer_sign).unwrap();
665 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
666 assert_eq!(invoice_request.chain(), mainnet);
667 assert_eq!(tlv_stream.chain, None);
669 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
671 .chain(Network::Testnet)
673 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
674 .chain(Network::Testnet).unwrap()
676 .sign(payer_sign).unwrap();
677 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
678 assert_eq!(invoice_request.chain(), testnet);
679 assert_eq!(tlv_stream.chain, Some(&testnet));
681 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
683 .chain(Network::Bitcoin)
684 .chain(Network::Testnet)
686 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
687 .chain(Network::Bitcoin).unwrap()
689 .sign(payer_sign).unwrap();
690 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
691 assert_eq!(invoice_request.chain(), mainnet);
692 assert_eq!(tlv_stream.chain, None);
694 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
696 .chain(Network::Bitcoin)
697 .chain(Network::Testnet)
699 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
700 .chain(Network::Bitcoin).unwrap()
701 .chain(Network::Testnet).unwrap()
703 .sign(payer_sign).unwrap();
704 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
705 assert_eq!(invoice_request.chain(), testnet);
706 assert_eq!(tlv_stream.chain, Some(&testnet));
708 match OfferBuilder::new("foo".into(), recipient_pubkey())
710 .chain(Network::Testnet)
712 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
713 .chain(Network::Bitcoin)
715 Ok(_) => panic!("expected error"),
716 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
719 match OfferBuilder::new("foo".into(), recipient_pubkey())
721 .chain(Network::Testnet)
723 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
726 Ok(_) => panic!("expected error"),
727 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
732 fn builds_invoice_request_with_amount() {
733 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
736 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
737 .amount_msats(1000).unwrap()
739 .sign(payer_sign).unwrap();
740 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
741 assert_eq!(invoice_request.amount_msats(), Some(1000));
742 assert_eq!(tlv_stream.amount, Some(1000));
744 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
747 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
748 .amount_msats(1001).unwrap()
749 .amount_msats(1000).unwrap()
751 .sign(payer_sign).unwrap();
752 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
753 assert_eq!(invoice_request.amount_msats(), Some(1000));
754 assert_eq!(tlv_stream.amount, Some(1000));
756 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
759 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
760 .amount_msats(1001).unwrap()
762 .sign(payer_sign).unwrap();
763 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
764 assert_eq!(invoice_request.amount_msats(), Some(1001));
765 assert_eq!(tlv_stream.amount, Some(1001));
767 match OfferBuilder::new("foo".into(), recipient_pubkey())
770 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
773 Ok(_) => panic!("expected error"),
774 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
777 match OfferBuilder::new("foo".into(), recipient_pubkey())
779 .supported_quantity(Quantity::Unbounded)
781 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
782 .quantity(2).unwrap()
785 Ok(_) => panic!("expected error"),
786 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
789 match OfferBuilder::new("foo".into(), recipient_pubkey())
792 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
793 .amount_msats(MAX_VALUE_MSAT + 1)
795 Ok(_) => panic!("expected error"),
796 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
799 match OfferBuilder::new("foo".into(), recipient_pubkey())
801 .supported_quantity(Quantity::Unbounded)
803 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
804 .amount_msats(1000).unwrap()
805 .quantity(2).unwrap()
808 Ok(_) => panic!("expected error"),
809 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
812 match OfferBuilder::new("foo".into(), recipient_pubkey())
814 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
817 Ok(_) => panic!("expected error"),
818 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
823 fn builds_invoice_request_with_features() {
824 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
827 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
828 .features_unchecked(InvoiceRequestFeatures::unknown())
830 .sign(payer_sign).unwrap();
831 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
832 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
833 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
835 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
838 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
839 .features_unchecked(InvoiceRequestFeatures::unknown())
840 .features_unchecked(InvoiceRequestFeatures::empty())
842 .sign(payer_sign).unwrap();
843 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
844 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
845 assert_eq!(tlv_stream.features, None);
849 fn builds_invoice_request_with_quantity() {
850 let one = NonZeroU64::new(1).unwrap();
851 let ten = NonZeroU64::new(10).unwrap();
853 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
855 .supported_quantity(Quantity::One)
857 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
859 .sign(payer_sign).unwrap();
860 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
861 assert_eq!(invoice_request.quantity(), None);
862 assert_eq!(tlv_stream.quantity, None);
864 match OfferBuilder::new("foo".into(), recipient_pubkey())
866 .supported_quantity(Quantity::One)
868 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
869 .amount_msats(2_000).unwrap()
872 Ok(_) => panic!("expected error"),
873 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
876 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
878 .supported_quantity(Quantity::Bounded(ten))
880 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
881 .amount_msats(10_000).unwrap()
882 .quantity(10).unwrap()
884 .sign(payer_sign).unwrap();
885 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
886 assert_eq!(invoice_request.amount_msats(), Some(10_000));
887 assert_eq!(tlv_stream.amount, Some(10_000));
889 match OfferBuilder::new("foo".into(), recipient_pubkey())
891 .supported_quantity(Quantity::Bounded(ten))
893 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
894 .amount_msats(11_000).unwrap()
897 Ok(_) => panic!("expected error"),
898 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
901 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
903 .supported_quantity(Quantity::Unbounded)
905 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
906 .amount_msats(2_000).unwrap()
907 .quantity(2).unwrap()
909 .sign(payer_sign).unwrap();
910 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
911 assert_eq!(invoice_request.amount_msats(), Some(2_000));
912 assert_eq!(tlv_stream.amount, Some(2_000));
914 match OfferBuilder::new("foo".into(), recipient_pubkey())
916 .supported_quantity(Quantity::Unbounded)
918 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
921 Ok(_) => panic!("expected error"),
922 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
925 match OfferBuilder::new("foo".into(), recipient_pubkey())
927 .supported_quantity(Quantity::Bounded(one))
929 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
932 Ok(_) => panic!("expected error"),
933 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
938 fn builds_invoice_request_with_payer_note() {
939 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
942 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
943 .payer_note("bar".into())
945 .sign(payer_sign).unwrap();
946 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
947 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
948 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
950 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
953 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
954 .payer_note("bar".into())
955 .payer_note("baz".into())
957 .sign(payer_sign).unwrap();
958 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
959 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
960 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
964 fn fails_signing_invoice_request() {
965 match OfferBuilder::new("foo".into(), recipient_pubkey())
968 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
972 Ok(_) => panic!("expected error"),
973 Err(e) => assert_eq!(e, SignError::Signing(())),
976 match OfferBuilder::new("foo".into(), recipient_pubkey())
979 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
981 .sign(recipient_sign)
983 Ok(_) => panic!("expected error"),
984 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
989 fn parses_invoice_request_with_metadata() {
990 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
993 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
995 .sign(payer_sign).unwrap();
997 let mut buffer = Vec::new();
998 invoice_request.write(&mut buffer).unwrap();
1000 if let Err(e) = InvoiceRequest::try_from(buffer) {
1001 panic!("error parsing invoice_request: {:?}", e);
1006 fn parses_invoice_request_with_chain() {
1007 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1010 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1011 .chain(Network::Bitcoin).unwrap()
1013 .sign(payer_sign).unwrap();
1015 let mut buffer = Vec::new();
1016 invoice_request.write(&mut buffer).unwrap();
1018 if let Err(e) = InvoiceRequest::try_from(buffer) {
1019 panic!("error parsing invoice_request: {:?}", e);
1022 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1025 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1026 .chain_unchecked(Network::Testnet)
1028 .sign(payer_sign).unwrap();
1030 let mut buffer = Vec::new();
1031 invoice_request.write(&mut buffer).unwrap();
1033 match InvoiceRequest::try_from(buffer) {
1034 Ok(_) => panic!("expected error"),
1035 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
1040 fn parses_invoice_request_with_amount() {
1041 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1044 .request_invoice(vec![1; 32], payer_pubkey()).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()
1058 .amount_msats(1000).unwrap()
1060 .sign(payer_sign).unwrap();
1062 let mut buffer = Vec::new();
1063 invoice_request.write(&mut buffer).unwrap();
1065 if let Err(e) = InvoiceRequest::try_from(buffer) {
1066 panic!("error parsing invoice_request: {:?}", e);
1069 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1071 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1073 .sign(payer_sign).unwrap();
1075 let mut buffer = Vec::new();
1076 invoice_request.write(&mut buffer).unwrap();
1078 match InvoiceRequest::try_from(buffer) {
1079 Ok(_) => panic!("expected error"),
1080 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1083 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1086 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1087 .amount_msats_unchecked(999)
1089 .sign(payer_sign).unwrap();
1091 let mut buffer = Vec::new();
1092 invoice_request.write(&mut buffer).unwrap();
1094 match InvoiceRequest::try_from(buffer) {
1095 Ok(_) => panic!("expected error"),
1096 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1099 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1100 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1102 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1104 .sign(payer_sign).unwrap();
1106 let mut buffer = Vec::new();
1107 invoice_request.write(&mut buffer).unwrap();
1109 match InvoiceRequest::try_from(buffer) {
1110 Ok(_) => panic!("expected error"),
1112 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1118 fn parses_invoice_request_with_quantity() {
1119 let one = NonZeroU64::new(1).unwrap();
1120 let ten = NonZeroU64::new(10).unwrap();
1122 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1124 .supported_quantity(Quantity::One)
1126 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1128 .sign(payer_sign).unwrap();
1130 let mut buffer = Vec::new();
1131 invoice_request.write(&mut buffer).unwrap();
1133 if let Err(e) = InvoiceRequest::try_from(buffer) {
1134 panic!("error parsing invoice_request: {:?}", e);
1137 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1139 .supported_quantity(Quantity::One)
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1142 .amount_msats(2_000).unwrap()
1143 .quantity_unchecked(2)
1145 .sign(payer_sign).unwrap();
1147 let mut buffer = Vec::new();
1148 invoice_request.write(&mut buffer).unwrap();
1150 match InvoiceRequest::try_from(buffer) {
1151 Ok(_) => panic!("expected error"),
1153 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1157 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1159 .supported_quantity(Quantity::Bounded(ten))
1161 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1162 .amount_msats(10_000).unwrap()
1163 .quantity(10).unwrap()
1165 .sign(payer_sign).unwrap();
1167 let mut buffer = Vec::new();
1168 invoice_request.write(&mut buffer).unwrap();
1170 if let Err(e) = InvoiceRequest::try_from(buffer) {
1171 panic!("error parsing invoice_request: {:?}", e);
1174 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1176 .supported_quantity(Quantity::Bounded(ten))
1178 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1179 .amount_msats(11_000).unwrap()
1180 .quantity_unchecked(11)
1182 .sign(payer_sign).unwrap();
1184 let mut buffer = Vec::new();
1185 invoice_request.write(&mut buffer).unwrap();
1187 match InvoiceRequest::try_from(buffer) {
1188 Ok(_) => panic!("expected error"),
1189 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1192 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1194 .supported_quantity(Quantity::Unbounded)
1196 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1197 .amount_msats(2_000).unwrap()
1198 .quantity(2).unwrap()
1200 .sign(payer_sign).unwrap();
1202 let mut buffer = Vec::new();
1203 invoice_request.write(&mut buffer).unwrap();
1205 if let Err(e) = InvoiceRequest::try_from(buffer) {
1206 panic!("error parsing invoice_request: {:?}", e);
1209 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1211 .supported_quantity(Quantity::Unbounded)
1213 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1215 .sign(payer_sign).unwrap();
1217 let mut buffer = Vec::new();
1218 invoice_request.write(&mut buffer).unwrap();
1220 match InvoiceRequest::try_from(buffer) {
1221 Ok(_) => panic!("expected error"),
1222 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1225 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1227 .supported_quantity(Quantity::Bounded(one))
1229 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231 .sign(payer_sign).unwrap();
1233 let mut buffer = Vec::new();
1234 invoice_request.write(&mut buffer).unwrap();
1236 match InvoiceRequest::try_from(buffer) {
1237 Ok(_) => panic!("expected error"),
1238 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1243 fn fails_parsing_invoice_request_without_metadata() {
1244 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1247 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1249 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1250 tlv_stream.0.metadata = None;
1252 let mut buffer = Vec::new();
1253 tlv_stream.write(&mut buffer).unwrap();
1255 match InvoiceRequest::try_from(buffer) {
1256 Ok(_) => panic!("expected error"),
1258 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1264 fn fails_parsing_invoice_request_without_payer_id() {
1265 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1268 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1270 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1271 tlv_stream.2.payer_id = None;
1273 let mut buffer = Vec::new();
1274 tlv_stream.write(&mut buffer).unwrap();
1276 match InvoiceRequest::try_from(buffer) {
1277 Ok(_) => panic!("expected error"),
1278 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1283 fn fails_parsing_invoice_request_without_node_id() {
1284 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1287 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1289 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1290 tlv_stream.1.node_id = None;
1292 let mut buffer = Vec::new();
1293 tlv_stream.write(&mut buffer).unwrap();
1295 match InvoiceRequest::try_from(buffer) {
1296 Ok(_) => panic!("expected error"),
1298 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1304 fn fails_parsing_invoice_request_without_signature() {
1305 let mut buffer = Vec::new();
1306 OfferBuilder::new("foo".into(), recipient_pubkey())
1309 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1312 .write(&mut buffer).unwrap();
1314 match InvoiceRequest::try_from(buffer) {
1315 Ok(_) => panic!("expected error"),
1316 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1321 fn fails_parsing_invoice_request_with_invalid_signature() {
1322 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1325 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1327 .sign(payer_sign).unwrap();
1328 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1329 *last_signature_byte = last_signature_byte.wrapping_add(1);
1331 let mut buffer = Vec::new();
1332 invoice_request.write(&mut buffer).unwrap();
1334 match InvoiceRequest::try_from(buffer) {
1335 Ok(_) => panic!("expected error"),
1337 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1343 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1344 let secp_ctx = Secp256k1::new();
1345 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1346 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1349 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1351 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1354 let mut encoded_invoice_request = Vec::new();
1355 invoice_request.write(&mut encoded_invoice_request).unwrap();
1356 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1357 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1358 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1360 match InvoiceRequest::try_from(encoded_invoice_request) {
1361 Ok(_) => panic!("expected error"),
1362 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),