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