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