ad59bf35b0c9c2cd2cf54b7d19297471e757d099
[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 //! ```ignore
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         fee_base_msat: u32,
585         fee_proportional_millionths: u32,
586         cltv_expiry_delta: u16,
587         htlc_minimum_msat: u64,
588         htlc_maximum_msat: u64,
589         features: BlindedHopFeatures,
590 }
591
592 impl_writeable!(BlindedPayInfo, {
593         fee_base_msat,
594         fee_proportional_millionths,
595         cltv_expiry_delta,
596         htlc_minimum_msat,
597         htlc_maximum_msat,
598         features
599 });
600
601 /// Wire representation for an on-chain fallback address.
602 #[derive(Clone, Debug, PartialEq)]
603 pub(super) struct FallbackAddress {
604         version: u8,
605         program: Vec<u8>,
606 }
607
608 impl_writeable!(FallbackAddress, { version, program });
609
610 type FullInvoiceTlvStream =
611         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
612
613 #[cfg(test)]
614 type FullInvoiceTlvStreamRef<'a> = (
615         PayerTlvStreamRef<'a>,
616         OfferTlvStreamRef<'a>,
617         InvoiceRequestTlvStreamRef<'a>,
618         InvoiceTlvStreamRef<'a>,
619         SignatureTlvStreamRef<'a>,
620 );
621
622 impl SeekReadable for FullInvoiceTlvStream {
623         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
624                 let payer = SeekReadable::read(r)?;
625                 let offer = SeekReadable::read(r)?;
626                 let invoice_request = SeekReadable::read(r)?;
627                 let invoice = SeekReadable::read(r)?;
628                 let signature = SeekReadable::read(r)?;
629
630                 Ok((payer, offer, invoice_request, invoice, signature))
631         }
632 }
633
634 type PartialInvoiceTlvStream =
635         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
636
637 type PartialInvoiceTlvStreamRef<'a> = (
638         PayerTlvStreamRef<'a>,
639         OfferTlvStreamRef<'a>,
640         InvoiceRequestTlvStreamRef<'a>,
641         InvoiceTlvStreamRef<'a>,
642 );
643
644 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
645         type Error = ParseError;
646
647         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
648                 let ParsedMessage { bytes, tlv_stream } = invoice;
649                 let (
650                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
651                         SignatureTlvStream { signature },
652                 ) = tlv_stream;
653                 let contents = InvoiceContents::try_from(
654                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
655                 )?;
656
657                 let signature = match signature {
658                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
659                         Some(signature) => signature,
660                 };
661                 let pubkey = contents.fields().signing_pubkey;
662                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
663
664                 Ok(Invoice { bytes, contents, signature })
665         }
666 }
667
668 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
669         type Error = SemanticError;
670
671         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
672                 let (
673                         payer_tlv_stream,
674                         offer_tlv_stream,
675                         invoice_request_tlv_stream,
676                         InvoiceTlvStream {
677                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
678                                 features, node_id,
679                         },
680                 ) = tlv_stream;
681
682                 let payment_paths = match (paths, blindedpay) {
683                         (None, _) => return Err(SemanticError::MissingPaths),
684                         (_, None) => return Err(SemanticError::InvalidPayInfo),
685                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
686                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
687                                 return Err(SemanticError::InvalidPayInfo);
688                         },
689                         (Some(paths), Some(blindedpay)) => {
690                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
691                         },
692                 };
693
694                 let created_at = match created_at {
695                         None => return Err(SemanticError::MissingCreationTime),
696                         Some(timestamp) => Duration::from_secs(timestamp),
697                 };
698
699                 let relative_expiry = relative_expiry
700                         .map(Into::<u64>::into)
701                         .map(Duration::from_secs);
702
703                 let payment_hash = match payment_hash {
704                         None => return Err(SemanticError::MissingPaymentHash),
705                         Some(payment_hash) => payment_hash,
706                 };
707
708                 let amount_msats = match amount {
709                         None => return Err(SemanticError::MissingAmount),
710                         Some(amount) => amount,
711                 };
712
713                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
714
715                 let signing_pubkey = match node_id {
716                         None => return Err(SemanticError::MissingSigningPubkey),
717                         Some(node_id) => node_id,
718                 };
719
720                 let fields = InvoiceFields {
721                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
722                         features, signing_pubkey,
723                 };
724
725                 match offer_tlv_stream.node_id {
726                         Some(expected_signing_pubkey) => {
727                                 if fields.signing_pubkey != expected_signing_pubkey {
728                                         return Err(SemanticError::InvalidSigningPubkey);
729                                 }
730
731                                 let invoice_request = InvoiceRequestContents::try_from(
732                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
733                                 )?;
734                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
735                         },
736                         None => {
737                                 let refund = RefundContents::try_from(
738                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
739                                 )?;
740                                 Ok(InvoiceContents::ForRefund { refund, fields })
741                         },
742                 }
743         }
744 }
745
746 #[cfg(test)]
747 mod tests {
748         use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
749
750         use bitcoin::blockdata::script::Script;
751         use bitcoin::hashes::Hash;
752         use bitcoin::network::constants::Network;
753         use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
754         use bitcoin::secp256k1::schnorr::Signature;
755         use bitcoin::util::address::{Address, Payload, WitnessVersion};
756         use bitcoin::util::schnorr::TweakedPublicKey;
757         use core::convert::{Infallible, TryFrom};
758         use core::time::Duration;
759         use crate::ln::PaymentHash;
760         use crate::ln::msgs::DecodeError;
761         use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
762         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
763         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
764         use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
765         use crate::offers::parse::{ParseError, SemanticError};
766         use crate::offers::payer::PayerTlvStreamRef;
767         use crate::offers::refund::RefundBuilder;
768         use crate::onion_message::{BlindedHop, BlindedPath};
769         use crate::util::ser::{BigSize, Iterable, Writeable};
770
771         fn payer_keys() -> KeyPair {
772                 let secp_ctx = Secp256k1::new();
773                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
774         }
775
776         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
777                 let secp_ctx = Secp256k1::new();
778                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
779                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
780         }
781
782         fn payer_pubkey() -> PublicKey {
783                 payer_keys().public_key()
784         }
785
786         fn recipient_keys() -> KeyPair {
787                 let secp_ctx = Secp256k1::new();
788                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
789         }
790
791         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
792                 let secp_ctx = Secp256k1::new();
793                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
794                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
795         }
796
797         fn recipient_pubkey() -> PublicKey {
798                 recipient_keys().public_key()
799         }
800
801         fn pubkey(byte: u8) -> PublicKey {
802                 let secp_ctx = Secp256k1::new();
803                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
804         }
805
806         fn privkey(byte: u8) -> SecretKey {
807                 SecretKey::from_slice(&[byte; 32]).unwrap()
808         }
809
810         trait ToBytes {
811                 fn to_bytes(&self) -> Vec<u8>;
812         }
813
814         impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
815                 fn to_bytes(&self) -> Vec<u8> {
816                         let mut buffer = Vec::new();
817                         self.0.write(&mut buffer).unwrap();
818                         self.1.write(&mut buffer).unwrap();
819                         self.2.write(&mut buffer).unwrap();
820                         self.3.write(&mut buffer).unwrap();
821                         self.4.write(&mut buffer).unwrap();
822                         buffer
823                 }
824         }
825
826         fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
827                 let paths = vec![
828                         BlindedPath {
829                                 introduction_node_id: pubkey(40),
830                                 blinding_point: pubkey(41),
831                                 blinded_hops: vec![
832                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
833                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
834                                 ],
835                         },
836                         BlindedPath {
837                                 introduction_node_id: pubkey(40),
838                                 blinding_point: pubkey(41),
839                                 blinded_hops: vec![
840                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
841                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
842                                 ],
843                         },
844                 ];
845
846                 let payinfo = vec![
847                         BlindedPayInfo {
848                                 fee_base_msat: 1,
849                                 fee_proportional_millionths: 1_000,
850                                 cltv_expiry_delta: 42,
851                                 htlc_minimum_msat: 100,
852                                 htlc_maximum_msat: 1_000_000_000_000,
853                                 features: BlindedHopFeatures::empty(),
854                         },
855                         BlindedPayInfo {
856                                 fee_base_msat: 1,
857                                 fee_proportional_millionths: 1_000,
858                                 cltv_expiry_delta: 42,
859                                 htlc_minimum_msat: 100,
860                                 htlc_maximum_msat: 1_000_000_000_000,
861                                 features: BlindedHopFeatures::empty(),
862                         },
863                 ];
864
865                 paths.into_iter().zip(payinfo.into_iter()).collect()
866         }
867
868         fn payment_hash() -> PaymentHash {
869                 PaymentHash([42; 32])
870         }
871
872         fn now() -> Duration {
873                 std::time::SystemTime::now()
874                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
875                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
876         }
877
878         #[test]
879         fn builds_invoice_for_offer_with_defaults() {
880                 let payment_paths = payment_paths();
881                 let payment_hash = payment_hash();
882                 let now = now();
883                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
884                         .amount_msats(1000)
885                         .build().unwrap()
886                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
887                         .build().unwrap()
888                         .sign(payer_sign).unwrap()
889                         .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
890                         .build().unwrap()
891                         .sign(recipient_sign).unwrap();
892
893                 let mut buffer = Vec::new();
894                 invoice.write(&mut buffer).unwrap();
895
896                 assert_eq!(invoice.bytes, buffer.as_slice());
897                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
898                 assert_eq!(invoice.created_at(), now);
899                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
900                 #[cfg(feature = "std")]
901                 assert!(!invoice.is_expired());
902                 assert_eq!(invoice.payment_hash(), payment_hash);
903                 assert_eq!(invoice.amount_msats(), 1000);
904                 assert_eq!(invoice.fallbacks(), vec![]);
905                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
906                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
907                 assert!(
908                         merkle::verify_signature(
909                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
910                         ).is_ok()
911                 );
912
913                 assert_eq!(
914                         invoice.as_tlv_stream(),
915                         (
916                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
917                                 OfferTlvStreamRef {
918                                         chains: None,
919                                         metadata: None,
920                                         currency: None,
921                                         amount: Some(1000),
922                                         description: Some(&String::from("foo")),
923                                         features: None,
924                                         absolute_expiry: None,
925                                         paths: None,
926                                         issuer: None,
927                                         quantity_max: None,
928                                         node_id: Some(&recipient_pubkey()),
929                                 },
930                                 InvoiceRequestTlvStreamRef {
931                                         chain: None,
932                                         amount: None,
933                                         features: None,
934                                         quantity: None,
935                                         payer_id: Some(&payer_pubkey()),
936                                         payer_note: None,
937                                 },
938                                 InvoiceTlvStreamRef {
939                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
940                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
941                                         created_at: Some(now.as_secs()),
942                                         relative_expiry: None,
943                                         payment_hash: Some(&payment_hash),
944                                         amount: Some(1000),
945                                         fallbacks: None,
946                                         features: None,
947                                         node_id: Some(&recipient_pubkey()),
948                                 },
949                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
950                         ),
951                 );
952
953                 if let Err(e) = Invoice::try_from(buffer) {
954                         panic!("error parsing invoice: {:?}", e);
955                 }
956         }
957
958         #[test]
959         fn builds_invoice_for_refund_with_defaults() {
960                 let payment_paths = payment_paths();
961                 let payment_hash = payment_hash();
962                 let now = now();
963                 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
964                         .build().unwrap()
965                         .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
966                         .unwrap()
967                         .build().unwrap()
968                         .sign(recipient_sign).unwrap();
969
970                 let mut buffer = Vec::new();
971                 invoice.write(&mut buffer).unwrap();
972
973                 assert_eq!(invoice.bytes, buffer.as_slice());
974                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
975                 assert_eq!(invoice.created_at(), now);
976                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
977                 #[cfg(feature = "std")]
978                 assert!(!invoice.is_expired());
979                 assert_eq!(invoice.payment_hash(), payment_hash);
980                 assert_eq!(invoice.amount_msats(), 1000);
981                 assert_eq!(invoice.fallbacks(), vec![]);
982                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
983                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
984                 assert!(
985                         merkle::verify_signature(
986                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
987                         ).is_ok()
988                 );
989
990                 assert_eq!(
991                         invoice.as_tlv_stream(),
992                         (
993                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
994                                 OfferTlvStreamRef {
995                                         chains: None,
996                                         metadata: None,
997                                         currency: None,
998                                         amount: None,
999                                         description: Some(&String::from("foo")),
1000                                         features: None,
1001                                         absolute_expiry: None,
1002                                         paths: None,
1003                                         issuer: None,
1004                                         quantity_max: None,
1005                                         node_id: None,
1006                                 },
1007                                 InvoiceRequestTlvStreamRef {
1008                                         chain: None,
1009                                         amount: Some(1000),
1010                                         features: None,
1011                                         quantity: None,
1012                                         payer_id: Some(&payer_pubkey()),
1013                                         payer_note: None,
1014                                 },
1015                                 InvoiceTlvStreamRef {
1016                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1017                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1018                                         created_at: Some(now.as_secs()),
1019                                         relative_expiry: None,
1020                                         payment_hash: Some(&payment_hash),
1021                                         amount: Some(1000),
1022                                         fallbacks: None,
1023                                         features: None,
1024                                         node_id: Some(&recipient_pubkey()),
1025                                 },
1026                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1027                         ),
1028                 );
1029
1030                 if let Err(e) = Invoice::try_from(buffer) {
1031                         panic!("error parsing invoice: {:?}", e);
1032                 }
1033         }
1034
1035         #[cfg(feature = "std")]
1036         #[test]
1037         fn builds_invoice_from_offer_with_expiration() {
1038                 let future_expiry = Duration::from_secs(u64::max_value());
1039                 let past_expiry = Duration::from_secs(0);
1040
1041                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1042                         .amount_msats(1000)
1043                         .absolute_expiry(future_expiry)
1044                         .build().unwrap()
1045                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1046                         .build().unwrap()
1047                         .sign(payer_sign).unwrap()
1048                         .respond_with(payment_paths(), payment_hash())
1049                         .unwrap()
1050                         .build()
1051                 {
1052                         panic!("error building invoice: {:?}", e);
1053                 }
1054
1055                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1056                         .amount_msats(1000)
1057                         .absolute_expiry(past_expiry)
1058                         .build().unwrap()
1059                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1060                         .build_unchecked()
1061                         .sign(payer_sign).unwrap()
1062                         .respond_with(payment_paths(), payment_hash())
1063                         .unwrap()
1064                         .build()
1065                 {
1066                         Ok(_) => panic!("expected error"),
1067                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1068                 }
1069         }
1070
1071         #[cfg(feature = "std")]
1072         #[test]
1073         fn builds_invoice_from_refund_with_expiration() {
1074                 let future_expiry = Duration::from_secs(u64::max_value());
1075                 let past_expiry = Duration::from_secs(0);
1076
1077                 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1078                         .absolute_expiry(future_expiry)
1079                         .build().unwrap()
1080                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1081                         .unwrap()
1082                         .build()
1083                 {
1084                         panic!("error building invoice: {:?}", e);
1085                 }
1086
1087                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1088                         .absolute_expiry(past_expiry)
1089                         .build().unwrap()
1090                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1091                         .unwrap()
1092                         .build()
1093                 {
1094                         Ok(_) => panic!("expected error"),
1095                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1096                 }
1097         }
1098
1099         #[test]
1100         fn builds_invoice_with_relative_expiry() {
1101                 let now = now();
1102                 let one_hour = Duration::from_secs(3600);
1103
1104                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1105                         .amount_msats(1000)
1106                         .build().unwrap()
1107                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1108                         .build().unwrap()
1109                         .sign(payer_sign).unwrap()
1110                         .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1111                         .relative_expiry(one_hour.as_secs() as u32)
1112                         .build().unwrap()
1113                         .sign(recipient_sign).unwrap();
1114                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1115                 #[cfg(feature = "std")]
1116                 assert!(!invoice.is_expired());
1117                 assert_eq!(invoice.relative_expiry(), one_hour);
1118                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1119
1120                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1121                         .amount_msats(1000)
1122                         .build().unwrap()
1123                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1124                         .build().unwrap()
1125                         .sign(payer_sign).unwrap()
1126                         .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1127                         .relative_expiry(one_hour.as_secs() as u32 - 1)
1128                         .build().unwrap()
1129                         .sign(recipient_sign).unwrap();
1130                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1131                 #[cfg(feature = "std")]
1132                 assert!(invoice.is_expired());
1133                 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1134                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1135         }
1136
1137         #[test]
1138         fn builds_invoice_with_amount_from_request() {
1139                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1140                         .amount_msats(1000)
1141                         .build().unwrap()
1142                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1143                         .amount_msats(1001).unwrap()
1144                         .build().unwrap()
1145                         .sign(payer_sign).unwrap()
1146                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1147                         .build().unwrap()
1148                         .sign(recipient_sign).unwrap();
1149                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1150                 assert_eq!(invoice.amount_msats(), 1001);
1151                 assert_eq!(tlv_stream.amount, Some(1001));
1152         }
1153
1154         #[test]
1155         fn builds_invoice_with_fallback_address() {
1156                 let script = Script::new();
1157                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1158                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1159                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1160
1161                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1162                         .amount_msats(1000)
1163                         .build().unwrap()
1164                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1165                         .build().unwrap()
1166                         .sign(payer_sign).unwrap()
1167                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1168                         .fallback_v0_p2wsh(&script.wscript_hash())
1169                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1170                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1171                         .build().unwrap()
1172                         .sign(recipient_sign).unwrap();
1173                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1174                 assert_eq!(
1175                         invoice.fallbacks(),
1176                         vec![
1177                                 Address::p2wsh(&script, Network::Bitcoin),
1178                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1179                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1180                         ],
1181                 );
1182                 assert_eq!(
1183                         tlv_stream.fallbacks,
1184                         Some(&vec![
1185                                 FallbackAddress {
1186                                         version: WitnessVersion::V0.to_num(),
1187                                         program: Vec::from(&script.wscript_hash().into_inner()[..]),
1188                                 },
1189                                 FallbackAddress {
1190                                         version: WitnessVersion::V0.to_num(),
1191                                         program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1192                                 },
1193                                 FallbackAddress {
1194                                         version: WitnessVersion::V1.to_num(),
1195                                         program: Vec::from(&tweaked_pubkey.serialize()[..]),
1196                                 },
1197                         ])
1198                 );
1199         }
1200
1201         #[test]
1202         fn builds_invoice_with_allow_mpp() {
1203                 let mut features = Bolt12InvoiceFeatures::empty();
1204                 features.set_basic_mpp_optional();
1205
1206                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1207                         .amount_msats(1000)
1208                         .build().unwrap()
1209                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1210                         .build().unwrap()
1211                         .sign(payer_sign).unwrap()
1212                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1213                         .allow_mpp()
1214                         .build().unwrap()
1215                         .sign(recipient_sign).unwrap();
1216                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1217                 assert_eq!(invoice.features(), &features);
1218                 assert_eq!(tlv_stream.features, Some(&features));
1219         }
1220
1221         #[test]
1222         fn fails_signing_invoice() {
1223                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1224                         .amount_msats(1000)
1225                         .build().unwrap()
1226                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1227                         .build().unwrap()
1228                         .sign(payer_sign).unwrap()
1229                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1230                         .build().unwrap()
1231                         .sign(|_| Err(()))
1232                 {
1233                         Ok(_) => panic!("expected error"),
1234                         Err(e) => assert_eq!(e, SignError::Signing(())),
1235                 }
1236
1237                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1238                         .amount_msats(1000)
1239                         .build().unwrap()
1240                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1241                         .build().unwrap()
1242                         .sign(payer_sign).unwrap()
1243                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1244                         .build().unwrap()
1245                         .sign(payer_sign)
1246                 {
1247                         Ok(_) => panic!("expected error"),
1248                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1249                 }
1250         }
1251
1252         #[test]
1253         fn parses_invoice_with_payment_paths() {
1254                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1255                         .amount_msats(1000)
1256                         .build().unwrap()
1257                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258                         .build().unwrap()
1259                         .sign(payer_sign).unwrap()
1260                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1261                         .build().unwrap()
1262                         .sign(recipient_sign).unwrap();
1263
1264                 let mut buffer = Vec::new();
1265                 invoice.write(&mut buffer).unwrap();
1266
1267                 if let Err(e) = Invoice::try_from(buffer) {
1268                         panic!("error parsing invoice: {:?}", e);
1269                 }
1270
1271                 let mut tlv_stream = invoice.as_tlv_stream();
1272                 tlv_stream.3.paths = None;
1273
1274                 match Invoice::try_from(tlv_stream.to_bytes()) {
1275                         Ok(_) => panic!("expected error"),
1276                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1277                 }
1278
1279                 let mut tlv_stream = invoice.as_tlv_stream();
1280                 tlv_stream.3.blindedpay = None;
1281
1282                 match Invoice::try_from(tlv_stream.to_bytes()) {
1283                         Ok(_) => panic!("expected error"),
1284                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1285                 }
1286
1287                 let empty_payment_paths = vec![];
1288                 let mut tlv_stream = invoice.as_tlv_stream();
1289                 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1290
1291                 match Invoice::try_from(tlv_stream.to_bytes()) {
1292                         Ok(_) => panic!("expected error"),
1293                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1294                 }
1295
1296                 let mut payment_paths = payment_paths();
1297                 payment_paths.pop();
1298                 let mut tlv_stream = invoice.as_tlv_stream();
1299                 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1300
1301                 match Invoice::try_from(tlv_stream.to_bytes()) {
1302                         Ok(_) => panic!("expected error"),
1303                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1304                 }
1305         }
1306
1307         #[test]
1308         fn parses_invoice_with_created_at() {
1309                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1310                         .amount_msats(1000)
1311                         .build().unwrap()
1312                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1313                         .build().unwrap()
1314                         .sign(payer_sign).unwrap()
1315                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1316                         .build().unwrap()
1317                         .sign(recipient_sign).unwrap();
1318
1319                 let mut buffer = Vec::new();
1320                 invoice.write(&mut buffer).unwrap();
1321
1322                 if let Err(e) = Invoice::try_from(buffer) {
1323                         panic!("error parsing invoice: {:?}", e);
1324                 }
1325
1326                 let mut tlv_stream = invoice.as_tlv_stream();
1327                 tlv_stream.3.created_at = None;
1328
1329                 match Invoice::try_from(tlv_stream.to_bytes()) {
1330                         Ok(_) => panic!("expected error"),
1331                         Err(e) => {
1332                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1333                         },
1334                 }
1335         }
1336
1337         #[test]
1338         fn parses_invoice_with_relative_expiry() {
1339                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1340                         .amount_msats(1000)
1341                         .build().unwrap()
1342                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1343                         .build().unwrap()
1344                         .sign(payer_sign).unwrap()
1345                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1346                         .relative_expiry(3600)
1347                         .build().unwrap()
1348                         .sign(recipient_sign).unwrap();
1349
1350                 let mut buffer = Vec::new();
1351                 invoice.write(&mut buffer).unwrap();
1352
1353                 match Invoice::try_from(buffer) {
1354                         Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1355                         Err(e) => panic!("error parsing invoice: {:?}", e),
1356                 }
1357         }
1358
1359         #[test]
1360         fn parses_invoice_with_payment_hash() {
1361                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1362                         .amount_msats(1000)
1363                         .build().unwrap()
1364                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1365                         .build().unwrap()
1366                         .sign(payer_sign).unwrap()
1367                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1368                         .build().unwrap()
1369                         .sign(recipient_sign).unwrap();
1370
1371                 let mut buffer = Vec::new();
1372                 invoice.write(&mut buffer).unwrap();
1373
1374                 if let Err(e) = Invoice::try_from(buffer) {
1375                         panic!("error parsing invoice: {:?}", e);
1376                 }
1377
1378                 let mut tlv_stream = invoice.as_tlv_stream();
1379                 tlv_stream.3.payment_hash = None;
1380
1381                 match Invoice::try_from(tlv_stream.to_bytes()) {
1382                         Ok(_) => panic!("expected error"),
1383                         Err(e) => {
1384                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1385                         },
1386                 }
1387         }
1388
1389         #[test]
1390         fn parses_invoice_with_amount() {
1391                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1392                         .amount_msats(1000)
1393                         .build().unwrap()
1394                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1395                         .build().unwrap()
1396                         .sign(payer_sign).unwrap()
1397                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1398                         .build().unwrap()
1399                         .sign(recipient_sign).unwrap();
1400
1401                 let mut buffer = Vec::new();
1402                 invoice.write(&mut buffer).unwrap();
1403
1404                 if let Err(e) = Invoice::try_from(buffer) {
1405                         panic!("error parsing invoice: {:?}", e);
1406                 }
1407
1408                 let mut tlv_stream = invoice.as_tlv_stream();
1409                 tlv_stream.3.amount = None;
1410
1411                 match Invoice::try_from(tlv_stream.to_bytes()) {
1412                         Ok(_) => panic!("expected error"),
1413                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1414                 }
1415         }
1416
1417         #[test]
1418         fn parses_invoice_with_allow_mpp() {
1419                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1420                         .amount_msats(1000)
1421                         .build().unwrap()
1422                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1423                         .build().unwrap()
1424                         .sign(payer_sign).unwrap()
1425                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1426                         .allow_mpp()
1427                         .build().unwrap()
1428                         .sign(recipient_sign).unwrap();
1429
1430                 let mut buffer = Vec::new();
1431                 invoice.write(&mut buffer).unwrap();
1432
1433                 match Invoice::try_from(buffer) {
1434                         Ok(invoice) => {
1435                                 let mut features = Bolt12InvoiceFeatures::empty();
1436                                 features.set_basic_mpp_optional();
1437                                 assert_eq!(invoice.features(), &features);
1438                         },
1439                         Err(e) => panic!("error parsing invoice: {:?}", e),
1440                 }
1441         }
1442
1443         #[test]
1444         fn parses_invoice_with_fallback_address() {
1445                 let script = Script::new();
1446                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1447                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1448                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1449
1450                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1451                         .amount_msats(1000)
1452                         .build().unwrap();
1453                 let invoice_request = offer
1454                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1455                         .build().unwrap()
1456                         .sign(payer_sign).unwrap();
1457                 let mut unsigned_invoice = invoice_request
1458                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1459                         .fallback_v0_p2wsh(&script.wscript_hash())
1460                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1461                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1462                         .build().unwrap();
1463
1464                 // Only standard addresses will be included.
1465                 let mut fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1466                 // Non-standard addresses
1467                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1468                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1469                 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1470                 // Standard address
1471                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1472                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1473
1474                 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1475                 let mut buffer = Vec::new();
1476                 invoice.write(&mut buffer).unwrap();
1477
1478                 match Invoice::try_from(buffer) {
1479                         Ok(invoice) => {
1480                                 assert_eq!(
1481                                         invoice.fallbacks(),
1482                                         vec![
1483                                                 Address::p2wsh(&script, Network::Bitcoin),
1484                                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1485                                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1486                                                 Address {
1487                                                         payload: Payload::WitnessProgram {
1488                                                                 version: WitnessVersion::V1,
1489                                                                 program: vec![0u8; 33],
1490                                                         },
1491                                                         network: Network::Bitcoin,
1492                                                 },
1493                                                 Address {
1494                                                         payload: Payload::WitnessProgram {
1495                                                                 version: WitnessVersion::V2,
1496                                                                 program: vec![0u8; 40],
1497                                                         },
1498                                                         network: Network::Bitcoin,
1499                                                 },
1500                                         ],
1501                                 );
1502                         },
1503                         Err(e) => panic!("error parsing invoice: {:?}", e),
1504                 }
1505         }
1506
1507         #[test]
1508         fn parses_invoice_with_node_id() {
1509                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1510                         .amount_msats(1000)
1511                         .build().unwrap()
1512                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1513                         .build().unwrap()
1514                         .sign(payer_sign).unwrap()
1515                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1516                         .build().unwrap()
1517                         .sign(recipient_sign).unwrap();
1518
1519                 let mut buffer = Vec::new();
1520                 invoice.write(&mut buffer).unwrap();
1521
1522                 if let Err(e) = Invoice::try_from(buffer) {
1523                         panic!("error parsing invoice: {:?}", e);
1524                 }
1525
1526                 let mut tlv_stream = invoice.as_tlv_stream();
1527                 tlv_stream.3.node_id = None;
1528
1529                 match Invoice::try_from(tlv_stream.to_bytes()) {
1530                         Ok(_) => panic!("expected error"),
1531                         Err(e) => {
1532                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1533                         },
1534                 }
1535
1536                 let invalid_pubkey = payer_pubkey();
1537                 let mut tlv_stream = invoice.as_tlv_stream();
1538                 tlv_stream.3.node_id = Some(&invalid_pubkey);
1539
1540                 match Invoice::try_from(tlv_stream.to_bytes()) {
1541                         Ok(_) => panic!("expected error"),
1542                         Err(e) => {
1543                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1544                         },
1545                 }
1546         }
1547
1548         #[test]
1549         fn fails_parsing_invoice_without_signature() {
1550                 let mut buffer = Vec::new();
1551                 OfferBuilder::new("foo".into(), recipient_pubkey())
1552                         .amount_msats(1000)
1553                         .build().unwrap()
1554                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1555                         .build().unwrap()
1556                         .sign(payer_sign).unwrap()
1557                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1558                         .build().unwrap()
1559                         .invoice
1560                         .write(&mut buffer).unwrap();
1561
1562                 match Invoice::try_from(buffer) {
1563                         Ok(_) => panic!("expected error"),
1564                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1565                 }
1566         }
1567
1568         #[test]
1569         fn fails_parsing_invoice_with_invalid_signature() {
1570                 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1571                         .amount_msats(1000)
1572                         .build().unwrap()
1573                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1574                         .build().unwrap()
1575                         .sign(payer_sign).unwrap()
1576                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1577                         .build().unwrap()
1578                         .sign(recipient_sign).unwrap();
1579                 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1580                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1581
1582                 let mut buffer = Vec::new();
1583                 invoice.write(&mut buffer).unwrap();
1584
1585                 match Invoice::try_from(buffer) {
1586                         Ok(_) => panic!("expected error"),
1587                         Err(e) => {
1588                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1589                         },
1590                 }
1591         }
1592
1593         #[test]
1594         fn fails_parsing_invoice_with_extra_tlv_records() {
1595                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1596                         .amount_msats(1000)
1597                         .build().unwrap()
1598                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1599                         .build().unwrap()
1600                         .sign(payer_sign).unwrap()
1601                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1602                         .build().unwrap()
1603                         .sign(recipient_sign).unwrap();
1604
1605                 let mut encoded_invoice = Vec::new();
1606                 invoice.write(&mut encoded_invoice).unwrap();
1607                 BigSize(1002).write(&mut encoded_invoice).unwrap();
1608                 BigSize(32).write(&mut encoded_invoice).unwrap();
1609                 [42u8; 32].write(&mut encoded_invoice).unwrap();
1610
1611                 match Invoice::try_from(encoded_invoice) {
1612                         Ok(_) => panic!("expected error"),
1613                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1614                 }
1615         }
1616 }