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