Refactor InvoiceRequestContents fields into a sub-struct
[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.inner.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.inner.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, .. } =>
497                                 invoice_request.inner.offer.is_expired(),
498                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
499                 }
500         }
501
502         fn chain(&self) -> ChainHash {
503                 match self {
504                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
505                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
506                 }
507         }
508
509         fn fields(&self) -> &InvoiceFields {
510                 match self {
511                         InvoiceContents::ForOffer { fields, .. } => fields,
512                         InvoiceContents::ForRefund { fields, .. } => fields,
513                 }
514         }
515
516         fn fields_mut(&mut self) -> &mut InvoiceFields {
517                 match self {
518                         InvoiceContents::ForOffer { fields, .. } => fields,
519                         InvoiceContents::ForRefund { fields, .. } => fields,
520                 }
521         }
522
523         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
524                 let (payer, offer, invoice_request) = match self {
525                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
526                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
527                 };
528                 let invoice = self.fields().as_tlv_stream();
529
530                 (payer, offer, invoice_request, invoice)
531         }
532 }
533
534 impl InvoiceFields {
535         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
536                 let features = {
537                         if self.features == Bolt12InvoiceFeatures::empty() { None }
538                         else { Some(&self.features) }
539                 };
540
541                 InvoiceTlvStreamRef {
542                         paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
543                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
544                         created_at: Some(self.created_at.as_secs()),
545                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
546                         payment_hash: Some(&self.payment_hash),
547                         amount: Some(self.amount_msats),
548                         fallbacks: self.fallbacks.as_ref(),
549                         features,
550                         node_id: Some(&self.signing_pubkey),
551                 }
552         }
553 }
554
555 impl Writeable for Invoice {
556         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
557                 WithoutLength(&self.bytes).write(writer)
558         }
559 }
560
561 impl Writeable for InvoiceContents {
562         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
563                 self.as_tlv_stream().write(writer)
564         }
565 }
566
567 impl TryFrom<Vec<u8>> for Invoice {
568         type Error = ParseError;
569
570         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
571                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
572                 Invoice::try_from(parsed_invoice)
573         }
574 }
575
576 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
577         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
578         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
579         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
580         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
581         (168, payment_hash: PaymentHash),
582         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
583         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
584         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
585         (176, node_id: PublicKey),
586 });
587
588 type BlindedPathIter<'a> = core::iter::Map<
589         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
590         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
591 >;
592
593 type BlindedPayInfoIter<'a> = core::iter::Map<
594         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
595         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
596 >;
597
598 /// Information needed to route a payment across a [`BlindedPath`].
599 #[derive(Clone, Debug, PartialEq)]
600 pub struct BlindedPayInfo {
601         /// Base fee charged (in millisatoshi) for the entire blinded path.
602         pub fee_base_msat: u32,
603
604         /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
605         /// (i.e., 10,000 is 1%).
606         pub fee_proportional_millionths: u32,
607
608         /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
609         /// path.
610         pub cltv_expiry_delta: u16,
611
612         /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
613         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
614         /// seen by the recipient.
615         pub htlc_minimum_msat: u64,
616
617         /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
618         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
619         /// seen by the recipient.
620         pub htlc_maximum_msat: u64,
621
622         /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
623         /// onion payload.
624         pub features: BlindedHopFeatures,
625 }
626
627 impl_writeable!(BlindedPayInfo, {
628         fee_base_msat,
629         fee_proportional_millionths,
630         cltv_expiry_delta,
631         htlc_minimum_msat,
632         htlc_maximum_msat,
633         features
634 });
635
636 /// Wire representation for an on-chain fallback address.
637 #[derive(Clone, Debug, PartialEq)]
638 pub(super) struct FallbackAddress {
639         version: u8,
640         program: Vec<u8>,
641 }
642
643 impl_writeable!(FallbackAddress, { version, program });
644
645 type FullInvoiceTlvStream =
646         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
647
648 #[cfg(test)]
649 type FullInvoiceTlvStreamRef<'a> = (
650         PayerTlvStreamRef<'a>,
651         OfferTlvStreamRef<'a>,
652         InvoiceRequestTlvStreamRef<'a>,
653         InvoiceTlvStreamRef<'a>,
654         SignatureTlvStreamRef<'a>,
655 );
656
657 impl SeekReadable for FullInvoiceTlvStream {
658         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
659                 let payer = SeekReadable::read(r)?;
660                 let offer = SeekReadable::read(r)?;
661                 let invoice_request = SeekReadable::read(r)?;
662                 let invoice = SeekReadable::read(r)?;
663                 let signature = SeekReadable::read(r)?;
664
665                 Ok((payer, offer, invoice_request, invoice, signature))
666         }
667 }
668
669 type PartialInvoiceTlvStream =
670         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
671
672 type PartialInvoiceTlvStreamRef<'a> = (
673         PayerTlvStreamRef<'a>,
674         OfferTlvStreamRef<'a>,
675         InvoiceRequestTlvStreamRef<'a>,
676         InvoiceTlvStreamRef<'a>,
677 );
678
679 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
680         type Error = ParseError;
681
682         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
683                 let ParsedMessage { bytes, tlv_stream } = invoice;
684                 let (
685                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
686                         SignatureTlvStream { signature },
687                 ) = tlv_stream;
688                 let contents = InvoiceContents::try_from(
689                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
690                 )?;
691
692                 let signature = match signature {
693                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
694                         Some(signature) => signature,
695                 };
696                 let pubkey = contents.fields().signing_pubkey;
697                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
698
699                 Ok(Invoice { bytes, contents, signature })
700         }
701 }
702
703 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
704         type Error = SemanticError;
705
706         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
707                 let (
708                         payer_tlv_stream,
709                         offer_tlv_stream,
710                         invoice_request_tlv_stream,
711                         InvoiceTlvStream {
712                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
713                                 features, node_id,
714                         },
715                 ) = tlv_stream;
716
717                 let payment_paths = match (paths, blindedpay) {
718                         (None, _) => return Err(SemanticError::MissingPaths),
719                         (_, None) => return Err(SemanticError::InvalidPayInfo),
720                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
721                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
722                                 return Err(SemanticError::InvalidPayInfo);
723                         },
724                         (Some(paths), Some(blindedpay)) => {
725                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
726                         },
727                 };
728
729                 let created_at = match created_at {
730                         None => return Err(SemanticError::MissingCreationTime),
731                         Some(timestamp) => Duration::from_secs(timestamp),
732                 };
733
734                 let relative_expiry = relative_expiry
735                         .map(Into::<u64>::into)
736                         .map(Duration::from_secs);
737
738                 let payment_hash = match payment_hash {
739                         None => return Err(SemanticError::MissingPaymentHash),
740                         Some(payment_hash) => payment_hash,
741                 };
742
743                 let amount_msats = match amount {
744                         None => return Err(SemanticError::MissingAmount),
745                         Some(amount) => amount,
746                 };
747
748                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
749
750                 let signing_pubkey = match node_id {
751                         None => return Err(SemanticError::MissingSigningPubkey),
752                         Some(node_id) => node_id,
753                 };
754
755                 let fields = InvoiceFields {
756                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
757                         features, signing_pubkey,
758                 };
759
760                 match offer_tlv_stream.node_id {
761                         Some(expected_signing_pubkey) => {
762                                 if fields.signing_pubkey != expected_signing_pubkey {
763                                         return Err(SemanticError::InvalidSigningPubkey);
764                                 }
765
766                                 let invoice_request = InvoiceRequestContents::try_from(
767                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
768                                 )?;
769                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
770                         },
771                         None => {
772                                 let refund = RefundContents::try_from(
773                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
774                                 )?;
775                                 Ok(InvoiceContents::ForRefund { refund, fields })
776                         },
777                 }
778         }
779 }
780
781 #[cfg(test)]
782 mod tests {
783         use super::{DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
784
785         use bitcoin::blockdata::script::Script;
786         use bitcoin::hashes::Hash;
787         use bitcoin::network::constants::Network;
788         use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
789         use bitcoin::util::address::{Address, Payload, WitnessVersion};
790         use bitcoin::util::schnorr::TweakedPublicKey;
791         use core::convert::TryFrom;
792         use core::time::Duration;
793         use crate::ln::msgs::DecodeError;
794         use crate::ln::features::Bolt12InvoiceFeatures;
795         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
796         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
797         use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef, Quantity};
798         use crate::offers::parse::{ParseError, SemanticError};
799         use crate::offers::payer::PayerTlvStreamRef;
800         use crate::offers::refund::RefundBuilder;
801         use crate::offers::test_utils::*;
802         use crate::util::ser::{BigSize, Iterable, Writeable};
803
804         trait ToBytes {
805                 fn to_bytes(&self) -> Vec<u8>;
806         }
807
808         impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
809                 fn to_bytes(&self) -> Vec<u8> {
810                         let mut buffer = Vec::new();
811                         self.0.write(&mut buffer).unwrap();
812                         self.1.write(&mut buffer).unwrap();
813                         self.2.write(&mut buffer).unwrap();
814                         self.3.write(&mut buffer).unwrap();
815                         self.4.write(&mut buffer).unwrap();
816                         buffer
817                 }
818         }
819
820         #[test]
821         fn builds_invoice_for_offer_with_defaults() {
822                 let payment_paths = payment_paths();
823                 let payment_hash = payment_hash();
824                 let now = now();
825                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
826                         .amount_msats(1000)
827                         .build().unwrap()
828                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
829                         .build().unwrap()
830                         .sign(payer_sign).unwrap()
831                         .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
832                         .build().unwrap()
833                         .sign(recipient_sign).unwrap();
834
835                 let mut buffer = Vec::new();
836                 invoice.write(&mut buffer).unwrap();
837
838                 assert_eq!(invoice.bytes, buffer.as_slice());
839                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
840                 assert_eq!(invoice.created_at(), now);
841                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
842                 #[cfg(feature = "std")]
843                 assert!(!invoice.is_expired());
844                 assert_eq!(invoice.payment_hash(), payment_hash);
845                 assert_eq!(invoice.amount_msats(), 1000);
846                 assert_eq!(invoice.fallbacks(), vec![]);
847                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
848                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
849                 assert!(
850                         merkle::verify_signature(
851                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
852                         ).is_ok()
853                 );
854
855                 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
856                 let pubkey = recipient_pubkey().into();
857                 let secp_ctx = Secp256k1::verification_only();
858                 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
859
860                 assert_eq!(
861                         invoice.as_tlv_stream(),
862                         (
863                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
864                                 OfferTlvStreamRef {
865                                         chains: None,
866                                         metadata: None,
867                                         currency: None,
868                                         amount: Some(1000),
869                                         description: Some(&String::from("foo")),
870                                         features: None,
871                                         absolute_expiry: None,
872                                         paths: None,
873                                         issuer: None,
874                                         quantity_max: None,
875                                         node_id: Some(&recipient_pubkey()),
876                                 },
877                                 InvoiceRequestTlvStreamRef {
878                                         chain: None,
879                                         amount: None,
880                                         features: None,
881                                         quantity: None,
882                                         payer_id: Some(&payer_pubkey()),
883                                         payer_note: None,
884                                 },
885                                 InvoiceTlvStreamRef {
886                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
887                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
888                                         created_at: Some(now.as_secs()),
889                                         relative_expiry: None,
890                                         payment_hash: Some(&payment_hash),
891                                         amount: Some(1000),
892                                         fallbacks: None,
893                                         features: None,
894                                         node_id: Some(&recipient_pubkey()),
895                                 },
896                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
897                         ),
898                 );
899
900                 if let Err(e) = Invoice::try_from(buffer) {
901                         panic!("error parsing invoice: {:?}", e);
902                 }
903         }
904
905         #[test]
906         fn builds_invoice_for_refund_with_defaults() {
907                 let payment_paths = payment_paths();
908                 let payment_hash = payment_hash();
909                 let now = now();
910                 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
911                         .build().unwrap()
912                         .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
913                         .unwrap()
914                         .build().unwrap()
915                         .sign(recipient_sign).unwrap();
916
917                 let mut buffer = Vec::new();
918                 invoice.write(&mut buffer).unwrap();
919
920                 assert_eq!(invoice.bytes, buffer.as_slice());
921                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
922                 assert_eq!(invoice.created_at(), now);
923                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
924                 #[cfg(feature = "std")]
925                 assert!(!invoice.is_expired());
926                 assert_eq!(invoice.payment_hash(), payment_hash);
927                 assert_eq!(invoice.amount_msats(), 1000);
928                 assert_eq!(invoice.fallbacks(), vec![]);
929                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
930                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
931                 assert!(
932                         merkle::verify_signature(
933                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
934                         ).is_ok()
935                 );
936
937                 assert_eq!(
938                         invoice.as_tlv_stream(),
939                         (
940                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
941                                 OfferTlvStreamRef {
942                                         chains: None,
943                                         metadata: None,
944                                         currency: None,
945                                         amount: None,
946                                         description: Some(&String::from("foo")),
947                                         features: None,
948                                         absolute_expiry: None,
949                                         paths: None,
950                                         issuer: None,
951                                         quantity_max: None,
952                                         node_id: None,
953                                 },
954                                 InvoiceRequestTlvStreamRef {
955                                         chain: None,
956                                         amount: Some(1000),
957                                         features: None,
958                                         quantity: None,
959                                         payer_id: Some(&payer_pubkey()),
960                                         payer_note: None,
961                                 },
962                                 InvoiceTlvStreamRef {
963                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
964                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
965                                         created_at: Some(now.as_secs()),
966                                         relative_expiry: None,
967                                         payment_hash: Some(&payment_hash),
968                                         amount: Some(1000),
969                                         fallbacks: None,
970                                         features: None,
971                                         node_id: Some(&recipient_pubkey()),
972                                 },
973                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
974                         ),
975                 );
976
977                 if let Err(e) = Invoice::try_from(buffer) {
978                         panic!("error parsing invoice: {:?}", e);
979                 }
980         }
981
982         #[cfg(feature = "std")]
983         #[test]
984         fn builds_invoice_from_offer_with_expiration() {
985                 let future_expiry = Duration::from_secs(u64::max_value());
986                 let past_expiry = Duration::from_secs(0);
987
988                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
989                         .amount_msats(1000)
990                         .absolute_expiry(future_expiry)
991                         .build().unwrap()
992                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
993                         .build().unwrap()
994                         .sign(payer_sign).unwrap()
995                         .respond_with(payment_paths(), payment_hash())
996                         .unwrap()
997                         .build()
998                 {
999                         panic!("error building invoice: {:?}", e);
1000                 }
1001
1002                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1003                         .amount_msats(1000)
1004                         .absolute_expiry(past_expiry)
1005                         .build().unwrap()
1006                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1007                         .build_unchecked()
1008                         .sign(payer_sign).unwrap()
1009                         .respond_with(payment_paths(), payment_hash())
1010                         .unwrap()
1011                         .build()
1012                 {
1013                         Ok(_) => panic!("expected error"),
1014                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1015                 }
1016         }
1017
1018         #[cfg(feature = "std")]
1019         #[test]
1020         fn builds_invoice_from_refund_with_expiration() {
1021                 let future_expiry = Duration::from_secs(u64::max_value());
1022                 let past_expiry = Duration::from_secs(0);
1023
1024                 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1025                         .absolute_expiry(future_expiry)
1026                         .build().unwrap()
1027                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1028                         .unwrap()
1029                         .build()
1030                 {
1031                         panic!("error building invoice: {:?}", e);
1032                 }
1033
1034                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1035                         .absolute_expiry(past_expiry)
1036                         .build().unwrap()
1037                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1038                         .unwrap()
1039                         .build()
1040                 {
1041                         Ok(_) => panic!("expected error"),
1042                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1043                 }
1044         }
1045
1046         #[test]
1047         fn builds_invoice_with_relative_expiry() {
1048                 let now = now();
1049                 let one_hour = Duration::from_secs(3600);
1050
1051                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1052                         .amount_msats(1000)
1053                         .build().unwrap()
1054                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1055                         .build().unwrap()
1056                         .sign(payer_sign).unwrap()
1057                         .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1058                         .relative_expiry(one_hour.as_secs() as u32)
1059                         .build().unwrap()
1060                         .sign(recipient_sign).unwrap();
1061                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1062                 #[cfg(feature = "std")]
1063                 assert!(!invoice.is_expired());
1064                 assert_eq!(invoice.relative_expiry(), one_hour);
1065                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1066
1067                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1068                         .amount_msats(1000)
1069                         .build().unwrap()
1070                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071                         .build().unwrap()
1072                         .sign(payer_sign).unwrap()
1073                         .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1074                         .relative_expiry(one_hour.as_secs() as u32 - 1)
1075                         .build().unwrap()
1076                         .sign(recipient_sign).unwrap();
1077                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1078                 #[cfg(feature = "std")]
1079                 assert!(invoice.is_expired());
1080                 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1081                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1082         }
1083
1084         #[test]
1085         fn builds_invoice_with_amount_from_request() {
1086                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1087                         .amount_msats(1000)
1088                         .build().unwrap()
1089                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1090                         .amount_msats(1001).unwrap()
1091                         .build().unwrap()
1092                         .sign(payer_sign).unwrap()
1093                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1094                         .build().unwrap()
1095                         .sign(recipient_sign).unwrap();
1096                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1097                 assert_eq!(invoice.amount_msats(), 1001);
1098                 assert_eq!(tlv_stream.amount, Some(1001));
1099         }
1100
1101         #[test]
1102         fn builds_invoice_with_quantity_from_request() {
1103                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1104                         .amount_msats(1000)
1105                         .supported_quantity(Quantity::Unbounded)
1106                         .build().unwrap()
1107                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1108                         .quantity(2).unwrap()
1109                         .build().unwrap()
1110                         .sign(payer_sign).unwrap()
1111                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1112                         .build().unwrap()
1113                         .sign(recipient_sign).unwrap();
1114                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1115                 assert_eq!(invoice.amount_msats(), 2000);
1116                 assert_eq!(tlv_stream.amount, Some(2000));
1117
1118                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1119                         .amount_msats(1000)
1120                         .supported_quantity(Quantity::Unbounded)
1121                         .build().unwrap()
1122                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1123                         .quantity(u64::max_value()).unwrap()
1124                         .build_unchecked()
1125                         .sign(payer_sign).unwrap()
1126                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1127                 {
1128                         Ok(_) => panic!("expected error"),
1129                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1130                 }
1131         }
1132
1133         #[test]
1134         fn builds_invoice_with_fallback_address() {
1135                 let script = Script::new();
1136                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1137                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1138                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1139
1140                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1141                         .amount_msats(1000)
1142                         .build().unwrap()
1143                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1144                         .build().unwrap()
1145                         .sign(payer_sign).unwrap()
1146                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1147                         .fallback_v0_p2wsh(&script.wscript_hash())
1148                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1149                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1150                         .build().unwrap()
1151                         .sign(recipient_sign).unwrap();
1152                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1153                 assert_eq!(
1154                         invoice.fallbacks(),
1155                         vec![
1156                                 Address::p2wsh(&script, Network::Bitcoin),
1157                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1158                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1159                         ],
1160                 );
1161                 assert_eq!(
1162                         tlv_stream.fallbacks,
1163                         Some(&vec![
1164                                 FallbackAddress {
1165                                         version: WitnessVersion::V0.to_num(),
1166                                         program: Vec::from(&script.wscript_hash().into_inner()[..]),
1167                                 },
1168                                 FallbackAddress {
1169                                         version: WitnessVersion::V0.to_num(),
1170                                         program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1171                                 },
1172                                 FallbackAddress {
1173                                         version: WitnessVersion::V1.to_num(),
1174                                         program: Vec::from(&tweaked_pubkey.serialize()[..]),
1175                                 },
1176                         ])
1177                 );
1178         }
1179
1180         #[test]
1181         fn builds_invoice_with_allow_mpp() {
1182                 let mut features = Bolt12InvoiceFeatures::empty();
1183                 features.set_basic_mpp_optional();
1184
1185                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1186                         .amount_msats(1000)
1187                         .build().unwrap()
1188                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1189                         .build().unwrap()
1190                         .sign(payer_sign).unwrap()
1191                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1192                         .allow_mpp()
1193                         .build().unwrap()
1194                         .sign(recipient_sign).unwrap();
1195                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1196                 assert_eq!(invoice.features(), &features);
1197                 assert_eq!(tlv_stream.features, Some(&features));
1198         }
1199
1200         #[test]
1201         fn fails_signing_invoice() {
1202                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1203                         .amount_msats(1000)
1204                         .build().unwrap()
1205                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1206                         .build().unwrap()
1207                         .sign(payer_sign).unwrap()
1208                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1209                         .build().unwrap()
1210                         .sign(|_| Err(()))
1211                 {
1212                         Ok(_) => panic!("expected error"),
1213                         Err(e) => assert_eq!(e, SignError::Signing(())),
1214                 }
1215
1216                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1217                         .amount_msats(1000)
1218                         .build().unwrap()
1219                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1220                         .build().unwrap()
1221                         .sign(payer_sign).unwrap()
1222                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1223                         .build().unwrap()
1224                         .sign(payer_sign)
1225                 {
1226                         Ok(_) => panic!("expected error"),
1227                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1228                 }
1229         }
1230
1231         #[test]
1232         fn parses_invoice_with_payment_paths() {
1233                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1234                         .amount_msats(1000)
1235                         .build().unwrap()
1236                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1237                         .build().unwrap()
1238                         .sign(payer_sign).unwrap()
1239                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1240                         .build().unwrap()
1241                         .sign(recipient_sign).unwrap();
1242
1243                 let mut buffer = Vec::new();
1244                 invoice.write(&mut buffer).unwrap();
1245
1246                 if let Err(e) = Invoice::try_from(buffer) {
1247                         panic!("error parsing invoice: {:?}", e);
1248                 }
1249
1250                 let mut tlv_stream = invoice.as_tlv_stream();
1251                 tlv_stream.3.paths = None;
1252
1253                 match Invoice::try_from(tlv_stream.to_bytes()) {
1254                         Ok(_) => panic!("expected error"),
1255                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1256                 }
1257
1258                 let mut tlv_stream = invoice.as_tlv_stream();
1259                 tlv_stream.3.blindedpay = None;
1260
1261                 match Invoice::try_from(tlv_stream.to_bytes()) {
1262                         Ok(_) => panic!("expected error"),
1263                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1264                 }
1265
1266                 let empty_payment_paths = vec![];
1267                 let mut tlv_stream = invoice.as_tlv_stream();
1268                 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1269
1270                 match Invoice::try_from(tlv_stream.to_bytes()) {
1271                         Ok(_) => panic!("expected error"),
1272                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1273                 }
1274
1275                 let mut payment_paths = payment_paths();
1276                 payment_paths.pop();
1277                 let mut tlv_stream = invoice.as_tlv_stream();
1278                 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1279
1280                 match Invoice::try_from(tlv_stream.to_bytes()) {
1281                         Ok(_) => panic!("expected error"),
1282                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1283                 }
1284         }
1285
1286         #[test]
1287         fn parses_invoice_with_created_at() {
1288                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1289                         .amount_msats(1000)
1290                         .build().unwrap()
1291                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1292                         .build().unwrap()
1293                         .sign(payer_sign).unwrap()
1294                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1295                         .build().unwrap()
1296                         .sign(recipient_sign).unwrap();
1297
1298                 let mut buffer = Vec::new();
1299                 invoice.write(&mut buffer).unwrap();
1300
1301                 if let Err(e) = Invoice::try_from(buffer) {
1302                         panic!("error parsing invoice: {:?}", e);
1303                 }
1304
1305                 let mut tlv_stream = invoice.as_tlv_stream();
1306                 tlv_stream.3.created_at = None;
1307
1308                 match Invoice::try_from(tlv_stream.to_bytes()) {
1309                         Ok(_) => panic!("expected error"),
1310                         Err(e) => {
1311                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1312                         },
1313                 }
1314         }
1315
1316         #[test]
1317         fn parses_invoice_with_relative_expiry() {
1318                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1319                         .amount_msats(1000)
1320                         .build().unwrap()
1321                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1322                         .build().unwrap()
1323                         .sign(payer_sign).unwrap()
1324                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1325                         .relative_expiry(3600)
1326                         .build().unwrap()
1327                         .sign(recipient_sign).unwrap();
1328
1329                 let mut buffer = Vec::new();
1330                 invoice.write(&mut buffer).unwrap();
1331
1332                 match Invoice::try_from(buffer) {
1333                         Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1334                         Err(e) => panic!("error parsing invoice: {:?}", e),
1335                 }
1336         }
1337
1338         #[test]
1339         fn parses_invoice_with_payment_hash() {
1340                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1341                         .amount_msats(1000)
1342                         .build().unwrap()
1343                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1344                         .build().unwrap()
1345                         .sign(payer_sign).unwrap()
1346                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1347                         .build().unwrap()
1348                         .sign(recipient_sign).unwrap();
1349
1350                 let mut buffer = Vec::new();
1351                 invoice.write(&mut buffer).unwrap();
1352
1353                 if let Err(e) = Invoice::try_from(buffer) {
1354                         panic!("error parsing invoice: {:?}", e);
1355                 }
1356
1357                 let mut tlv_stream = invoice.as_tlv_stream();
1358                 tlv_stream.3.payment_hash = None;
1359
1360                 match Invoice::try_from(tlv_stream.to_bytes()) {
1361                         Ok(_) => panic!("expected error"),
1362                         Err(e) => {
1363                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1364                         },
1365                 }
1366         }
1367
1368         #[test]
1369         fn parses_invoice_with_amount() {
1370                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1371                         .amount_msats(1000)
1372                         .build().unwrap()
1373                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1374                         .build().unwrap()
1375                         .sign(payer_sign).unwrap()
1376                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1377                         .build().unwrap()
1378                         .sign(recipient_sign).unwrap();
1379
1380                 let mut buffer = Vec::new();
1381                 invoice.write(&mut buffer).unwrap();
1382
1383                 if let Err(e) = Invoice::try_from(buffer) {
1384                         panic!("error parsing invoice: {:?}", e);
1385                 }
1386
1387                 let mut tlv_stream = invoice.as_tlv_stream();
1388                 tlv_stream.3.amount = None;
1389
1390                 match Invoice::try_from(tlv_stream.to_bytes()) {
1391                         Ok(_) => panic!("expected error"),
1392                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1393                 }
1394         }
1395
1396         #[test]
1397         fn parses_invoice_with_allow_mpp() {
1398                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1399                         .amount_msats(1000)
1400                         .build().unwrap()
1401                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1402                         .build().unwrap()
1403                         .sign(payer_sign).unwrap()
1404                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1405                         .allow_mpp()
1406                         .build().unwrap()
1407                         .sign(recipient_sign).unwrap();
1408
1409                 let mut buffer = Vec::new();
1410                 invoice.write(&mut buffer).unwrap();
1411
1412                 match Invoice::try_from(buffer) {
1413                         Ok(invoice) => {
1414                                 let mut features = Bolt12InvoiceFeatures::empty();
1415                                 features.set_basic_mpp_optional();
1416                                 assert_eq!(invoice.features(), &features);
1417                         },
1418                         Err(e) => panic!("error parsing invoice: {:?}", e),
1419                 }
1420         }
1421
1422         #[test]
1423         fn parses_invoice_with_fallback_address() {
1424                 let script = Script::new();
1425                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1426                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1427                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1428
1429                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1430                         .amount_msats(1000)
1431                         .build().unwrap();
1432                 let invoice_request = offer
1433                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1434                         .build().unwrap()
1435                         .sign(payer_sign).unwrap();
1436                 let mut unsigned_invoice = invoice_request
1437                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1438                         .fallback_v0_p2wsh(&script.wscript_hash())
1439                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1440                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1441                         .build().unwrap();
1442
1443                 // Only standard addresses will be included.
1444                 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1445                 // Non-standard addresses
1446                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1447                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1448                 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1449                 // Standard address
1450                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1451                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1452
1453                 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1454                 let mut buffer = Vec::new();
1455                 invoice.write(&mut buffer).unwrap();
1456
1457                 match Invoice::try_from(buffer) {
1458                         Ok(invoice) => {
1459                                 assert_eq!(
1460                                         invoice.fallbacks(),
1461                                         vec![
1462                                                 Address::p2wsh(&script, Network::Bitcoin),
1463                                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1464                                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1465                                                 Address {
1466                                                         payload: Payload::WitnessProgram {
1467                                                                 version: WitnessVersion::V1,
1468                                                                 program: vec![0u8; 33],
1469                                                         },
1470                                                         network: Network::Bitcoin,
1471                                                 },
1472                                                 Address {
1473                                                         payload: Payload::WitnessProgram {
1474                                                                 version: WitnessVersion::V2,
1475                                                                 program: vec![0u8; 40],
1476                                                         },
1477                                                         network: Network::Bitcoin,
1478                                                 },
1479                                         ],
1480                                 );
1481                         },
1482                         Err(e) => panic!("error parsing invoice: {:?}", e),
1483                 }
1484         }
1485
1486         #[test]
1487         fn parses_invoice_with_node_id() {
1488                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1489                         .amount_msats(1000)
1490                         .build().unwrap()
1491                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1492                         .build().unwrap()
1493                         .sign(payer_sign).unwrap()
1494                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1495                         .build().unwrap()
1496                         .sign(recipient_sign).unwrap();
1497
1498                 let mut buffer = Vec::new();
1499                 invoice.write(&mut buffer).unwrap();
1500
1501                 if let Err(e) = Invoice::try_from(buffer) {
1502                         panic!("error parsing invoice: {:?}", e);
1503                 }
1504
1505                 let mut tlv_stream = invoice.as_tlv_stream();
1506                 tlv_stream.3.node_id = None;
1507
1508                 match Invoice::try_from(tlv_stream.to_bytes()) {
1509                         Ok(_) => panic!("expected error"),
1510                         Err(e) => {
1511                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1512                         },
1513                 }
1514
1515                 let invalid_pubkey = payer_pubkey();
1516                 let mut tlv_stream = invoice.as_tlv_stream();
1517                 tlv_stream.3.node_id = Some(&invalid_pubkey);
1518
1519                 match Invoice::try_from(tlv_stream.to_bytes()) {
1520                         Ok(_) => panic!("expected error"),
1521                         Err(e) => {
1522                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1523                         },
1524                 }
1525         }
1526
1527         #[test]
1528         fn fails_parsing_invoice_without_signature() {
1529                 let mut buffer = Vec::new();
1530                 OfferBuilder::new("foo".into(), recipient_pubkey())
1531                         .amount_msats(1000)
1532                         .build().unwrap()
1533                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534                         .build().unwrap()
1535                         .sign(payer_sign).unwrap()
1536                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1537                         .build().unwrap()
1538                         .invoice
1539                         .write(&mut buffer).unwrap();
1540
1541                 match Invoice::try_from(buffer) {
1542                         Ok(_) => panic!("expected error"),
1543                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1544                 }
1545         }
1546
1547         #[test]
1548         fn fails_parsing_invoice_with_invalid_signature() {
1549                 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1550                         .amount_msats(1000)
1551                         .build().unwrap()
1552                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1553                         .build().unwrap()
1554                         .sign(payer_sign).unwrap()
1555                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1556                         .build().unwrap()
1557                         .sign(recipient_sign).unwrap();
1558                 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1559                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1560
1561                 let mut buffer = Vec::new();
1562                 invoice.write(&mut buffer).unwrap();
1563
1564                 match Invoice::try_from(buffer) {
1565                         Ok(_) => panic!("expected error"),
1566                         Err(e) => {
1567                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1568                         },
1569                 }
1570         }
1571
1572         #[test]
1573         fn fails_parsing_invoice_with_extra_tlv_records() {
1574                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1575                         .amount_msats(1000)
1576                         .build().unwrap()
1577                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1578                         .build().unwrap()
1579                         .sign(payer_sign).unwrap()
1580                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1581                         .build().unwrap()
1582                         .sign(recipient_sign).unwrap();
1583
1584                 let mut encoded_invoice = Vec::new();
1585                 invoice.write(&mut encoded_invoice).unwrap();
1586                 BigSize(1002).write(&mut encoded_invoice).unwrap();
1587                 BigSize(32).write(&mut encoded_invoice).unwrap();
1588                 [42u8; 32].write(&mut encoded_invoice).unwrap();
1589
1590                 match Invoice::try_from(encoded_invoice) {
1591                         Ok(_) => panic!("expected error"),
1592                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1593                 }
1594         }
1595 }