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