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