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