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