Builder for creating invoice requests
[rust-lightning] / lightning / src / offers / invoice_request.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Data structures and encoding for `invoice_request` messages.
11 //!
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.
17 //!
18 //! The recipient of the request responds with an `Invoice`.
19 //!
20 //! ```ignore
21 //! extern crate bitcoin;
22 //! extern crate lightning;
23 //!
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;
30 //!
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();
36 //!
37 //! // "offer to be paid" flow
38 //! "lno1qcp4256ypq"
39 //!     .parse::<Offer>()?
40 //!     .request_invoice(vec![42; 64], pubkey)?
41 //!     .chain(Network::Testnet)?
42 //!     .amount_msats(1000)?
43 //!     .quantity(5)?
44 //!     .payer_note("foo".to_string())
45 //!     .build()?
46 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
47 //!     .expect("failed verifying signature")
48 //!     .write(&mut buffer)
49 //!     .unwrap();
50 //! # Ok(())
51 //! # }
52 //! ```
53
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;
59 use crate::io;
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;
68
69 use crate::prelude::*;
70
71 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");
72
73 /// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
74 ///
75 /// See [module-level documentation] for usage.
76 ///
77 /// [module-level documentation]: self
78 pub struct InvoiceRequestBuilder<'a> {
79         offer: &'a Offer,
80         invoice_request: InvoiceRequestContents,
81 }
82
83 impl<'a> InvoiceRequestBuilder<'a> {
84         pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
85                 Self {
86                         offer,
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,
91                         },
92                 }
93         }
94
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
97         /// by the offer.
98         ///
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);
104                 }
105
106                 self.invoice_request.chain = Some(chain);
107                 Ok(self)
108         }
109
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`]).
112         ///
113         /// Successive calls to this method will override the previous setting.
114         ///
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
119                 )?;
120                 self.invoice_request.amount_msats = Some(amount_msats);
121                 Ok(self)
122         }
123
124         /// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
125         /// does not conform to [`Offer::is_valid_quantity`].
126         ///
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);
131                 Ok(self)
132         }
133
134         /// Sets the [`InvoiceRequest::payer_note`].
135         ///
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);
139                 self
140         }
141
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);
148                         }
149                 }
150
151                 let chain = self.invoice_request.chain();
152                 if !self.offer.supports_chain(chain) {
153                         return Err(SemanticError::UnsupportedChain);
154                 }
155
156                 if chain == self.offer.implied_chain() {
157                         self.invoice_request.chain = None;
158                 }
159
160                 if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
161                         return Err(SemanticError::MissingAmount);
162                 }
163
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
167                 )?;
168
169                 let InvoiceRequestBuilder { offer, invoice_request } = self;
170                 Ok(UnsignedInvoiceRequest { offer, invoice_request })
171         }
172 }
173
174 /// A semantically valid [`InvoiceRequest`] that hasn't been signed.
175 pub struct UnsignedInvoiceRequest<'a> {
176         offer: &'a Offer,
177         invoice_request: InvoiceRequestContents,
178 }
179
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>>
183         where
184                 F: FnOnce(&Message) -> Result<Signature, E>
185         {
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);
192
193                 let mut bytes = Vec::new();
194                 unsigned_tlv_stream.write(&mut bytes).unwrap();
195
196                 let pubkey = self.invoice_request.payer_id;
197                 let signature = Some(merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?);
198
199                 // Append the signature TLV record to the bytes.
200                 let signature_tlv_stream = SignatureTlvStreamRef {
201                         signature: signature.as_ref(),
202                 };
203                 signature_tlv_stream.write(&mut bytes).unwrap();
204
205                 Ok(InvoiceRequest {
206                         bytes,
207                         contents: self.invoice_request,
208                         signature,
209                 })
210         }
211 }
212
213 /// An `InvoiceRequest` is a request for an `Invoice` formulated from an [`Offer`].
214 ///
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.
217 ///
218 /// [`Offer`]: crate::offers::offer::Offer
219 #[derive(Clone, Debug)]
220 pub struct InvoiceRequest {
221         bytes: Vec<u8>,
222         contents: InvoiceRequestContents,
223         signature: Option<Signature>,
224 }
225
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>,
235         payer_id: PublicKey,
236         payer_note: Option<String>,
237 }
238
239 impl InvoiceRequest {
240         /// An unpredictable series of bytes, typically containing information about the derivation of
241         /// [`payer_id`].
242         ///
243         /// [`payer_id`]: Self::payer_id
244         pub fn metadata(&self) -> &[u8] {
245                 &self.contents.payer.0[..]
246         }
247
248         /// A chain from [`Offer::chains`] that the offer is valid for.
249         pub fn chain(&self) -> ChainHash {
250                 self.contents.chain()
251         }
252
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.
255         ///
256         /// [`chain`]: Self::chain
257         pub fn amount_msats(&self) -> Option<u64> {
258                 self.contents.amount_msats
259         }
260
261         /// Features for paying the invoice.
262         pub fn features(&self) -> &InvoiceRequestFeatures {
263                 &self.contents.features
264         }
265
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
269         }
270
271         /// A possibly transient pubkey used to sign the invoice request.
272         pub fn payer_id(&self) -> PublicKey {
273                 self.contents.payer_id
274         }
275
276         /// A payer-provided note which will be seen by the recipient and reflected back in the invoice
277         /// response.
278         pub fn payer_note(&self) -> Option<PrintableString> {
279                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
280         }
281
282         /// Signature of the invoice request using [`payer_id`].
283         ///
284         /// [`payer_id`]: Self::payer_id
285         pub fn signature(&self) -> Option<Signature> {
286                 self.signature
287         }
288 }
289
290 impl InvoiceRequestContents {
291         fn chain(&self) -> ChainHash {
292                 self.chain.unwrap_or_else(|| self.offer.implied_chain())
293         }
294
295         pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
296                 let payer = PayerTlvStreamRef {
297                         metadata: Some(&self.payer.0),
298                 };
299
300                 let offer = self.offer.as_tlv_stream();
301
302                 let features = {
303                         if self.features == InvoiceRequestFeatures::empty() { None }
304                         else { Some(&self.features) }
305                 };
306
307                 let invoice_request = InvoiceRequestTlvStreamRef {
308                         chain: self.chain.as_ref(),
309                         amount: self.amount_msats,
310                         features,
311                         quantity: self.quantity,
312                         payer_id: Some(&self.payer_id),
313                         payer_note: self.payer_note.as_ref(),
314                 };
315
316                 (payer, offer, invoice_request)
317         }
318 }
319
320 impl Writeable for InvoiceRequest {
321         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
322                 WithoutLength(&self.bytes).write(writer)
323         }
324 }
325
326 impl Writeable for InvoiceRequestContents {
327         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
328                 self.as_tlv_stream().write(writer)
329         }
330 }
331
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)),
339 });
340
341 type FullInvoiceRequestTlvStream =
342         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);
343
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)?;
350
351                 Ok((payer, offer, invoice_request, signature))
352         }
353 }
354
355 type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
356
357 type PartialInvoiceRequestTlvStreamRef<'a> = (
358         PayerTlvStreamRef<'a>,
359         OfferTlvStreamRef<'a>,
360         InvoiceRequestTlvStreamRef<'a>,
361 );
362
363 impl TryFrom<Vec<u8>> for InvoiceRequest {
364         type Error = ParseError;
365
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;
369                 let (
370                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
371                         SignatureTlvStream { signature },
372                 ) = tlv_stream;
373                 let contents = InvoiceRequestContents::try_from(
374                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
375                 )?;
376
377                 if let Some(signature) = &signature {
378                         merkle::verify_signature(signature, SIGNATURE_TAG, &bytes, contents.payer_id)?;
379                 }
380
381                 Ok(InvoiceRequest { bytes, contents, signature })
382         }
383 }
384
385 impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
386         type Error = SemanticError;
387
388         fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
389                 let (
390                         PayerTlvStream { metadata },
391                         offer_tlv_stream,
392                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
393                 ) = tlv_stream;
394
395                 let payer = match metadata {
396                         None => return Err(SemanticError::MissingPayerMetadata),
397                         Some(metadata) => PayerContents(metadata),
398                 };
399                 let offer = OfferContents::try_from(offer_tlv_stream)?;
400
401                 if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
402                         return Err(SemanticError::UnsupportedChain);
403                 }
404
405                 if offer.amount().is_none() && amount.is_none() {
406                         return Err(SemanticError::MissingAmount);
407                 }
408
409                 offer.check_quantity(quantity)?;
410                 offer.check_amount_msats_for_quantity(amount, quantity)?;
411
412                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
413
414                 let payer_id = match payer_id {
415                         None => return Err(SemanticError::MissingPayerId),
416                         Some(payer_id) => payer_id,
417                 };
418
419                 Ok(InvoiceRequestContents {
420                         payer, offer, chain, amount_msats: amount, features, quantity, payer_id, payer_note,
421                 })
422         }
423 }
424
425 #[cfg(test)]
426 mod tests {
427         use super::InvoiceRequest;
428
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};
435
436         #[test]
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())
441                         .amount_msats(1000)
442                         .build().unwrap()
443                         .request_invoice(vec![1; 32], keys.public_key()).unwrap()
444                         .build().unwrap()
445                         .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
446                         .unwrap();
447
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();
453
454                 match InvoiceRequest::try_from(encoded_invoice_request) {
455                         Ok(_) => panic!("expected error"),
456                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
457                 }
458         }
459 }