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