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