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