1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `invoice_request` messages.
12 //! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
13 //! typically constructed by a customer and sent to the merchant who had published the corresponding
14 //! offer. The recipient of the request responds with an `Invoice`.
16 //! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17 //! precursor, see [`Refund`].
19 //! [`Refund`]: crate::offers::refund::Refund
22 //! extern crate bitcoin;
23 //! extern crate lightning;
25 //! use bitcoin::network::constants::Network;
26 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
27 //! use core::convert::Infallible;
28 //! use lightning::ln::features::OfferFeatures;
29 //! use lightning::offers::offer::Offer;
30 //! use lightning::util::ser::Writeable;
32 //! # fn parse() -> Result<(), lightning::offers::parse::ParseError> {
33 //! let secp_ctx = Secp256k1::new();
34 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
35 //! let pubkey = PublicKey::from(keys);
36 //! let mut buffer = Vec::new();
39 //! .parse::<Offer>()?
40 //! .request_invoice(vec![42; 64], pubkey)?
41 //! .chain(Network::Testnet)?
42 //! .amount_msats(1000)?
44 //! .payer_note("foo".to_string())
46 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
47 //! .expect("failed verifying signature")
48 //! .write(&mut buffer)
54 use bitcoin::blockdata::constants::ChainHash;
55 use bitcoin::network::constants::Network;
56 use bitcoin::secp256k1::{Message, PublicKey};
57 use bitcoin::secp256k1::schnorr::Signature;
58 use core::convert::TryFrom;
60 use crate::ln::features::InvoiceRequestFeatures;
61 use crate::ln::msgs::DecodeError;
62 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, self};
63 use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
64 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
65 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
66 use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
67 use crate::util::string::PrintableString;
69 use crate::prelude::*;
71 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
73 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
75 /// See [module-level documentation] for usage.
77 /// [module-level documentation]: self
78 pub struct InvoiceRequestBuilder<'a> {
80 invoice_request: InvoiceRequestContents,
83 impl<'a> InvoiceRequestBuilder<'a> {
84 pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
87 invoice_request: InvoiceRequestContents {
88 payer: PayerContents(metadata), offer: offer.contents.clone(), chain: None,
89 amount_msats: None, features: InvoiceRequestFeatures::empty(), quantity: None,
90 payer_id, payer_note: None,
95 /// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
96 /// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
99 /// Successive calls to this method will override the previous setting.
100 pub fn chain(mut self, network: Network) -> Result<Self, SemanticError> {
101 let chain = ChainHash::using_genesis_block(network);
102 if !self.offer.supports_chain(chain) {
103 return Err(SemanticError::UnsupportedChain);
106 self.invoice_request.chain = Some(chain);
110 /// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
111 /// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
113 /// Successive calls to this method will override the previous setting.
115 /// [`quantity`]: Self::quantity
116 pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, SemanticError> {
117 self.invoice_request.offer.check_amount_msats_for_quantity(
118 Some(amount_msats), self.invoice_request.quantity
120 self.invoice_request.amount_msats = Some(amount_msats);
124 /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
125 /// does not conform to [`Offer::is_valid_quantity`].
127 /// Successive calls to this method will override the previous setting.
128 pub fn quantity(mut self, quantity: u64) -> Result<Self, SemanticError> {
129 self.invoice_request.offer.check_quantity(Some(quantity))?;
130 self.invoice_request.quantity = Some(quantity);
134 /// Sets the [`InvoiceRequest::payer_note`].
136 /// Successive calls to this method will override the previous setting.
137 pub fn payer_note(mut self, payer_note: String) -> Self {
138 self.invoice_request.payer_note = Some(payer_note);
142 /// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
143 /// by [`UnsignedInvoiceRequest::sign`].
144 pub fn build(mut self) -> Result<UnsignedInvoiceRequest<'a>, SemanticError> {
145 #[cfg(feature = "std")] {
146 if self.offer.is_expired() {
147 return Err(SemanticError::AlreadyExpired);
151 let chain = self.invoice_request.chain();
152 if !self.offer.supports_chain(chain) {
153 return Err(SemanticError::UnsupportedChain);
156 if chain == self.offer.implied_chain() {
157 self.invoice_request.chain = None;
160 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
161 return Err(SemanticError::MissingAmount);
164 self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
165 self.invoice_request.offer.check_amount_msats_for_quantity(
166 self.invoice_request.amount_msats, self.invoice_request.quantity
169 let InvoiceRequestBuilder { offer, invoice_request } = self;
170 Ok(UnsignedInvoiceRequest { offer, invoice_request })
175 impl<'a> InvoiceRequestBuilder<'a> {
176 fn chain_unchecked(mut self, network: Network) -> Self {
177 let chain = ChainHash::using_genesis_block(network);
178 self.invoice_request.chain = Some(chain);
182 fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
183 self.invoice_request.amount_msats = Some(amount_msats);
187 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
188 self.invoice_request.features = features;
192 fn quantity_unchecked(mut self, quantity: u64) -> Self {
193 self.invoice_request.quantity = Some(quantity);
197 pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest<'a> {
198 let InvoiceRequestBuilder { offer, invoice_request } = self;
199 UnsignedInvoiceRequest { offer, invoice_request }
203 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
204 pub struct UnsignedInvoiceRequest<'a> {
206 invoice_request: InvoiceRequestContents,
209 impl<'a> UnsignedInvoiceRequest<'a> {
210 /// Signs the invoice request using the given function.
211 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
213 F: FnOnce(&Message) -> Result<Signature, E>
215 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
216 // unknown TLV records, which are not stored in `OfferContents`.
217 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
218 self.invoice_request.as_tlv_stream();
219 let offer_bytes = WithoutLength(&self.offer.bytes);
220 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
222 let mut bytes = Vec::new();
223 unsigned_tlv_stream.write(&mut bytes).unwrap();
225 let pubkey = self.invoice_request.payer_id;
226 let signature = 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: Some(&signature),
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: Signature,
255 /// The contents of an [`InvoiceRequest`], which may be shared with an `Invoice`.
256 #[derive(Clone, Debug)]
257 pub(super) struct InvoiceRequestContents {
258 payer: PayerContents,
259 offer: OfferContents,
260 chain: Option<ChainHash>,
261 amount_msats: Option<u64>,
262 features: InvoiceRequestFeatures,
263 quantity: Option<u64>,
265 payer_note: Option<String>,
268 impl InvoiceRequest {
269 /// An unpredictable series of bytes, typically containing information about the derivation of
272 /// [`payer_id`]: Self::payer_id
273 pub fn metadata(&self) -> &[u8] {
274 &self.contents.payer.0[..]
277 /// A chain from [`Offer::chains`] that the offer is valid for.
278 pub fn chain(&self) -> ChainHash {
279 self.contents.chain()
282 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
283 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
285 /// [`chain`]: Self::chain
286 pub fn amount_msats(&self) -> Option<u64> {
287 self.contents.amount_msats
290 /// Features pertaining to requesting an invoice.
291 pub fn features(&self) -> &InvoiceRequestFeatures {
292 &self.contents.features
295 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
296 pub fn quantity(&self) -> Option<u64> {
297 self.contents.quantity
300 /// A possibly transient pubkey used to sign the invoice request.
301 pub fn payer_id(&self) -> PublicKey {
302 self.contents.payer_id
305 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
307 pub fn payer_note(&self) -> Option<PrintableString> {
308 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
311 /// Signature of the invoice request using [`payer_id`].
313 /// [`payer_id`]: Self::payer_id
314 pub fn signature(&self) -> 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: Some(&self.signature),
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, WithoutLength)),
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 let signature = match signature {
425 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
426 Some(signature) => signature,
428 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
430 Ok(InvoiceRequest { bytes, contents, signature })
434 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
435 type Error = SemanticError;
437 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
439 PayerTlvStream { metadata },
441 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
444 let payer = match metadata {
445 None => return Err(SemanticError::MissingPayerMetadata),
446 Some(metadata) => PayerContents(metadata),
448 let offer = OfferContents::try_from(offer_tlv_stream)?;
450 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
451 return Err(SemanticError::UnsupportedChain);
454 if offer.amount().is_none() && amount.is_none() {
455 return Err(SemanticError::MissingAmount);
458 offer.check_quantity(quantity)?;
459 offer.check_amount_msats_for_quantity(amount, quantity)?;
461 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
463 let payer_id = match payer_id {
464 None => return Err(SemanticError::MissingPayerId),
465 Some(payer_id) => payer_id,
468 Ok(InvoiceRequestContents {
469 payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
476 use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG};
478 use bitcoin::blockdata::constants::ChainHash;
479 use bitcoin::network::constants::Network;
480 use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, self};
481 use bitcoin::secp256k1::schnorr::Signature;
482 use core::convert::{Infallible, TryFrom};
483 use core::num::NonZeroU64;
484 #[cfg(feature = "std")]
485 use core::time::Duration;
486 use crate::ln::features::InvoiceRequestFeatures;
487 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
488 use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
489 use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
490 use crate::offers::parse::{ParseError, SemanticError};
491 use crate::offers::payer::PayerTlvStreamRef;
492 use crate::util::ser::{BigSize, Writeable};
493 use crate::util::string::PrintableString;
495 fn payer_keys() -> KeyPair {
496 let secp_ctx = Secp256k1::new();
497 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
500 fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
501 let secp_ctx = Secp256k1::new();
502 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
503 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
506 fn payer_pubkey() -> PublicKey {
507 payer_keys().public_key()
510 fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
511 let secp_ctx = Secp256k1::new();
512 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
513 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
516 fn recipient_pubkey() -> PublicKey {
517 let secp_ctx = Secp256k1::new();
518 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap()).public_key()
522 fn builds_invoice_request_with_defaults() {
523 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
526 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
528 .sign(payer_sign).unwrap();
530 let mut buffer = Vec::new();
531 invoice_request.write(&mut buffer).unwrap();
533 assert_eq!(invoice_request.bytes, buffer.as_slice());
534 assert_eq!(invoice_request.metadata(), &[1; 32]);
535 assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
536 assert_eq!(invoice_request.amount_msats(), None);
537 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
538 assert_eq!(invoice_request.quantity(), None);
539 assert_eq!(invoice_request.payer_id(), payer_pubkey());
540 assert_eq!(invoice_request.payer_note(), None);
542 merkle::verify_signature(
543 &invoice_request.signature, SIGNATURE_TAG, &invoice_request.bytes, payer_pubkey()
548 invoice_request.as_tlv_stream(),
550 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
556 description: Some(&String::from("foo")),
558 absolute_expiry: None,
562 node_id: Some(&recipient_pubkey()),
564 InvoiceRequestTlvStreamRef {
569 payer_id: Some(&payer_pubkey()),
572 SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
576 if let Err(e) = InvoiceRequest::try_from(buffer) {
577 panic!("error parsing invoice request: {:?}", e);
581 #[cfg(feature = "std")]
583 fn builds_invoice_request_from_offer_with_expiration() {
584 let future_expiry = Duration::from_secs(u64::max_value());
585 let past_expiry = Duration::from_secs(0);
587 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
589 .absolute_expiry(future_expiry)
591 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
594 panic!("error building invoice_request: {:?}", e);
597 match OfferBuilder::new("foo".into(), recipient_pubkey())
599 .absolute_expiry(past_expiry)
601 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
604 Ok(_) => panic!("expected error"),
605 Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
610 fn builds_invoice_request_with_chain() {
611 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
612 let testnet = ChainHash::using_genesis_block(Network::Testnet);
614 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
617 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
618 .chain(Network::Bitcoin).unwrap()
620 .sign(payer_sign).unwrap();
621 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
622 assert_eq!(invoice_request.chain(), mainnet);
623 assert_eq!(tlv_stream.chain, None);
625 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
627 .chain(Network::Testnet)
629 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
630 .chain(Network::Testnet).unwrap()
632 .sign(payer_sign).unwrap();
633 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
634 assert_eq!(invoice_request.chain(), testnet);
635 assert_eq!(tlv_stream.chain, Some(&testnet));
637 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
639 .chain(Network::Bitcoin)
640 .chain(Network::Testnet)
642 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
643 .chain(Network::Bitcoin).unwrap()
645 .sign(payer_sign).unwrap();
646 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
647 assert_eq!(invoice_request.chain(), mainnet);
648 assert_eq!(tlv_stream.chain, None);
650 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
652 .chain(Network::Bitcoin)
653 .chain(Network::Testnet)
655 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
656 .chain(Network::Bitcoin).unwrap()
657 .chain(Network::Testnet).unwrap()
659 .sign(payer_sign).unwrap();
660 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
661 assert_eq!(invoice_request.chain(), testnet);
662 assert_eq!(tlv_stream.chain, Some(&testnet));
664 match OfferBuilder::new("foo".into(), recipient_pubkey())
666 .chain(Network::Testnet)
668 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
669 .chain(Network::Bitcoin)
671 Ok(_) => panic!("expected error"),
672 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
675 match OfferBuilder::new("foo".into(), recipient_pubkey())
677 .chain(Network::Testnet)
679 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
682 Ok(_) => panic!("expected error"),
683 Err(e) => assert_eq!(e, SemanticError::UnsupportedChain),
688 fn builds_invoice_request_with_amount() {
689 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
692 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
693 .amount_msats(1000).unwrap()
695 .sign(payer_sign).unwrap();
696 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
697 assert_eq!(invoice_request.amount_msats(), Some(1000));
698 assert_eq!(tlv_stream.amount, Some(1000));
700 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
703 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
704 .amount_msats(1001).unwrap()
705 .amount_msats(1000).unwrap()
707 .sign(payer_sign).unwrap();
708 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
709 assert_eq!(invoice_request.amount_msats(), Some(1000));
710 assert_eq!(tlv_stream.amount, Some(1000));
712 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
715 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
716 .amount_msats(1001).unwrap()
718 .sign(payer_sign).unwrap();
719 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
720 assert_eq!(invoice_request.amount_msats(), Some(1001));
721 assert_eq!(tlv_stream.amount, Some(1001));
723 match OfferBuilder::new("foo".into(), recipient_pubkey())
726 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
729 Ok(_) => panic!("expected error"),
730 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
733 match OfferBuilder::new("foo".into(), recipient_pubkey())
735 .supported_quantity(Quantity::Unbounded)
737 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
738 .quantity(2).unwrap()
741 Ok(_) => panic!("expected error"),
742 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
745 match OfferBuilder::new("foo".into(), recipient_pubkey())
748 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
749 .amount_msats(MAX_VALUE_MSAT + 1)
751 Ok(_) => panic!("expected error"),
752 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
755 match OfferBuilder::new("foo".into(), recipient_pubkey())
757 .supported_quantity(Quantity::Unbounded)
759 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
760 .amount_msats(1000).unwrap()
761 .quantity(2).unwrap()
764 Ok(_) => panic!("expected error"),
765 Err(e) => assert_eq!(e, SemanticError::InsufficientAmount),
768 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::MissingAmount),
779 fn builds_invoice_request_with_features() {
780 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
783 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
784 .features_unchecked(InvoiceRequestFeatures::unknown())
786 .sign(payer_sign).unwrap();
787 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
788 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::unknown());
789 assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));
791 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
794 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
795 .features_unchecked(InvoiceRequestFeatures::unknown())
796 .features_unchecked(InvoiceRequestFeatures::empty())
798 .sign(payer_sign).unwrap();
799 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
800 assert_eq!(invoice_request.features(), &InvoiceRequestFeatures::empty());
801 assert_eq!(tlv_stream.features, None);
805 fn builds_invoice_request_with_quantity() {
806 let ten = NonZeroU64::new(10).unwrap();
808 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
810 .supported_quantity(Quantity::one())
812 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
814 .sign(payer_sign).unwrap();
815 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
816 assert_eq!(invoice_request.quantity(), None);
817 assert_eq!(tlv_stream.quantity, None);
819 match OfferBuilder::new("foo".into(), recipient_pubkey())
821 .supported_quantity(Quantity::one())
823 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
824 .amount_msats(2_000).unwrap()
827 Ok(_) => panic!("expected error"),
828 Err(e) => assert_eq!(e, SemanticError::UnexpectedQuantity),
831 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
833 .supported_quantity(Quantity::Bounded(ten))
835 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
836 .amount_msats(10_000).unwrap()
837 .quantity(10).unwrap()
839 .sign(payer_sign).unwrap();
840 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
841 assert_eq!(invoice_request.amount_msats(), Some(10_000));
842 assert_eq!(tlv_stream.amount, Some(10_000));
844 match OfferBuilder::new("foo".into(), recipient_pubkey())
846 .supported_quantity(Quantity::Bounded(ten))
848 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
849 .amount_msats(11_000).unwrap()
852 Ok(_) => panic!("expected error"),
853 Err(e) => assert_eq!(e, SemanticError::InvalidQuantity),
856 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
858 .supported_quantity(Quantity::Unbounded)
860 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
861 .amount_msats(2_000).unwrap()
862 .quantity(2).unwrap()
864 .sign(payer_sign).unwrap();
865 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
866 assert_eq!(invoice_request.amount_msats(), Some(2_000));
867 assert_eq!(tlv_stream.amount, Some(2_000));
869 match OfferBuilder::new("foo".into(), recipient_pubkey())
871 .supported_quantity(Quantity::Unbounded)
873 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
876 Ok(_) => panic!("expected error"),
877 Err(e) => assert_eq!(e, SemanticError::MissingQuantity),
882 fn builds_invoice_request_with_payer_note() {
883 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
886 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
887 .payer_note("bar".into())
889 .sign(payer_sign).unwrap();
890 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
891 assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
892 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
894 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
897 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
898 .payer_note("bar".into())
899 .payer_note("baz".into())
901 .sign(payer_sign).unwrap();
902 let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
903 assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
904 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
908 fn fails_signing_invoice_request() {
909 match OfferBuilder::new("foo".into(), recipient_pubkey())
912 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
916 Ok(_) => panic!("expected error"),
917 Err(e) => assert_eq!(e, SignError::Signing(())),
920 match OfferBuilder::new("foo".into(), recipient_pubkey())
923 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
925 .sign(recipient_sign)
927 Ok(_) => panic!("expected error"),
928 Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
933 fn parses_invoice_request_with_metadata() {
934 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
937 .request_invoice(vec![42; 32], payer_pubkey()).unwrap()
939 .sign(payer_sign).unwrap();
941 let mut buffer = Vec::new();
942 invoice_request.write(&mut buffer).unwrap();
944 if let Err(e) = InvoiceRequest::try_from(buffer) {
945 panic!("error parsing invoice_request: {:?}", e);
950 fn parses_invoice_request_with_chain() {
951 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
954 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
955 .chain(Network::Bitcoin).unwrap()
957 .sign(payer_sign).unwrap();
959 let mut buffer = Vec::new();
960 invoice_request.write(&mut buffer).unwrap();
962 if let Err(e) = InvoiceRequest::try_from(buffer) {
963 panic!("error parsing invoice_request: {:?}", e);
966 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
969 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
970 .chain_unchecked(Network::Testnet)
972 .sign(payer_sign).unwrap();
974 let mut buffer = Vec::new();
975 invoice_request.write(&mut buffer).unwrap();
977 match InvoiceRequest::try_from(buffer) {
978 Ok(_) => panic!("expected error"),
979 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedChain)),
984 fn parses_invoice_request_with_amount() {
985 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
988 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
990 .sign(payer_sign).unwrap();
992 let mut buffer = Vec::new();
993 invoice_request.write(&mut buffer).unwrap();
995 if let Err(e) = InvoiceRequest::try_from(buffer) {
996 panic!("error parsing invoice_request: {:?}", e);
999 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1001 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1002 .amount_msats(1000).unwrap()
1004 .sign(payer_sign).unwrap();
1006 let mut buffer = Vec::new();
1007 invoice_request.write(&mut buffer).unwrap();
1009 if let Err(e) = InvoiceRequest::try_from(buffer) {
1010 panic!("error parsing invoice_request: {:?}", e);
1013 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1015 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1017 .sign(payer_sign).unwrap();
1019 let mut buffer = Vec::new();
1020 invoice_request.write(&mut buffer).unwrap();
1022 match InvoiceRequest::try_from(buffer) {
1023 Ok(_) => panic!("expected error"),
1024 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1027 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1030 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1031 .amount_msats_unchecked(999)
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"),
1040 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InsufficientAmount)),
1043 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1044 .amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
1046 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1048 .sign(payer_sign).unwrap();
1050 let mut buffer = Vec::new();
1051 invoice_request.write(&mut buffer).unwrap();
1053 match InvoiceRequest::try_from(buffer) {
1054 Ok(_) => panic!("expected error"),
1056 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnsupportedCurrency));
1062 fn parses_invoice_request_with_quantity() {
1063 let ten = NonZeroU64::new(10).unwrap();
1065 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1067 .supported_quantity(Quantity::one())
1069 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 .sign(payer_sign).unwrap();
1073 let mut buffer = Vec::new();
1074 invoice_request.write(&mut buffer).unwrap();
1076 if let Err(e) = InvoiceRequest::try_from(buffer) {
1077 panic!("error parsing invoice_request: {:?}", e);
1080 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1082 .supported_quantity(Quantity::one())
1084 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1085 .amount_msats(2_000).unwrap()
1086 .quantity_unchecked(2)
1088 .sign(payer_sign).unwrap();
1090 let mut buffer = Vec::new();
1091 invoice_request.write(&mut buffer).unwrap();
1093 match InvoiceRequest::try_from(buffer) {
1094 Ok(_) => panic!("expected error"),
1096 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1100 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1102 .supported_quantity(Quantity::Bounded(ten))
1104 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1105 .amount_msats(10_000).unwrap()
1106 .quantity(10).unwrap()
1108 .sign(payer_sign).unwrap();
1110 let mut buffer = Vec::new();
1111 invoice_request.write(&mut buffer).unwrap();
1113 if let Err(e) = InvoiceRequest::try_from(buffer) {
1114 panic!("error parsing invoice_request: {:?}", e);
1117 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1119 .supported_quantity(Quantity::Bounded(ten))
1121 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1122 .amount_msats(11_000).unwrap()
1123 .quantity_unchecked(11)
1125 .sign(payer_sign).unwrap();
1127 let mut buffer = Vec::new();
1128 invoice_request.write(&mut buffer).unwrap();
1130 match InvoiceRequest::try_from(buffer) {
1131 Ok(_) => panic!("expected error"),
1132 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity)),
1135 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1137 .supported_quantity(Quantity::Unbounded)
1139 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1140 .amount_msats(2_000).unwrap()
1141 .quantity(2).unwrap()
1143 .sign(payer_sign).unwrap();
1145 let mut buffer = Vec::new();
1146 invoice_request.write(&mut buffer).unwrap();
1148 if let Err(e) = InvoiceRequest::try_from(buffer) {
1149 panic!("error parsing invoice_request: {:?}", e);
1152 let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1154 .supported_quantity(Quantity::Unbounded)
1156 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1158 .sign(payer_sign).unwrap();
1160 let mut buffer = Vec::new();
1161 invoice_request.write(&mut buffer).unwrap();
1163 match InvoiceRequest::try_from(buffer) {
1164 Ok(_) => panic!("expected error"),
1165 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingQuantity)),
1170 fn fails_parsing_invoice_request_without_metadata() {
1171 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1174 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1176 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1177 tlv_stream.0.metadata = None;
1179 let mut buffer = Vec::new();
1180 tlv_stream.write(&mut buffer).unwrap();
1182 match InvoiceRequest::try_from(buffer) {
1183 Ok(_) => panic!("expected error"),
1185 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1191 fn fails_parsing_invoice_request_without_payer_id() {
1192 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1195 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1197 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1198 tlv_stream.2.payer_id = None;
1200 let mut buffer = Vec::new();
1201 tlv_stream.write(&mut buffer).unwrap();
1203 match InvoiceRequest::try_from(buffer) {
1204 Ok(_) => panic!("expected error"),
1205 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId)),
1210 fn fails_parsing_invoice_request_without_node_id() {
1211 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1214 let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1216 let mut tlv_stream = unsigned_invoice_request.invoice_request.as_tlv_stream();
1217 tlv_stream.1.node_id = None;
1219 let mut buffer = Vec::new();
1220 tlv_stream.write(&mut buffer).unwrap();
1222 match InvoiceRequest::try_from(buffer) {
1223 Ok(_) => panic!("expected error"),
1225 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1231 fn fails_parsing_invoice_request_without_signature() {
1232 let mut buffer = Vec::new();
1233 OfferBuilder::new("foo".into(), recipient_pubkey())
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1239 .write(&mut buffer).unwrap();
1241 match InvoiceRequest::try_from(buffer) {
1242 Ok(_) => panic!("expected error"),
1243 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1248 fn fails_parsing_invoice_request_with_invalid_signature() {
1249 let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
1252 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1254 .sign(payer_sign).unwrap();
1255 let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
1256 *last_signature_byte = last_signature_byte.wrapping_add(1);
1258 let mut buffer = Vec::new();
1259 invoice_request.write(&mut buffer).unwrap();
1261 match InvoiceRequest::try_from(buffer) {
1262 Ok(_) => panic!("expected error"),
1264 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1270 fn fails_parsing_invoice_request_with_extra_tlv_records() {
1271 let secp_ctx = Secp256k1::new();
1272 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1273 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
1276 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
1278 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
1281 let mut encoded_invoice_request = Vec::new();
1282 invoice_request.write(&mut encoded_invoice_request).unwrap();
1283 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
1284 BigSize(32).write(&mut encoded_invoice_request).unwrap();
1285 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
1287 match InvoiceRequest::try_from(encoded_invoice_request) {
1288 Ok(_) => panic!("expected error"),
1289 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),