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