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