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