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