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