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