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 })
174 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
175 pub struct UnsignedInvoiceRequest<'a> {
177 invoice_request: InvoiceRequestContents,
180 impl<'a> UnsignedInvoiceRequest<'a> {
181 /// Signs the invoice request using the given function.
182 pub fn sign<F, E>(self, sign: F) -> Result<InvoiceRequest, SignError<E>>
184 F: FnOnce(&Message) -> Result<Signature, E>
186 // Use the offer bytes instead of the offer TLV stream as the offer may have contained
187 // unknown TLV records, which are not stored in `OfferContents`.
188 let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
189 self.invoice_request.as_tlv_stream();
190 let offer_bytes = WithoutLength(&self.offer.bytes);
191 let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);
193 let mut bytes = Vec::new();
194 unsigned_tlv_stream.write(&mut bytes).unwrap();
196 let pubkey = self.invoice_request.payer_id;
197 let signature = Some(merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?);
199 // Append the signature TLV record to the bytes.
200 let signature_tlv_stream = SignatureTlvStreamRef {
201 signature: signature.as_ref(),
203 signature_tlv_stream.write(&mut bytes).unwrap();
207 contents: self.invoice_request,
213 /// An `InvoiceRequest` is a request for an `Invoice` formulated from an [`Offer`].
215 /// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
216 /// specifies these such that its recipient can send an invoice for payment.
218 /// [`Offer`]: crate::offers::offer::Offer
219 #[derive(Clone, Debug)]
220 pub struct InvoiceRequest {
222 contents: InvoiceRequestContents,
223 signature: Option<Signature>,
226 /// The contents of an [`InvoiceRequest`], which may be shared with an `Invoice`.
227 #[derive(Clone, Debug)]
228 pub(super) struct InvoiceRequestContents {
229 payer: PayerContents,
230 offer: OfferContents,
231 chain: Option<ChainHash>,
232 amount_msats: Option<u64>,
233 features: InvoiceRequestFeatures,
234 quantity: Option<u64>,
236 payer_note: Option<String>,
239 impl InvoiceRequest {
240 /// An unpredictable series of bytes, typically containing information about the derivation of
243 /// [`payer_id`]: Self::payer_id
244 pub fn metadata(&self) -> &[u8] {
245 &self.contents.payer.0[..]
248 /// A chain from [`Offer::chains`] that the offer is valid for.
249 pub fn chain(&self) -> ChainHash {
250 self.contents.chain()
253 /// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
254 /// must be greater than or equal to [`Offer::amount`], converted if necessary.
256 /// [`chain`]: Self::chain
257 pub fn amount_msats(&self) -> Option<u64> {
258 self.contents.amount_msats
261 /// Features for paying the invoice.
262 pub fn features(&self) -> &InvoiceRequestFeatures {
263 &self.contents.features
266 /// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
267 pub fn quantity(&self) -> Option<u64> {
268 self.contents.quantity
271 /// A possibly transient pubkey used to sign the invoice request.
272 pub fn payer_id(&self) -> PublicKey {
273 self.contents.payer_id
276 /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
278 pub fn payer_note(&self) -> Option<PrintableString> {
279 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
282 /// Signature of the invoice request using [`payer_id`].
284 /// [`payer_id`]: Self::payer_id
285 pub fn signature(&self) -> Option<Signature> {
290 impl InvoiceRequestContents {
291 fn chain(&self) -> ChainHash {
292 self.chain.unwrap_or_else(|| self.offer.implied_chain())
295 pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
296 let payer = PayerTlvStreamRef {
297 metadata: Some(&self.payer.0),
300 let offer = self.offer.as_tlv_stream();
303 if self.features == InvoiceRequestFeatures::empty() { None }
304 else { Some(&self.features) }
307 let invoice_request = InvoiceRequestTlvStreamRef {
308 chain: self.chain.as_ref(),
309 amount: self.amount_msats,
311 quantity: self.quantity,
312 payer_id: Some(&self.payer_id),
313 payer_note: self.payer_note.as_ref(),
316 (payer, offer, invoice_request)
320 impl Writeable for InvoiceRequest {
321 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
322 WithoutLength(&self.bytes).write(writer)
326 impl Writeable for InvoiceRequestContents {
327 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
328 self.as_tlv_stream().write(writer)
332 tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, 80..160, {
333 (80, chain: ChainHash),
334 (82, amount: (u64, HighZeroBytesDroppedBigSize)),
335 (84, features: InvoiceRequestFeatures),
336 (86, quantity: (u64, HighZeroBytesDroppedBigSize)),
337 (88, payer_id: PublicKey),
338 (89, payer_note: (String, WithoutLength)),
341 type FullInvoiceRequestTlvStream =
342 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
344 impl SeekReadable for FullInvoiceRequestTlvStream {
345 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
346 let payer = SeekReadable::read(r)?;
347 let offer = SeekReadable::read(r)?;
348 let invoice_request = SeekReadable::read(r)?;
349 let signature = SeekReadable::read(r)?;
351 Ok((payer, offer, invoice_request, signature))
355 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
357 type PartialInvoiceRequestTlvStreamRef<'a> = (
358 PayerTlvStreamRef<'a>,
359 OfferTlvStreamRef<'a>,
360 InvoiceRequestTlvStreamRef<'a>,
363 impl TryFrom<Vec<u8>> for InvoiceRequest {
364 type Error = ParseError;
366 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
367 let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
368 let ParsedMessage { bytes, tlv_stream } = invoice_request;
370 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
371 SignatureTlvStream { signature },
373 let contents = InvoiceRequestContents::try_from(
374 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
377 if let Some(signature) = &signature {
378 merkle::verify_signature(signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
381 Ok(InvoiceRequest { bytes, contents, signature })
385 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
386 type Error = SemanticError;
388 fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
390 PayerTlvStream { metadata },
392 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
395 let payer = match metadata {
396 None => return Err(SemanticError::MissingPayerMetadata),
397 Some(metadata) => PayerContents(metadata),
399 let offer = OfferContents::try_from(offer_tlv_stream)?;
401 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
402 return Err(SemanticError::UnsupportedChain);
405 if offer.amount().is_none() && amount.is_none() {
406 return Err(SemanticError::MissingAmount);
409 offer.check_quantity(quantity)?;
410 offer.check_amount_msats_for_quantity(amount, quantity)?;
412 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
414 let payer_id = match payer_id {
415 None => return Err(SemanticError::MissingPayerId),
416 Some(payer_id) => payer_id,
419 Ok(InvoiceRequestContents {
420 payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
427 use super::InvoiceRequest;
429 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
430 use core::convert::{Infallible, TryFrom};
431 use crate::ln::msgs::DecodeError;
432 use crate::offers::offer::OfferBuilder;
433 use crate::offers::parse::ParseError;
434 use crate::util::ser::{BigSize, Writeable};
437 fn fails_parsing_invoice_request_with_extra_tlv_records() {
438 let secp_ctx = Secp256k1::new();
439 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
440 let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
443 .request_invoice(vec![1; 32], keys.public_key()).unwrap()
445 .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
448 let mut encoded_invoice_request = Vec::new();
449 invoice_request.write(&mut encoded_invoice_request).unwrap();
450 BigSize(1002).write(&mut encoded_invoice_request).unwrap();
451 BigSize(32).write(&mut encoded_invoice_request).unwrap();
452 [42u8; 32].write(&mut encoded_invoice_request).unwrap();
454 match InvoiceRequest::try_from(encoded_invoice_request) {
455 Ok(_) => panic!("expected error"),
456 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),