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