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