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