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