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