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