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