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