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