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