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