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