Offer metadata and signing pubkey derivation
[rust-lightning] / lightning / src / offers / invoice.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` messages.
11 //!
12 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! the invoice to the intended payer, who will then pay it.
15 //!
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
18 //!
19 //! ```
20 //! extern crate bitcoin;
21 //! extern crate lightning;
22 //!
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
29 //!
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::onion_message::BlindedPath;
33 //! #
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
36 //! #
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
45 //!
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49     .respond_with(payment_paths, payment_hash)?
50 ")]
51 #![cfg_attr(not(feature = "std"), doc = "
52     .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
53 ")]
54 //!     .relative_expiry(3600)
55 //!     .allow_mpp()
56 //!     .fallback_v0_p2wpkh(&wpubkey_hash)
57 //!     .build()?
58 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //!     .expect("failed verifying signature")
60 //!     .write(&mut buffer)
61 //!     .unwrap();
62 //! # Ok(())
63 //! # }
64 //!
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
73 //!
74 //! // Invoice for the "offer for money" flow.
75 //! "lnr1qcp4256ypq"
76 //!     .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78     .respond_with(payment_paths, payment_hash, pubkey)?
79 ")]
80 #![cfg_attr(not(feature = "std"), doc = "
81     .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
82 ")]
83 //!     .relative_expiry(3600)
84 //!     .allow_mpp()
85 //!     .fallback_v0_p2wpkh(&wpubkey_hash)
86 //!     .build()?
87 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //!     .expect("failed verifying signature")
89 //!     .write(&mut buffer)
90 //!     .unwrap();
91 //! # Ok(())
92 //! # }
93 //!
94 //! ```
95
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{Message, PublicKey};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::TryFrom;
105 use core::time::Duration;
106 use crate::io;
107 use crate::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
118
119 use crate::prelude::*;
120
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
123
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
125
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
127
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
131 ///
132 /// See [module-level documentation] for usage.
133 ///
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138         invreq_bytes: &'a Vec<u8>,
139         invoice: InvoiceContents,
140 }
141
142 impl<'a> InvoiceBuilder<'a> {
143         pub(super) fn for_offer(
144                 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145                 created_at: Duration, payment_hash: PaymentHash
146         ) -> Result<Self, SemanticError> {
147                 let amount_msats = match invoice_request.amount_msats() {
148                         Some(amount_msats) => amount_msats,
149                         None => match invoice_request.contents.offer.amount() {
150                                 Some(Amount::Bitcoin { amount_msats }) => {
151                                         amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
152                                                 .ok_or(SemanticError::InvalidAmount)?
153                                 },
154                                 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
155                                 None => return Err(SemanticError::MissingAmount),
156                         },
157                 };
158
159                 let contents = InvoiceContents::ForOffer {
160                         invoice_request: invoice_request.contents.clone(),
161                         fields: InvoiceFields {
162                                 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
163                                 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
164                                 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
165                         },
166                 };
167
168                 Self::new(&invoice_request.bytes, contents)
169         }
170
171         pub(super) fn for_refund(
172                 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
173                 payment_hash: PaymentHash, signing_pubkey: PublicKey
174         ) -> Result<Self, SemanticError> {
175                 let contents = InvoiceContents::ForRefund {
176                         refund: refund.contents.clone(),
177                         fields: InvoiceFields {
178                                 payment_paths, created_at, relative_expiry: None, payment_hash,
179                                 amount_msats: refund.amount_msats(), fallbacks: None,
180                                 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
181                         },
182                 };
183
184                 Self::new(&refund.bytes, contents)
185         }
186
187         fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
188                 if contents.fields().payment_paths.is_empty() {
189                         return Err(SemanticError::MissingPaths);
190                 }
191
192                 Ok(Self { invreq_bytes, invoice: contents })
193         }
194
195         /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
196         /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
197         ///
198         /// Successive calls to this method will override the previous setting.
199         pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
200                 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
201                 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
202                 self
203         }
204
205         /// Adds a P2WSH address to [`Invoice::fallbacks`].
206         ///
207         /// Successive calls to this method will add another address. Caller is responsible for not
208         /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
209         pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
210                 let address = FallbackAddress {
211                         version: WitnessVersion::V0.to_num(),
212                         program: Vec::from(&script_hash.into_inner()[..]),
213                 };
214                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
215                 self
216         }
217
218         /// Adds a P2WPKH address to [`Invoice::fallbacks`].
219         ///
220         /// Successive calls to this method will add another address. Caller is responsible for not
221         /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
222         pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
223                 let address = FallbackAddress {
224                         version: WitnessVersion::V0.to_num(),
225                         program: Vec::from(&pubkey_hash.into_inner()[..]),
226                 };
227                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
228                 self
229         }
230
231         /// Adds a P2TR address to [`Invoice::fallbacks`].
232         ///
233         /// Successive calls to this method will add another address. Caller is responsible for not
234         /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
235         pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
236                 let address = FallbackAddress {
237                         version: WitnessVersion::V1.to_num(),
238                         program: Vec::from(&output_key.serialize()[..]),
239                 };
240                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
241                 self
242         }
243
244         /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
245         pub fn allow_mpp(mut self) -> Self {
246                 self.invoice.fields_mut().features.set_basic_mpp_optional();
247                 self
248         }
249
250         /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
251         /// [`UnsignedInvoice::sign`].
252         pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
253                 #[cfg(feature = "std")] {
254                         if self.invoice.is_offer_or_refund_expired() {
255                                 return Err(SemanticError::AlreadyExpired);
256                         }
257                 }
258
259                 let InvoiceBuilder { invreq_bytes, invoice } = self;
260                 Ok(UnsignedInvoice { invreq_bytes, invoice })
261         }
262 }
263
264 /// A semantically valid [`Invoice`] that hasn't been signed.
265 pub struct UnsignedInvoice<'a> {
266         invreq_bytes: &'a Vec<u8>,
267         invoice: InvoiceContents,
268 }
269
270 impl<'a> UnsignedInvoice<'a> {
271         /// The public key corresponding to the key needed to sign the invoice.
272         pub fn signing_pubkey(&self) -> PublicKey {
273                 self.invoice.fields().signing_pubkey
274         }
275
276         /// Signs the invoice using the given function.
277         pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
278         where
279                 F: FnOnce(&Message) -> Result<Signature, E>
280         {
281                 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
282                 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
283                 // `RefundContents`.
284                 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
285                 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
286                 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
287
288                 let mut bytes = Vec::new();
289                 unsigned_tlv_stream.write(&mut bytes).unwrap();
290
291                 let pubkey = self.invoice.fields().signing_pubkey;
292                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
293
294                 // Append the signature TLV record to the bytes.
295                 let signature_tlv_stream = SignatureTlvStreamRef {
296                         signature: Some(&signature),
297                 };
298                 signature_tlv_stream.write(&mut bytes).unwrap();
299
300                 Ok(Invoice {
301                         bytes,
302                         contents: self.invoice,
303                         signature,
304                 })
305         }
306 }
307
308 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
309 ///
310 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
311 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
312 ///
313 /// [`Offer`]: crate::offers::offer::Offer
314 /// [`Refund`]: crate::offers::refund::Refund
315 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
316 #[derive(Clone, Debug)]
317 #[cfg_attr(test, derive(PartialEq))]
318 pub struct Invoice {
319         bytes: Vec<u8>,
320         contents: InvoiceContents,
321         signature: Signature,
322 }
323
324 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
325 ///
326 /// [`Offer`]: crate::offers::offer::Offer
327 /// [`Refund`]: crate::offers::refund::Refund
328 #[derive(Clone, Debug)]
329 #[cfg_attr(test, derive(PartialEq))]
330 enum InvoiceContents {
331         /// Contents for an [`Invoice`] corresponding to an [`Offer`].
332         ///
333         /// [`Offer`]: crate::offers::offer::Offer
334         ForOffer {
335                 invoice_request: InvoiceRequestContents,
336                 fields: InvoiceFields,
337         },
338         /// Contents for an [`Invoice`] corresponding to a [`Refund`].
339         ///
340         /// [`Refund`]: crate::offers::refund::Refund
341         ForRefund {
342                 refund: RefundContents,
343                 fields: InvoiceFields,
344         },
345 }
346
347 /// Invoice-specific fields for an `invoice` message.
348 #[derive(Clone, Debug, PartialEq)]
349 struct InvoiceFields {
350         payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
351         created_at: Duration,
352         relative_expiry: Option<Duration>,
353         payment_hash: PaymentHash,
354         amount_msats: u64,
355         fallbacks: Option<Vec<FallbackAddress>>,
356         features: Bolt12InvoiceFeatures,
357         signing_pubkey: PublicKey,
358 }
359
360 impl Invoice {
361         /// Paths to the recipient originating from publicly reachable nodes, including information
362         /// needed for routing payments across them.
363         ///
364         /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
365         /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
366         pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
367                 &self.contents.fields().payment_paths[..]
368         }
369
370         /// Duration since the Unix epoch when the invoice was created.
371         pub fn created_at(&self) -> Duration {
372                 self.contents.fields().created_at
373         }
374
375         /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
376         /// longer be paid.
377         pub fn relative_expiry(&self) -> Duration {
378                 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
379         }
380
381         /// Whether the invoice has expired.
382         #[cfg(feature = "std")]
383         pub fn is_expired(&self) -> bool {
384                 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
385                 match absolute_expiry {
386                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
387                                 Ok(elapsed) => elapsed > seconds_from_epoch,
388                                 Err(_) => false,
389                         },
390                         None => false,
391                 }
392         }
393
394         /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
395         pub fn payment_hash(&self) -> PaymentHash {
396                 self.contents.fields().payment_hash
397         }
398
399         /// The minimum amount required for a successful payment of the invoice.
400         pub fn amount_msats(&self) -> u64 {
401                 self.contents.fields().amount_msats
402         }
403
404         /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
405         /// least-preferred.
406         pub fn fallbacks(&self) -> Vec<Address> {
407                 let network = match self.network() {
408                         None => return Vec::new(),
409                         Some(network) => network,
410                 };
411
412                 let to_valid_address = |address: &FallbackAddress| {
413                         let version = match WitnessVersion::try_from(address.version) {
414                                 Ok(version) => version,
415                                 Err(_) => return None,
416                         };
417
418                         let program = &address.program;
419                         if program.len() < 2 || program.len() > 40 {
420                                 return None;
421                         }
422
423                         let address = Address {
424                                 payload: Payload::WitnessProgram {
425                                         version,
426                                         program: address.program.clone(),
427                                 },
428                                 network,
429                         };
430
431                         if !address.is_standard() && version == WitnessVersion::V0 {
432                                 return None;
433                         }
434
435                         Some(address)
436                 };
437
438                 self.contents.fields().fallbacks
439                         .as_ref()
440                         .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
441                         .unwrap_or_else(Vec::new)
442         }
443
444         fn network(&self) -> Option<Network> {
445                 let chain = self.contents.chain();
446                 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
447                         Some(Network::Bitcoin)
448                 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
449                         Some(Network::Testnet)
450                 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
451                         Some(Network::Signet)
452                 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
453                         Some(Network::Regtest)
454                 } else {
455                         None
456                 }
457         }
458
459         /// Features pertaining to paying an invoice.
460         pub fn features(&self) -> &Bolt12InvoiceFeatures {
461                 &self.contents.fields().features
462         }
463
464         /// The public key corresponding to the key used to sign the invoice.
465         pub fn signing_pubkey(&self) -> PublicKey {
466                 self.contents.fields().signing_pubkey
467         }
468
469         /// Signature of the invoice verified using [`Invoice::signing_pubkey`].
470         pub fn signature(&self) -> Signature {
471                 self.signature
472         }
473
474         /// Hash that was used for signing the invoice.
475         pub fn signable_hash(&self) -> [u8; 32] {
476                 merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
477         }
478
479         #[cfg(test)]
480         fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
481                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
482                         self.contents.as_tlv_stream();
483                 let signature_tlv_stream = SignatureTlvStreamRef {
484                         signature: Some(&self.signature),
485                 };
486                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
487                  signature_tlv_stream)
488         }
489 }
490
491 impl InvoiceContents {
492         /// Whether the original offer or refund has expired.
493         #[cfg(feature = "std")]
494         fn is_offer_or_refund_expired(&self) -> bool {
495                 match self {
496                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
497                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
498                 }
499         }
500
501         fn chain(&self) -> ChainHash {
502                 match self {
503                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
504                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
505                 }
506         }
507
508         fn fields(&self) -> &InvoiceFields {
509                 match self {
510                         InvoiceContents::ForOffer { fields, .. } => fields,
511                         InvoiceContents::ForRefund { fields, .. } => fields,
512                 }
513         }
514
515         fn fields_mut(&mut self) -> &mut InvoiceFields {
516                 match self {
517                         InvoiceContents::ForOffer { fields, .. } => fields,
518                         InvoiceContents::ForRefund { fields, .. } => fields,
519                 }
520         }
521
522         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
523                 let (payer, offer, invoice_request) = match self {
524                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
525                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
526                 };
527                 let invoice = self.fields().as_tlv_stream();
528
529                 (payer, offer, invoice_request, invoice)
530         }
531 }
532
533 impl InvoiceFields {
534         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
535                 let features = {
536                         if self.features == Bolt12InvoiceFeatures::empty() { None }
537                         else { Some(&self.features) }
538                 };
539
540                 InvoiceTlvStreamRef {
541                         paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
542                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
543                         created_at: Some(self.created_at.as_secs()),
544                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
545                         payment_hash: Some(&self.payment_hash),
546                         amount: Some(self.amount_msats),
547                         fallbacks: self.fallbacks.as_ref(),
548                         features,
549                         node_id: Some(&self.signing_pubkey),
550                 }
551         }
552 }
553
554 impl Writeable for Invoice {
555         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
556                 WithoutLength(&self.bytes).write(writer)
557         }
558 }
559
560 impl Writeable for InvoiceContents {
561         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
562                 self.as_tlv_stream().write(writer)
563         }
564 }
565
566 impl TryFrom<Vec<u8>> for Invoice {
567         type Error = ParseError;
568
569         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
570                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
571                 Invoice::try_from(parsed_invoice)
572         }
573 }
574
575 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
576         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
577         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
578         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
579         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
580         (168, payment_hash: PaymentHash),
581         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
582         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
583         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
584         (176, node_id: PublicKey),
585 });
586
587 type BlindedPathIter<'a> = core::iter::Map<
588         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
589         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
590 >;
591
592 type BlindedPayInfoIter<'a> = core::iter::Map<
593         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
594         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
595 >;
596
597 /// Information needed to route a payment across a [`BlindedPath`].
598 #[derive(Clone, Debug, PartialEq)]
599 pub struct BlindedPayInfo {
600         /// Base fee charged (in millisatoshi) for the entire blinded path.
601         pub fee_base_msat: u32,
602
603         /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
604         /// (i.e., 10,000 is 1%).
605         pub fee_proportional_millionths: u32,
606
607         /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
608         /// path.
609         pub cltv_expiry_delta: u16,
610
611         /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
612         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
613         /// seen by the recipient.
614         pub htlc_minimum_msat: u64,
615
616         /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
617         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
618         /// seen by the recipient.
619         pub htlc_maximum_msat: u64,
620
621         /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
622         /// onion payload.
623         pub features: BlindedHopFeatures,
624 }
625
626 impl_writeable!(BlindedPayInfo, {
627         fee_base_msat,
628         fee_proportional_millionths,
629         cltv_expiry_delta,
630         htlc_minimum_msat,
631         htlc_maximum_msat,
632         features
633 });
634
635 /// Wire representation for an on-chain fallback address.
636 #[derive(Clone, Debug, PartialEq)]
637 pub(super) struct FallbackAddress {
638         version: u8,
639         program: Vec<u8>,
640 }
641
642 impl_writeable!(FallbackAddress, { version, program });
643
644 type FullInvoiceTlvStream =
645         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
646
647 #[cfg(test)]
648 type FullInvoiceTlvStreamRef<'a> = (
649         PayerTlvStreamRef<'a>,
650         OfferTlvStreamRef<'a>,
651         InvoiceRequestTlvStreamRef<'a>,
652         InvoiceTlvStreamRef<'a>,
653         SignatureTlvStreamRef<'a>,
654 );
655
656 impl SeekReadable for FullInvoiceTlvStream {
657         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
658                 let payer = SeekReadable::read(r)?;
659                 let offer = SeekReadable::read(r)?;
660                 let invoice_request = SeekReadable::read(r)?;
661                 let invoice = SeekReadable::read(r)?;
662                 let signature = SeekReadable::read(r)?;
663
664                 Ok((payer, offer, invoice_request, invoice, signature))
665         }
666 }
667
668 type PartialInvoiceTlvStream =
669         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
670
671 type PartialInvoiceTlvStreamRef<'a> = (
672         PayerTlvStreamRef<'a>,
673         OfferTlvStreamRef<'a>,
674         InvoiceRequestTlvStreamRef<'a>,
675         InvoiceTlvStreamRef<'a>,
676 );
677
678 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
679         type Error = ParseError;
680
681         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
682                 let ParsedMessage { bytes, tlv_stream } = invoice;
683                 let (
684                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
685                         SignatureTlvStream { signature },
686                 ) = tlv_stream;
687                 let contents = InvoiceContents::try_from(
688                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
689                 )?;
690
691                 let signature = match signature {
692                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
693                         Some(signature) => signature,
694                 };
695                 let pubkey = contents.fields().signing_pubkey;
696                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
697
698                 Ok(Invoice { bytes, contents, signature })
699         }
700 }
701
702 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
703         type Error = SemanticError;
704
705         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
706                 let (
707                         payer_tlv_stream,
708                         offer_tlv_stream,
709                         invoice_request_tlv_stream,
710                         InvoiceTlvStream {
711                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
712                                 features, node_id,
713                         },
714                 ) = tlv_stream;
715
716                 let payment_paths = match (paths, blindedpay) {
717                         (None, _) => return Err(SemanticError::MissingPaths),
718                         (_, None) => return Err(SemanticError::InvalidPayInfo),
719                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
720                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
721                                 return Err(SemanticError::InvalidPayInfo);
722                         },
723                         (Some(paths), Some(blindedpay)) => {
724                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
725                         },
726                 };
727
728                 let created_at = match created_at {
729                         None => return Err(SemanticError::MissingCreationTime),
730                         Some(timestamp) => Duration::from_secs(timestamp),
731                 };
732
733                 let relative_expiry = relative_expiry
734                         .map(Into::<u64>::into)
735                         .map(Duration::from_secs);
736
737                 let payment_hash = match payment_hash {
738                         None => return Err(SemanticError::MissingPaymentHash),
739                         Some(payment_hash) => payment_hash,
740                 };
741
742                 let amount_msats = match amount {
743                         None => return Err(SemanticError::MissingAmount),
744                         Some(amount) => amount,
745                 };
746
747                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
748
749                 let signing_pubkey = match node_id {
750                         None => return Err(SemanticError::MissingSigningPubkey),
751                         Some(node_id) => node_id,
752                 };
753
754                 let fields = InvoiceFields {
755                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
756                         features, signing_pubkey,
757                 };
758
759                 match offer_tlv_stream.node_id {
760                         Some(expected_signing_pubkey) => {
761                                 if fields.signing_pubkey != expected_signing_pubkey {
762                                         return Err(SemanticError::InvalidSigningPubkey);
763                                 }
764
765                                 let invoice_request = InvoiceRequestContents::try_from(
766                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
767                                 )?;
768                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
769                         },
770                         None => {
771                                 let refund = RefundContents::try_from(
772                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
773                                 )?;
774                                 Ok(InvoiceContents::ForRefund { refund, fields })
775                         },
776                 }
777         }
778 }
779
780 #[cfg(test)]
781 mod tests {
782         use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
783
784         use bitcoin::blockdata::script::Script;
785         use bitcoin::hashes::Hash;
786         use bitcoin::network::constants::Network;
787         use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
788         use bitcoin::util::address::{Address, Payload, WitnessVersion};
789         use bitcoin::util::schnorr::TweakedPublicKey;
790         use core::convert::TryFrom;
791         use core::time::Duration;
792         use crate::ln::msgs::DecodeError;
793         use crate::ln::features::Bolt12InvoiceFeatures;
794         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
795         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
796         use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
797         use crate::offers::parse::{ParseError, SemanticError};
798         use crate::offers::payer::PayerTlvStreamRef;
799         use crate::offers::refund::RefundBuilder;
800         use crate::offers::test_utils::*;
801         use crate::util::ser::{BigSize, Iterable, Writeable};
802
803         trait ToBytes {
804                 fn to_bytes(&self) -> Vec<u8>;
805         }
806
807         impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
808                 fn to_bytes(&self) -> Vec<u8> {
809                         let mut buffer = Vec::new();
810                         self.0.write(&mut buffer).unwrap();
811                         self.1.write(&mut buffer).unwrap();
812                         self.2.write(&mut buffer).unwrap();
813                         self.3.write(&mut buffer).unwrap();
814                         self.4.write(&mut buffer).unwrap();
815                         buffer
816                 }
817         }
818
819         #[test]
820         fn builds_invoice_for_offer_with_defaults() {
821                 let payment_paths = payment_paths();
822                 let payment_hash = payment_hash();
823                 let now = now();
824                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
825                         .amount_msats(1000)
826                         .build().unwrap()
827                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
828                         .build().unwrap()
829                         .sign(payer_sign).unwrap()
830                         .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
831                         .build().unwrap()
832                         .sign(recipient_sign).unwrap();
833
834                 let mut buffer = Vec::new();
835                 invoice.write(&mut buffer).unwrap();
836
837                 assert_eq!(invoice.bytes, buffer.as_slice());
838                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
839                 assert_eq!(invoice.created_at(), now);
840                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
841                 #[cfg(feature = "std")]
842                 assert!(!invoice.is_expired());
843                 assert_eq!(invoice.payment_hash(), payment_hash);
844                 assert_eq!(invoice.amount_msats(), 1000);
845                 assert_eq!(invoice.fallbacks(), vec![]);
846                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
847                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
848                 assert!(
849                         merkle::verify_signature(
850                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
851                         ).is_ok()
852                 );
853
854                 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
855                 let pubkey = recipient_pubkey().into();
856                 let secp_ctx = Secp256k1::verification_only();
857                 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
858
859                 assert_eq!(
860                         invoice.as_tlv_stream(),
861                         (
862                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
863                                 OfferTlvStreamRef {
864                                         chains: None,
865                                         metadata: None,
866                                         currency: None,
867                                         amount: Some(1000),
868                                         description: Some(&String::from("foo")),
869                                         features: None,
870                                         absolute_expiry: None,
871                                         paths: None,
872                                         issuer: None,
873                                         quantity_max: None,
874                                         node_id: Some(&recipient_pubkey()),
875                                 },
876                                 InvoiceRequestTlvStreamRef {
877                                         chain: None,
878                                         amount: None,
879                                         features: None,
880                                         quantity: None,
881                                         payer_id: Some(&payer_pubkey()),
882                                         payer_note: None,
883                                 },
884                                 InvoiceTlvStreamRef {
885                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
886                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
887                                         created_at: Some(now.as_secs()),
888                                         relative_expiry: None,
889                                         payment_hash: Some(&payment_hash),
890                                         amount: Some(1000),
891                                         fallbacks: None,
892                                         features: None,
893                                         node_id: Some(&recipient_pubkey()),
894                                 },
895                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
896                         ),
897                 );
898
899                 if let Err(e) = Invoice::try_from(buffer) {
900                         panic!("error parsing invoice: {:?}", e);
901                 }
902         }
903
904         #[test]
905         fn builds_invoice_for_refund_with_defaults() {
906                 let payment_paths = payment_paths();
907                 let payment_hash = payment_hash();
908                 let now = now();
909                 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
910                         .build().unwrap()
911                         .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
912                         .unwrap()
913                         .build().unwrap()
914                         .sign(recipient_sign).unwrap();
915
916                 let mut buffer = Vec::new();
917                 invoice.write(&mut buffer).unwrap();
918
919                 assert_eq!(invoice.bytes, buffer.as_slice());
920                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
921                 assert_eq!(invoice.created_at(), now);
922                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
923                 #[cfg(feature = "std")]
924                 assert!(!invoice.is_expired());
925                 assert_eq!(invoice.payment_hash(), payment_hash);
926                 assert_eq!(invoice.amount_msats(), 1000);
927                 assert_eq!(invoice.fallbacks(), vec![]);
928                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
929                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
930                 assert!(
931                         merkle::verify_signature(
932                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
933                         ).is_ok()
934                 );
935
936                 assert_eq!(
937                         invoice.as_tlv_stream(),
938                         (
939                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
940                                 OfferTlvStreamRef {
941                                         chains: None,
942                                         metadata: None,
943                                         currency: None,
944                                         amount: None,
945                                         description: Some(&String::from("foo")),
946                                         features: None,
947                                         absolute_expiry: None,
948                                         paths: None,
949                                         issuer: None,
950                                         quantity_max: None,
951                                         node_id: None,
952                                 },
953                                 InvoiceRequestTlvStreamRef {
954                                         chain: None,
955                                         amount: Some(1000),
956                                         features: None,
957                                         quantity: None,
958                                         payer_id: Some(&payer_pubkey()),
959                                         payer_note: None,
960                                 },
961                                 InvoiceTlvStreamRef {
962                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
963                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
964                                         created_at: Some(now.as_secs()),
965                                         relative_expiry: None,
966                                         payment_hash: Some(&payment_hash),
967                                         amount: Some(1000),
968                                         fallbacks: None,
969                                         features: None,
970                                         node_id: Some(&recipient_pubkey()),
971                                 },
972                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
973                         ),
974                 );
975
976                 if let Err(e) = Invoice::try_from(buffer) {
977                         panic!("error parsing invoice: {:?}", e);
978                 }
979         }
980
981         #[cfg(feature = "std")]
982         #[test]
983         fn builds_invoice_from_offer_with_expiration() {
984                 let future_expiry = Duration::from_secs(u64::max_value());
985                 let past_expiry = Duration::from_secs(0);
986
987                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
988                         .amount_msats(1000)
989                         .absolute_expiry(future_expiry)
990                         .build().unwrap()
991                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
992                         .build().unwrap()
993                         .sign(payer_sign).unwrap()
994                         .respond_with(payment_paths(), payment_hash())
995                         .unwrap()
996                         .build()
997                 {
998                         panic!("error building invoice: {:?}", e);
999                 }
1000
1001                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1002                         .amount_msats(1000)
1003                         .absolute_expiry(past_expiry)
1004                         .build().unwrap()
1005                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1006                         .build_unchecked()
1007                         .sign(payer_sign).unwrap()
1008                         .respond_with(payment_paths(), payment_hash())
1009                         .unwrap()
1010                         .build()
1011                 {
1012                         Ok(_) => panic!("expected error"),
1013                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1014                 }
1015         }
1016
1017         #[cfg(feature = "std")]
1018         #[test]
1019         fn builds_invoice_from_refund_with_expiration() {
1020                 let future_expiry = Duration::from_secs(u64::max_value());
1021                 let past_expiry = Duration::from_secs(0);
1022
1023                 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1024                         .absolute_expiry(future_expiry)
1025                         .build().unwrap()
1026                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1027                         .unwrap()
1028                         .build()
1029                 {
1030                         panic!("error building invoice: {:?}", e);
1031                 }
1032
1033                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1034                         .absolute_expiry(past_expiry)
1035                         .build().unwrap()
1036                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1037                         .unwrap()
1038                         .build()
1039                 {
1040                         Ok(_) => panic!("expected error"),
1041                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1042                 }
1043         }
1044
1045         #[test]
1046         fn builds_invoice_with_relative_expiry() {
1047                 let now = now();
1048                 let one_hour = Duration::from_secs(3600);
1049
1050                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1051                         .amount_msats(1000)
1052                         .build().unwrap()
1053                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1054                         .build().unwrap()
1055                         .sign(payer_sign).unwrap()
1056                         .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1057                         .relative_expiry(one_hour.as_secs() as u32)
1058                         .build().unwrap()
1059                         .sign(recipient_sign).unwrap();
1060                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1061                 #[cfg(feature = "std")]
1062                 assert!(!invoice.is_expired());
1063                 assert_eq!(invoice.relative_expiry(), one_hour);
1064                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1065
1066                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1067                         .amount_msats(1000)
1068                         .build().unwrap()
1069                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1070                         .build().unwrap()
1071                         .sign(payer_sign).unwrap()
1072                         .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1073                         .relative_expiry(one_hour.as_secs() as u32 - 1)
1074                         .build().unwrap()
1075                         .sign(recipient_sign).unwrap();
1076                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1077                 #[cfg(feature = "std")]
1078                 assert!(invoice.is_expired());
1079                 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1080                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1081         }
1082
1083         #[test]
1084         fn builds_invoice_with_amount_from_request() {
1085                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1086                         .amount_msats(1000)
1087                         .build().unwrap()
1088                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1089                         .amount_msats(1001).unwrap()
1090                         .build().unwrap()
1091                         .sign(payer_sign).unwrap()
1092                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1093                         .build().unwrap()
1094                         .sign(recipient_sign).unwrap();
1095                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1096                 assert_eq!(invoice.amount_msats(), 1001);
1097                 assert_eq!(tlv_stream.amount, Some(1001));
1098         }
1099
1100         #[test]
1101         fn builds_invoice_with_quantity_from_request() {
1102                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1103                         .amount_msats(1000)
1104                         .supported_quantity(Quantity::Unbounded)
1105                         .build().unwrap()
1106                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1107                         .quantity(2).unwrap()
1108                         .build().unwrap()
1109                         .sign(payer_sign).unwrap()
1110                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1111                         .build().unwrap()
1112                         .sign(recipient_sign).unwrap();
1113                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1114                 assert_eq!(invoice.amount_msats(), 2000);
1115                 assert_eq!(tlv_stream.amount, Some(2000));
1116
1117                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1118                         .amount_msats(1000)
1119                         .supported_quantity(Quantity::Unbounded)
1120                         .build().unwrap()
1121                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1122                         .quantity(u64::max_value()).unwrap()
1123                         .build_unchecked()
1124                         .sign(payer_sign).unwrap()
1125                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1126                 {
1127                         Ok(_) => panic!("expected error"),
1128                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1129                 }
1130         }
1131
1132         #[test]
1133         fn builds_invoice_with_fallback_address() {
1134                 let script = Script::new();
1135                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1136                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1137                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1138
1139                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1140                         .amount_msats(1000)
1141                         .build().unwrap()
1142                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1143                         .build().unwrap()
1144                         .sign(payer_sign).unwrap()
1145                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1146                         .fallback_v0_p2wsh(&script.wscript_hash())
1147                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1148                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1149                         .build().unwrap()
1150                         .sign(recipient_sign).unwrap();
1151                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1152                 assert_eq!(
1153                         invoice.fallbacks(),
1154                         vec![
1155                                 Address::p2wsh(&script, Network::Bitcoin),
1156                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1157                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1158                         ],
1159                 );
1160                 assert_eq!(
1161                         tlv_stream.fallbacks,
1162                         Some(&vec![
1163                                 FallbackAddress {
1164                                         version: WitnessVersion::V0.to_num(),
1165                                         program: Vec::from(&script.wscript_hash().into_inner()[..]),
1166                                 },
1167                                 FallbackAddress {
1168                                         version: WitnessVersion::V0.to_num(),
1169                                         program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1170                                 },
1171                                 FallbackAddress {
1172                                         version: WitnessVersion::V1.to_num(),
1173                                         program: Vec::from(&tweaked_pubkey.serialize()[..]),
1174                                 },
1175                         ])
1176                 );
1177         }
1178
1179         #[test]
1180         fn builds_invoice_with_allow_mpp() {
1181                 let mut features = Bolt12InvoiceFeatures::empty();
1182                 features.set_basic_mpp_optional();
1183
1184                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1185                         .amount_msats(1000)
1186                         .build().unwrap()
1187                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1188                         .build().unwrap()
1189                         .sign(payer_sign).unwrap()
1190                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1191                         .allow_mpp()
1192                         .build().unwrap()
1193                         .sign(recipient_sign).unwrap();
1194                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1195                 assert_eq!(invoice.features(), &features);
1196                 assert_eq!(tlv_stream.features, Some(&features));
1197         }
1198
1199         #[test]
1200         fn fails_signing_invoice() {
1201                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1202                         .amount_msats(1000)
1203                         .build().unwrap()
1204                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1205                         .build().unwrap()
1206                         .sign(payer_sign).unwrap()
1207                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1208                         .build().unwrap()
1209                         .sign(|_| Err(()))
1210                 {
1211                         Ok(_) => panic!("expected error"),
1212                         Err(e) => assert_eq!(e, SignError::Signing(())),
1213                 }
1214
1215                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1216                         .amount_msats(1000)
1217                         .build().unwrap()
1218                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1219                         .build().unwrap()
1220                         .sign(payer_sign).unwrap()
1221                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1222                         .build().unwrap()
1223                         .sign(payer_sign)
1224                 {
1225                         Ok(_) => panic!("expected error"),
1226                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1227                 }
1228         }
1229
1230         #[test]
1231         fn parses_invoice_with_payment_paths() {
1232                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1233                         .amount_msats(1000)
1234                         .build().unwrap()
1235                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1236                         .build().unwrap()
1237                         .sign(payer_sign).unwrap()
1238                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1239                         .build().unwrap()
1240                         .sign(recipient_sign).unwrap();
1241
1242                 let mut buffer = Vec::new();
1243                 invoice.write(&mut buffer).unwrap();
1244
1245                 if let Err(e) = Invoice::try_from(buffer) {
1246                         panic!("error parsing invoice: {:?}", e);
1247                 }
1248
1249                 let mut tlv_stream = invoice.as_tlv_stream();
1250                 tlv_stream.3.paths = None;
1251
1252                 match Invoice::try_from(tlv_stream.to_bytes()) {
1253                         Ok(_) => panic!("expected error"),
1254                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1255                 }
1256
1257                 let mut tlv_stream = invoice.as_tlv_stream();
1258                 tlv_stream.3.blindedpay = None;
1259
1260                 match Invoice::try_from(tlv_stream.to_bytes()) {
1261                         Ok(_) => panic!("expected error"),
1262                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1263                 }
1264
1265                 let empty_payment_paths = vec![];
1266                 let mut tlv_stream = invoice.as_tlv_stream();
1267                 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1268
1269                 match Invoice::try_from(tlv_stream.to_bytes()) {
1270                         Ok(_) => panic!("expected error"),
1271                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1272                 }
1273
1274                 let mut payment_paths = payment_paths();
1275                 payment_paths.pop();
1276                 let mut tlv_stream = invoice.as_tlv_stream();
1277                 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1278
1279                 match Invoice::try_from(tlv_stream.to_bytes()) {
1280                         Ok(_) => panic!("expected error"),
1281                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1282                 }
1283         }
1284
1285         #[test]
1286         fn parses_invoice_with_created_at() {
1287                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1288                         .amount_msats(1000)
1289                         .build().unwrap()
1290                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1291                         .build().unwrap()
1292                         .sign(payer_sign).unwrap()
1293                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1294                         .build().unwrap()
1295                         .sign(recipient_sign).unwrap();
1296
1297                 let mut buffer = Vec::new();
1298                 invoice.write(&mut buffer).unwrap();
1299
1300                 if let Err(e) = Invoice::try_from(buffer) {
1301                         panic!("error parsing invoice: {:?}", e);
1302                 }
1303
1304                 let mut tlv_stream = invoice.as_tlv_stream();
1305                 tlv_stream.3.created_at = None;
1306
1307                 match Invoice::try_from(tlv_stream.to_bytes()) {
1308                         Ok(_) => panic!("expected error"),
1309                         Err(e) => {
1310                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1311                         },
1312                 }
1313         }
1314
1315         #[test]
1316         fn parses_invoice_with_relative_expiry() {
1317                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1318                         .amount_msats(1000)
1319                         .build().unwrap()
1320                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1321                         .build().unwrap()
1322                         .sign(payer_sign).unwrap()
1323                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1324                         .relative_expiry(3600)
1325                         .build().unwrap()
1326                         .sign(recipient_sign).unwrap();
1327
1328                 let mut buffer = Vec::new();
1329                 invoice.write(&mut buffer).unwrap();
1330
1331                 match Invoice::try_from(buffer) {
1332                         Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1333                         Err(e) => panic!("error parsing invoice: {:?}", e),
1334                 }
1335         }
1336
1337         #[test]
1338         fn parses_invoice_with_payment_hash() {
1339                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1340                         .amount_msats(1000)
1341                         .build().unwrap()
1342                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1343                         .build().unwrap()
1344                         .sign(payer_sign).unwrap()
1345                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1346                         .build().unwrap()
1347                         .sign(recipient_sign).unwrap();
1348
1349                 let mut buffer = Vec::new();
1350                 invoice.write(&mut buffer).unwrap();
1351
1352                 if let Err(e) = Invoice::try_from(buffer) {
1353                         panic!("error parsing invoice: {:?}", e);
1354                 }
1355
1356                 let mut tlv_stream = invoice.as_tlv_stream();
1357                 tlv_stream.3.payment_hash = None;
1358
1359                 match Invoice::try_from(tlv_stream.to_bytes()) {
1360                         Ok(_) => panic!("expected error"),
1361                         Err(e) => {
1362                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1363                         },
1364                 }
1365         }
1366
1367         #[test]
1368         fn parses_invoice_with_amount() {
1369                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1370                         .amount_msats(1000)
1371                         .build().unwrap()
1372                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1373                         .build().unwrap()
1374                         .sign(payer_sign).unwrap()
1375                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1376                         .build().unwrap()
1377                         .sign(recipient_sign).unwrap();
1378
1379                 let mut buffer = Vec::new();
1380                 invoice.write(&mut buffer).unwrap();
1381
1382                 if let Err(e) = Invoice::try_from(buffer) {
1383                         panic!("error parsing invoice: {:?}", e);
1384                 }
1385
1386                 let mut tlv_stream = invoice.as_tlv_stream();
1387                 tlv_stream.3.amount = None;
1388
1389                 match Invoice::try_from(tlv_stream.to_bytes()) {
1390                         Ok(_) => panic!("expected error"),
1391                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1392                 }
1393         }
1394
1395         #[test]
1396         fn parses_invoice_with_allow_mpp() {
1397                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1398                         .amount_msats(1000)
1399                         .build().unwrap()
1400                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1401                         .build().unwrap()
1402                         .sign(payer_sign).unwrap()
1403                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1404                         .allow_mpp()
1405                         .build().unwrap()
1406                         .sign(recipient_sign).unwrap();
1407
1408                 let mut buffer = Vec::new();
1409                 invoice.write(&mut buffer).unwrap();
1410
1411                 match Invoice::try_from(buffer) {
1412                         Ok(invoice) => {
1413                                 let mut features = Bolt12InvoiceFeatures::empty();
1414                                 features.set_basic_mpp_optional();
1415                                 assert_eq!(invoice.features(), &features);
1416                         },
1417                         Err(e) => panic!("error parsing invoice: {:?}", e),
1418                 }
1419         }
1420
1421         #[test]
1422         fn parses_invoice_with_fallback_address() {
1423                 let script = Script::new();
1424                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1425                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1426                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1427
1428                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1429                         .amount_msats(1000)
1430                         .build().unwrap();
1431                 let invoice_request = offer
1432                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1433                         .build().unwrap()
1434                         .sign(payer_sign).unwrap();
1435                 let mut unsigned_invoice = invoice_request
1436                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1437                         .fallback_v0_p2wsh(&script.wscript_hash())
1438                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1439                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1440                         .build().unwrap();
1441
1442                 // Only standard addresses will be included.
1443                 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1444                 // Non-standard addresses
1445                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1446                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1447                 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1448                 // Standard address
1449                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1450                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1451
1452                 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1453                 let mut buffer = Vec::new();
1454                 invoice.write(&mut buffer).unwrap();
1455
1456                 match Invoice::try_from(buffer) {
1457                         Ok(invoice) => {
1458                                 assert_eq!(
1459                                         invoice.fallbacks(),
1460                                         vec![
1461                                                 Address::p2wsh(&script, Network::Bitcoin),
1462                                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1463                                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1464                                                 Address {
1465                                                         payload: Payload::WitnessProgram {
1466                                                                 version: WitnessVersion::V1,
1467                                                                 program: vec![0u8; 33],
1468                                                         },
1469                                                         network: Network::Bitcoin,
1470                                                 },
1471                                                 Address {
1472                                                         payload: Payload::WitnessProgram {
1473                                                                 version: WitnessVersion::V2,
1474                                                                 program: vec![0u8; 40],
1475                                                         },
1476                                                         network: Network::Bitcoin,
1477                                                 },
1478                                         ],
1479                                 );
1480                         },
1481                         Err(e) => panic!("error parsing invoice: {:?}", e),
1482                 }
1483         }
1484
1485         #[test]
1486         fn parses_invoice_with_node_id() {
1487                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1488                         .amount_msats(1000)
1489                         .build().unwrap()
1490                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1491                         .build().unwrap()
1492                         .sign(payer_sign).unwrap()
1493                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1494                         .build().unwrap()
1495                         .sign(recipient_sign).unwrap();
1496
1497                 let mut buffer = Vec::new();
1498                 invoice.write(&mut buffer).unwrap();
1499
1500                 if let Err(e) = Invoice::try_from(buffer) {
1501                         panic!("error parsing invoice: {:?}", e);
1502                 }
1503
1504                 let mut tlv_stream = invoice.as_tlv_stream();
1505                 tlv_stream.3.node_id = None;
1506
1507                 match Invoice::try_from(tlv_stream.to_bytes()) {
1508                         Ok(_) => panic!("expected error"),
1509                         Err(e) => {
1510                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1511                         },
1512                 }
1513
1514                 let invalid_pubkey = payer_pubkey();
1515                 let mut tlv_stream = invoice.as_tlv_stream();
1516                 tlv_stream.3.node_id = Some(&invalid_pubkey);
1517
1518                 match Invoice::try_from(tlv_stream.to_bytes()) {
1519                         Ok(_) => panic!("expected error"),
1520                         Err(e) => {
1521                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1522                         },
1523                 }
1524         }
1525
1526         #[test]
1527         fn fails_parsing_invoice_without_signature() {
1528                 let mut buffer = Vec::new();
1529                 OfferBuilder::new("foo".into(), recipient_pubkey())
1530                         .amount_msats(1000)
1531                         .build().unwrap()
1532                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1533                         .build().unwrap()
1534                         .sign(payer_sign).unwrap()
1535                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1536                         .build().unwrap()
1537                         .invoice
1538                         .write(&mut buffer).unwrap();
1539
1540                 match Invoice::try_from(buffer) {
1541                         Ok(_) => panic!("expected error"),
1542                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1543                 }
1544         }
1545
1546         #[test]
1547         fn fails_parsing_invoice_with_invalid_signature() {
1548                 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1549                         .amount_msats(1000)
1550                         .build().unwrap()
1551                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1552                         .build().unwrap()
1553                         .sign(payer_sign).unwrap()
1554                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1555                         .build().unwrap()
1556                         .sign(recipient_sign).unwrap();
1557                 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1558                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1559
1560                 let mut buffer = Vec::new();
1561                 invoice.write(&mut buffer).unwrap();
1562
1563                 match Invoice::try_from(buffer) {
1564                         Ok(_) => panic!("expected error"),
1565                         Err(e) => {
1566                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1567                         },
1568                 }
1569         }
1570
1571         #[test]
1572         fn fails_parsing_invoice_with_extra_tlv_records() {
1573                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1574                         .amount_msats(1000)
1575                         .build().unwrap()
1576                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1577                         .build().unwrap()
1578                         .sign(payer_sign).unwrap()
1579                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1580                         .build().unwrap()
1581                         .sign(recipient_sign).unwrap();
1582
1583                 let mut encoded_invoice = Vec::new();
1584                 invoice.write(&mut encoded_invoice).unwrap();
1585                 BigSize(1002).write(&mut encoded_invoice).unwrap();
1586                 BigSize(32).write(&mut encoded_invoice).unwrap();
1587                 [42u8; 32].write(&mut encoded_invoice).unwrap();
1588
1589                 match Invoice::try_from(encoded_invoice) {
1590                         Ok(_) => panic!("expected error"),
1591                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1592                 }
1593         }
1594 }