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