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