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