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