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