Merge pull request #2924 from tnull/2024-03-add-user-channel-id-to-payment-forwarded
[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::hashes::Hash;
108 use bitcoin::network::constants::Network;
109 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
110 use bitcoin::secp256k1::schnorr::Signature;
111 use bitcoin::address::{Address, Payload, WitnessProgram, WitnessVersion};
112 use bitcoin::key::TweakedPublicKey;
113 use core::convert::{AsRef, TryFrom};
114 use core::time::Duration;
115 use crate::io;
116 use crate::blinded_path::BlindedPath;
117 use crate::ln::PaymentHash;
118 use crate::ln::channelmanager::PaymentId;
119 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
120 use crate::ln::inbound_payment::ExpandedKey;
121 use crate::ln::msgs::DecodeError;
122 use crate::offers::invoice_request::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, IV_BYTES as INVOICE_REQUEST_IV_BYTES, InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
123 use crate::offers::merkle::{SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream, WithoutSignatures, self};
124 use crate::offers::offer::{Amount, OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef, Quantity};
125 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
126 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerTlvStream, PayerTlvStreamRef};
127 use crate::offers::refund::{IV_BYTES as REFUND_IV_BYTES, Refund, RefundContents};
128 use crate::offers::signer;
129 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
130 use crate::util::string::PrintableString;
131
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
214         ) -> Result<Self, Bolt12SemanticError> {
215                 let amount_msats = Self::amount_msats(invoice_request)?;
216                 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
217                 let contents = InvoiceContents::ForOffer {
218                         invoice_request: invoice_request.contents.clone(),
219                         fields: Self::fields(
220                                 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
221                         ),
222                 };
223
224                 Self::new(&invoice_request.bytes, contents, ExplicitSigningPubkey {})
225         }
226
227         #[cfg_attr(c_bindings, allow(dead_code))]
228         pub(super) fn for_refund(
229                 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
230                 payment_hash: PaymentHash, signing_pubkey: PublicKey
231         ) -> Result<Self, Bolt12SemanticError> {
232                 let amount_msats = refund.amount_msats();
233                 let contents = InvoiceContents::ForRefund {
234                         refund: refund.contents.clone(),
235                         fields: Self::fields(
236                                 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
237                         ),
238                 };
239
240                 Self::new(&refund.bytes, contents, ExplicitSigningPubkey {})
241         }
242
243         /// Builds an unsigned [`Bolt12Invoice`] after checking for valid semantics. It can be signed by
244         /// [`UnsignedBolt12Invoice::sign`].
245         pub fn build($self: $self_type) -> Result<UnsignedBolt12Invoice, Bolt12SemanticError> {
246                 #[cfg(feature = "std")] {
247                         if $self.invoice.is_offer_or_refund_expired() {
248                                 return Err(Bolt12SemanticError::AlreadyExpired);
249                         }
250                 }
251
252                 #[cfg(not(feature = "std"))] {
253                         if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
254                                 return Err(Bolt12SemanticError::AlreadyExpired);
255                         }
256                 }
257
258                 let Self { invreq_bytes, invoice, .. } = $self;
259                 #[cfg(not(c_bindings))] {
260                         Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice))
261                 }
262                 #[cfg(c_bindings)] {
263                         Ok(UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone()))
264                 }
265         }
266 } }
267
268 macro_rules! invoice_derived_signing_pubkey_builder_methods { ($self: ident, $self_type: ty) => {
269         #[cfg_attr(c_bindings, allow(dead_code))]
270         pub(super) fn for_offer_using_keys(
271                 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
272                 created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
273         ) -> Result<Self, Bolt12SemanticError> {
274                 let amount_msats = Self::amount_msats(invoice_request)?;
275                 let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
276                 let contents = InvoiceContents::ForOffer {
277                         invoice_request: invoice_request.contents.clone(),
278                         fields: Self::fields(
279                                 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
280                         ),
281                 };
282
283                 Self::new(&invoice_request.bytes, contents, DerivedSigningPubkey(keys))
284         }
285
286         #[cfg_attr(c_bindings, allow(dead_code))]
287         pub(super) fn for_refund_using_keys(
288                 refund: &'a Refund, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
289                 payment_hash: PaymentHash, keys: KeyPair,
290         ) -> Result<Self, Bolt12SemanticError> {
291                 let amount_msats = refund.amount_msats();
292                 let signing_pubkey = keys.public_key();
293                 let contents = InvoiceContents::ForRefund {
294                         refund: refund.contents.clone(),
295                         fields: Self::fields(
296                                 payment_paths, created_at, payment_hash, amount_msats, signing_pubkey
297                         ),
298                 };
299
300                 Self::new(&refund.bytes, contents, DerivedSigningPubkey(keys))
301         }
302
303         /// Builds a signed [`Bolt12Invoice`] after checking for valid semantics.
304         pub fn build_and_sign<T: secp256k1::Signing>(
305                 $self: $self_type, secp_ctx: &Secp256k1<T>
306         ) -> Result<Bolt12Invoice, Bolt12SemanticError> {
307                 #[cfg(feature = "std")] {
308                         if $self.invoice.is_offer_or_refund_expired() {
309                                 return Err(Bolt12SemanticError::AlreadyExpired);
310                         }
311                 }
312
313                 #[cfg(not(feature = "std"))] {
314                         if $self.invoice.is_offer_or_refund_expired_no_std($self.invoice.created_at()) {
315                                 return Err(Bolt12SemanticError::AlreadyExpired);
316                         }
317                 }
318
319                 let Self {
320                         invreq_bytes, invoice, signing_pubkey_strategy: DerivedSigningPubkey(keys)
321                 } = $self;
322                 #[cfg(not(c_bindings))]
323                 let unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice);
324                 #[cfg(c_bindings)]
325                 let mut unsigned_invoice = UnsignedBolt12Invoice::new(invreq_bytes, invoice.clone());
326
327                 let invoice = unsigned_invoice
328                         .sign(|message: &UnsignedBolt12Invoice|
329                                 Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
330                         )
331                         .unwrap();
332                 Ok(invoice)
333         }
334 } }
335
336 macro_rules! invoice_builder_methods { (
337         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $type_param: ty $(, $self_mut: tt)?
338 ) => {
339         pub(crate) fn amount_msats(
340                 invoice_request: &InvoiceRequest
341         ) -> Result<u64, Bolt12SemanticError> {
342                 match invoice_request.amount_msats() {
343                         Some(amount_msats) => Ok(amount_msats),
344                         None => match invoice_request.contents.inner.offer.amount() {
345                                 Some(Amount::Bitcoin { amount_msats }) => {
346                                         amount_msats.checked_mul(invoice_request.quantity().unwrap_or(1))
347                                                 .ok_or(Bolt12SemanticError::InvalidAmount)
348                                 },
349                                 Some(Amount::Currency { .. }) => Err(Bolt12SemanticError::UnsupportedCurrency),
350                                 None => Err(Bolt12SemanticError::MissingAmount),
351                         },
352                 }
353         }
354
355         #[cfg_attr(c_bindings, allow(dead_code))]
356         fn fields(
357                 payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, created_at: Duration,
358                 payment_hash: PaymentHash, amount_msats: u64, signing_pubkey: PublicKey
359         ) -> InvoiceFields {
360                 InvoiceFields {
361                         payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
362                         fallbacks: None, features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
363                 }
364         }
365
366         #[cfg_attr(c_bindings, allow(dead_code))]
367         fn new(
368                 invreq_bytes: &'a Vec<u8>, contents: InvoiceContents, signing_pubkey_strategy: $type_param
369         ) -> Result<Self, Bolt12SemanticError> {
370                 if contents.fields().payment_paths.is_empty() {
371                         return Err(Bolt12SemanticError::MissingPaths);
372                 }
373
374                 Ok(Self { invreq_bytes, invoice: contents, signing_pubkey_strategy })
375         }
376
377         /// Sets the [`Bolt12Invoice::relative_expiry`] as seconds since [`Bolt12Invoice::created_at`].
378         /// Any expiry that has already passed is valid and can be checked for using
379         /// [`Bolt12Invoice::is_expired`].
380         ///
381         /// Successive calls to this method will override the previous setting.
382         pub fn relative_expiry($($self_mut)* $self: $self_type, relative_expiry_secs: u32) -> $return_type {
383                 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
384                 $self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
385                 $return_value
386         }
387
388         /// Adds a P2WSH address to [`Bolt12Invoice::fallbacks`].
389         ///
390         /// Successive calls to this method will add another address. Caller is responsible for not
391         /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
392         pub fn fallback_v0_p2wsh($($self_mut)* $self: $self_type, script_hash: &WScriptHash) -> $return_type {
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                 let address = FallbackAddress {
407                         version: WitnessVersion::V0.to_num(),
408                         program: Vec::from(pubkey_hash.to_byte_array()),
409                 };
410                 $self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
411                 $return_value
412         }
413
414         /// Adds a P2TR address to [`Bolt12Invoice::fallbacks`].
415         ///
416         /// Successive calls to this method will add another address. Caller is responsible for not
417         /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
418         pub fn fallback_v1_p2tr_tweaked($($self_mut)* $self: $self_type, output_key: &TweakedPublicKey) -> $return_type {
419                 let address = FallbackAddress {
420                         version: WitnessVersion::V1.to_num(),
421                         program: Vec::from(&output_key.serialize()[..]),
422                 };
423                 $self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
424                 $return_value
425         }
426
427         /// Sets [`Bolt12Invoice::invoice_features`] to indicate MPP may be used. Otherwise, MPP is
428         /// disallowed.
429         pub fn allow_mpp($($self_mut)* $self: $self_type) -> $return_type {
430                 $self.invoice.fields_mut().features.set_basic_mpp_optional();
431                 $return_value
432         }
433 } }
434
435 impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
436         invoice_explicit_signing_pubkey_builder_methods!(self, Self);
437 }
438
439 impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
440         invoice_derived_signing_pubkey_builder_methods!(self, Self);
441 }
442
443 impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
444         invoice_builder_methods!(self, Self, Self, self, S, mut);
445 }
446
447 #[cfg(all(c_bindings, not(test)))]
448 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
449         invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
450         invoice_builder_methods!(self, &mut Self, (), (), ExplicitSigningPubkey);
451 }
452
453 #[cfg(all(c_bindings, test))]
454 impl<'a> InvoiceWithExplicitSigningPubkeyBuilder<'a> {
455         invoice_explicit_signing_pubkey_builder_methods!(self, &mut Self);
456         invoice_builder_methods!(self, &mut Self, &mut Self, self, ExplicitSigningPubkey);
457 }
458
459 #[cfg(all(c_bindings, not(test)))]
460 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
461         invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
462         invoice_builder_methods!(self, &mut Self, (), (), DerivedSigningPubkey);
463 }
464
465 #[cfg(all(c_bindings, test))]
466 impl<'a> InvoiceWithDerivedSigningPubkeyBuilder<'a> {
467         invoice_derived_signing_pubkey_builder_methods!(self, &mut Self);
468         invoice_builder_methods!(self, &mut Self, &mut Self, self, DerivedSigningPubkey);
469 }
470
471 #[cfg(c_bindings)]
472 impl<'a> From<InvoiceWithExplicitSigningPubkeyBuilder<'a>>
473 for InvoiceBuilder<'a, ExplicitSigningPubkey> {
474         fn from(builder: InvoiceWithExplicitSigningPubkeyBuilder<'a>) -> Self {
475                 let InvoiceWithExplicitSigningPubkeyBuilder {
476                         invreq_bytes, invoice, signing_pubkey_strategy,
477                 } = builder;
478
479                 Self {
480                         invreq_bytes, invoice, signing_pubkey_strategy,
481                 }
482         }
483 }
484
485 #[cfg(c_bindings)]
486 impl<'a> From<InvoiceWithDerivedSigningPubkeyBuilder<'a>>
487 for InvoiceBuilder<'a, DerivedSigningPubkey> {
488         fn from(builder: InvoiceWithDerivedSigningPubkeyBuilder<'a>) -> Self {
489                 let InvoiceWithDerivedSigningPubkeyBuilder {
490                         invreq_bytes, invoice, signing_pubkey_strategy,
491                 } = builder;
492
493                 Self {
494                         invreq_bytes, invoice, signing_pubkey_strategy,
495                 }
496         }
497 }
498
499 /// A semantically valid [`Bolt12Invoice`] that hasn't been signed.
500 ///
501 /// # Serialization
502 ///
503 /// This is serialized as a TLV stream, which includes TLV records from the originating message. As
504 /// such, it may include unknown, odd TLV records.
505 pub struct UnsignedBolt12Invoice {
506         bytes: Vec<u8>,
507         contents: InvoiceContents,
508         tagged_hash: TaggedHash,
509 }
510
511 /// A function for signing an [`UnsignedBolt12Invoice`].
512 pub trait SignBolt12InvoiceFn {
513         /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
514         fn sign_invoice(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()>;
515 }
516
517 impl<F> SignBolt12InvoiceFn for F
518 where
519         F: Fn(&UnsignedBolt12Invoice) -> Result<Signature, ()>,
520 {
521         fn sign_invoice(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()> {
522                 self(message)
523         }
524 }
525
526 impl<F> SignFn<UnsignedBolt12Invoice> for F
527 where
528         F: SignBolt12InvoiceFn,
529 {
530         fn sign(&self, message: &UnsignedBolt12Invoice) -> Result<Signature, ()> {
531                 self.sign_invoice(message)
532         }
533 }
534
535 impl UnsignedBolt12Invoice {
536         fn new(invreq_bytes: &[u8], contents: InvoiceContents) -> Self {
537                 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
538                 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
539                 // `RefundContents`.
540                 let (_, _, _, invoice_tlv_stream) = contents.as_tlv_stream();
541                 let invoice_request_bytes = WithoutSignatures(invreq_bytes);
542                 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
543
544                 let mut bytes = Vec::new();
545                 unsigned_tlv_stream.write(&mut bytes).unwrap();
546
547                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
548
549                 Self { bytes, contents, tagged_hash }
550         }
551
552         /// Returns the [`TaggedHash`] of the invoice to sign.
553         pub fn tagged_hash(&self) -> &TaggedHash {
554                 &self.tagged_hash
555         }
556 }
557
558 macro_rules! unsigned_invoice_sign_method { ($self: ident, $self_type: ty $(, $self_mut: tt)?) => {
559         /// Signs the [`TaggedHash`] of the invoice using the given function.
560         ///
561         /// Note: The hash computation may have included unknown, odd TLV records.
562         pub fn sign<F: SignBolt12InvoiceFn>(
563                 $($self_mut)* $self: $self_type, sign: F
564         ) -> Result<Bolt12Invoice, SignError> {
565                 let pubkey = $self.contents.fields().signing_pubkey;
566                 let signature = merkle::sign_message(sign, &$self, pubkey)?;
567
568                 // Append the signature TLV record to the bytes.
569                 let signature_tlv_stream = SignatureTlvStreamRef {
570                         signature: Some(&signature),
571                 };
572                 signature_tlv_stream.write(&mut $self.bytes).unwrap();
573
574                 Ok(Bolt12Invoice {
575                         #[cfg(not(c_bindings))]
576                         bytes: $self.bytes,
577                         #[cfg(c_bindings)]
578                         bytes: $self.bytes.clone(),
579                         #[cfg(not(c_bindings))]
580                         contents: $self.contents,
581                         #[cfg(c_bindings)]
582                         contents: $self.contents.clone(),
583                         signature,
584                         #[cfg(not(c_bindings))]
585                         tagged_hash: $self.tagged_hash,
586                         #[cfg(c_bindings)]
587                         tagged_hash: $self.tagged_hash.clone(),
588                 })
589         }
590 } }
591
592 #[cfg(not(c_bindings))]
593 impl UnsignedBolt12Invoice {
594         unsigned_invoice_sign_method!(self, Self, mut);
595 }
596
597 #[cfg(c_bindings)]
598 impl UnsignedBolt12Invoice {
599         unsigned_invoice_sign_method!(self, &mut Self);
600 }
601
602 impl AsRef<TaggedHash> for UnsignedBolt12Invoice {
603         fn as_ref(&self) -> &TaggedHash {
604                 &self.tagged_hash
605         }
606 }
607
608 /// A `Bolt12Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
609 ///
610 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
611 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
612 ///
613 /// [`Offer`]: crate::offers::offer::Offer
614 /// [`Refund`]: crate::offers::refund::Refund
615 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
616 #[derive(Clone, Debug)]
617 #[cfg_attr(test, derive(PartialEq))]
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 InvoiceContents {
890         /// Whether the original offer or refund has expired.
891         #[cfg(feature = "std")]
892         fn is_offer_or_refund_expired(&self) -> bool {
893                 match self {
894                         InvoiceContents::ForOffer { invoice_request, .. } =>
895                                 invoice_request.inner.offer.is_expired(),
896                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
897                 }
898         }
899
900         #[cfg(not(feature = "std"))]
901         fn is_offer_or_refund_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
902                 match self {
903                         InvoiceContents::ForOffer { invoice_request, .. } =>
904                                 invoice_request.inner.offer.is_expired_no_std(duration_since_epoch),
905                         InvoiceContents::ForRefund { refund, .. } =>
906                                 refund.is_expired_no_std(duration_since_epoch),
907                 }
908         }
909
910         fn offer_chains(&self) -> Option<Vec<ChainHash>> {
911                 match self {
912                         InvoiceContents::ForOffer { invoice_request, .. } =>
913                                 Some(invoice_request.inner.offer.chains()),
914                         InvoiceContents::ForRefund { .. } => None,
915                 }
916         }
917
918         fn chain(&self) -> ChainHash {
919                 match self {
920                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
921                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
922                 }
923         }
924
925         fn metadata(&self) -> Option<&Vec<u8>> {
926                 match self {
927                         InvoiceContents::ForOffer { invoice_request, .. } =>
928                                 invoice_request.inner.offer.metadata(),
929                         InvoiceContents::ForRefund { .. } => None,
930                 }
931         }
932
933         fn amount(&self) -> Option<&Amount> {
934                 match self {
935                         InvoiceContents::ForOffer { invoice_request, .. } =>
936                                 invoice_request.inner.offer.amount(),
937                         InvoiceContents::ForRefund { .. } => None,
938                 }
939         }
940
941         fn description(&self) -> PrintableString {
942                 match self {
943                         InvoiceContents::ForOffer { invoice_request, .. } => {
944                                 invoice_request.inner.offer.description()
945                         },
946                         InvoiceContents::ForRefund { refund, .. } => refund.description(),
947                 }
948         }
949
950         fn offer_features(&self) -> Option<&OfferFeatures> {
951                 match self {
952                         InvoiceContents::ForOffer { invoice_request, .. } => {
953                                 Some(invoice_request.inner.offer.features())
954                         },
955                         InvoiceContents::ForRefund { .. } => None,
956                 }
957         }
958
959         fn absolute_expiry(&self) -> Option<Duration> {
960                 match self {
961                         InvoiceContents::ForOffer { invoice_request, .. } => {
962                                 invoice_request.inner.offer.absolute_expiry()
963                         },
964                         InvoiceContents::ForRefund { refund, .. } => refund.absolute_expiry(),
965                 }
966         }
967
968         fn issuer(&self) -> Option<PrintableString> {
969                 match self {
970                         InvoiceContents::ForOffer { invoice_request, .. } => {
971                                 invoice_request.inner.offer.issuer()
972                         },
973                         InvoiceContents::ForRefund { refund, .. } => refund.issuer(),
974                 }
975         }
976
977         fn message_paths(&self) -> &[BlindedPath] {
978                 match self {
979                         InvoiceContents::ForOffer { invoice_request, .. } => {
980                                 invoice_request.inner.offer.paths()
981                         },
982                         InvoiceContents::ForRefund { refund, .. } => refund.paths(),
983                 }
984         }
985
986         fn supported_quantity(&self) -> Option<Quantity> {
987                 match self {
988                         InvoiceContents::ForOffer { invoice_request, .. } => {
989                                 Some(invoice_request.inner.offer.supported_quantity())
990                         },
991                         InvoiceContents::ForRefund { .. } => None,
992                 }
993         }
994
995         fn payer_metadata(&self) -> &[u8] {
996                 match self {
997                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.metadata(),
998                         InvoiceContents::ForRefund { refund, .. } => refund.metadata(),
999                 }
1000         }
1001
1002         fn invoice_request_features(&self) -> &InvoiceRequestFeatures {
1003                 match self {
1004                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.features(),
1005                         InvoiceContents::ForRefund { refund, .. } => refund.features(),
1006                 }
1007         }
1008
1009         fn quantity(&self) -> Option<u64> {
1010                 match self {
1011                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.quantity(),
1012                         InvoiceContents::ForRefund { refund, .. } => refund.quantity(),
1013                 }
1014         }
1015
1016         fn payer_id(&self) -> PublicKey {
1017                 match self {
1018                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_id(),
1019                         InvoiceContents::ForRefund { refund, .. } => refund.payer_id(),
1020                 }
1021         }
1022
1023         fn payer_note(&self) -> Option<PrintableString> {
1024                 match self {
1025                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.payer_note(),
1026                         InvoiceContents::ForRefund { refund, .. } => refund.payer_note(),
1027                 }
1028         }
1029
1030         fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1031                 &self.fields().payment_paths[..]
1032         }
1033
1034         fn created_at(&self) -> Duration {
1035                 self.fields().created_at
1036         }
1037
1038         fn relative_expiry(&self) -> Duration {
1039                 self.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
1040         }
1041
1042         #[cfg(feature = "std")]
1043         fn is_expired(&self) -> bool {
1044                 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
1045                 match absolute_expiry {
1046                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
1047                                 Ok(elapsed) => elapsed > seconds_from_epoch,
1048                                 Err(_) => false,
1049                         },
1050                         None => false,
1051                 }
1052         }
1053
1054         fn payment_hash(&self) -> PaymentHash {
1055                 self.fields().payment_hash
1056         }
1057
1058         fn amount_msats(&self) -> u64 {
1059                 self.fields().amount_msats
1060         }
1061
1062         fn fallbacks(&self) -> Vec<Address> {
1063                 let chain = self.chain();
1064                 let network = if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
1065                         Network::Bitcoin
1066                 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
1067                         Network::Testnet
1068                 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
1069                         Network::Signet
1070                 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
1071                         Network::Regtest
1072                 } else {
1073                         return Vec::new()
1074                 };
1075
1076                 let to_valid_address = |address: &FallbackAddress| {
1077                         let version = match WitnessVersion::try_from(address.version) {
1078                                 Ok(version) => version,
1079                                 Err(_) => return None,
1080                         };
1081
1082                         let program = &address.program;
1083                         let witness_program = match WitnessProgram::new(version, program.clone()) {
1084                                 Ok(witness_program) => witness_program,
1085                                 Err(_) => return None,
1086                         };
1087                         Some(Address::new(network, Payload::WitnessProgram(witness_program)))
1088                 };
1089
1090                 self.fields().fallbacks
1091                         .as_ref()
1092                         .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
1093                         .unwrap_or_else(Vec::new)
1094         }
1095
1096         fn features(&self) -> &Bolt12InvoiceFeatures {
1097                 &self.fields().features
1098         }
1099
1100         fn signing_pubkey(&self) -> PublicKey {
1101                 self.fields().signing_pubkey
1102         }
1103
1104         fn fields(&self) -> &InvoiceFields {
1105                 match self {
1106                         InvoiceContents::ForOffer { fields, .. } => fields,
1107                         InvoiceContents::ForRefund { fields, .. } => fields,
1108                 }
1109         }
1110
1111         fn fields_mut(&mut self) -> &mut InvoiceFields {
1112                 match self {
1113                         InvoiceContents::ForOffer { fields, .. } => fields,
1114                         InvoiceContents::ForRefund { fields, .. } => fields,
1115                 }
1116         }
1117
1118         fn verify<T: secp256k1::Signing>(
1119                 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
1120         ) -> Result<PaymentId, ()> {
1121                 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
1122                 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
1123                         match record.r#type {
1124                                 PAYER_METADATA_TYPE => false, // Should be outside range
1125                                 INVOICE_REQUEST_PAYER_ID_TYPE => !self.derives_keys(),
1126                                 _ => true,
1127                         }
1128                 });
1129                 let tlv_stream = offer_records.chain(invreq_records);
1130
1131                 let (metadata, payer_id, iv_bytes) = match self {
1132                         InvoiceContents::ForOffer { invoice_request, .. } => {
1133                                 (invoice_request.metadata(), invoice_request.payer_id(), INVOICE_REQUEST_IV_BYTES)
1134                         },
1135                         InvoiceContents::ForRefund { refund, .. } => {
1136                                 (refund.metadata(), refund.payer_id(), REFUND_IV_BYTES)
1137                         },
1138                 };
1139
1140                 signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
1141         }
1142
1143         fn derives_keys(&self) -> bool {
1144                 match self {
1145                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.derives_keys(),
1146                         InvoiceContents::ForRefund { refund, .. } => refund.derives_keys(),
1147                 }
1148         }
1149
1150         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
1151                 let (payer, offer, invoice_request) = match self {
1152                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
1153                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
1154                 };
1155                 let invoice = self.fields().as_tlv_stream();
1156
1157                 (payer, offer, invoice_request, invoice)
1158         }
1159 }
1160
1161 impl InvoiceFields {
1162         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
1163                 let features = {
1164                         if self.features == Bolt12InvoiceFeatures::empty() { None }
1165                         else { Some(&self.features) }
1166                 };
1167
1168                 InvoiceTlvStreamRef {
1169                         paths: Some(Iterable(self.payment_paths.iter().map(|(_, path)| path))),
1170                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(payinfo, _)| payinfo))),
1171                         created_at: Some(self.created_at.as_secs()),
1172                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
1173                         payment_hash: Some(&self.payment_hash),
1174                         amount: Some(self.amount_msats),
1175                         fallbacks: self.fallbacks.as_ref(),
1176                         features,
1177                         node_id: Some(&self.signing_pubkey),
1178                 }
1179         }
1180 }
1181
1182 impl Writeable for UnsignedBolt12Invoice {
1183         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1184                 WithoutLength(&self.bytes).write(writer)
1185         }
1186 }
1187
1188 impl Writeable for Bolt12Invoice {
1189         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1190                 WithoutLength(&self.bytes).write(writer)
1191         }
1192 }
1193
1194 impl Writeable for InvoiceContents {
1195         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1196                 self.as_tlv_stream().write(writer)
1197         }
1198 }
1199
1200 impl TryFrom<Vec<u8>> for UnsignedBolt12Invoice {
1201         type Error = Bolt12ParseError;
1202
1203         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1204                 let invoice = ParsedMessage::<PartialInvoiceTlvStream>::try_from(bytes)?;
1205                 let ParsedMessage { bytes, tlv_stream } = invoice;
1206                 let (
1207                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1208                 ) = tlv_stream;
1209                 let contents = InvoiceContents::try_from(
1210                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1211                 )?;
1212
1213                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1214
1215                 Ok(UnsignedBolt12Invoice { bytes, contents, tagged_hash })
1216         }
1217 }
1218
1219 impl TryFrom<Vec<u8>> for Bolt12Invoice {
1220         type Error = Bolt12ParseError;
1221
1222         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1223                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
1224                 Bolt12Invoice::try_from(parsed_invoice)
1225         }
1226 }
1227
1228 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
1229         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
1230         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
1231         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
1232         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
1233         (168, payment_hash: PaymentHash),
1234         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
1235         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
1236         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
1237         (176, node_id: PublicKey),
1238 });
1239
1240 type BlindedPathIter<'a> = core::iter::Map<
1241         core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1242         for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPath,
1243 >;
1244
1245 type BlindedPayInfoIter<'a> = core::iter::Map<
1246         core::slice::Iter<'a, (BlindedPayInfo, BlindedPath)>,
1247         for<'r> fn(&'r (BlindedPayInfo, BlindedPath)) -> &'r BlindedPayInfo,
1248 >;
1249
1250 /// Information needed to route a payment across a [`BlindedPath`].
1251 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
1252 pub struct BlindedPayInfo {
1253         /// Base fee charged (in millisatoshi) for the entire blinded path.
1254         pub fee_base_msat: u32,
1255
1256         /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
1257         /// (i.e., 10,000 is 1%).
1258         pub fee_proportional_millionths: u32,
1259
1260         /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
1261         /// path.
1262         pub cltv_expiry_delta: u16,
1263
1264         /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1265         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1266         /// seen by the recipient.
1267         pub htlc_minimum_msat: u64,
1268
1269         /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
1270         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
1271         /// seen by the recipient.
1272         pub htlc_maximum_msat: u64,
1273
1274         /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
1275         /// onion payload.
1276         pub features: BlindedHopFeatures,
1277 }
1278
1279 impl_writeable!(BlindedPayInfo, {
1280         fee_base_msat,
1281         fee_proportional_millionths,
1282         cltv_expiry_delta,
1283         htlc_minimum_msat,
1284         htlc_maximum_msat,
1285         features
1286 });
1287
1288 /// Wire representation for an on-chain fallback address.
1289 #[derive(Clone, Debug, PartialEq)]
1290 pub(super) struct FallbackAddress {
1291         version: u8,
1292         program: Vec<u8>,
1293 }
1294
1295 impl_writeable!(FallbackAddress, { version, program });
1296
1297 type FullInvoiceTlvStream =
1298         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
1299
1300 type FullInvoiceTlvStreamRef<'a> = (
1301         PayerTlvStreamRef<'a>,
1302         OfferTlvStreamRef<'a>,
1303         InvoiceRequestTlvStreamRef<'a>,
1304         InvoiceTlvStreamRef<'a>,
1305         SignatureTlvStreamRef<'a>,
1306 );
1307
1308 impl SeekReadable for FullInvoiceTlvStream {
1309         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1310                 let payer = SeekReadable::read(r)?;
1311                 let offer = SeekReadable::read(r)?;
1312                 let invoice_request = SeekReadable::read(r)?;
1313                 let invoice = SeekReadable::read(r)?;
1314                 let signature = SeekReadable::read(r)?;
1315
1316                 Ok((payer, offer, invoice_request, invoice, signature))
1317         }
1318 }
1319
1320 type PartialInvoiceTlvStream =
1321         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
1322
1323 type PartialInvoiceTlvStreamRef<'a> = (
1324         PayerTlvStreamRef<'a>,
1325         OfferTlvStreamRef<'a>,
1326         InvoiceRequestTlvStreamRef<'a>,
1327         InvoiceTlvStreamRef<'a>,
1328 );
1329
1330 impl SeekReadable for PartialInvoiceTlvStream {
1331         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
1332                 let payer = SeekReadable::read(r)?;
1333                 let offer = SeekReadable::read(r)?;
1334                 let invoice_request = SeekReadable::read(r)?;
1335                 let invoice = SeekReadable::read(r)?;
1336
1337                 Ok((payer, offer, invoice_request, invoice))
1338         }
1339 }
1340
1341 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Bolt12Invoice {
1342         type Error = Bolt12ParseError;
1343
1344         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
1345                 let ParsedMessage { bytes, tlv_stream } = invoice;
1346                 let (
1347                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
1348                         SignatureTlvStream { signature },
1349                 ) = tlv_stream;
1350                 let contents = InvoiceContents::try_from(
1351                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
1352                 )?;
1353
1354                 let signature = match signature {
1355                         None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
1356                         Some(signature) => signature,
1357                 };
1358                 let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);
1359                 let pubkey = contents.fields().signing_pubkey;
1360                 merkle::verify_signature(&signature, &tagged_hash, pubkey)?;
1361
1362                 Ok(Bolt12Invoice { bytes, contents, signature, tagged_hash })
1363         }
1364 }
1365
1366 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
1367         type Error = Bolt12SemanticError;
1368
1369         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
1370                 let (
1371                         payer_tlv_stream,
1372                         offer_tlv_stream,
1373                         invoice_request_tlv_stream,
1374                         InvoiceTlvStream {
1375                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
1376                                 features, node_id,
1377                         },
1378                 ) = tlv_stream;
1379
1380                 let payment_paths = match (blindedpay, paths) {
1381                         (_, None) => return Err(Bolt12SemanticError::MissingPaths),
1382                         (None, _) => return Err(Bolt12SemanticError::InvalidPayInfo),
1383                         (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1384                         (Some(blindedpay), Some(paths)) if paths.len() != blindedpay.len() => {
1385                                 return Err(Bolt12SemanticError::InvalidPayInfo);
1386                         },
1387                         (Some(blindedpay), Some(paths)) => {
1388                                 blindedpay.into_iter().zip(paths.into_iter()).collect::<Vec<_>>()
1389                         },
1390                 };
1391
1392                 let created_at = match created_at {
1393                         None => return Err(Bolt12SemanticError::MissingCreationTime),
1394                         Some(timestamp) => Duration::from_secs(timestamp),
1395                 };
1396
1397                 let relative_expiry = relative_expiry
1398                         .map(Into::<u64>::into)
1399                         .map(Duration::from_secs);
1400
1401                 let payment_hash = match payment_hash {
1402                         None => return Err(Bolt12SemanticError::MissingPaymentHash),
1403                         Some(payment_hash) => payment_hash,
1404                 };
1405
1406                 let amount_msats = match amount {
1407                         None => return Err(Bolt12SemanticError::MissingAmount),
1408                         Some(amount) => amount,
1409                 };
1410
1411                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
1412
1413                 let signing_pubkey = match node_id {
1414                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1415                         Some(node_id) => node_id,
1416                 };
1417
1418                 let fields = InvoiceFields {
1419                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
1420                         features, signing_pubkey,
1421                 };
1422
1423                 match offer_tlv_stream.node_id {
1424                         Some(expected_signing_pubkey) => {
1425                                 if fields.signing_pubkey != expected_signing_pubkey {
1426                                         return Err(Bolt12SemanticError::InvalidSigningPubkey);
1427                                 }
1428
1429                                 let invoice_request = InvoiceRequestContents::try_from(
1430                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1431                                 )?;
1432                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
1433                         },
1434                         None => {
1435                                 let refund = RefundContents::try_from(
1436                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
1437                                 )?;
1438                                 Ok(InvoiceContents::ForRefund { refund, fields })
1439                         },
1440                 }
1441         }
1442 }
1443
1444 #[cfg(test)]
1445 mod tests {
1446         use super::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, FallbackAddress, FullInvoiceTlvStreamRef, InvoiceTlvStreamRef, SIGNATURE_TAG, UnsignedBolt12Invoice};
1447
1448         use bitcoin::blockdata::constants::ChainHash;
1449         use bitcoin::blockdata::script::ScriptBuf;
1450         use bitcoin::hashes::Hash;
1451         use bitcoin::network::constants::Network;
1452         use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey, self};
1453         use bitcoin::address::{Address, Payload, WitnessProgram, WitnessVersion};
1454         use bitcoin::key::TweakedPublicKey;
1455         use core::convert::TryFrom;
1456         use core::time::Duration;
1457         use crate::blinded_path::{BlindedHop, BlindedPath};
1458         use crate::sign::KeyMaterial;
1459         use crate::ln::features::{Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
1460         use crate::ln::inbound_payment::ExpandedKey;
1461         use crate::ln::msgs::DecodeError;
1462         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
1463         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
1464         use crate::offers::offer::{Amount, OfferTlvStreamRef, Quantity};
1465         #[cfg(not(c_bindings))]
1466         use {
1467                 crate::offers::offer::OfferBuilder,
1468                 crate::offers::refund::RefundBuilder,
1469         };
1470         #[cfg(c_bindings)]
1471         use {
1472                 crate::offers::offer::OfferWithExplicitMetadataBuilder as OfferBuilder,
1473                 crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
1474         };
1475         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1476         use crate::offers::payer::PayerTlvStreamRef;
1477         use crate::offers::test_utils::*;
1478         use crate::util::ser::{BigSize, Iterable, Writeable};
1479         use crate::util::string::PrintableString;
1480
1481         trait ToBytes {
1482                 fn to_bytes(&self) -> Vec<u8>;
1483         }
1484
1485         impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
1486                 fn to_bytes(&self) -> Vec<u8> {
1487                         let mut buffer = Vec::new();
1488                         self.0.write(&mut buffer).unwrap();
1489                         self.1.write(&mut buffer).unwrap();
1490                         self.2.write(&mut buffer).unwrap();
1491                         self.3.write(&mut buffer).unwrap();
1492                         self.4.write(&mut buffer).unwrap();
1493                         buffer
1494                 }
1495         }
1496
1497         #[test]
1498         fn builds_invoice_for_offer_with_defaults() {
1499                 let payment_paths = payment_paths();
1500                 let payment_hash = payment_hash();
1501                 let now = now();
1502                 let unsigned_invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1503                         .amount_msats(1000)
1504                         .build().unwrap()
1505                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1506                         .build().unwrap()
1507                         .sign(payer_sign).unwrap()
1508                         .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
1509                         .build().unwrap();
1510
1511                 let mut buffer = Vec::new();
1512                 unsigned_invoice.write(&mut buffer).unwrap();
1513
1514                 assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
1515                 assert_eq!(unsigned_invoice.payer_metadata(), &[1; 32]);
1516                 assert_eq!(unsigned_invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1517                 assert_eq!(unsigned_invoice.metadata(), None);
1518                 assert_eq!(unsigned_invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1519                 assert_eq!(unsigned_invoice.description(), PrintableString("foo"));
1520                 assert_eq!(unsigned_invoice.offer_features(), Some(&OfferFeatures::empty()));
1521                 assert_eq!(unsigned_invoice.absolute_expiry(), None);
1522                 assert_eq!(unsigned_invoice.message_paths(), &[]);
1523                 assert_eq!(unsigned_invoice.issuer(), None);
1524                 assert_eq!(unsigned_invoice.supported_quantity(), Some(Quantity::One));
1525                 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1526                 assert_eq!(unsigned_invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1527                 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1528                 assert_eq!(unsigned_invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1529                 assert_eq!(unsigned_invoice.quantity(), None);
1530                 assert_eq!(unsigned_invoice.payer_id(), payer_pubkey());
1531                 assert_eq!(unsigned_invoice.payer_note(), None);
1532                 assert_eq!(unsigned_invoice.payment_paths(), payment_paths.as_slice());
1533                 assert_eq!(unsigned_invoice.created_at(), now);
1534                 assert_eq!(unsigned_invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1535                 #[cfg(feature = "std")]
1536                 assert!(!unsigned_invoice.is_expired());
1537                 assert_eq!(unsigned_invoice.payment_hash(), payment_hash);
1538                 assert_eq!(unsigned_invoice.amount_msats(), 1000);
1539                 assert_eq!(unsigned_invoice.fallbacks(), vec![]);
1540                 assert_eq!(unsigned_invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1541                 assert_eq!(unsigned_invoice.signing_pubkey(), recipient_pubkey());
1542
1543                 match UnsignedBolt12Invoice::try_from(buffer) {
1544                         Err(e) => panic!("error parsing unsigned invoice: {:?}", e),
1545                         Ok(parsed) => {
1546                                 assert_eq!(parsed.bytes, unsigned_invoice.bytes);
1547                                 assert_eq!(parsed.tagged_hash, unsigned_invoice.tagged_hash);
1548                         },
1549                 }
1550
1551                 #[cfg(c_bindings)]
1552                 let mut unsigned_invoice = unsigned_invoice;
1553                 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1554
1555                 let mut buffer = Vec::new();
1556                 invoice.write(&mut buffer).unwrap();
1557
1558                 assert_eq!(invoice.bytes, buffer.as_slice());
1559                 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1560                 assert_eq!(invoice.offer_chains(), Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)]));
1561                 assert_eq!(invoice.metadata(), None);
1562                 assert_eq!(invoice.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
1563                 assert_eq!(invoice.description(), PrintableString("foo"));
1564                 assert_eq!(invoice.offer_features(), Some(&OfferFeatures::empty()));
1565                 assert_eq!(invoice.absolute_expiry(), None);
1566                 assert_eq!(invoice.message_paths(), &[]);
1567                 assert_eq!(invoice.issuer(), None);
1568                 assert_eq!(invoice.supported_quantity(), Some(Quantity::One));
1569                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1570                 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1571                 assert_eq!(invoice.amount_msats(), 1000);
1572                 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1573                 assert_eq!(invoice.quantity(), None);
1574                 assert_eq!(invoice.payer_id(), payer_pubkey());
1575                 assert_eq!(invoice.payer_note(), None);
1576                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1577                 assert_eq!(invoice.created_at(), now);
1578                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1579                 #[cfg(feature = "std")]
1580                 assert!(!invoice.is_expired());
1581                 assert_eq!(invoice.payment_hash(), payment_hash);
1582                 assert_eq!(invoice.amount_msats(), 1000);
1583                 assert_eq!(invoice.fallbacks(), vec![]);
1584                 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1585                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1586
1587                 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1588                 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1589
1590                 let digest = Message::from_slice(&invoice.signable_hash()).unwrap();
1591                 let pubkey = recipient_pubkey().into();
1592                 let secp_ctx = Secp256k1::verification_only();
1593                 assert!(secp_ctx.verify_schnorr(&invoice.signature, &digest, &pubkey).is_ok());
1594
1595                 assert_eq!(
1596                         invoice.as_tlv_stream(),
1597                         (
1598                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1599                                 OfferTlvStreamRef {
1600                                         chains: None,
1601                                         metadata: None,
1602                                         currency: None,
1603                                         amount: Some(1000),
1604                                         description: Some(&String::from("foo")),
1605                                         features: None,
1606                                         absolute_expiry: None,
1607                                         paths: None,
1608                                         issuer: None,
1609                                         quantity_max: None,
1610                                         node_id: Some(&recipient_pubkey()),
1611                                 },
1612                                 InvoiceRequestTlvStreamRef {
1613                                         chain: None,
1614                                         amount: None,
1615                                         features: None,
1616                                         quantity: None,
1617                                         payer_id: Some(&payer_pubkey()),
1618                                         payer_note: None,
1619                                 },
1620                                 InvoiceTlvStreamRef {
1621                                         paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1622                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1623                                         created_at: Some(now.as_secs()),
1624                                         relative_expiry: None,
1625                                         payment_hash: Some(&payment_hash),
1626                                         amount: Some(1000),
1627                                         fallbacks: None,
1628                                         features: None,
1629                                         node_id: Some(&recipient_pubkey()),
1630                                 },
1631                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1632                         ),
1633                 );
1634
1635                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1636                         panic!("error parsing invoice: {:?}", e);
1637                 }
1638         }
1639
1640         #[test]
1641         fn builds_invoice_for_refund_with_defaults() {
1642                 let payment_paths = payment_paths();
1643                 let payment_hash = payment_hash();
1644                 let now = now();
1645                 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1646                         .build().unwrap()
1647                         .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
1648                         .unwrap()
1649                         .build().unwrap()
1650                         .sign(recipient_sign).unwrap();
1651
1652                 let mut buffer = Vec::new();
1653                 invoice.write(&mut buffer).unwrap();
1654
1655                 assert_eq!(invoice.bytes, buffer.as_slice());
1656                 assert_eq!(invoice.payer_metadata(), &[1; 32]);
1657                 assert_eq!(invoice.offer_chains(), None);
1658                 assert_eq!(invoice.metadata(), None);
1659                 assert_eq!(invoice.amount(), None);
1660                 assert_eq!(invoice.description(), PrintableString("foo"));
1661                 assert_eq!(invoice.offer_features(), None);
1662                 assert_eq!(invoice.absolute_expiry(), None);
1663                 assert_eq!(invoice.message_paths(), &[]);
1664                 assert_eq!(invoice.issuer(), None);
1665                 assert_eq!(invoice.supported_quantity(), None);
1666                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1667                 assert_eq!(invoice.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
1668                 assert_eq!(invoice.amount_msats(), 1000);
1669                 assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
1670                 assert_eq!(invoice.quantity(), None);
1671                 assert_eq!(invoice.payer_id(), payer_pubkey());
1672                 assert_eq!(invoice.payer_note(), None);
1673                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
1674                 assert_eq!(invoice.created_at(), now);
1675                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
1676                 #[cfg(feature = "std")]
1677                 assert!(!invoice.is_expired());
1678                 assert_eq!(invoice.payment_hash(), payment_hash);
1679                 assert_eq!(invoice.amount_msats(), 1000);
1680                 assert_eq!(invoice.fallbacks(), vec![]);
1681                 assert_eq!(invoice.invoice_features(), &Bolt12InvoiceFeatures::empty());
1682                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1683
1684                 let message = TaggedHash::new(SIGNATURE_TAG, &invoice.bytes);
1685                 assert!(merkle::verify_signature(&invoice.signature, &message, recipient_pubkey()).is_ok());
1686
1687                 assert_eq!(
1688                         invoice.as_tlv_stream(),
1689                         (
1690                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1691                                 OfferTlvStreamRef {
1692                                         chains: None,
1693                                         metadata: None,
1694                                         currency: None,
1695                                         amount: None,
1696                                         description: Some(&String::from("foo")),
1697                                         features: None,
1698                                         absolute_expiry: None,
1699                                         paths: None,
1700                                         issuer: None,
1701                                         quantity_max: None,
1702                                         node_id: None,
1703                                 },
1704                                 InvoiceRequestTlvStreamRef {
1705                                         chain: None,
1706                                         amount: Some(1000),
1707                                         features: None,
1708                                         quantity: None,
1709                                         payer_id: Some(&payer_pubkey()),
1710                                         payer_note: None,
1711                                 },
1712                                 InvoiceTlvStreamRef {
1713                                         paths: Some(Iterable(payment_paths.iter().map(|(_, path)| path))),
1714                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo))),
1715                                         created_at: Some(now.as_secs()),
1716                                         relative_expiry: None,
1717                                         payment_hash: Some(&payment_hash),
1718                                         amount: Some(1000),
1719                                         fallbacks: None,
1720                                         features: None,
1721                                         node_id: Some(&recipient_pubkey()),
1722                                 },
1723                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1724                         ),
1725                 );
1726
1727                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
1728                         panic!("error parsing invoice: {:?}", e);
1729                 }
1730         }
1731
1732         #[cfg(feature = "std")]
1733         #[test]
1734         fn builds_invoice_from_offer_with_expiration() {
1735                 let future_expiry = Duration::from_secs(u64::max_value());
1736                 let past_expiry = Duration::from_secs(0);
1737
1738                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1739                         .amount_msats(1000)
1740                         .absolute_expiry(future_expiry)
1741                         .build().unwrap()
1742                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1743                         .build().unwrap()
1744                         .sign(payer_sign).unwrap()
1745                         .respond_with(payment_paths(), payment_hash())
1746                         .unwrap()
1747                         .build()
1748                 {
1749                         panic!("error building invoice: {:?}", e);
1750                 }
1751
1752                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1753                         .amount_msats(1000)
1754                         .absolute_expiry(past_expiry)
1755                         .build().unwrap()
1756                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1757                         .build_unchecked()
1758                         .sign(payer_sign).unwrap()
1759                         .respond_with(payment_paths(), payment_hash())
1760                         .unwrap()
1761                         .build()
1762                 {
1763                         Ok(_) => panic!("expected error"),
1764                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1765                 }
1766         }
1767
1768         #[cfg(feature = "std")]
1769         #[test]
1770         fn builds_invoice_from_refund_with_expiration() {
1771                 let future_expiry = Duration::from_secs(u64::max_value());
1772                 let past_expiry = Duration::from_secs(0);
1773
1774                 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1775                         .absolute_expiry(future_expiry)
1776                         .build().unwrap()
1777                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1778                         .unwrap()
1779                         .build()
1780                 {
1781                         panic!("error building invoice: {:?}", e);
1782                 }
1783
1784                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1785                         .absolute_expiry(past_expiry)
1786                         .build().unwrap()
1787                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1788                         .unwrap()
1789                         .build()
1790                 {
1791                         Ok(_) => panic!("expected error"),
1792                         Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
1793                 }
1794         }
1795
1796         #[test]
1797         fn builds_invoice_from_offer_using_derived_keys() {
1798                 let desc = "foo".to_string();
1799                 let node_id = recipient_pubkey();
1800                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1801                 let entropy = FixedEntropy {};
1802                 let secp_ctx = Secp256k1::new();
1803
1804                 let blinded_path = BlindedPath {
1805                         introduction_node_id: pubkey(40),
1806                         blinding_point: pubkey(41),
1807                         blinded_hops: vec![
1808                                 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1809                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1810                         ],
1811                 };
1812
1813                 #[cfg(c_bindings)]
1814                 use crate::offers::offer::OfferWithDerivedMetadataBuilder as OfferBuilder;
1815                 let offer = OfferBuilder
1816                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1817                         .amount_msats(1000)
1818                         .path(blinded_path)
1819                         .build().unwrap();
1820                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1821                         .build().unwrap()
1822                         .sign(payer_sign).unwrap();
1823
1824                 if let Err(e) = invoice_request.clone()
1825                         .verify(&expanded_key, &secp_ctx).unwrap()
1826                         .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
1827                         .build_and_sign(&secp_ctx)
1828                 {
1829                         panic!("error building invoice: {:?}", e);
1830                 }
1831
1832                 let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
1833                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1834
1835                 let desc = "foo".to_string();
1836                 let offer = OfferBuilder
1837                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1838                         .amount_msats(1000)
1839                         // Omit the path so that node_id is used for the signing pubkey instead of deriving
1840                         .build().unwrap();
1841                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1842                         .build().unwrap()
1843                         .sign(payer_sign).unwrap();
1844
1845                 match invoice_request
1846                         .verify(&expanded_key, &secp_ctx).unwrap()
1847                         .respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
1848                 {
1849                         Ok(_) => panic!("expected error"),
1850                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
1851                 }
1852         }
1853
1854         #[test]
1855         fn builds_invoice_from_refund_using_derived_keys() {
1856                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1857                 let entropy = FixedEntropy {};
1858                 let secp_ctx = Secp256k1::new();
1859
1860                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1861                         .build().unwrap();
1862
1863                 if let Err(e) = refund
1864                         .respond_using_derived_keys_no_std(
1865                                 payment_paths(), payment_hash(), now(), &expanded_key, &entropy
1866                         )
1867                         .unwrap()
1868                         .build_and_sign(&secp_ctx)
1869                 {
1870                         panic!("error building invoice: {:?}", e);
1871                 }
1872         }
1873
1874         #[test]
1875         fn builds_invoice_with_relative_expiry() {
1876                 let now = now();
1877                 let one_hour = Duration::from_secs(3600);
1878
1879                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1880                         .amount_msats(1000)
1881                         .build().unwrap()
1882                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1883                         .build().unwrap()
1884                         .sign(payer_sign).unwrap()
1885                         .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1886                         .relative_expiry(one_hour.as_secs() as u32)
1887                         .build().unwrap()
1888                         .sign(recipient_sign).unwrap();
1889                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1890                 #[cfg(feature = "std")]
1891                 assert!(!invoice.is_expired());
1892                 assert_eq!(invoice.relative_expiry(), one_hour);
1893                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1894
1895                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1896                         .amount_msats(1000)
1897                         .build().unwrap()
1898                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1899                         .build().unwrap()
1900                         .sign(payer_sign).unwrap()
1901                         .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1902                         .relative_expiry(one_hour.as_secs() as u32 - 1)
1903                         .build().unwrap()
1904                         .sign(recipient_sign).unwrap();
1905                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1906                 #[cfg(feature = "std")]
1907                 assert!(invoice.is_expired());
1908                 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1909                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1910         }
1911
1912         #[test]
1913         fn builds_invoice_with_amount_from_request() {
1914                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1915                         .amount_msats(1000)
1916                         .build().unwrap()
1917                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1918                         .amount_msats(1001).unwrap()
1919                         .build().unwrap()
1920                         .sign(payer_sign).unwrap()
1921                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1922                         .build().unwrap()
1923                         .sign(recipient_sign).unwrap();
1924                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1925                 assert_eq!(invoice.amount_msats(), 1001);
1926                 assert_eq!(tlv_stream.amount, Some(1001));
1927         }
1928
1929         #[test]
1930         fn builds_invoice_with_quantity_from_request() {
1931                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1932                         .amount_msats(1000)
1933                         .supported_quantity(Quantity::Unbounded)
1934                         .build().unwrap()
1935                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1936                         .quantity(2).unwrap()
1937                         .build().unwrap()
1938                         .sign(payer_sign).unwrap()
1939                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1940                         .build().unwrap()
1941                         .sign(recipient_sign).unwrap();
1942                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1943                 assert_eq!(invoice.amount_msats(), 2000);
1944                 assert_eq!(tlv_stream.amount, Some(2000));
1945
1946                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1947                         .amount_msats(1000)
1948                         .supported_quantity(Quantity::Unbounded)
1949                         .build().unwrap()
1950                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1951                         .quantity(u64::max_value()).unwrap()
1952                         .build_unchecked()
1953                         .sign(payer_sign).unwrap()
1954                         .respond_with_no_std(payment_paths(), payment_hash(), now())
1955                 {
1956                         Ok(_) => panic!("expected error"),
1957                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1958                 }
1959         }
1960
1961         #[test]
1962         fn builds_invoice_with_fallback_address() {
1963                 let script = ScriptBuf::new();
1964                 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
1965                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1966                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1967
1968                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1969                         .amount_msats(1000)
1970                         .build().unwrap()
1971                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1972                         .build().unwrap()
1973                         .sign(payer_sign).unwrap()
1974                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1975                         .fallback_v0_p2wsh(&script.wscript_hash())
1976                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1977                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1978                         .build().unwrap()
1979                         .sign(recipient_sign).unwrap();
1980                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1981                 assert_eq!(
1982                         invoice.fallbacks(),
1983                         vec![
1984                                 Address::p2wsh(&script, Network::Bitcoin),
1985                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1986                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1987                         ],
1988                 );
1989                 assert_eq!(
1990                         tlv_stream.fallbacks,
1991                         Some(&vec![
1992                                 FallbackAddress {
1993                                         version: WitnessVersion::V0.to_num(),
1994                                         program: Vec::from(script.wscript_hash().to_byte_array()),
1995                                 },
1996                                 FallbackAddress {
1997                                         version: WitnessVersion::V0.to_num(),
1998                                         program: Vec::from(pubkey.wpubkey_hash().unwrap().to_byte_array()),
1999                                 },
2000                                 FallbackAddress {
2001                                         version: WitnessVersion::V1.to_num(),
2002                                         program: Vec::from(&tweaked_pubkey.serialize()[..]),
2003                                 },
2004                         ])
2005                 );
2006         }
2007
2008         #[test]
2009         fn builds_invoice_with_allow_mpp() {
2010                 let mut features = Bolt12InvoiceFeatures::empty();
2011                 features.set_basic_mpp_optional();
2012
2013                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2014                         .amount_msats(1000)
2015                         .build().unwrap()
2016                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2017                         .build().unwrap()
2018                         .sign(payer_sign).unwrap()
2019                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2020                         .allow_mpp()
2021                         .build().unwrap()
2022                         .sign(recipient_sign).unwrap();
2023                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
2024                 assert_eq!(invoice.invoice_features(), &features);
2025                 assert_eq!(tlv_stream.features, Some(&features));
2026         }
2027
2028         #[test]
2029         fn fails_signing_invoice() {
2030                 match OfferBuilder::new("foo".into(), recipient_pubkey())
2031                         .amount_msats(1000)
2032                         .build().unwrap()
2033                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2034                         .build().unwrap()
2035                         .sign(payer_sign).unwrap()
2036                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2037                         .build().unwrap()
2038                         .sign(fail_sign)
2039                 {
2040                         Ok(_) => panic!("expected error"),
2041                         Err(e) => assert_eq!(e, SignError::Signing),
2042                 }
2043
2044                 match OfferBuilder::new("foo".into(), recipient_pubkey())
2045                         .amount_msats(1000)
2046                         .build().unwrap()
2047                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2048                         .build().unwrap()
2049                         .sign(payer_sign).unwrap()
2050                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2051                         .build().unwrap()
2052                         .sign(payer_sign)
2053                 {
2054                         Ok(_) => panic!("expected error"),
2055                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
2056                 }
2057         }
2058
2059         #[test]
2060         fn parses_invoice_with_payment_paths() {
2061                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2062                         .amount_msats(1000)
2063                         .build().unwrap()
2064                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2065                         .build().unwrap()
2066                         .sign(payer_sign).unwrap()
2067                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2068                         .build().unwrap()
2069                         .sign(recipient_sign).unwrap();
2070
2071                 let mut buffer = Vec::new();
2072                 invoice.write(&mut buffer).unwrap();
2073
2074                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2075                         panic!("error parsing invoice: {:?}", e);
2076                 }
2077
2078                 let mut tlv_stream = invoice.as_tlv_stream();
2079                 tlv_stream.3.paths = None;
2080
2081                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2082                         Ok(_) => panic!("expected error"),
2083                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2084                 }
2085
2086                 let mut tlv_stream = invoice.as_tlv_stream();
2087                 tlv_stream.3.blindedpay = None;
2088
2089                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2090                         Ok(_) => panic!("expected error"),
2091                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2092                 }
2093
2094                 let empty_payment_paths = vec![];
2095                 let mut tlv_stream = invoice.as_tlv_stream();
2096                 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(_, path)| path)));
2097
2098                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2099                         Ok(_) => panic!("expected error"),
2100                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths)),
2101                 }
2102
2103                 let mut payment_paths = payment_paths();
2104                 payment_paths.pop();
2105                 let mut tlv_stream = invoice.as_tlv_stream();
2106                 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(payinfo, _)| payinfo)));
2107
2108                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2109                         Ok(_) => panic!("expected error"),
2110                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidPayInfo)),
2111                 }
2112         }
2113
2114         #[test]
2115         fn parses_invoice_with_created_at() {
2116                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2117                         .amount_msats(1000)
2118                         .build().unwrap()
2119                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2120                         .build().unwrap()
2121                         .sign(payer_sign).unwrap()
2122                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2123                         .build().unwrap()
2124                         .sign(recipient_sign).unwrap();
2125
2126                 let mut buffer = Vec::new();
2127                 invoice.write(&mut buffer).unwrap();
2128
2129                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2130                         panic!("error parsing invoice: {:?}", e);
2131                 }
2132
2133                 let mut tlv_stream = invoice.as_tlv_stream();
2134                 tlv_stream.3.created_at = None;
2135
2136                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2137                         Ok(_) => panic!("expected error"),
2138                         Err(e) => {
2139                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingCreationTime));
2140                         },
2141                 }
2142         }
2143
2144         #[test]
2145         fn parses_invoice_with_relative_expiry() {
2146                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2147                         .amount_msats(1000)
2148                         .build().unwrap()
2149                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2150                         .build().unwrap()
2151                         .sign(payer_sign).unwrap()
2152                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2153                         .relative_expiry(3600)
2154                         .build().unwrap()
2155                         .sign(recipient_sign).unwrap();
2156
2157                 let mut buffer = Vec::new();
2158                 invoice.write(&mut buffer).unwrap();
2159
2160                 match Bolt12Invoice::try_from(buffer) {
2161                         Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
2162                         Err(e) => panic!("error parsing invoice: {:?}", e),
2163                 }
2164         }
2165
2166         #[test]
2167         fn parses_invoice_with_payment_hash() {
2168                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2169                         .amount_msats(1000)
2170                         .build().unwrap()
2171                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2172                         .build().unwrap()
2173                         .sign(payer_sign).unwrap()
2174                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2175                         .build().unwrap()
2176                         .sign(recipient_sign).unwrap();
2177
2178                 let mut buffer = Vec::new();
2179                 invoice.write(&mut buffer).unwrap();
2180
2181                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2182                         panic!("error parsing invoice: {:?}", e);
2183                 }
2184
2185                 let mut tlv_stream = invoice.as_tlv_stream();
2186                 tlv_stream.3.payment_hash = None;
2187
2188                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2189                         Ok(_) => panic!("expected error"),
2190                         Err(e) => {
2191                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaymentHash));
2192                         },
2193                 }
2194         }
2195
2196         #[test]
2197         fn parses_invoice_with_amount() {
2198                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2199                         .amount_msats(1000)
2200                         .build().unwrap()
2201                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2202                         .build().unwrap()
2203                         .sign(payer_sign).unwrap()
2204                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2205                         .build().unwrap()
2206                         .sign(recipient_sign).unwrap();
2207
2208                 let mut buffer = Vec::new();
2209                 invoice.write(&mut buffer).unwrap();
2210
2211                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2212                         panic!("error parsing invoice: {:?}", e);
2213                 }
2214
2215                 let mut tlv_stream = invoice.as_tlv_stream();
2216                 tlv_stream.3.amount = None;
2217
2218                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2219                         Ok(_) => panic!("expected error"),
2220                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
2221                 }
2222         }
2223
2224         #[test]
2225         fn parses_invoice_with_allow_mpp() {
2226                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2227                         .amount_msats(1000)
2228                         .build().unwrap()
2229                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2230                         .build().unwrap()
2231                         .sign(payer_sign).unwrap()
2232                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2233                         .allow_mpp()
2234                         .build().unwrap()
2235                         .sign(recipient_sign).unwrap();
2236
2237                 let mut buffer = Vec::new();
2238                 invoice.write(&mut buffer).unwrap();
2239
2240                 match Bolt12Invoice::try_from(buffer) {
2241                         Ok(invoice) => {
2242                                 let mut features = Bolt12InvoiceFeatures::empty();
2243                                 features.set_basic_mpp_optional();
2244                                 assert_eq!(invoice.invoice_features(), &features);
2245                         },
2246                         Err(e) => panic!("error parsing invoice: {:?}", e),
2247                 }
2248         }
2249
2250         #[test]
2251         fn parses_invoice_with_fallback_address() {
2252                 let script = ScriptBuf::new();
2253                 let pubkey = bitcoin::key::PublicKey::new(recipient_pubkey());
2254                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
2255                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
2256
2257                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
2258                         .amount_msats(1000)
2259                         .build().unwrap();
2260                 let invoice_request = offer
2261                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2262                         .build().unwrap()
2263                         .sign(payer_sign).unwrap();
2264                 #[cfg(not(c_bindings))]
2265                 let invoice_builder = invoice_request
2266                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2267                 #[cfg(c_bindings)]
2268                 let mut invoice_builder = invoice_request
2269                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap();
2270                 let invoice_builder = invoice_builder
2271                         .fallback_v0_p2wsh(&script.wscript_hash())
2272                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
2273                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey);
2274                 #[cfg(not(c_bindings))]
2275                 let mut invoice_builder = invoice_builder;
2276
2277                 // Only standard addresses will be included.
2278                 let fallbacks = invoice_builder.invoice.fields_mut().fallbacks.as_mut().unwrap();
2279                 // Non-standard addresses
2280                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
2281                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
2282                 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
2283                 // Standard address
2284                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
2285                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
2286
2287                 let invoice = invoice_builder.build().unwrap().sign(recipient_sign).unwrap();
2288                 let mut buffer = Vec::new();
2289                 invoice.write(&mut buffer).unwrap();
2290
2291                 match Bolt12Invoice::try_from(buffer) {
2292                         Ok(invoice) => {
2293                                 let v1_witness_program = WitnessProgram::new(WitnessVersion::V1, vec![0u8; 33]).unwrap();
2294                                 let v2_witness_program = WitnessProgram::new(WitnessVersion::V2, vec![0u8; 40]).unwrap();
2295                                 assert_eq!(
2296                                         invoice.fallbacks(),
2297                                         vec![
2298                                                 Address::p2wsh(&script, Network::Bitcoin),
2299                                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
2300                                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
2301                                                 Address::new(Network::Bitcoin, Payload::WitnessProgram(v1_witness_program)),
2302                                                 Address::new(Network::Bitcoin, Payload::WitnessProgram(v2_witness_program)),
2303                                         ],
2304                                 );
2305                         },
2306                         Err(e) => panic!("error parsing invoice: {:?}", e),
2307                 }
2308         }
2309
2310         #[test]
2311         fn parses_invoice_with_node_id() {
2312                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2313                         .amount_msats(1000)
2314                         .build().unwrap()
2315                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2316                         .build().unwrap()
2317                         .sign(payer_sign).unwrap()
2318                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2319                         .build().unwrap()
2320                         .sign(recipient_sign).unwrap();
2321
2322                 let mut buffer = Vec::new();
2323                 invoice.write(&mut buffer).unwrap();
2324
2325                 if let Err(e) = Bolt12Invoice::try_from(buffer) {
2326                         panic!("error parsing invoice: {:?}", e);
2327                 }
2328
2329                 let mut tlv_stream = invoice.as_tlv_stream();
2330                 tlv_stream.3.node_id = None;
2331
2332                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2333                         Ok(_) => panic!("expected error"),
2334                         Err(e) => {
2335                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
2336                         },
2337                 }
2338
2339                 let invalid_pubkey = payer_pubkey();
2340                 let mut tlv_stream = invoice.as_tlv_stream();
2341                 tlv_stream.3.node_id = Some(&invalid_pubkey);
2342
2343                 match Bolt12Invoice::try_from(tlv_stream.to_bytes()) {
2344                         Ok(_) => panic!("expected error"),
2345                         Err(e) => {
2346                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidSigningPubkey));
2347                         },
2348                 }
2349         }
2350
2351         #[test]
2352         fn fails_parsing_invoice_without_signature() {
2353                 let mut buffer = Vec::new();
2354                 OfferBuilder::new("foo".into(), recipient_pubkey())
2355                         .amount_msats(1000)
2356                         .build().unwrap()
2357                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2358                         .build().unwrap()
2359                         .sign(payer_sign).unwrap()
2360                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2361                         .build().unwrap()
2362                         .contents
2363                         .write(&mut buffer).unwrap();
2364
2365                 match Bolt12Invoice::try_from(buffer) {
2366                         Ok(_) => panic!("expected error"),
2367                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
2368                 }
2369         }
2370
2371         #[test]
2372         fn fails_parsing_invoice_with_invalid_signature() {
2373                 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2374                         .amount_msats(1000)
2375                         .build().unwrap()
2376                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2377                         .build().unwrap()
2378                         .sign(payer_sign).unwrap()
2379                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2380                         .build().unwrap()
2381                         .sign(recipient_sign).unwrap();
2382                 let last_signature_byte = invoice.bytes.last_mut().unwrap();
2383                 *last_signature_byte = last_signature_byte.wrapping_add(1);
2384
2385                 let mut buffer = Vec::new();
2386                 invoice.write(&mut buffer).unwrap();
2387
2388                 match Bolt12Invoice::try_from(buffer) {
2389                         Ok(_) => panic!("expected error"),
2390                         Err(e) => {
2391                                 assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
2392                         },
2393                 }
2394         }
2395
2396         #[test]
2397         fn fails_parsing_invoice_with_extra_tlv_records() {
2398                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2399                         .amount_msats(1000)
2400                         .build().unwrap()
2401                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2402                         .build().unwrap()
2403                         .sign(payer_sign).unwrap()
2404                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2405                         .build().unwrap()
2406                         .sign(recipient_sign).unwrap();
2407
2408                 let mut encoded_invoice = Vec::new();
2409                 invoice.write(&mut encoded_invoice).unwrap();
2410                 BigSize(1002).write(&mut encoded_invoice).unwrap();
2411                 BigSize(32).write(&mut encoded_invoice).unwrap();
2412                 [42u8; 32].write(&mut encoded_invoice).unwrap();
2413
2414                 match Bolt12Invoice::try_from(encoded_invoice) {
2415                         Ok(_) => panic!("expected error"),
2416                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2417                 }
2418         }
2419 }