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 either built from a parsed [`Offer`] as an "offer to be paid" or
13 //! built directly as an "offer for money" (e.g., refund, ATM withdrawal). In the former case, it is
14 //! typically constructed by a customer and sent to the merchant who had published the corresponding
15 //! offer. In the latter case, an offer doesn't exist as a precursor to the request. Rather the
16 //! merchant would typically construct the invoice request and present it to the customer.
18 //! The recipient of the request responds with an `Invoice`.
21 //! extern crate bitcoin;
22 //! extern crate lightning;
24 //! use bitcoin::network::constants::Network;
25 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
26 //! use core::convert::Infallible;
27 //! use lightning::ln::features::OfferFeatures;
28 //! use lightning::offers::offer::Offer;
29 //! use lightning::util::ser::Writeable;
31 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
32 //! let secp_ctx = Secp256k1::new();
33 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
34 //! let pubkey = PublicKey::from(keys);
35 //! let mut buffer = Vec::new();
37 //! // "offer to be paid" flow
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 for paying the 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;
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;
487 use crate::offers::offer::{Amount, OfferBuilder, Quantity};
488 use crate::offers::parse::{ParseError, SemanticError};
489 use crate::util::ser::{BigSize, Writeable};
490 use crate::util::string::PrintableString;
492 fn payer_keys() -> KeyPair {
493 let secp_ctx = Secp256k1::new();
494 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
497 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
498 let secp_ctx = Secp256k1::new();
499 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
500 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
503 fn payer_pubkey() -> PublicKey {
504 payer_keys().public_key()
507 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
508 let secp_ctx = Secp256k1::new();
509 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
510 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
513 fn recipient_pubkey() -> PublicKey {
514 let secp_ctx = Secp256k1::new();
515 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
519 fn builds_invoice_request_with_defaults() {
520 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
523 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
524 .build().unwrap().sign(payer_sign).unwrap();
526 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream) =
527 invoice_request.as_tlv_stream();
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());
541 assert_eq!(payer_tlv_stream.metadata, Some(&vec![1; 32]));
542 assert_eq!(offer_tlv_stream.chains, None);
543 assert_eq!(offer_tlv_stream.metadata, None);
544 assert_eq!(offer_tlv_stream.currency, None);
545 assert_eq!(offer_tlv_stream.amount, Some(1000));
546 assert_eq!(offer_tlv_stream.description, Some(&String::from("foo")));
547 assert_eq!(offer_tlv_stream.features, None);
548 assert_eq!(offer_tlv_stream.absolute_expiry, None);
549 assert_eq!(offer_tlv_stream.paths, None);
550 assert_eq!(offer_tlv_stream.issuer, None);
551 assert_eq!(offer_tlv_stream.quantity_max, None);
552 assert_eq!(offer_tlv_stream.node_id, Some(&recipient_pubkey()));
553 assert_eq!(invoice_request_tlv_stream.chain, None);
554 assert_eq!(invoice_request_tlv_stream.amount, None);
555 assert_eq!(invoice_request_tlv_stream.features, None);
556 assert_eq!(invoice_request_tlv_stream.quantity, None);
557 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&payer_pubkey()));
558 assert_eq!(invoice_request_tlv_stream.payer_note, None);
559 assert!(signature_tlv_stream.signature.is_some());
561 if let Err(e) = InvoiceRequest::try_from(buffer) {
562 panic!("error parsing invoice request: {:?}", e);
566 #[cfg(feature = "std")]
568 fn builds_invoice_request_from_offer_with_expiration() {
569 let future_expiry = Duration::from_secs(u64::max_value());
570 let past_expiry = Duration::from_secs(0);
572 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
574 .absolute_expiry(future_expiry)
576 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
579 panic!("error building invoice_request: {:?}", e);
582 match OfferBuilder::new("foo".into(), recipient_pubkey())
584 .absolute_expiry(past_expiry)
586 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
589 Ok(_) => panic!("expected error"),
590 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
595 fn builds_invoice_request_with_chain() {
596 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
597 let testnet = ChainHash::using_genesis_block(Network::Testnet);
599 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
602 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
603 .chain(Network::Bitcoin).unwrap()
605 .sign(payer_sign).unwrap();
606 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
607 assert_eq!(invoice_request.chain(), mainnet);
608 assert_eq!(tlv_stream.chain, None);
610 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
612 .chain(Network::Testnet)
614 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
615 .chain(Network::Testnet).unwrap()
617 .sign(payer_sign).unwrap();
618 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
619 assert_eq!(invoice_request.chain(), testnet);
620 assert_eq!(tlv_stream.chain, Some(&testnet));
622 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
624 .chain(Network::Bitcoin)
625 .chain(Network::Testnet)
627 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
628 .chain(Network::Bitcoin).unwrap()
630 .sign(payer_sign).unwrap();
631 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
632 assert_eq!(invoice_request.chain(), mainnet);
633 assert_eq!(tlv_stream.chain, None);
635 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
637 .chain(Network::Bitcoin)
638 .chain(Network::Testnet)
640 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
641 .chain(Network::Bitcoin).unwrap()
642 .chain(Network::Testnet).unwrap()
644 .sign(payer_sign).unwrap();
645 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
646 assert_eq!(invoice_request.chain(), testnet);
647 assert_eq!(tlv_stream.chain, Some(&testnet));
649 match OfferBuilder::new("foo".into(), recipient_pubkey())
651 .chain(Network::Testnet)
653 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
654 .chain(Network::Bitcoin)
656 Ok(_) => panic!("expected error"),
657 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
660 match OfferBuilder::new("foo".into(), recipient_pubkey())
662 .chain(Network::Testnet)
664 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
667 Ok(_) => panic!("expected error"),
668 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
673 fn builds_invoice_request_with_amount() {
674 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
677 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
678 .amount_msats(1000).unwrap()
680 .sign(payer_sign).unwrap();
681 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
682 assert_eq!(invoice_request.amount_msats(), Some(1000));
683 assert_eq!(tlv_stream.amount, Some(1000));
685 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
688 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
689 .amount_msats(1001).unwrap()
690 .amount_msats(1000).unwrap()
692 .sign(payer_sign).unwrap();
693 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
694 assert_eq!(invoice_request.amount_msats(), Some(1000));
695 assert_eq!(tlv_stream.amount, Some(1000));
697 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
700 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
701 .amount_msats(1001).unwrap()
703 .sign(payer_sign).unwrap();
704 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
705 assert_eq!(invoice_request.amount_msats(), Some(1001));
706 assert_eq!(tlv_stream.amount, Some(1001));
708 match OfferBuilder::new("foo".into(), recipient_pubkey())
711 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
714 Ok(_) => panic!("expected error"),
715 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
718 match OfferBuilder::new("foo".into(), recipient_pubkey())
720 .supported_quantity(Quantity::Unbounded)
722 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
723 .quantity(2).unwrap()
726 Ok(_) => panic!("expected error"),
727 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
730 match OfferBuilder::new("foo".into(), recipient_pubkey())
733 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
734 .amount_msats(MAX_VALUE_MSAT + 1)
736 Ok(_) => panic!("expected error"),
737 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
740 match OfferBuilder::new("foo".into(), recipient_pubkey())
742 .supported_quantity(Quantity::Unbounded)
744 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
745 .amount_msats(1000).unwrap()
746 .quantity(2).unwrap()
749 Ok(_) => panic!("expected error"),
750 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
753 match OfferBuilder::new("foo".into(), recipient_pubkey())
755 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
758 Ok(_) => panic!("expected error"),
759 Err(e) => assert_eq!(e, SemanticError::MissingAmount),
764 fn builds_invoice_request_with_features() {
765 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
768 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
769 .features_unchecked(InvoiceRequestFeatures::unknown())
771 .sign(payer_sign).unwrap();
772 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
773 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
774 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
776 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
779 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
780 .features_unchecked(InvoiceRequestFeatures::unknown())
781 .features_unchecked(InvoiceRequestFeatures::empty())
783 .sign(payer_sign).unwrap();
784 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
785 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
786 assert_eq!(tlv_stream.features, None);
790 fn builds_invoice_request_with_quantity() {
791 let ten = NonZeroU64::new(10).unwrap();
793 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
795 .supported_quantity(Quantity::one())
797 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
799 .sign(payer_sign).unwrap();
800 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
801 assert_eq!(invoice_request.quantity(), None);
802 assert_eq!(tlv_stream.quantity, None);
804 match OfferBuilder::new("foo".into(), recipient_pubkey())
806 .supported_quantity(Quantity::one())
808 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
809 .amount_msats(2_000).unwrap()
812 Ok(_) => panic!("expected error"),
813 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
816 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
818 .supported_quantity(Quantity::Bounded(ten))
820 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
821 .amount_msats(10_000).unwrap()
822 .quantity(10).unwrap()
824 .sign(payer_sign).unwrap();
825 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
826 assert_eq!(invoice_request.amount_msats(), Some(10_000));
827 assert_eq!(tlv_stream.amount, Some(10_000));
829 match OfferBuilder::new("foo".into(), recipient_pubkey())
831 .supported_quantity(Quantity::Bounded(ten))
833 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
834 .amount_msats(11_000).unwrap()
837 Ok(_) => panic!("expected error"),
838 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
841 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
843 .supported_quantity(Quantity::Unbounded)
845 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
846 .amount_msats(2_000).unwrap()
847 .quantity(2).unwrap()
849 .sign(payer_sign).unwrap();
850 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
851 assert_eq!(invoice_request.amount_msats(), Some(2_000));
852 assert_eq!(tlv_stream.amount, Some(2_000));
854 match OfferBuilder::new("foo".into(), recipient_pubkey())
856 .supported_quantity(Quantity::Unbounded)
858 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
861 Ok(_) => panic!("expected error"),
862 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
867 fn builds_invoice_request_with_payer_note() {
868 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
871 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
872 .payer_note("bar".into())
874 .sign(payer_sign).unwrap();
875 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
876 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
877 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
879 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
882 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
883 .payer_note("bar".into())
884 .payer_note("baz".into())
886 .sign(payer_sign).unwrap();
887 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
888 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
889 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
893 fn fails_signing_invoice_request() {
894 match OfferBuilder::new("foo".into(), recipient_pubkey())
897 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
901 Ok(_) => panic!("expected error"),
902 Err(e) => assert_eq!(e, SignError::Signing(())),
905 match OfferBuilder::new("foo".into(), recipient_pubkey())
908 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
910 .sign(recipient_sign)
912 Ok(_) => panic!("expected error"),
913 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
918 fn parses_invoice_request_with_metadata() {
919 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
922 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
924 .sign(payer_sign).unwrap();
926 let mut buffer = Vec::new();
927 invoice_request.write(&mut buffer).unwrap();
929 if let Err(e) = InvoiceRequest::try_from(buffer) {
930 panic!("error parsing invoice_request: {:?}", e);
935 fn parses_invoice_request_with_chain() {
936 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
939 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
940 .chain(Network::Bitcoin).unwrap()
942 .sign(payer_sign).unwrap();
944 let mut buffer = Vec::new();
945 invoice_request.write(&mut buffer).unwrap();
947 if let Err(e) = InvoiceRequest::try_from(buffer) {
948 panic!("error parsing invoice_request: {:?}", e);
951 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
954 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
955 .chain_unchecked(Network::Testnet)
957 .sign(payer_sign).unwrap();
959 let mut buffer = Vec::new();
960 invoice_request.write(&mut buffer).unwrap();
962 match InvoiceRequest::try_from(buffer) {
963 Ok(_) => panic!("expected error"),
964 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
969 fn parses_invoice_request_with_amount() {
970 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
973 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
975 .sign(payer_sign).unwrap();
977 let mut buffer = Vec::new();
978 invoice_request.write(&mut buffer).unwrap();
980 if let Err(e) = InvoiceRequest::try_from(buffer) {
981 panic!("error parsing invoice_request: {:?}", e);
984 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
986 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
987 .amount_msats(1000).unwrap()
989 .sign(payer_sign).unwrap();
991 let mut buffer = Vec::new();
992 invoice_request.write(&mut buffer).unwrap();
994 if let Err(e) = InvoiceRequest::try_from(buffer) {
995 panic!("error parsing invoice_request: {:?}", e);
998 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1000 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1002 .sign(payer_sign).unwrap();
1004 let mut buffer = Vec::new();
1005 invoice_request.write(&mut buffer).unwrap();
1007 match InvoiceRequest::try_from(buffer) {
1008 Ok(_) => panic!("expected error"),
1009 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1012 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1015 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1016 .amount_msats_unchecked(999)
1018 .sign(payer_sign).unwrap();
1020 let mut buffer = Vec::new();
1021 invoice_request.write(&mut buffer).unwrap();
1023 match InvoiceRequest::try_from(buffer) {
1024 Ok(_) => panic!("expected error"),
1025 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1028 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1029 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1031 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1033 .sign(payer_sign).unwrap();
1035 let mut buffer = Vec::new();
1036 invoice_request.write(&mut buffer).unwrap();
1038 match InvoiceRequest::try_from(buffer) {
1039 Ok(_) => panic!("expected error"),
1041 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1047 fn parses_invoice_request_with_quantity() {
1048 let ten = NonZeroU64::new(10).unwrap();
1050 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1052 .supported_quantity(Quantity::one())
1054 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1056 .sign(payer_sign).unwrap();
1058 let mut buffer = Vec::new();
1059 invoice_request.write(&mut buffer).unwrap();
1061 if let Err(e) = InvoiceRequest::try_from(buffer) {
1062 panic!("error parsing invoice_request: {:?}", e);
1065 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1067 .supported_quantity(Quantity::one())
1069 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1070 .amount_msats(2_000).unwrap()
1071 .quantity_unchecked(2)
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"),
1081 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1085 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1087 .supported_quantity(Quantity::Bounded(ten))
1089 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1090 .amount_msats(10_000).unwrap()
1091 .quantity(10).unwrap()
1093 .sign(payer_sign).unwrap();
1095 let mut buffer = Vec::new();
1096 invoice_request.write(&mut buffer).unwrap();
1098 if let Err(e) = InvoiceRequest::try_from(buffer) {
1099 panic!("error parsing invoice_request: {:?}", e);
1102 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1104 .supported_quantity(Quantity::Bounded(ten))
1106 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1107 .amount_msats(11_000).unwrap()
1108 .quantity_unchecked(11)
1110 .sign(payer_sign).unwrap();
1112 let mut buffer = Vec::new();
1113 invoice_request.write(&mut buffer).unwrap();
1115 match InvoiceRequest::try_from(buffer) {
1116 Ok(_) => panic!("expected error"),
1117 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1120 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1122 .supported_quantity(Quantity::Unbounded)
1124 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1125 .amount_msats(2_000).unwrap()
1126 .quantity(2).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::Unbounded)
1141 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1143 .sign(payer_sign).unwrap();
1145 let mut buffer = Vec::new();
1146 invoice_request.write(&mut buffer).unwrap();
1148 match InvoiceRequest::try_from(buffer) {
1149 Ok(_) => panic!("expected error"),
1150 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1155 fn fails_parsing_invoice_request_without_metadata() {
1156 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1159 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1161 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1162 tlv_stream.0.metadata = None;
1164 let mut buffer = Vec::new();
1165 tlv_stream.write(&mut buffer).unwrap();
1167 match InvoiceRequest::try_from(buffer) {
1168 Ok(_) => panic!("expected error"),
1170 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1176 fn fails_parsing_invoice_request_without_payer_id() {
1177 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1180 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1182 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1183 tlv_stream.2.payer_id = None;
1185 let mut buffer = Vec::new();
1186 tlv_stream.write(&mut buffer).unwrap();
1188 match InvoiceRequest::try_from(buffer) {
1189 Ok(_) => panic!("expected error"),
1190 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1195 fn fails_parsing_invoice_request_without_node_id() {
1196 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1199 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1201 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1202 tlv_stream.1.node_id = None;
1204 let mut buffer = Vec::new();
1205 tlv_stream.write(&mut buffer).unwrap();
1207 match InvoiceRequest::try_from(buffer) {
1208 Ok(_) => panic!("expected error"),
1210 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1216 fn parses_invoice_request_without_signature() {
1217 let mut buffer = Vec::new();
1218 OfferBuilder::new("foo".into(), recipient_pubkey())
1221 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1224 .write(&mut buffer).unwrap();
1226 if let Err(e) = InvoiceRequest::try_from(buffer) {
1227 panic!("error parsing invoice_request: {:?}", e);
1232 fn fails_parsing_invoice_request_with_invalid_signature() {
1233 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1238 .sign(payer_sign).unwrap();
1239 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1240 *last_signature_byte = last_signature_byte.wrapping_add(1);
1242 let mut buffer = Vec::new();
1243 invoice_request.write(&mut buffer).unwrap();
1245 match InvoiceRequest::try_from(buffer) {
1246 Ok(_) => panic!("expected error"),
1248 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1254 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1255 let secp_ctx = Secp256k1::new();
1256 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1257 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1260 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1262 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1265 let mut encoded_invoice_request = Vec::new();
1266 invoice_request.write(&mut encoded_invoice_request).unwrap();
1267 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1268 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1269 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1271 match InvoiceRequest::try_from(encoded_invoice_request) {
1272 Ok(_) => panic!("expected error"),
1273 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),